diff --git a/build-pq-bundle.js b/build-pq-bundle.js new file mode 100644 index 0000000..798c84a --- /dev/null +++ b/build-pq-bundle.js @@ -0,0 +1,36 @@ +/** + * Build script for the post-quantum crypto bundle. + * Bundles pq-crypto.mjs and all its dependencies into a single + * ESM file that can be loaded directly in the browser. + * + * Usage: node build-pq-bundle.js + */ + +const esbuild = require('esbuild'); +const path = require('path'); + +async function build() { + console.log('🔧 Building PQ crypto bundle...'); + + await esbuild.build({ + entryPoints: ['www/js/pq-crypto.mjs'], + bundle: true, + format: 'esm', + target: ['es2020'], + outfile: 'www/pq-crypto.bundle.js', + sourcemap: true, + minify: false, // keep readable for demo + logLevel: 'info', + // Pure JS — no WASM files to handle + define: { + 'process.env.NODE_ENV': '"production"' + } + }); + + console.log('✅ PQ crypto bundle built: www/pq-crypto.bundle.js'); +} + +build().catch(err => { + console.error('❌ Build failed:', err); + process.exit(1); +}); diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index 2614512..d2fb40a 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,296 +1,8 @@ { - "name": "client-ndk", + "name": "client", "lockfileVersion": 3, "requires": true, "packages": { - "node_modules/@esbuild/aix-ppc64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", - "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", - "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", - "cpu": [ - "arm" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", - "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", - "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", - "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", - "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", - "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", - "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", - "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", - "cpu": [ - "arm" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", - "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", - "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", - "cpu": [ - "ia32" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", - "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", - "cpu": [ - "loong64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", - "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", - "cpu": [ - "mips64el" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", - "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", - "cpu": [ - "ppc64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", - "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", - "cpu": [ - "riscv64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", - "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", - "cpu": [ - "s390x" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, "node_modules/@esbuild/linux-x64": { "version": "0.27.2", "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", @@ -308,166 +20,96 @@ "node": ">=18" } }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", - "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@noble/ciphers": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.2.0.tgz", + "integrity": "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==", "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], "engines": { - "node": ">=18" + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", - "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@noble/curves": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz", + "integrity": "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==", "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], + "dependencies": { + "@noble/hashes": "2.2.0" + }, "engines": { - "node": ">=18" + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", - "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@noble/hashes": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz", + "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==", "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], "engines": { - "node": ">=18" + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", - "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@noble/post-quantum": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.6.1.tgz", + "integrity": "sha512-+pormrDZwjRw05U8ADK4JpHejo87+gBd+muRBB/ozztH5yhDLMDF4jHQWN3NQQAsu1zBNPWTG0ZwVI0CR29H0A==", "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], + "dependencies": { + "@noble/ciphers": "~2.2.0", + "@noble/curves": "~2.2.0", + "@noble/hashes": "~2.2.0" + }, "engines": { - "node": ">=18" + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", - "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@scure/base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.2.0.tgz", + "integrity": "sha512-b8XEupJibegiXV+tDUseI8oLQc8ei3d/4Jkb2RpbHh3MfE054ov3uIz2dhFkB3FI8iwYkEh0gGCApkrYggkPNg==", "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", - "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@scure/bip32": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.2.0.tgz", + "integrity": "sha512-zFr7t2F+a9+5tB7QbarF2HQNYrgjCNaoLAupZdKkrFMYMozJf5zqH2WJCQibMzm1qQ0QogrxVGO3qXfQDYMaQg==", "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" + "dependencies": { + "@noble/curves": "2.2.0", + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", - "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", - "cpu": [ - "arm64" - ], - "dev": true, - "ideallyInert": true, + "node_modules/@scure/bip39": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.2.0.tgz", + "integrity": "sha512-T/Bj/YvYMNkIPq6EENO6/rcs2e7qTNuyoUXf0KBFDmp0ZDu0H2X4Lq6yC3i0c8PcWkov5EbW+yQZZbdMmk154A==", "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", - "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", - "cpu": [ - "ia32" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.27.2", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", - "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", - "cpu": [ - "x64" - ], - "dev": true, - "ideallyInert": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" + "dependencies": { + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" } }, "node_modules/esbuild": { diff --git a/node_modules/@noble/ciphers/LICENSE b/node_modules/@noble/ciphers/LICENSE new file mode 100644 index 0000000..5a53d5f --- /dev/null +++ b/node_modules/@noble/ciphers/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/ciphers/README.md b/node_modules/@noble/ciphers/README.md new file mode 100644 index 0000000..aea8e6b --- /dev/null +++ b/node_modules/@noble/ciphers/README.md @@ -0,0 +1,607 @@ +# noble-ciphers + +Audited & minimal JS implementation of Salsa20, ChaCha and AES. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🏎 Fast: hand-optimized for caveats of JS engines +- 🔍 Reliable: property-based / cross-library / wycheproof tests ensure correctness +- 💼 AES: ECB, CBC, CTR, CFB, GCM, SIV (nonce misuse-resistant), AESKW, AESKWP +- 💃 Salsa20, ChaCha, XSalsa20, XChaCha, ChaCha8, ChaCha12, Poly1305 +- 🥈 Two AES implementations: pure JS or friendly WebCrypto wrapper +- 🪶 11KB (gzipped) for everything, 3KB for ChaCha-only build + +Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative. Check out [Upgrading](#upgrading) for information about upgrading from previous versions. +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-ciphers/discussions) for questions and support. + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out the homepage](https://paulmillr.com/noble/) + for reading resources, documentation, and apps built with noble + +## Usage + +> `npm install @noble/ciphers` + +> `deno add jsr:@noble/ciphers` + +We support all major platforms and runtimes. +For React Native, you may need a +[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file +[noble-ciphers.js](https://github.com/paulmillr/noble-ciphers/releases) is also available. + +```ts +// import * from '@noble/ciphers'; // Error: use sub-imports, to ensure small app size +import { gcm, gcmsiv } from '@noble/ciphers/aes.js'; +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js'; +import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; + +// Unauthenticated encryption: make sure to use HMAC or similar +import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js'; +import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js'; +import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js'; +import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; // KW +import { bytesToHex, hexToBytes, managedNonce, randomBytes } from '@noble/ciphers/utils.js'; +``` + +- [Examples](#examples) + - [XChaCha20-Poly1305 encryption](#xchacha20-poly1305-encryption) + - [AES-256-GCM encryption](#aes-256-gcm-encryption) + - [managedNonce: automatic nonce handling](#managednonce-automatic-nonce-handling) + - [AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw](#aes-gcm-siv-ctr-cfb-cbc-ecb-aeskw) + - [AES: friendly WebCrypto wrapper](#aes-friendly-webcrypto-wrapper) + - [Reuse array for input and output](#reuse-array-for-input-and-output) + - [Use password for encryption](#use-password-for-encryption) +- [Internals](#internals) + - [Picking a cipher](#picking-a-cipher) + - [How to encrypt properly](#how-to-encrypt-properly) + - [Nonces](#nonces) + - [Encryption limits](#encryption-limits) + - [AES block modes](#aes-block-modes) + - [Implemented primitives](#implemented-primitives) +- [Security](#security) +- [Speed](#speed) +- [Upgrading](#upgrading) +- [Contributing & testing](#contributing--testing) +- [License](#license) + +## Examples + +> [!NOTE] +> Use different nonce every time `encrypt()` is done. + +#### XChaCha20-Poly1305 encryption + +```js +import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; +const key = randomBytes(32); // random key +// const key = new Uint8Array([ // existing key +// 169, 88, 160, 139, 168, 29, 147, 196, 14, 88, 237, 76, 243, 177, 109, 140, +// 195, 140, 80, 10, 216, 134, 215, 71, 191, 48, 20, 104, 189, 37, 38, 55, +// ]); +// import { hexToBytes } from '@noble/ciphers/utils.js'; // hex key +// const key = hexToBytes('4b7f89bac90a1086fef73f5da2cbe93b2fae9dfbf7678ae1f3e75fd118ddf999'); +const nonce = randomBytes(24); +const chacha = xchacha20poly1305(key, nonce); +const data = new TextEncoder().encode('hello noble'); +const ciphertext = chacha.encrypt(data); +const data_ = chacha.decrypt(ciphertext); // new TextDecoder().decode(data_) === data +``` + +#### AES-256-GCM encryption + +```js +import { gcm } from '@noble/ciphers/aes.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; +const key = randomBytes(32); +const nonce = randomBytes(24); +const data = new TextEncoder().encode('hello noble'); +const aes = gcm(key, nonce); +const ciphertext = aes.encrypt(data); +const data_ = aes.decrypt(ciphertext); // new TextDecoder().decode(data_) === data +``` + +#### managedNonce: automatic nonce handling + +We provide API that manages nonce internally instead of exposing them to library's user. + +For `encrypt`: a `nonceBytes`-length buffer is fetched from CSPRNG and prenended to encrypted ciphertext. + +For `decrypt`: first `nonceBytes` of ciphertext are treated as nonce. + +> [!NOTE] +> AES-GCM & ChaCha (NOT XChaCha) [limit amount of messages](#encryption-limits) +> encryptable under the same key. + +```js +import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; +import { hexToBytes, managedNonce } from '@noble/ciphers/utils.js'; +const key = hexToBytes('fa686bfdffd3758f6377abbc23bf3d9bdc1a0dda4a6e7f8dbdd579fa1ff6d7e1'); +const chacha = managedNonce(xchacha20poly1305)(key); // manages nonces for you +const data = new TextEncoder().encode('hello noble'); +const ciphertext = chacha.encrypt(data); +const data_ = chacha.decrypt(ciphertext); +``` + +#### AES: gcm, siv, ctr, cfb, cbc, ecb, aeskw + +```js +import { gcm, gcmsiv, aessiv, ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; +const plaintext = new Uint8Array(32).fill(16); +for (let cipher of [gcm, gcmsiv, aessiv]) { + const key = randomBytes(32); // 24 for AES-192, 16 for AES-128 + const nonce = randomBytes(12); + const ciphertext_ = cipher(key, nonce).encrypt(plaintext); + const plaintext_ = cipher(key, nonce).decrypt(ciphertext_); +} +for (const cipher of [ctr, cbc, cfb]) { + const key = randomBytes(32); // 24 for AES-192, 16 for AES-128 + const nonce = randomBytes(16); + const ciphertext_ = cipher(key, nonce).encrypt(plaintext); + const plaintext_ = cipher(key, nonce).decrypt(ciphertext_); +} +for (const cipher of [ecb]) { + const key = randomBytes(32); // 24 for AES-192, 16 for AES-128 + const ciphertext_ = cipher(key).encrypt(plaintext); + const plaintext_ = cipher(key).decrypt(ciphertext_); +} + +// AESKW, AESKWP +import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; +import { hexToBytes } from '@noble/ciphers/utils.js'; + +const kek = hexToBytes('000102030405060708090A0B0C0D0E0F'); +const keyData = hexToBytes('00112233445566778899AABBCCDDEEFF'); +const ciphertext = aeskw(kek).encrypt(keyData); +``` + +#### AES: friendly WebCrypto wrapper + +Noble implements AES. Sometimes people want to use built-in `crypto.subtle` instead. However, it has terrible API. We simplify access to built-ins. + +> [!NOTE] +> Webcrypto methods are always async. + +```js +import { gcm, ctr, cbc } from '@noble/ciphers/webcrypto.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; +const plaintext = new Uint8Array(32).fill(16); +const key = randomBytes(32); +for (const cipher of [gcm]) { + const nonce = randomBytes(12); + const ciphertext_ = await cipher(key, nonce).encrypt(plaintext); + const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_); +} +for (const cipher of [ctr, cbc]) { + const nonce = randomBytes(16); + const ciphertext_ = await cipher(key, nonce).encrypt(plaintext); + const plaintext_ = await cipher(key, nonce).decrypt(ciphertext_); +} +``` + +#### Reuse array for input and output + +To avoid additional allocations, Uint8Array can be reused +between encryption and decryption calls. + +> [!NOTE] +> Some ciphers don't support unaligned (`byteOffset % 4 !== 0`) Uint8Array as +> destination. It can decrease performance, making the optimization pointless. + +```js +import { chacha20poly1305 } from '@noble/ciphers/chacha.js'; +import { randomBytes } from '@noble/ciphers/utils.js'; + +const key = randomBytes(32); +const nonce = randomBytes(12); +const chacha = chacha20poly1305(key, nonce); + +const input = new TextEncoder().encode('hello noble'); // length == 12 +const inputLength = input.length; +const tagLength = 16; + +const buf = new Uint8Array(inputLength + tagLength); +const start = buf.subarray(0, inputLength); +start.set(input); // copy input to buf + +chacha.encrypt(start, buf); // encrypt into `buf` +chacha.decrypt(buf, start); // decrypt into `start` +``` + +xsalsa20poly1305 also supports this, but requires 32 additional bytes for encryption / decryption, +due to its inner workings. + +#### Randomness generation + +We provide userspace CSPRNG (cryptographically secure pseudorandom number generator). +It's best to limit their usage to non-production, non-critical cases: for example, test-only usage. +ChaCha-based CSPRNG does not have a specification as per 2025, which makes it less secure. + +```js +import { randomBytes } from '@noble/ciphers/utils.js'; +import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; +import { rngChacha8, rngChacha20 } from '@noble/ciphers/chacha.js'; + +// 1. Best: WebCrypto +const rnd1 = randomBytes(32); +// 2. AES-CTR DRBG +const seed2 = randomBytes(48); +const rnd2 = rngAesCtrDrbg256(seed2).randomBytes(1024); +// 3. ChaCha8 CSPRNG +const seed3 = randomBytes(32); +const rnd3 = rngChacha8(seed3).randomBytes(1024); +``` + +#### Use password for encryption + +It is not safe to convert password into Uint8Array. +Instead, KDF stretching function like PBKDF2 / Scrypt / Argon2id +should be applied to convert password to AES key. +Make sure to use salt (app-specific secret) in addition to password. + +> `npm install @noble/hashes` + +```js +import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; +import { managedNonce } from '@noble/ciphers/utils.js'; +import { scrypt } from '@noble/hashes/scrypt.js'; + +// Convert password into 32-byte key using scrypt +const PASSWORD = 'correct-horse-battery-staple'; +const APP_SPECIFIC_SECRET = 'salt-12345678-secret'; +const SECURITY_LEVEL = 2 ** 20; // requires 1GB of RAM to calculate +// sync, but scryptAsync is also available +const key = scrypt(PASSWORD, APP_SPECIFIC_SECRET, { N: SECURITY_LEVEL, r: 8, p: 1, dkLen: 32 }); + +// Use random, managed nonce +const chacha = managedNonce(xchacha20poly1305)(key); + +const data = new TextEncoder().encode('hello noble'); +const ciphertext = chacha.encrypt(data); +const data_ = chacha.decrypt(ciphertext); +``` + +## Internals + +### Picking a cipher + +We suggest to use **XChaCha20-Poly1305** because it's very fast and allows random keys. +**AES-GCM-SIV** is also a good idea, because it provides resistance against nonce reuse. +**AES-GCM** is a good option when those two are not available. + +### How to encrypt properly + +- Use unpredictable key with enough entropy + - Random key must be using cryptographically secure random number generator (CSPRNG), not `Math.random` etc. + - Non-random key generated from KDF is fine + - Re-using key is fine, but be aware of rules for cryptographic key wear-out and [encryption limits](#encryption-limits) +- Use new nonce every time and [don't repeat it](#nonces) + - chacha and salsa20 are fine for sequential counters that _never_ repeat: `01, 02...` + - xchacha and xsalsa20 can use random nonces instead + - AES-GCM should use 12-byte nonces: smaller nonces are security risk +- Prefer authenticated encryption (AEAD) + - Good: chacha20poly1305, GCM, GCM-SIV, ChaCha+HMAC, CTR+HMAC, CBC+HMAC + - Bad: chacha20, raw CTR, raw CBC + - Flipping bits or ciphertext substitution won't be detected in unauthenticated ciphers + - Polynomial MACs are not perfect for every situation: + they lack Random Key Robustness: the MAC can be forged, and can't + be used in PAKE schemes. See + [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/). + To combat salamanders, `hash(key)` can be included in ciphertext, + however, this would violate ciphertext indistinguishability: + an attacker would know which key was used - so `HKDF(key, i)` + could be used instead. +- Don't re-use keys between different protocols + - For example, using ECDH key in AES can be bad + - Use hkdf or, at least, a hash function to create sub-key instead + +### Nonces + +Most ciphers need a key and a nonce (aka initialization vector / IV) to encrypt a data. +Repeating (key, nonce) pair with different plaintexts would allow an attacker to decrypt it. + + ciphertext_a = encrypt(plaintext_a, key, nonce) + ciphertext_b = encrypt(plaintext_b, key, nonce) + stream_diff = xor(ciphertext_a, ciphertext_b) # Break encryption + +One way of not repeating nonces is using counters: + + for i in 0..: + ciphertext[i] = encrypt(plaintexts[i], key, i) + +Another is generating random nonce every time: + + for i in 0..: + rand_nonces[i] = random() + ciphertext[i] = encrypt(plaintexts[i], key, rand_nonces[i]) + +- Counters are OK, but it's not always possible to store current counter value: + e.g. in decentralized, unsyncable systems. +- Randomness is OK, but there's a catch: + ChaCha20 and AES-GCM use 96-bit / 12-byte nonces, which implies higher chance of collision. + In the example above, `random()` can collide and produce repeating nonce. + Chance is even higher for 64-bit nonces, which GCM allows - don't use them. +- To safely use random nonces, utilize XSalsa20 or XChaCha: + they increased nonce length to 192-bit, minimizing a chance of collision. + AES-SIV is also fine. In situations where you can't use eXtended-nonce + algorithms, key rotation is advised. hkdf would work great for this case. + +### Encryption limits + +A "protected message" would mean a probability of `2**-50` that a passive attacker +successfully distinguishes the ciphertext outputs of the AEAD scheme from the outputs +of a random function. + +- Max message size: + - AES-GCM: ~68GB, `2**36-256` + - Salsa, ChaCha, XSalsa, XChaCha: ~256GB, `2**38-64` +- Max amount of protected messages, under same key: + - AES-GCM: `2**32.5` + - Salsa, ChaCha: `2**46`, but only integrity (MAC) is affected, not confidentiality (encryption) + - XSalsa, XChaCha: `2**72` +- Max amount of protected messages, across all keys: + - AES-GCM: `2**69/B` where B is max blocks encrypted by a key. Meaning + `2**59` for 1KB, `2**49` for 1MB, `2**39` for 1GB + - Salsa, ChaCha, XSalsa, XChaCha: `2**100` +- Max amount of protected messages, under same key, using **random nonce**: + - Relevant for 12-byte nonces with `managedNonce`: AES-GCM, ChaCha + - `2**23` (8M) messages for `2**-50` chance, `2**32.5` (4B) for `2**-32.5` chance + +Check out [draft-irtf-cfrg-aead-limits](https://datatracker.ietf.org/doc/draft-irtf-cfrg-aead-limits/) for details. + +### Implemented primitives + +- Salsa20 stream cipher, released in 2005. + Salsa's goal was to implement AES replacement that does not rely on S-Boxes, + which are hard to implement in a constant-time manner. + Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones. + - [XSalsa20](https://cr.yp.to/snuffle/xsalsa-20110204.pdf), extended-nonce + variant was released in 2008. It switched nonces from 96-bit to 192-bit, + and became safe to be picked at random. + - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305. + We provide the alias and corresponding seal / open methods. + "crypto_box" and "sealedbox" are available in package [noble-sodium](https://github.com/serenity-kit/noble-sodium). + - Check out [PDF](https://cr.yp.to/snuffle/salsafamily-20071225.pdf) + and [website](https://cr.yp.to/snuffle.html). +- ChaCha20 stream cipher, released in 2008. Developed after Salsa20, + ChaCha aims to increase diffusion per round. + - [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha) + extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with + randomly-generated nonces. + - Check out + [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439), + [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and + [website](https://cr.yp.to/chacha.html). +- AES is a variant of Rijndael block cipher, standardized by NIST in 2001. + We provide the fastest available pure JS implementation. + - We support AES-128, AES-192 and AES-256: the mode is selected dynamically, + based on key length (16, 24, 32). + - AES-GCM-SIV nonce-misuse-resistant mode is also provided. Our implementation of SIV + has the same speed as GCM: there is no performance hit. + The mode is described in [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452). + - There is a separate AES-SIV mode, described in [RFC 5297](https://www.rfc-editor.org/rfc/rfc5297) + - We also have AESKW and AESKWP from + [RFC 3394](https://www.rfc-editor.org/rfc/rfc3394) & [RFC 5649](https://www.rfc-editor.org/rfc/rfc5649) + - Format-preserving encryption algorithm (FPE-FF1) specified in + [NIST SP 800-38G](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf). + - Check out [AES block modes](#aes-block-modes), + [FIPS 197](https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf) and + [original proposal](https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf). +- Polynomial-evaluation MACs are available: Poly1305, AES-GCM's GHash and AES-SIV's Polyval. + - Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf), + [website](https://cr.yp.to/mac.html)) + is a fast and parallel secret-key message-authentication code suitable for + a wide variety of applications. It was standardized in + [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3. + - Ghash is used in AES-GCM: see NIST SP 800-38G + - Polyval is used in AES-GCM-SIV: see [RFC 8452](https://www.rfc-editor.org/rfc/rfc8452) + +##### AES block modes + +For non-deterministic (not ECB) schemes, initialization vector (IV) is mixed to block/key; +and each new round either depends on previous block's key, or on some counter. + +- **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield identical ciphertexts. Not secure due to pattern leakage. due to pattern leakage. + See [AES Penguin](https://words.filippo.io/the-ecb-penguin/) +- **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the previous block of ciphertext + before encryption. Hard to use: requires proper padding and an IV. Unauthenticated: needs MAC. +- **CTR** (Counter Mode): Turns a block cipher into a stream cipher using a counter and IV (nonce). + Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC. +- **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. Not perfect: + a) conservative key wear-out is `2**32` (4B) msgs. + b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance. + c) MAC can be forged: see Poly1305 documentation. +- **SIV** (Synthetic IV): GCM with nonce-misuse resistance; repeating nonces reveal only the fact plaintexts + are identical. Also suffers from GCM issues: key wear-out limits & MAC forging. +- **XTS**: Designed for disk encryption. + Similar to ECB (deterministic), but has `[i][j]` tweak arguments corresponding to + sector i and 16-byte block (part of sector) j. Lacks MAC. + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/2.2.0..main) +- at version 1.0.0, in Sep 2024, independently, by [cure53](https://cure53.de) + - PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-ciphers/compare/1.0.0..main) + - Scope: everything + - The audit has been funded by [OpenSats](https://opensats.org) + +It is tested against property-based, cross-library and Wycheproof vectors, +and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time" +extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. + +The library uses T-tables for AES, which +[leak access timings](https://cr.yp.to/antiforgery/cachetiming-20050414.pdf). +This is also done in [OpenSSL](https://github.com/openssl/openssl/blob/2f33265039cdbd0e4589c80970e02e208f3f94d2/crypto/aes/aes_core.c#L706) and +[Go stdlib](https://cs.opensource.google/go/go/+/refs/tags/go1.22.6:src/crypto/aes/const.go;l=90) for performance reasons. +The analysis was mentioned in [hal-04652991](https://hal.science/hal-04652991/document). + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there are 0 dependencies; and a few dev dependencies: + +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +### Randomness + +We rely on the built-in +[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), +which is considered a cryptographically secure PRNG. + +Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy. + +### Quantum computers + +Cryptographically relevant quantum computer, if built, will allow to +utilize Grover's algorithm to break ciphers in 2^n/2 operations, instead of 2^n. + +This means AES128 should be replaced with AES256. Salsa and ChaCha are already safe. + +Australian ASD prohibits AES128 [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography). + +## Speed + +```sh +npm run bench +``` + +Benchmarks measured on Apple M4. +If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble). + +``` +64B +xsalsa20poly1305 x 735,835 ops/sec @ 1μs/op +chacha20poly1305 x 581,395 ops/sec @ 1μs/op +xchacha20poly1305 x 468,384 ops/sec @ 2μs/op +aes-256-gcm x 201,126 ops/sec @ 4μs/op +aes-256-gcm-siv x 162,284 ops/sec @ 6μs/op +# Unauthenticated encryption +salsa20 x 1,655,629 ops/sec @ 604ns/op +xsalsa20 x 1,400,560 ops/sec @ 714ns/op +chacha20 x 1,996,007 ops/sec @ 501ns/op +xchacha20 x 1,404,494 ops/sec @ 712ns/op +chacha8 x 2,145,922 ops/sec @ 466ns/op +chacha12 x 2,036,659 ops/sec @ 491ns/op +aes-ecb-256 x 1,019,367 ops/sec @ 981ns/op +aes-cbc-256 x 931,966 ops/sec @ 1μs/op +aes-ctr-256 x 954,198 ops/sec @ 1μs/op + +1MB +xsalsa20poly1305 x 334 ops/sec @ 2ms/op +chacha20poly1305 x 333 ops/sec @ 2ms/op +xchacha20poly1305 x 334 ops/sec @ 2ms/op +aes-256-gcm x 94 ops/sec @ 10ms/op +aes-256-gcm-siv x 90 ops/sec @ 11ms/op +# Unauthenticated encryption +salsa20 x 831 ops/sec @ 1ms/op +xsalsa20 x 830 ops/sec @ 1ms/op +chacha20 x 804 ops/sec @ 1ms/op +xchacha20 x 797 ops/sec @ 1ms/op +chacha8 x 1,495 ops/sec @ 668μs/op +chacha12 x 1,148 ops/sec @ 871μs/op +aes-ecb-256 x 289 ops/sec @ 3ms/op +aes-cbc-256 x 114 ops/sec @ 8ms/op +aes-ctr-256 x 127 ops/sec @ 7ms/op +# Wrapper over built-in webcrypto +webcrypto ctr-256 x 6,508 ops/sec @ 153μs/op +webcrypto cbc-256 x 1,820 ops/sec @ 549μs/op +webcrypto gcm-256 x 5,106 ops/sec @ 195μs/op +``` + +Compare to other implementations: + +``` +xsalsa20poly1305 (encrypt, 1MB) +├─tweetnacl x 196 mb/sec +├─awasm-noble_threads x 2,318 mb/sec +├─awasm-noble_no_threads x 1,196 mb/sec +└─noble x 305 mb/sec + +aes-ctr-256 (encrypt, 1MB) +├─stablelib x 123 mb/sec +├─aesjs x 42 mb/sec +├─awasm-noble_thread x 2,105 mb/sec +├─awasm-noble_no_threads x 272 mb/sec +├─noble_webcrypto x 5,965 mb/sec +└─noble x 124 mb/sec +``` + +## Upgrading + +Supported node.js versions: + +- v2: v20.19+ (ESM-only) +- v1: v14.21+ (ESM & CJS) + +Changelog of v2, when upgrading from ciphers v1: + +- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+ +- `.js` extension must be used for all modules + - Old: `@noble/ciphers/aes` + - New: `@noble/ciphers/aes.js` + - This simplifies working in browsers natively without transpilers +- webcrypto: move `randomBytes` and `managedNonce` to `utils.js` +- ghash, poly1305, polyval: only allow Uint8Array as hash inputs, prohibit `string` +- utils: new abytes; remove ahash, toBytes +- Remove modules `_assert` (use `utils`), `_micro` and `crypto` (use `webcrypto`) +- Bump TS compilation target from es2020 to es2022 +- Massively improve error messages, make them more descriptive + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run bench` will run benchmarks +- `npm run build:release` will build single file + +See [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +## License + +The MIT License (MIT) + +Copyright (c) 2023 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) +Copyright (c) 2016 Thomas Pornin + +See LICENSE file. diff --git a/node_modules/@noble/ciphers/_arx.d.ts b/node_modules/@noble/ciphers/_arx.d.ts new file mode 100644 index 0000000..e8c7931 --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.d.ts @@ -0,0 +1,145 @@ +/** + * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. + +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | cnt(1) | nonce(3) + chacha20orig: s(4) | k(8) | cnt(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce). +Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}. +Current noble policy is strict non-wrap for the shared 32-bit counter path: +exported ARX ciphers reject initial `0xffffffff` and stop before any implicit +wrap back to zero. +See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction. + + * @module + */ +import { type PRG, type TArg, type TRet, type XorStream } from './utils.ts'; +/** + * Rotates a 32-bit word left. + * @param a - Input word. + * @param b - Rotation count in bits. + * @returns Rotated 32-bit word. + * @example + * Moves the top byte of `0x12345678` into the low byte position. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export declare function rotl(a: number, b: number): number; +/** + * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency. + * @param sigma - Sigma constants for the selected cipher layout. + * @param key - Expanded key words. + * @param nonce - Nonce and counter words prepared for the round function. + * @param output - Output block written in place. + * @param counter - Block counter value. + * @param rounds - Optional round count override. + */ +export type CipherCoreFn = (sigma: TArg, key: TArg, nonce: TArg, output: TArg, counter: number, rounds?: number) => void; +/** + * Nonce-extension function used by XChaCha and XSalsa. + * @param sigma - Sigma constants for the selected cipher layout. + * @param key - Expanded key words. + * @param input - Input nonce words used for subkey derivation. + * @param output - Output buffer written with the derived nonce words. + */ +export type ExtendNonceFn = (sigma: TArg, key: TArg, input: TArg, output: TArg) => void; +/** ARX cipher options. + * * `allowShortKeys` for 16-byte keys + * * `counterLength` in bytes + * * `counterRight`: right: `nonce|counter`; left: `counter|nonce` + * */ +export type CipherOpts = { + /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */ + allowShortKeys?: boolean; + /** Optional nonce-expansion hook used by extended-nonce variants. */ + extendNonceFn?: ExtendNonceFn; + /** Counter length in bytes inside the nonce/counter layout. */ + counterLength?: number; + /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */ + counterRight?: boolean; + /** Number of core rounds to execute. */ + rounds?: number; +}; +/** + * Creates an ARX stream cipher from a 32-bit core permutation. + * Used internally to build the exported Salsa and ChaCha stream ciphers. + * @param core - Core function that fills one keystream block. + * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}. + * @returns Stream cipher function over byte arrays. + * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error} + */ +export declare function createCipher(core: TArg, opts: TArg): TRet; +/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */ +export declare class _XorStreamPRG implements PRG { + readonly blockLen: number; + readonly keyLen: number; + readonly nonceLen: number; + private state; + private buf; + private key; + private nonce; + private pos; + private ctr; + private cipher; + constructor(cipher: TArg, blockLen: number, keyLen: number, nonceLen: number, seed: TArg); + private reseed; + addEntropy(seed: TArg): void; + randomBytes(len: number): TRet; + clone(): _XorStreamPRG; + clean(): void; +} +/** + * PRG constructor backed by an ARX stream cipher. + * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32 + * random bytes are mixed in by default: larger states keep a zero tail, while smaller states + * wrap those bytes through `reseed()`'s XOR schedule. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + */ +export type XorPRG = (seed?: TArg) => TRet<_XorStreamPRG>; +/** + * Creates a PRG constructor from a stream cipher. + * @param cipher - Stream cipher used to fill output blocks. + * @param blockLen - Keystream block length in bytes. + * @param keyLen - Internal key length in bytes. + * @param nonceLen - Internal nonce length in bytes. + * @returns PRG factory for seeded concrete `_XorStreamPRG` instances. + * @example + * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance. + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { createPRG } from '@noble/ciphers/_arx.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const init = createPRG(xchacha20, 64, 32, 24); + * const prg = init(seed); + * prg.randomBytes(8); + * ``` + */ +export declare const createPRG: (cipher: TArg, blockLen: number, keyLen: number, nonceLen: number) => TRet; +//# sourceMappingURL=_arx.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.d.ts.map b/node_modules/@noble/ciphers/_arx.d.ts.map new file mode 100644 index 0000000..2d385c0 --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_arx.d.ts","sourceRoot":"","sources":["src/_arx.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,OAAO,EACL,KAAK,GAAG,EACR,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EAaf,MAAM,YAAY,CAAC;AAcpB;;;;;;;;;;GAUG;AACH,wBAAgB,IAAI,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjD;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,EACzB,OAAO,EAAE,MAAM,EACf,MAAM,CAAC,EAAE,MAAM,KACZ,IAAI,CAAC;AAEV;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,CAC1B,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EACtB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,MAAM,EAAE,IAAI,CAAC,WAAW,CAAC,KACtB,IAAI,CAAC;AAEV;;;;KAI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Md;AAED;;;;;;GAMG;AACH,MAAM,MAAM,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,aAAa,CAAC,CAAC;AAEtE;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,GACpB,QAAQ,IAAI,CAAC,SAAS,CAAC,EACvB,UAAU,MAAM,EAChB,QAAQ,MAAM,EACd,UAAU,MAAM,KACf,IAAI,CAAC,MAAM,CASb,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.js b/node_modules/@noble/ciphers/_arx.js new file mode 100644 index 0000000..e182c7b --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.js @@ -0,0 +1,369 @@ +/** + * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. + +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | cnt(1) | nonce(3) + chacha20orig: s(4) | k(8) | cnt(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce). +Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}. +Current noble policy is strict non-wrap for the shared 32-bit counter path: +exported ARX ciphers reject initial `0xffffffff` and stop before any implicit +wrap back to zero. +See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction. + + * @module + */ +import { abool, abytes, anumber, checkOpts, clean, copyBytes, getOutput, isAligned32, isLE, randomBytes, swap32IfBE, u32, } from "./utils.js"; +// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants. +// Non-ASCII input would not match UTF-8 `TextEncoder` output. +const encodeStr = (str) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0)); +// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly. +// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path. +// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is +// kept for legacy allowShortKeys Salsa/ChaCha variants. +const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))(); +// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as +// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`. +const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))(); +/** + * Rotates a 32-bit word left. + * @param a - Input word. + * @param b - Rotation count in bits. + * @returns Rotated 32-bit word. + * @example + * Moves the top byte of `0x12345678` into the low byte position. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export function rotl(a, b) { + return (a << b) | (a >>> (32 - b)); +} +// Salsa and Chacha block length is always 512-bit +const BLOCK_LEN = 64; +// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words. +const BLOCK_LEN32 = 16; +// Counter policy for the shared public `counter` argument: +// - RFC/IETF ChaCha20 uses a 32-bit counter. +// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit +// counter state and carry into the next word. +// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium +// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max +// boundary instead of carrying. +// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from +// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset. +// Noble intentionally throws instead of silently picking one wrap model for users. In the default +// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically +// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement +// whatever wider carry / wrap policy they need on top. +const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); +const U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); +function runCipher(core, sigma, key, nonce, data, output, counter, rounds) { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + // Make sure that buffers aligned to 4 bytes + const isAligned = isLE && isAligned32(data) && isAligned32(output); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output) : U32_EMPTY; + // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and + // truncating the final partial block instead of materializing the whole keystream. + if (!isLE) { + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order. + swap32IfBE(b32); + if (counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } + return; + } + for (let pos = 0; pos < len; counter++) { + core(sigma, key, nonce, b32, counter, rounds); + // See MAX_COUNTER policy note above: never silently wrap the shared public counter. + if (counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + // aligned to 4 bytes + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) + throw new Error('arx: invalid block position'); + for (let j = 0, posj; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} +/** + * Creates an ARX stream cipher from a 32-bit core permutation. + * Used internally to build the exported Salsa and ChaCha stream ciphers. + * @param core - Core function that fills one keystream block. + * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}. + * @returns Stream cipher function over byte arrays. + * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error} + */ +export function createCipher(core, opts) { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts({ allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, opts); + if (typeof core !== 'function') + throw new Error('core must be a function'); + anumber(counterLength); + anumber(rounds); + abool(counterRight); + abool(allowShortKeys); + return (key, nonce, data, output, counter = 0) => { + abytes(key, undefined, 'key'); + abytes(nonce, undefined, 'nonce'); + abytes(data, undefined, 'data'); + const len = data.length; + // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs + // must match the logical result length exactly instead of returning an oversized workspace. + output = getOutput(len, output, false); + anumber(counter); + // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap. + if (counter < 0 || counter >= MAX_COUNTER) + throw new Error('arx: counter overflow'); + const toClean = []; + // Key & sigma + // key=16 -> sigma16, k=key|key + // key=32 -> sigma32, k=key + let l = key.length; + let k; + let sigma; + if (l === 32) { + // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and + // final clean(...) all mutate or wipe the temporary buffer in place. + toClean.push((k = copyBytes(key))); + sigma = sigma32_32; + } + else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } + else { + abytes(key, 32, 'arx key'); + throw new Error('invalid key size'); + // throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`); + } + // Nonce + // salsa20: 8 (8-byte counter) + // chacha20orig: 8 (8-byte counter) + // chacha20: 12 (4-byte counter) + // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce) + // xchacha20: 24 (16 -> hchacha, 8 -> old nonce) + // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later + // swap32IfBE(...) never mutates caller nonce bytes in place. + if (!isLE || !isAligned32(nonce)) + toClean.push((nonce = copyBytes(nonce))); + let k32 = u32(k); + // hsalsa & hchacha: handle extended nonce + if (extendNonceFn) { + if (nonce.length !== 24) + throw new Error(`arx: extended nonce must be 24 bytes`); + const n16 = nonce.subarray(0, 16); + if (isLE) + extendNonceFn(sigma, k32, u32(n16), k32); + else { + const sigmaRaw = swap32IfBE(Uint32Array.from(sigma)); + extendNonceFn(sigmaRaw, k32, u32(n16), k32); + clean(sigmaRaw); + swap32IfBE(k32); + } + nonce = nonce.subarray(16); + } + else if (!isLE) + swap32IfBE(k32); + // Handle nonce counter + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero + // counter bytes, while Salsa/XSalsa append them after the nonce words. + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = swap32IfBE(u32(nonce)); + // Ensure temporary key/nonce copies are wiped even if the remaining + // runtime guard in runCipher(...) throws on counter overflow. + try { + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + return output; + } + finally { + clean(...toClean); + } + }; +} +/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */ +export class _XorStreamPRG { + blockLen; + keyLen; + nonceLen; + state; + buf; + key; + nonce; + pos; + ctr; + cipher; + constructor(cipher, blockLen, keyLen, nonceLen, seed) { + this.cipher = cipher; + this.blockLen = blockLen; + this.keyLen = keyLen; + this.nonceLen = nonceLen; + this.state = new Uint8Array(this.keyLen + this.nonceLen); + this.reseed(seed); + this.ctr = 0; + this.pos = this.blockLen; + this.buf = new Uint8Array(this.blockLen); + // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher + // inputs in place through these subarray views. + this.key = this.state.subarray(0, this.keyLen); + this.nonce = this.state.subarray(this.keyLen); + } + reseed(seed) { + abytes(seed); + if (!seed || seed.length === 0) + throw new Error('entropy required'); + // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the + // keystream so buffered leftovers from the previous state are never reused. + for (let i = 0; i < seed.length; i++) + this.state[i % this.state.length] ^= seed[i]; + this.ctr = 0; + this.pos = this.blockLen; + } + addEntropy(seed) { + // Reject empty entropy before re-keying, otherwise a throwing call would still advance state. + abytes(seed); + if (seed.length === 0) + throw new Error('entropy required'); + // Re-key from the current stream first, then mix external entropy into the fresh key||nonce + // state through reseed() so stale buffered bytes are discarded. + this.state.set(this.randomBytes(this.state.length)); + this.reseed(seed); + } + randomBytes(len) { + anumber(len); + if (len === 0) + return new Uint8Array(0); + const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0; + const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen); + // Preflight overflow so failed reads don't partially consume keystream + // and leave the PRG repeating blocks. + if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) + throw new Error('arx: counter overflow'); + const out = new Uint8Array(len); + let outPos = 0; + // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream + // ciphers then emit raw keystream bytes directly into those buffers. + // Serve buffered leftovers first so split reads stay identical to one larger read. + if (this.pos < this.blockLen) { + const take = Math.min(len, this.blockLen - this.pos); + out.set(this.buf.subarray(this.pos, this.pos + take), 0); + this.pos += take; + outPos += take; + if (outPos === len) + return out; // fast path + } + // Full blocks directly to out + const full = Math.floor((len - outPos) / this.blockLen); + if (full > 0) { + const blockBytes = full * this.blockLen; + const b = out.subarray(outPos, outPos + blockBytes); + this.cipher(this.key, this.nonce, b, b, this.ctr); + this.ctr += full; + outPos += blockBytes; + } + // Save leftovers + const left = len - outPos; + if (left > 0) { + this.buf.fill(0); + // NOTE: cipher will handle overflow + this.cipher(this.key, this.nonce, this.buf, this.buf, this.ctr++); + out.set(this.buf.subarray(0, left), outPos); + this.pos = left; + } + return out; + } + // Clone seeds the new instance from this stream, so the source PRG advances too. + clone() { + return new _XorStreamPRG(this.cipher, this.blockLen, this.keyLen, this.nonceLen, this.randomBytes(this.state.length)); + } + // Zeroes the current state and leftover buffer, but does not make the instance unusable: + // Later reads first drain zeros from the cleared buffer and then continue + // from zero key||nonce state. + clean() { + this.pos = 0; + this.ctr = 0; + this.buf.fill(0); + this.state.fill(0); + } +} +/** + * Creates a PRG constructor from a stream cipher. + * @param cipher - Stream cipher used to fill output blocks. + * @param blockLen - Keystream block length in bytes. + * @param keyLen - Internal key length in bytes. + * @param nonceLen - Internal nonce length in bytes. + * @returns PRG factory for seeded concrete `_XorStreamPRG` instances. + * @example + * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance. + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { createPRG } from '@noble/ciphers/_arx.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const init = createPRG(xchacha20, 64, 32, 24); + * const prg = init(seed); + * prg.randomBytes(8); + * ``` + */ +export const createPRG = (cipher, blockLen, keyLen, nonceLen) => { + return ((seed = randomBytes(32)) => new _XorStreamPRG(cipher, blockLen, keyLen, nonceLen, seed)); +}; +//# sourceMappingURL=_arx.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_arx.js.map b/node_modules/@noble/ciphers/_arx.js.map new file mode 100644 index 0000000..ac5be2d --- /dev/null +++ b/node_modules/@noble/ciphers/_arx.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_arx.js","source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,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,QAAQ,EACb,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CACpC,CAAC;IACJ,CAAC;IACD,yFAAyF;IACzF,0EAA0E;IAC1E,8BAA8B;IAC9B,KAAK;QACH,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC;QACb,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACjB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACrB,CAAC;CACF;AAWD;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CACvB,MAAuB,EACvB,QAAgB,EAChB,MAAc,EACd,QAAgB,EACF,EAAE;IAChB,OAAO,CAAC,CAAC,OAAyB,WAAW,CAAC,EAAE,CAAC,EAAuB,EAAE,CACxE,IAAI,aAAa,CACf,MAAM,EACN,QAAQ,EACR,MAAM,EACN,QAAQ,EACR,IAAI,CACkB,CAAiB,CAAC;AAC9C,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.d.ts b/node_modules/@noble/ciphers/_poly1305.d.ts new file mode 100644 index 0000000..479a890 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.d.ts @@ -0,0 +1,73 @@ +/** + * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki}) + * is a fast and parallel secret-key message-authentication code suitable for + * a wide variety of applications. It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3. + * + * Polynomial MACs are not perfect for every situation: + * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes. + * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}. + * To combat invisible salamanders, `hash(key)` can be included in ciphertext, + * however, this would violate ciphertext indistinguishability: + * an attacker would know which key was used - so `HKDF(key, i)` + * could be used instead. + * + * Check out the {@link https://cr.yp.to/mac.html | original website}. + * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}. + * @module + */ +import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts'; +/** + * Incremental Poly1305 MAC state. + * Prefer `poly1305()` for one-shot use. + * @param key - 32-byte Poly1305 one-time key. + * @example + * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key. + * + * ```ts + * import { Poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const mac = new Poly1305(key); + * mac.update(new Uint8Array([1, 2, 3])); + * mac.digest(); + * ``` + */ +export declare class Poly1305 implements IHash2 { + readonly blockLen = 16; + readonly outputLen = 16; + private buffer; + private r; + private h; + private pad; + private pos; + protected finished: boolean; + protected destroyed: boolean; + constructor(key: TArg); + private process; + private finalize; + update(data: TArg): this; + destroy(): void; + digestInto(out: TArg): void; + digest(): TRet; +} +/** One-shot keyed hash helper with `.create()`. */ +export type CHash = CMac; +/** + * Poly1305 MAC from RFC 8439. + * @param msg - Message bytes to authenticate. + * @param key - 32-byte Poly1305 one-time key. + * @returns 16-byte authentication tag. + * @example + * Authenticates one message with a one-shot Poly1305 call and a fresh key. + * + * ```ts + * import { poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * poly1305(new Uint8Array(), key); + * ``` + */ +export declare const poly1305: TRet; +//# sourceMappingURL=_poly1305.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.d.ts.map b/node_modules/@noble/ciphers/_poly1305.d.ts.map new file mode 100644 index 0000000..bd03e62 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_poly1305.d.ts","sourceRoot":"","sources":["src/_poly1305.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAGe,KAAK,IAAI,EAAE,KAAK,MAAM,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EACjE,MAAM,YAAY,CAAC;AA2DpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,QAAS,YAAW,MAAM;IACrC,QAAQ,CAAC,QAAQ,MAAM;IACvB,QAAQ,CAAC,SAAS,MAAM;IACxB,OAAO,CAAC,MAAM,CAAsB;IACpC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,CAAC,CAAuB;IAChC,OAAO,CAAC,GAAG,CAAsB;IACjC,OAAO,CAAC,GAAG,CAAK;IAChB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,SAAS,UAAS;gBAGhB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC;IA4BjC,OAAO,CAAC,OAAO;IA+Hf,OAAO,CAAC,QAAQ;IAmDhB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAwBpC,OAAO,IAAI,IAAI;IAKf,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAqBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAQ3B;AAED,mDAAmD;AACnD,MAAM,MAAM,KAAK,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC;AAEnC;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAGhC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.js b/node_modules/@noble/ciphers/_poly1305.js new file mode 100644 index 0000000..deff7b0 --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.js @@ -0,0 +1,364 @@ +/** + * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki}) + * is a fast and parallel secret-key message-authentication code suitable for + * a wide variety of applications. It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3. + * + * Polynomial MACs are not perfect for every situation: + * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes. + * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}. + * To combat invisible salamanders, `hash(key)` can be included in ciphertext, + * however, this would violate ciphertext indistinguishability: + * an attacker would know which key was used - so `HKDF(key, i)` + * could be used instead. + * + * Check out the {@link https://cr.yp.to/mac.html | original website}. + * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}. + * @module + */ +// prettier-ignore +import { abytes, aexists, aoutput, bytesToHex, clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, wrapMacConstructor } from "./utils.js"; +// Little-endian 2-byte load used by the Poly1305 limb decomposition. +function u8to16(a, i) { + return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8); +} +function bytesToNumberLE(bytes) { + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} +/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */ +function poly1305_small(msg, key) { + abytes(msg); + abytes(key, 32, 'key'); + const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5 + const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1 + const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff'); + const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R; + const s = bytesToNumberLE(key.subarray(16)); + // Process by 16 byte chunks + let acc = BigInt(0); + for (let i = 0; i < msg.length; i += 16) { + const m = msg.subarray(i, i + 16); + // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r. + const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length)); + acc = ((acc + n) * r) % POW_2_130_5; + } + const res = (acc + s) & POW_2_128_1; + // RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order. + return numberToBytesBE(res, 16).reverse(); // LE +} +// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability. +// @ts-expect-error +function poly1305_computeTag_small(authKey, +// AEAD trailer must already be the 16-byte length block: +// 8-byte little-endian AAD length || 8-byte little-endian ciphertext length. +lengths, ciphertext, AAD) { + // RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is + // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths. + const res = []; + const updatePadded2 = (msg) => { + res.push(msg); + const leftover = msg.length % 16; + // RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned + // inputs, else 16-(len%16) zero bytes. + if (leftover) + res.push(new Uint8Array(16).slice(leftover)); + }; + if (AAD) + updatePadded2(AAD); + updatePadded2(ciphertext); + res.push(lengths); + return poly1305_small(concatBytes(...res), authKey); +} +/** + * Incremental Poly1305 MAC state. + * Prefer `poly1305()` for one-shot use. + * @param key - 32-byte Poly1305 one-time key. + * @example + * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key. + * + * ```ts + * import { Poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const mac = new Poly1305(key); + * mac.update(new Uint8Array([1, 2, 3])); + * mac.digest(); + * ``` + */ +export class Poly1305 { + blockLen = 16; + outputLen = 16; + buffer = new Uint8Array(16); + r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3 + h = new Uint16Array(10); + pad = new Uint16Array(8); + pos = 0; + finished = false; + destroyed = false; + // Can be speed-up using BigUint64Array, at the cost of complexity + constructor(key) { + key = copyBytes(abytes(key, 32, 'key')); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication. + // These masks unpack that clamped value into 13-bit limbs, while pad + // keeps the raw s half for finalize(). + // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference} + this.r[0] = t0 & 0x1fff; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = (t4 >>> 1) & 0x1ffe; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = (t7 >>> 5) & 0x007f; + for (let i = 0; i < 8; i++) + this.pad[i] = u8to16(key, 16 + 2 * i); + } + process(data, offset, isLast = false) { + // RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high + // bit to every full 16-byte block. The final partial block gets its + // explicit `1` byte during digestInto(), so `hibit` stays zero there. + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + let h0 = h[0] + (t0 & 0x1fff); + let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff); + let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff); + let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff); + let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff); + let h5 = h[5] + ((t4 >>> 1) & 0x1fff); + let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff); + let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff); + let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff); + let h9 = h[9] + ((t7 >>> 5) | hibit); + let c = 0; + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 0x1fff; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 0x1fff; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 0x1fff; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 0x1fff; + h[2] += c; + // RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking + // to 16-bit words and adding the raw s half. + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= 1 << 13; + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) + g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) + h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 0xffff; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff; + let f = h[0] + pad[0]; + h[0] = f & 0xffff; + for (let i = 1; i < 8; i++) { + f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0; + h[i] = f & 0xffff; + } + clean(g); + } + update(data) { + aexists(this); + abytes(data); + data = copyBytes(data); + const { buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) + this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy() { + // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too. + this.destroyed = true; + clean(this.h, this.r, this.buffer, this.pad); + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + // RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a + // single `0x01` byte and zero-fills the remaining bytes before the + // last multiplication step. + buffer[pos++] = 1; + for (; pos < 16; pos++) + buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy out before destroy() zeroes the internal buffer. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +} +/** + * Poly1305 MAC from RFC 8439. + * @param msg - Message bytes to authenticate. + * @param key - 32-byte Poly1305 one-time key. + * @returns 16-byte authentication tag. + * @example + * Authenticates one message with a one-shot Poly1305 call and a fresh key. + * + * ```ts + * import { poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * poly1305(new Uint8Array(), key); + * ``` + */ +export const poly1305 = /* @__PURE__ */ wrapMacConstructor(32, (key) => new Poly1305(key)); +//# sourceMappingURL=_poly1305.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_poly1305.js.map b/node_modules/@noble/ciphers/_poly1305.js.map new file mode 100644 index 0000000..d6f4f2f --- /dev/null +++ b/node_modules/@noble/ciphers/_poly1305.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_poly1305.js","sourceRoot":"","sources":["src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AAQ,CAAC,GAAG,CAAC,CAC7C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.d.ts b/node_modules/@noble/ciphers/_polyval.d.ts new file mode 100644 index 0000000..ba5f5fb --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.d.ts @@ -0,0 +1,121 @@ +/** + * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. + * + * Implemented in terms of GHash with conversion function for keys + * GCM GHASH from + * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d}, + * SIV from + * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * + * GHASH modulo: x^128 + x^7 + x^2 + x + 1 + * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 + * + * @module + */ +import { type CMac, type IHash2, type TArg, type TRet } from './utils.ts'; +/** + * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A. + * @param k mutated in place + */ +export declare function _toGHASHKey(k: TArg): TRet; +type Value = { + s0: number; + s1: number; + s2: number; + s3: number; +}; +/** + * Incremental GHASH state for AES-GCM. + * @param key - 16-byte GHASH key. + * @param expectedLength - Expected message length for table sizing. + * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded + * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM + * use where AAD, payload, and length block are separate padded segments. + * @example + * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key. + * + * ```ts + * import { GHASH } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new GHASH(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export declare class GHASH implements IHash2 { + readonly blockLen: number; + readonly outputLen: number; + protected s0: number; + protected s1: number; + protected s2: number; + protected s3: number; + protected finished: boolean; + protected destroyed: boolean; + protected t: Value[]; + private W; + private windowSize; + constructor(key: TArg, expectedLength?: number); + protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void; + update(data: TArg): this; + destroy(): void; + digestInto(out: TArg): void; + digest(): TRet; +} +/** + * Incremental POLYVAL state for AES-SIV. + * @param key - 16-byte POLYVAL key. + * @param expectedLength - Expected message length for table sizing. + * Inherits GHASH's segment-padded `update()` behavior: each call is padded + * independently to a 16-byte boundary before absorption. + * @example + * Feeds one block into an incremental POLYVAL state with a fresh hash key. + * + * ```ts + * import { Polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new Polyval(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export declare class Polyval extends GHASH { + constructor(key: TArg, expectedLength?: number); + update(data: TArg): this; + digestInto(out: TArg): void; +} +/** + * GHash MAC for AES-GCM. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte GHASH key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with GHASH and a fresh hash key. + * + * ```ts + * import { ghash } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * ghash(new Uint8Array(), key); + * ``` + */ +export declare const ghash: TRet>; +/** + * POLYVAL MAC for AES-SIV. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte POLYVAL key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with POLYVAL and a fresh hash key. + * + * ```ts + * import { polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * polyval(new Uint8Array(), key); + * ``` + */ +export declare const polyval: TRet>; +export {}; +//# sourceMappingURL=_polyval.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.d.ts.map b/node_modules/@noble/ciphers/_polyval.d.ts.map new file mode 100644 index 0000000..ac3f9c6 --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_polyval.d.ts","sourceRoot":"","sources":["src/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IAAI;IAiBvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAO3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,qBAAa,OAAQ,SAAQ,KAAK;gBACpB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC,EAAE,MAAM;IAS1D,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA6BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;CAkBxC;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAK5D,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,CAAC,CAKhE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.js b/node_modules/@noble/ciphers/_polyval.js new file mode 100644 index 0000000..38db8e4 --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.js @@ -0,0 +1,330 @@ +/** + * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. + * + * Implemented in terms of GHash with conversion function for keys + * GCM GHASH from + * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d}, + * SIV from + * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * + * GHASH modulo: x^128 + x^7 + x^2 + x + 1 + * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 + * + * @module + */ +import { abytes, aexists, aoutput, clean, copyBytes, createView, swap32IfBE, swap8IfBE, u32, wrapMacConstructor, } from "./utils.js"; +const BLOCK_SIZE = 16; +// TODO: rewrite +// temporary padding buffer +// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch. +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = /* @__PURE__ */ u32(ZEROS16); +// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms +// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120. +const POLY = 0xe1; +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// Montgomery ladder can multiply any field element with this doubling step; +// addition stays simple xor. +const mul2 = (s0, s1, s2, s3) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this + // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0. + s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly + }; +}; +// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order. +const swapLE = (n) => (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes +// host-endian u32 loads to the little-endian word value `_updateBlock()` expects. +const swap8IfLE = (n) => swap8IfBE(swapLE(n)); +/** + * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A. + * @param k mutated in place + */ +export function _toGHASHKey(k) { + // The input is the original POLYVAL key H; reverse() materializes + // RFC 8452's `ByteReverse(H)` before the GHASH mulX step. + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k; +} +// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups. +// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}. +const estimateWindow = (bytes) => { + if (bytes > 64 * 1024) + return 8; + if (bytes > 1024) + return 4; + return 2; +}; +/** + * Incremental GHASH state for AES-GCM. + * @param key - 16-byte GHASH key. + * @param expectedLength - Expected message length for table sizing. + * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded + * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM + * use where AAD, payload, and length block are separate padded segments. + * @example + * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key. + * + * ```ts + * import { GHASH } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new GHASH(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export class GHASH { + blockLen = BLOCK_SIZE; + outputLen = BLOCK_SIZE; + s0 = 0; + s1 = 0; + s2 = 0; + s3 = 0; + finished = false; + destroyed = false; + t; + W; + windowSize; + // We select bits per window adaptively based on expectedLength + constructor(key, expectedLength) { + abytes(key, 16, 'key'); + key = copyBytes(key); + const kView = createView(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error('ghash: invalid window size, expected 2, 4 or 8'); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) + continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3)); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + _updateBlock(s0, s1, s2, s3) { + ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3)); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + // NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials, + // so the lookup walk consumes each word byte-by-byte from + // least-significant to most-significant bits. + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3)); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data) { + aexists(this); + abytes(data); + data = copyBytes(data); + const b32 = u32(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i = 0; i < blocks; i++) { + this._updateBlock(swap8IfBE(b32[i * 4 + 0]), swap8IfBE(b32[i * 4 + 1]), swap8IfBE(b32[i * 4 + 2]), swap8IfBE(b32[i * 4 + 3])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian + // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE. + this._updateBlock(swap8IfBE(ZEROS32[0]), swap8IfBE(ZEROS32[1]), swap8IfBE(ZEROS32[2]), swap8IfBE(ZEROS32[3])); + clean(ZEROS32); // clean tmp buffer + } + return this; + } + destroy() { + // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too. + this.destroyed = true; + const { t } = this; + // Wipe the key-derived precompute table; scalar accumulator words remain, + // but the destroyed guard blocks further use. + // clean precompute table + for (const elm of t) { + ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0)); + } + } + digestInto(out) { + aexists(this); + // `digestInto(out)` is the no-allocation fast path, so callers must pass a + // 32-bit-aligned buffer before we reinterpret it with `u32(out)`. + aoutput(out, this, true); + this.finished = true; + // NIST SP 800-38D §6.4 returns the final 128-bit block Y_m. + // `digestInto()` follows the relaxed `aoutput()` contract, so only + // out[0..15] may be touched. + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + swap32IfBE(o32); + } + digest() { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + // `res` is independent of internal state, so it stays valid after destroy() wipes the table. + this.destroy(); + return res; + } +} +/** + * Incremental POLYVAL state for AES-SIV. + * @param key - 16-byte POLYVAL key. + * @param expectedLength - Expected message length for table sizing. + * Inherits GHASH's segment-padded `update()` behavior: each call is padded + * independently to a 16-byte boundary before absorption. + * @example + * Feeds one block into an incremental POLYVAL state with a fresh hash key. + * + * ```ts + * import { Polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new Polyval(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export class Polyval extends GHASH { + constructor(key, expectedLength) { + abytes(key); + // RFC 8452 Appendix A converts the POLYVAL key with + // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)` + // mutates in place. + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data) { + aexists(this); + abytes(data); + data = copyBytes(data); + const b32 = u32(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i = 0; i < blocks; i++) { + // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL + // reverses the 32-bit word order in addition to the per-word byte swap. + this._updateBlock(swap8IfLE(b32[i * 4 + 3]), swap8IfLE(b32[i * 4 + 2]), swap8IfLE(b32[i * 4 + 1]), swap8IfLE(b32[i * 4 + 0])); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock(swap8IfLE(ZEROS32[3]), swap8IfLE(ZEROS32[2]), swap8IfLE(ZEROS32[1]), swap8IfLE(ZEROS32[0])); + clean(ZEROS32); + } + return this; + } + digestInto(out) { + aexists(this); + // `digestInto(out)` is the no-allocation fast path, so callers must pass a + // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`. + aoutput(out, this, true); + this.finished = true; + // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`. + // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched. + const view = out.subarray(0, this.outputLen); + const { s0, s1, s2, s3 } = this; + const o32 = u32(view); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + swap32IfBE(o32); + view.reverse(); + } +} +/** + * GHash MAC for AES-GCM. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte GHASH key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with GHASH and a fresh hash key. + * + * ```ts + * import { ghash } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * ghash(new Uint8Array(), key); + * ``` + */ +export const ghash = +/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new GHASH(key, expectedLength), (msg) => [msg.length]); +/** + * POLYVAL MAC for AES-SIV. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte POLYVAL key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with POLYVAL and a fresh hash key. + * + * ```ts + * import { polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * polyval(new Uint8Array(), key); + * ``` + */ +export const polyval = +/* @__PURE__ */ wrapMacConstructor(16, (key, expectedLength) => new Polyval(key, expectedLength), (msg) => [msg.length]); +//# sourceMappingURL=_polyval.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/_polyval.js.map b/node_modules/@noble/ciphers/_polyval.js.map new file mode 100644 index 0000000..bb454fd --- /dev/null +++ b/node_modules/@noble/ciphers/_polyval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_polyval.js","sourceRoot":"","sources":["src/_polyval.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,KAAK,EACL,SAAS,EACT,UAAU,EACV,UAAU,EACV,SAAS,EACT,GAAG,EACH,kBAAkB,GAKnB,MAAM,YAAY,CAAC;AAEpB,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,gBAAgB;AAChB,2BAA2B;AAC3B,+FAA+F;AAC/F,MAAM,OAAO,GAAG,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC;AACnD,MAAM,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;AAC7C,0EAA0E;AAC1E,wEAAwE;AACxE,MAAM,IAAI,GAAG,IAAI,CAAC;AAElB,iBAAiB;AACjB,4DAA4D;AAC5D,4EAA4E;AAC5E,6BAA6B;AAC7B,MAAM,IAAI,GAAG,CAAC,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAE;IAC9D,MAAM,KAAK,GAAG,EAAE,GAAG,CAAC,CAAC;IACrB,OAAO;QACL,EAAE,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,GAAG,CAAC,E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C,MAAM,GAAG,GAAG,GAAG,CAAC,IAAI,CAAC,CAAC;QACtB,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;QACZ,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;QACZ,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;QACZ,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC;QACZ,UAAU,CAAC,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,KAAK;AAChB,eAAe,CAAC,kBAAkB,CAChC,EAAE,EACF,CAAC,GAAqB,EAAE,cAAuB,EAAE,EAAE,CAAC,IAAI,KAAK,CAAC,GAAG,EAAE,cAAc,CAAC,EAClF,CAAC,GAAqB,EAA6B,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CACnE,CAAC;AAEJ;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,OAAO;AAClB,eAAe,CAAC,kBAAkB,CAChC,EAAE,EACF,CAAC,GAAqB,EAAE,cAAuB,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,GAAG,EAAE,cAAc,CAAC,EACpF,CAAC,GAAqB,EAA6B,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CACnE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.d.ts b/node_modules/@noble/ciphers/aes.d.ts new file mode 100644 index 0000000..1dab65f --- /dev/null +++ b/node_modules/@noble/ciphers/aes.d.ts @@ -0,0 +1,462 @@ +import { type Cipher, type CipherWithOutput, type CMac, type IHash2, type PRG, type TArg, type TRet, type Uint8ArrayBuffer } from './utils.ts'; +/** + * Increments a counter block with wrap around. + * AES call sites here currently use the big-endian branch, but the helper supports both layouts. + * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the + * least-significant/rightmost bits. + * `isLE=false` matches that standard counter-block layout, while `isLE=true` + * is a generic extension for non-AES callers. + * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`; + * larger values throw instead of silently overflowing before the next-byte propagation step. + */ +declare const incBytes: (data: TArg, isLE: boolean, carry?: number) => void; +/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */ +declare function expandKeyLE(key: TArg): TRet; +declare function expandKeyDecLE(key: TArg): TRet; +declare function encrypt(xk: TArg, s0: number, s1: number, s2: number, s3: number): { + s0: number; + s1: number; + s2: number; + s3: number; +}; +declare function decrypt(xk: TArg, s0: number, s1: number, s2: number, s3: number): { + s0: number; + s1: number; + s2: number; + s3: number; +}; +declare function ctrCounter(xk: TArg, nonce: TArg, src: TArg, dst?: TArg): TRet; +declare function ctr32(xk: TArg, isLE: boolean, nonce: TArg, src: TArg, dst?: TArg): TRet; +/** + * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a + * full 16-byte counter block. + * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block, incremented as a full AES block. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short payload with a fresh AES key and counter block. + * + * ```ts + * import { ctr } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const ctr: TRet<((key: TArg, nonce: TArg) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}>; +/** Options for ECB and CBC. */ +export type BlockOpts = { + /** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */ + disablePadding?: boolean; +}; +/** + * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield + * identical ciphertexts. Not secure due to pattern leakage. + * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}. + * @param key - AES key bytes. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs. + * + * ```ts + * import { ecb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const cipher = ecb(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const ecb: TRet<((key: TArg, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; +}>; +/** + * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the + * previous block of ciphertext before encryption. + * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a padded message with a fresh key and 16-byte IV. + * + * ```ts + * import { cbc } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const cbc: TRet<((key: TArg, iv: TArg, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}>; +/** + * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the + * block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short message with feedback mode and a fresh key/IV pair. + * + * ```ts + * import { cfb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cfb(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const cfb: TRet<((key: TArg, iv: TArg) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; +}>; +/** + * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. + * Not perfect: + * a) conservative key wear-out is `2**32` (4B) msgs. + * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance. + * c) MAC can be forged: see Poly1305 documentation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation). + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance with a fixed 16-byte tag. + * @example + * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const gcm: TRet<((key: TArg, nonce: TArg, AAD?: TArg) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; + varSizeNonce: true; +}>; +/** + * **SIV** (Synthetic IV): GCM with nonce-misuse resistance. + * Repeating nonces reveal only the fact plaintexts are identical. + * Also suffers from GCM issues: key wear-out limits & MAC forging. + * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * RFC 8452 defines 16-byte and 32-byte AES keys for this mode. + * This implementation also accepts 24-byte AES-192 keys as a local + * extension; see the inline comment next to `validateKeyLength(key)` below + * for the exact scope note. + * @param key - AES key bytes. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const gcmsiv: TRet<((key: TArg, nonce: TArg, AAD?: TArg) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; + varSizeNonce: true; +}>; +declare function encryptBlock(xk: TArg, block: TArg): TRet; +declare function decryptBlock(xk: TArg, block: TArg): TRet; +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes. + * 8-byte inputs use aeskwp. + * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes. + * For padded version, use aeskwp. + * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}. + * @param kek - AES key-encryption key. + * @returns Key-wrap cipher instance. + * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per + * instance. + * @example + * Wraps a 128-bit content-encryption key with a fresh key-encryption key. + * + * ```ts + * import { aeskw } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const cek = randomBytes(16); + * const wrap = aeskw(kek); + * wrap.encrypt(cek); + * ``` + */ +export declare const aeskw: TRet<((kek: TArg) => Cipher) & { + blockSize: number; +}>; +/** + * AES-KW, but with padding and allows random keys. + * Uses the RFC 5649 alternative initial value; the second u32 stores the + * 32-bit MLI in network order. + * Wrapped ciphertext must be at least 16 bytes; malformed lengths are + * rejected during AIV/padding checks. + * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}. + * @param kek - AES key-encryption key. + * @returns Padded key-wrap cipher instance. + * @example + * Wraps a short key blob using the padded variant and a fresh key-encryption key. + * + * ```ts + * import { aeskwp } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const wrap = aeskwp(kek); + * wrap.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const aeskwp: TRet<((kek: TArg) => Cipher) & { + blockSize: number; +}>; +declare class _AesCtrDRBG implements PRG { + readonly blockLen: number; + private key; + private nonce; + private state; + private reseedCnt; + constructor(keyLen: number, seed: TArg, personalization?: TArg); + private update; + addEntropy(seed: TArg, info?: TArg): void; + randomBytes(len: number, info?: TArg): TRet; + clean(): void; +} +/** + * Factory for AES-CTR DRBG instances. + * @param seed - Initial entropy input. + * @param personalization - Optional personalization string mixed into the state. + * @returns Seeded AES-CTR DRBG instance. + */ +export type AesCtrDrbg = (seed: TArg, personalization?: TArg) => TRet<_AesCtrDRBG>; +/** + * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 32-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngAesCtrDrbg128(seed); + * prg.randomBytes(8); + * ``` + */ +export declare const rngAesCtrDrbg128: TRet; +/** + * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 48-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(48); + * const prg = rngAesCtrDrbg256(seed); + * prg.randomBytes(8); + * ``` + */ +export declare const rngAesCtrDrbg256: TRet; +/** + * Left-shift by one bit and conditionally XOR with 0x87: + * ``` + * if MSB(L) is equal to 0 + * then K1 := L << 1; + * else K1 := (L << 1) XOR const_Rb; + * ``` + * + * Specs: + * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}, + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3} + * + * @returns modified `block` (for chaining) + */ +declare function dbl(block: T): T; +/** + * `a XOR b`, running in-place on `a`. + * @param a left operand and output + * @param b right operand + * @returns `a` (for chaining) + */ +declare function xorBlock>(a: T, b: TArg): T; +/** + * xorend as defined in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}. + * + * ``` + * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B) + * ``` + * + * Mutates `a` in place so the left prefix stays untouched and only the + * rightmost `len(B)` bytes are xored with `b`. + */ +declare function xorend>(a: T, b: TArg): T; +/** + * Internal CMAC class. + */ +declare class _CMAC implements IHash2 { + readonly blockLen: number; + readonly outputLen: number; + private buffer; + private pos; + private finished; + private destroyed; + private k1; + private k2; + private x; + private xk; + constructor(key: TArg); + private process; + update(data: TArg): this; + digestInto(out: TArg): void; + digest(): Uint8ArrayBuffer; + destroy(): void; +} +/** + * AES-CMAC (Cipher-based Message Authentication Code). + * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}. + * @param msg - Message bytes to authenticate. + * @param key - AES key bytes. + * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as + * the other keyed helpers in this repo, including `blockLen`, + * `outputLen`, `digestInto()` and `destroy()`. + * @example + * Authenticates a message with AES-CMAC and a fresh key. + * + * ```ts + * import { cmac } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * cmac(new Uint8Array(), key); + * ``` + */ +export declare const cmac: TRet>; +/** + * S2V (Synthetic Initialization Vector) function as described in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}. + * + * ``` + * S2V(K, S1, ..., Sn) { + * if n = 0 then + * return V = AES-CMAC(K, ) + * fi + * D = AES-CMAC(K, ) + * for i = 1 to n-1 do + * D = dbl(D) xor AES-CMAC(K, Si) + * done + * if len(Sn) >= 128 then + * T = Sn xorend D + * else + * T = dbl(D) xor pad(Sn) + * fi + * return V = AES-CMAC(K, T) + * } + * ``` + * + * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string. + * The S2V function is used to generate a synthetic IV for AES-SIV. + * + * @param key - AES key (128, 192, or 256 bits) + * @param strings - Array of byte arrays to process + * @returns 128-bit synthetic IV + */ +declare function s2v(key: TArg, strings: TArg): TRet; +/** + * Use `gcmsiv` or `aessiv`. + * @returns Never; always throws with the migration hint. + * @throws If called; `siv()` is a removed v1 alias. {@link Error} + * @example + * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const siv: () => never; +/** + * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption + * Nonce is derived from the plaintext and AAD using the S2V function. + * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by + * passing the nonce as the final AAD component before the plaintext. + * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}. + * @param key - 32-byte, 48-byte, or 64-byte key. + * @param AAD - Additional authenticated data chunks (up to 126). + * @returns AEAD cipher instance. + * @example + * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces. + * + * ```ts + * import { aessiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const cipher = aessiv(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const aessiv: TRet<((key: TArg, ...AAD: TArg) => Cipher) & { + blockSize: number; + tagLength: number; +}>; +/** + * Unsafe low-level internal methods. May change at any time. + * Callers are expected to use reviewed expanded-key outputs, pass mutable and + * aligned 16-byte blocks where required, and treat several helpers as in-place + * mutations of their input buffers or counters. + */ +export declare const unsafe: { + expandKeyLE: typeof expandKeyLE; + expandKeyDecLE: typeof expandKeyDecLE; + encrypt: typeof encrypt; + decrypt: typeof decrypt; + encryptBlock: typeof encryptBlock; + decryptBlock: typeof decryptBlock; + ctrCounter: typeof ctrCounter; + ctr32: typeof ctr32; + dbl: typeof dbl; + xorBlock: typeof xorBlock; + xorend: typeof xorend; + s2v: typeof s2v; +}; +export declare const __TESTS: { + incBytes: typeof incBytes; +}; +export {}; +//# sourceMappingURL=aes.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.d.ts.map b/node_modules/@noble/ciphers/aes.d.ts.map new file mode 100644 index 0000000..f1ce7e8 --- /dev/null +++ b/node_modules/@noble/ciphers/aes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"aes.d.ts","sourceRoot":"","sources":["src/aes.ts"],"names":[],"mappings":"AAuBA,OAAO,EAUL,KAAK,MAAM,EAAE,KAAK,gBAAgB,EAClC,KAAK,IAAI,EAAE,KAAK,MAAM,EACtB,KAAK,GAAG,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,KAAK,gBAAgB,EACtD,MAAM,YAAY,CAAC;AAyCpB;;;;;;;;;GASG;AAGH,QAAA,MAAM,QAAQ,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,KAAK,IAgB1E,CAAC;AAkFF,iFAAiF;AACjF,iBAAS,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,WAAW,CAAC,CA2B7D;AAED,iBAAS,cAAc,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,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;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CACvB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,GAAG,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,KAAK,MAAM,CAAC,GAAG;IAChE,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;CACnB,CAkEF,CAAC;AAGF;;;;;GAKG;AACH,eAAO,MAAM,MAAM,EAAE;IACnB,WAAW,EAAE,OAAO,WAAW,CAAC;IAChC,cAAc,EAAE,OAAO,cAAc,CAAC;IACtC,OAAO,EAAE,OAAO,OAAO,CAAC;IACxB,OAAO,EAAE,OAAO,OAAO,CAAC;IACxB,YAAY,EAAE,OAAO,YAAY,CAAC;IAClC,YAAY,EAAE,OAAO,YAAY,CAAC;IAClC,UAAU,EAAE,OAAO,UAAU,CAAC;IAC9B,KAAK,EAAE,OAAO,KAAK,CAAC;IACpB,GAAG,EAAE,OAAO,GAAG,CAAC;IAChB,QAAQ,EAAE,OAAO,QAAQ,CAAC;IAC1B,MAAM,EAAE,OAAO,MAAM,CAAC;IACtB,GAAG,EAAE,OAAO,GAAG,CAAC;CAchB,CAAC;AAEH,eAAO,MAAM,OAAO,EAAE;IAAE,QAAQ,EAAE,OAAO,QAAQ,CAAA;CAE/C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.js b/node_modules/@noble/ciphers/aes.js new file mode 100644 index 0000000..fdd85a5 --- /dev/null +++ b/node_modules/@noble/ciphers/aes.js @@ -0,0 +1,1765 @@ +/** + * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES} + * a.k.a. Advanced Encryption Standard + * is a variant of Rijndael block cipher, standardized by NIST in 2001. + * We provide the fastest available pure JS implementation. + * + * `cipher = encrypt(block, key)` + * + * Data is split into 128-bit blocks. + * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: + * 1. **S-box**, table substitution + * 2. **Shift rows**, cyclic shift left of all rows of data array + * 3. **Mix columns**, multiplying every column by fixed polynomial + * 4. **Add round key**, round_key xor i-th column of array + * + * Check out + * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197}, + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}, + * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}. + * @module + */ +import { ghash, polyval } from "./_polyval.js"; +// prettier-ignore +import { abytes, anumber, aoutput, byteSwap, clean, complexOverlapBytes, concatBytes, copyBytes, createView, equalBytes, getOutput, isAligned32, isLE, overlapBytes, swap32IfBE, swap8IfBE, u32, u64Lengths, u8, wrapCipher, wrapMacConstructor } from "./utils.js"; +const BLOCK_SIZE = 16; +// AES operates on 16-byte blocks, i.e. 4 32-bit words. +const BLOCK_SIZE32 = 4; +// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch +// and by CMAC / SIV helpers; callers take `.slice()` before mutating it. +const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE); +// RFC 5297 §2.1 / §2.4: S2V uses ` = 0^127 || 1` for the `n = 0` special case. +const ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, +]); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere. +function validateKeyLength(key) { + if (![16, 24, 32].includes(key.length)) + throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length); +} +// TODO: remove multiplication, binary ops only +// Doubles one GF(2^8) field element; callers are expected to stay in byte range. +// FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when +// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result +// as XORing with {1b} after the shift. +function mul2(n) { + return (n << 1) ^ (POLY & -(n >> 7)); +} +// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values. +// FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated +// XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}. +function mul(a, b) { + let res = 0; + for (; b > 0; b >>= 1) { + // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder. + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} +/** + * Increments a counter block with wrap around. + * AES call sites here currently use the big-endian branch, but the helper supports both layouts. + * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the + * least-significant/rightmost bits. + * `isLE=false` matches that standard counter-block layout, while `isLE=true` + * is a generic extension for non-AES callers. + * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`; + * larger values throw instead of silently overflowing before the next-byte propagation step. + */ +// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it +// through the test-only `__TESTS` export without inference errors. +const incBytes = (data, isLE, carry = 1) => { + // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below + // never truncates a real carry bit. + if (!Number.isSafeInteger(carry) || carry > 0xffffff00) + throw new Error('incBytes: wrong carry ' + carry); + abytes(data); + for (let i = 0; i < data.length; i++) { + const pos = !isLE ? data.length - 1 - i : i; + carry = (carry + (data[pos] & 0xff)) | 0; + data[pos] = carry & 0xff; + carry >>>= 8; + } +}; +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + // Repeated multiplication by {03} walks all 255 nonzero field elements + // once, so t[255 - i] is the multiplicative inverse of t[i] for the + // affine step. + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) + t[i] = x; + const box = new Uint8Array(256); + // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves + // {00} at {00}, then the affine transform xors in c = {63}. + box[0] = 0x63; + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); +// FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input +// and output roles (Table 6). +// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths. +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); +// FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE +// word packing that is a right rotate by 8 bits. +const rotr32_8 = (n) => (n << 24) | (n >>> 8); +// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3 +// reuse T0's substitution/mix result in the other byte lanes. +const rotl32_8 = (n) => (n << 8) | (n >>> 24); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox, fn) { + if (sbox.length !== 256) + throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted + // byte lanes per lookup in the LE round layout. + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} +// Forward round precompute: the packed word stores the MIXCOLUMNS row +// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2` +// is also reused by key expansion and the final round. +const tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2)); +// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row +// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused +// by decrypt() and expandKeyDecLE(). +const tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14)); +// FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES(). +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) + p[i] = x; + return p; +})(); +/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */ +function expandKeyLE(key) { + abytes(key); + const len = key.length; + validateKeyLength(key); + const { sbox2 } = tableEncoding; + const toClean = []; + // Copy on BE or misaligned inputs so the LE word normalization below never + // mutates caller key bytes in place. + if (!isLE || !isAligned32(key)) + toClean.push((key = copyBytes(key))); + const k32 = swap32IfBE(u32(key)); + const Nk = k32.length; + // `applySbox` normally reads one byte lane from each argument; repeating + // `n` across all four lanes turns it into SUBWORD(n). + const subByte = (n) => applySbox(sbox2, n, n, n, n); + // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60 + // schedule words from FIPS 197 §5.2 / Table 3. + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) + t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) + t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk; +} +function expandKeyDecLE(key) { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Local decrypt() walks round keys forward from xk[0], so reverse the + // encryption round-key blocks first before applying the equivalent-inverse + // middle-round transform. + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) + xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // Apply InvMixColumn to the reversed round keys using the same LE sbox2 + // packing as the forward path. + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk; +} +// Apply tables +function apply0123(T01, T23, s0, s1, s2, s3) { + // `T01` takes the low byte lane from `s0` plus the next lane from `s1`; + // `T23` does the same for `s2`/`s3`. + // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^ + // T3[s3>>>24]`, but with two merged-table fetches. + return (T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)]); +} +function applySbox(sbox2, s0, s1, s2, s3) { + // `sbox2` packs two substituted byte lanes at a time in the same LE + // layout used by the round code. + // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 | + // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`. + return (sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16)); +} +function encrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the + // final S-box-only round there are Nr-1 full table/MixColumns rounds left. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt(xk, s0, s1, s2, s3) { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // With `expandKeyDecLE()` the round keys are already reversed and middle + // rounds are InvMixColumns-adjusted, so this loop follows the equivalent + // inverse cipher order directly. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // Final equivalent-inverse round omits InvMixColumns, so use inverse + // S-box lanes in InvShiftRows order. + const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} +function ctrCounter(xk, nonce, src, dst) { + abytes(nonce, BLOCK_SIZE, 'nonce'); + abytes(src); + const srcLen = src.length; + dst = getOutput(srcLen, dst); + complexOverlapBytes(src, dst); + // Internal helper: mutate `nonce` in place as the live counter block so + // each encrypted block uses the next CTR value. + const ctr = nonce; + const c32 = u32(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0); + dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1); + dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2); + dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3); + incBytes(ctr, false, 1); // Full 128 bit counter with wrap around + ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]))); + } + // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output + // block for the final short block. + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(b32); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + // Unsafe mutable-counter API only advances whole blocks. Callers that want to + // resume after consuming part of this block must re-run from the same counter + // with left-padding and strip the already-consumed prefix themselves. + return dst; +} +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`, +// and uses `isLE` to choose which 32-bit counter word is incremented. +function ctr32(xk, isLE, nonce, src, dst) { + abytes(nonce, BLOCK_SIZE, 'nonce'); + abytes(src); + dst = getOutput(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32(ctr); + const view = createView(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while + // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32. + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3])); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0); + dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1); + dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2); + dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3); + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt(xk, swap8IfBE(c32[0]), swap8IfBE(c32[1]), swap8IfBE(c32[2]), swap8IfBE(c32[3]))); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(b32); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + // Same unsafe contract as ctrCounter(): only full blocks advance the stored + // mutable counter state; partial-block continuation is caller-managed. + return dst; +} +/** + * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a + * full 16-byte counter block. + * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block, incremented as a full AES block. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short payload with a fresh AES key and counter block. + * + * ```ts + * import { ctr } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ctr = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aesctr(key, nonce) { + function processCtr(buf, dst) { + abytes(buf); + if (dst !== undefined) { + abytes(dst); + // Optional output buffers must stay 4-byte aligned because + // ctrCounter() reinterprets them as Uint32Array words. + if (!isAligned32(dst)) + throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + // Public CTR keeps caller nonce bytes immutable even though ctrCounter() + // advances the live 16-byte counter block in place. + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) + toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out; + } + return { + encrypt: (plaintext, dst) => processCtr(plaintext, dst), + decrypt: (ciphertext, dst) => processCtr(ciphertext, dst), + }; +}); +function validateBlockDecrypt(data) { + abytes(data); + // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS + // padding, when enabled, is removed only after decrypting the final block. + if (data.length % BLOCK_SIZE !== 0) { + throw new Error('aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE); + } +} +// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's +// PKCS#7/CMS-compatible final-block padding convenience before encryption. +function validateBlockEncrypt(plaintext, pkcs5, dst) { + abytes(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pkcs5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (pkcs5) { + let left = BLOCK_SIZE - remaining; + // RFC 5652 pads even already-aligned inputs, so a full extra block is + // appended when the plaintext length is already a multiple of 16 bytes. + if (!left) + left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + dst = getOutput(outLen, dst); + complexOverlapBytes(plaintext, dst); + // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never + // mutates caller plaintext bytes in place before ECB/CBC processing. + if (!isLE || !isAligned32(plaintext)) + plaintext = copyBytes(plaintext); + const b = u32(plaintext); + swap32IfBE(b); + const o = u32(dst); + return { b, o, out: dst }; +} +// `pkcs5` is the historical option name; for AES's 16-byte block this is the +// generic PKCS#7/CMS-style block-padding rule on decrypt. +function validatePKCS(data, pkcs5) { + if (!pkcs5) + return data; + const len = data.length; + // RFC 5652 pads even empty / already-aligned inputs, so a valid padded + // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled. + // AES-CBC/ECB ciphertext should be full blocks before unpadding + if (len === 0) + throw new Error('aes/pkcs7: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + let valid = 1; + valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1 + valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16 + // Check exactly 16 tail bytes in constant-shape loop + // For i < pad: byte must equal pad + // For i >= pad: ignore byte + for (let i = 0; i < 16; i++) { + // const b = data[len - 1 - i]; + const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0 + const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal + valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked + } + // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16'); + if (!valid) + throw new Error('aes/pkcs7: wrong padding'); + return data.subarray(0, len - lastByte); +} +// ECB/CBC callers only pass the final short block here, so `left.length` is +// 0..15 and the helper always emits exactly one padded 16-byte block. +function padPCKS(left) { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + // RFC 5652 §6.3 fills the whole suffix with the padding length byte: + // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block. + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) + tmp[i] = paddingByte; + return tmp32; +} +/** + * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield + * identical ciphertexts. Not secure due to pattern leakage. + * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}. + * @param key - AES key bytes. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs. + * + * ```ts + * import { ecb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const cipher = ecb(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key, opts = {}) { + const pkcs5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst); + const xk = expandKeyLE(key); + let i = 0; + for (; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + if (pkcs5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + swap32IfBE(tmp32); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(xk); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + dst = getOutput(ciphertext.length, dst); + const toClean = [xk]; + complexOverlapBytes(ciphertext, dst); + // Copy on BE or misaligned ciphertext so u32()/swap32IfBE() + // normalization never mutates caller bytes in place before decrypt(). + if (!isLE || !isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32(ciphertext); + const o = u32(dst); + swap32IfBE(b); + for (let i = 0; i + 4 <= b.length;) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(...toClean); + return validatePKCS(dst, pkcs5); + }, + }; +}); +/** + * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the + * previous block of ciphertext before encryption. + * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a padded message with a fresh key and 16-byte IV. + * + * ```ts + * import { cbc } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const cbc = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescbc(key, iv, opts = {}) { + const pkcs5 = !opts.disablePadding; + return { + encrypt(plaintext, dst) { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst); + let _iv = iv; + const toClean = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length;) { + ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + if (pkcs5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + swap32IfBE(tmp32); + ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(...toClean); + return _out; + }, + decrypt(ciphertext, dst) { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + dst = getOutput(ciphertext.length, dst); + complexOverlapBytes(ciphertext, dst); + // Copy on BE or misaligned ciphertext so u32()/swap32IfBE() + // normalization never mutates caller bytes in place before decrypt(). + if (!isLE || !isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32(ciphertext); + const o = u32(dst); + swap32IfBE(b); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length;) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3])); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3)); + } + swap32IfBE(o); + clean(...toClean); + return validatePKCS(dst, pkcs5); + }, + }; +}); +/** + * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the + * block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short message with feedback mode and a fresh key/IV pair. + * + * ```ts + * import { cfb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cfb(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const cfb = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 16 }, function aescfb(key, iv) { + function processCfb(src, isEncrypt, dst) { + abytes(src); + const srcLen = src.length; + dst = getOutput(srcLen, dst); + // CFB feeds back previous ciphertext, so overlapping src/dst could + // overwrite bytes that are still needed as the next feedback block. + if (overlapBytes(src, dst)) + throw new Error('overlapping src and dst not supported.'); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean = [xk]; + // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization + // never mutates caller IV/src bytes in place before CFB processing. + if (!isLE || !isAligned32(_iv)) + toClean.push((_iv = copyBytes(_iv))); + if (!isLE || !isAligned32(src)) + toClean.push((src = copyBytes(src))); + const src32 = u32(src); + const dst32 = u32(dst); + // NIST SP 800-38A §6.3 feeds back the previous ciphertext segment in + // both directions: encrypt reuses freshly written dst words, decrypt + // reuses the source ciphertext words. + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32(_iv); + swap32IfBE(src32); + swap32IfBE(n32); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length;) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++])); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + // Byte-oriented API: for a final short tail, reuse the next CFB-128 + // output block and XOR only the needed prefix. RFC 3826 §3.1.3 / + // §3.1.4 describes the same no-padding rule at bit granularity for a + // final r<=128 segment. + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + const tmp = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(tmp); + const buf = u8(tmp); + for (let i = start, pos = 0; i < srcLen; i++, pos++) + dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + swap32IfBE(dst32); + clean(...toClean); + return dst; + } + return { + encrypt: (plaintext, dst) => processCfb(plaintext, true, dst), + decrypt: (ciphertext, dst) => processCfb(ciphertext, false, dst), + }; +}); +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +// `data` is the payload covered by the polynomial MAC: ciphertext for GCM, +// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because +// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the +// spec-defined segments instead of arbitrary concatenation boundaries. +function computeTag(fn, isLE, key, data, AAD) { + const aadLength = AAD ? AAD.length : 0; + const h = fn.create(key, data.length + aadLength); + if (AAD) + h.update(AAD); + // u64Lengths() takes (dataBits, aadBits) but still serializes the final + // block as len(AAD) || len(data), matching both GCM and GCM-SIV. + const num = u64Lengths(8 * data.length, 8 * aadLength, isLE); + h.update(data); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} +/** + * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. + * Not perfect: + * a) conservative key wear-out is `2**32` (4B) msgs. + * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance. + * c) MAC can be forged: see Poly1305 documentation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation). + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance with a fixed 16-byte tag. + * @example + * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcm = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aesgcm(key, nonce, AAD) { + // SP 800-38D lets implementations narrow supported IV lengths. + // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too. + // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0. + if (nonce.length < 8) + throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag(authKey, tagMask, data) { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) + tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); + } + else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView(nonceLen); + view.setBigUint64(8, BigInt(nonce.length * 8), false); + // GHASH.update() pads each call to 16 bytes, so + // update(nonce).update(nonceLen) realizes + // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces. + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag + // mask and leaves `counter` advanced to inc32(J0) for payload GCTR. + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext) { + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length)); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + // NIST SP 800-38D §7.2 permits equivalent step orderings; verify the + // tag before CTR so unauthenticated plaintext is never materialized. + if (!equalBytes(tag, passedTag)) { + clean(...toClean); + throw new Error('aes/gcm: invalid ghash tag'); + } + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out; + }, + }; +}); +const limit = (name, min, max) => (value) => { + // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297, + // not arbitrary library-preference bounds. + // Callers feed Uint8Array.length values here, so safe-integer rejection + // does not exclude any representable input even when an RFC bound is larger. + if (!Number.isSafeInteger(value) || min > value || value > max) { + const minmax = '[' + min + '..' + max + ']'; + throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value); + } +}; +/** + * **SIV** (Synthetic IV): GCM with nonce-misuse resistance. + * Repeating nonces reveal only the fact plaintexts are identical. + * Also suffers from GCM issues: key wear-out limits & MAC forging. + * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * RFC 8452 defines 16-byte and 32-byte AES keys for this mode. + * This implementation also accepts 24-byte AES-192 keys as a local + * extension; see the inline comment next to `validateKeyLength(key)` below + * for the exact scope note. + * @param key - AES key bytes. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcmsiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, function aessiv(key, nonce, AAD) { + const tagLength = 16; + // From RFC 8452: Section 6 + const AAD_LIMIT = limit('AAD', 0, 2 ** 36); + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36); + const NONCE_LIMIT = limit('nonce', 12, 12); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16); + abytes(key); + // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys. + // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs. + validateKeyLength(key); + NONCE_LIMIT(nonce.length); + if (AAD !== undefined) + AAD_LIMIT(AAD.length); + function deriveKeys() { + const xk = expandKeyLE(key); + const encKey = new Uint8Array(key.length); + const authKey = new Uint8Array(16); + const toClean = [xk, encKey]; + let _nonce = nonce; + // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization + // never mutates caller nonce bytes before RFC 8452 key derivation. + if (!isLE || !isAligned32(_nonce)) + toClean.push((_nonce = copyBytes(_nonce))); + const n32 = u32(_nonce); + swap32IfBE(n32); + // prettier-ignore + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(u32)) { + const d32 = u32(derivedKey); + for (let i = 0; i < d32.length; i += 2) { + // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ... + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i + 0] = o0; + d32[i + 1] = o1; + s0 = ++counter; // increment counter inside state + } + swap32IfBE(d32); + } + const res = { authKey, encKey: expandKeyLE(encKey) }; + // Cleanup + clean(...toClean); + return res; + } + function _computeTag(encKey, authKey, data) { + const tag = computeTag(polyval, true, authKey, data, AAD); + // Compute the expected tag by XORing S_s and the nonce, clearing the + // most significant bit of the last byte and encrypting with the + // message-encryption key. + for (let i = 0; i < 12; i++) + tag[i] ^= nonce[i]; + tag[15] &= 0x7f; // Clear the highest bit + // encrypt tag as block + const t32 = u32(tag); + swap32IfBE(t32); + // prettier-ignore + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3)); + swap32IfBE(t32); + return tag; + } + // actual decrypt/encrypt of message. + function processSiv(encKey, tag, input) { + let block = copyBytes(tag); + // RFC 8452 §4 / §5 use the tag with the highest bit of the last byte + // forced to one as the initial AES-CTR counter block. + block[15] |= 0x80; // Force highest bit + const res = ctr32(encKey, true, block, input); + // Cleanup + clean(block); + return res; + } + return { + encrypt(plaintext) { + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const toClean = [encKey, authKey, tag]; + if (!isAligned32(plaintext)) + toClean.push((plaintext = copyBytes(plaintext))); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + // Cleanup + clean(...toClean); + return out; + }, + decrypt(ciphertext) { + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const toClean = [encKey, authKey]; + if (!isAligned32(ciphertext)) + toClean.push((ciphertext = copyBytes(ciphertext))); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + toClean.push(expectedTag); + // RFC 8452 §5: plaintext is unauthenticated here and MUST NOT be + // returned until the expected-tag check completes successfully. + if (!equalBytes(tag, expectedTag)) { + clean(...toClean); + throw new Error('invalid polyval tag'); + } + // Cleanup + clean(...toClean); + return plaintext; + }, + }; +}); +function isBytes32(a) { + // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views. + // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`. + return (a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array')); +} +// Unsafe single-block helpers: mutate `block` in place and require its 16-byte +// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it. +function encryptBlock(xk, block) { + abytes(block, 16, 'block'); + if (!isBytes32(xk)) + throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + swap32IfBE(b32); + let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]); + ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3)); + swap32IfBE(b32); + return block; +} +function decryptBlock(xk, block) { + abytes(block, 16, 'block'); + if (!isBytes32(xk)) + throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + swap32IfBE(b32); + let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]); + ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3)); + swap32IfBE(b32); + return block; +} +/** + * AES-W (base for AESKW/AESKWP). + * Specs: + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F}, + * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394}, + * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}. + * Shared core mutates `out` in place; callers are responsible for prepending + * the right IV/AIV and checking the recovered value after decrypt. + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek, out) { + // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter, + // so the shared core caps plaintext below 4 GiB even though the specs allow more. + if (out.length >= 2 ** 32) + throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1; + // KW callers never reach it because KW requires at least two plaintext semiblocks. + if (out.length === 16) + encryptBlock(xk, out); + else { + const o32 = u32(out); + swap32IfBE(o32); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap + // above, `t` fits in the low half of `[t]_64`, so xor only the low + // 32 bits of A after converting `ctr` to network order. + ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3)); + } + } + ((o32[0] = a0), (o32[1] = a1)); // out = A || out + swap32IfBE(o32); + } + xk.fill(0); + }, + decrypt(kek, out) { + // Same implementation cap on the recovered plaintext length after + // removing the 8-byte A/IV prefix. + if (out.length - 8 >= 2 ** 32) + throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts + // always have at least three semiblocks and therefore use the W^-1 loop. + if (chunks === 1) + decryptBlock(xk, out); + else { + const o32 = u32(out); + swap32IfBE(o32); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap(ctr); + const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]); + ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3)); + } + } + ((o32[0] = a0), (o32[1] = a1)); + swap32IfBE(o32); + } + xk.fill(0); + }, +}; +// RFC 3394 §2.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends +// the default 64-bit ICV1 and unwrap must verify the same value. +const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes. + * 8-byte inputs use aeskwp. + * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes. + * For padded version, use aeskwp. + * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}. + * @param kek - AES key-encryption key. + * @returns Key-wrap cipher instance. + * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per + * instance. + * @example + * Wraps a 128-bit content-encryption key with a fresh key-encryption key. + * + * ```ts + * import { aeskw } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const cek = randomBytes(16); + * const wrap = aeskw(kek); + * wrap.encrypt(cek); + * ``` + */ +export const aeskw = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext + // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP. + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext + // immutable across the unwrap, ICV1 check, and IV scrubbing below. + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes(out.subarray(0, 8), AESKW_IV)) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8); + }, +})); +/* +We don't support 8-byte keys. The rabbit hole: + +- Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys. + RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped + by directly encrypting one block with AES." + - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note} + - "RFC 3394 specifies in Section 2, that the input for the key wrap + algorithm must be at least two blocks and otherwise the constant + field and key are simply encrypted with ECB as a single block" +- What RFC 3394 actually says (in Section 2): + - "Before being wrapped, the key data is parsed into n blocks of 64 bits. + The only restriction the key wrap algorithm places on n is that n be + at least two" + - "For key data with length less than or equal to 64 bits, the constant + field used in this specification and the key data form a single + 128-bit codebook input making this key wrap unnecessary." +- Which means "assert(n >= 2)" and "use something else for 8 byte keys" +- NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits". + It states that plaintext for KW should be "2 to 2^54 -1 semiblocks". +- So, where does "directly encrypt single block with AES" come from? + - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses + loop of 6 for any code path + - There is a weird W3C spec: + {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section} + - This spec is outdated, as admitted by Wycheproof authors + - There is RFC 5649 for padded key wrap, which is padding construction on + top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly + eight octets, then prepend the AIV as defined in Section 3 above to P[1] and + encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key + K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:" + - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes: + `Error: error:1C8000E6:Provider routines::invalid input length] + { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]` + +In the end, seems like a bug in Wycheproof. +The 8-byte check can be easily disabled inside of AES_W. +*/ +// RFC 5649 §3 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as +// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order. +const AESKWP_IV = 0xa65959a6; // single u32le value +/** + * AES-KW, but with padding and allows random keys. + * Uses the RFC 5649 alternative initial value; the second u32 stores the + * 32-bit MLI in network order. + * Wrapped ciphertext must be at least 16 bytes; malformed lengths are + * rejected during AIV/padding checks. + * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}. + * @param kek - AES key-encryption key. + * @returns Padded key-wrap cipher instance. + * @example + * Wraps a short key blob using the padded variant and a fresh key-encryption key. + * + * ```ts + * import { aeskwp } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const wrap = aeskwp(kek); + * wrap.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const aeskwp = /* @__PURE__ */ wrapCipher({ blockSize: 8 }, (kek) => ({ + encrypt(plaintext) { + if (!plaintext.length) + throw new Error('invalid plaintext length'); + const padded = Math.ceil(plaintext.length / 8) * 8; + const out = new Uint8Array(8 + padded); + out.set(plaintext, 8); + const out32 = u32(out); + out32[0] = swap8IfBE(AESKWP_IV); + // RFC 5649 §3: the low 32 bits of the AIV carry the octet-length MLI in + // network order, even though this buffer is addressed through LE u32s. + out32[1] = swap8IfBE(byteSwap(plaintext.length)); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext) { + // 16 because should have at least one block + if (ciphertext.length < 16) + throw new Error('invalid ciphertext length'); + // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext + // immutable across the unwrap, AIV checks, and IV scrubbing below. + const out = copyBytes(ciphertext); + const o32 = u32(out); + AESW.decrypt(kek, out); + const len = byteSwap(swap8IfBE(o32[1])) >>> 0; + const padded = Math.ceil(len / 8) * 8; + if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded) + throw new Error('integrity check failed'); + // RFC 5649 §3 / NIST SP 800-38F Algorithm 6: recovered padding length + // must be in [0,7], and every recovered pad octet must be zero. + for (let i = len; i < padded; i++) + if (out[8 + i] !== 0) + throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8, 8 + len); + }, +})); +class _AesCtrDRBG { + blockLen; + key; + nonce; + state; + reseedCnt; + constructor(keyLen, seed, personalization) { + this.blockLen = ctr.blockSize; + const keyLenBytes = keyLen / 8; + const nonceLen = 16; + // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps + // can rewrite the entire internal state in place. + this.state = new Uint8Array(keyLenBytes + nonceLen); + this.key = this.state.subarray(0, keyLenBytes); + this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen); + this.reseedCnt = 1; + // Keep the stored counter one step ahead of SP 800-90A's formal V so + // ctr(key, nonce) uses the next counter block directly. + incBytes(this.nonce, false, 1); + this.addEntropy(seed, personalization); + } + update(data) { + // cannot re-use state here, because we will wipe current key + ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state); + if (data) { + abytes(data); + // CTR_DRBG without a derivation function pads shorter additional_input + // with zeros to seedlen, so XOR only the provided prefix here. + for (let i = 0; i < data.length; i++) + this.state[i] ^= data[i]; + } + // Keep storing V+1 so the next ctr(key, nonce) call starts from the + // spec's post-update counter state. + incBytes(this.nonce, false, 1); + } + // Optional `info` is additional input XORed into the reseed block and is + // limited to the internal state width. + addEntropy(seed, info) { + abytes(seed, this.state.length, 'seed'); + // Copy caller entropy before XORing in personalization/additional input, + // then wipe the mixed seed material after CTR_DRBG_Update consumes it. + const _seed = seed.slice(); + if (info) { + abytes(info); + if (info.length > _seed.length) + throw new Error('info length is too big'); + for (let i = 0; i < info.length; i++) + _seed[i] ^= info[i]; + } + this.update(_seed); + _seed.fill(0); + this.reseedCnt = 1; + } + // Optional `info` is additional input for the pre/post-update steps; bytes + // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits + // additional_input to seedlen, which is exactly this internal state width. + randomBytes(len, info) { + anumber(len); + // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes. + if (len > 2 ** 16) + throw new Error('requested output is too big'); + // The spec allows generate while reseed_counter == reseed_interval and increments afterwards. + if (this.reseedCnt > 2 ** 48) + throw new Error('entropy exhausted'); + if (info) { + abytes(info); + if (info.length > this.state.length) + throw new Error('info length is too big'); + this.update(info); + } + const res = new Uint8Array(len); + ctr(this.key, this.nonce).encrypt(res, res); + incBytes(this.nonce, false, Math.ceil(len / this.blockLen)); + this.update(info); + this.reseedCnt++; + return res; + } + // Zeroes the current state and resets the counter, but does not make the + // instance unusable: later calls continue from the zeroed state. + clean() { + // `key` and `nonce` alias this backing buffer, so one fill wipes the full + // secret state in place. + this.state.fill(0); + this.reseedCnt = 0; + } +} +// Internal helper for the exported 128-bit and 256-bit aliases; other key +// lengths are not validated here. +const createAesDrbg = (keyLen) => { + return (seed, personalization = undefined) => new _AesCtrDRBG(keyLen, seed, personalization); +}; +/** + * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 32-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngAesCtrDrbg128(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngAesCtrDrbg128 = /* @__PURE__ */ createAesDrbg(128); +/** + * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 48-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(48); + * const prg = rngAesCtrDrbg256(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngAesCtrDrbg256 = /* @__PURE__ */ createAesDrbg(256); +//#region CMAC +/** + * Left-shift by one bit and conditionally XOR with 0x87: + * ``` + * if MSB(L) is equal to 0 + * then K1 := L << 1; + * else K1 := (L << 1) XOR const_Rb; + * ``` + * + * Specs: + * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}, + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3} + * + * @returns modified `block` (for chaining) + */ +function dbl(block) { + let carry = 0; + // Left shift by 1 bit + for (let i = BLOCK_SIZE - 1; i >= 0; i--) { + const newCarry = (block[i] & 0x80) >>> 7; + block[i] = (block[i] << 1) | carry; + carry = newCarry; + } + // XOR with 0x87 if there was a carry from the most significant bit + if (carry) { + // RFC 4493 §2.3 / RFC 5297 §2.1: 0x87 is const_Rb for doubling in the + // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1. + block[BLOCK_SIZE - 1] ^= 0x87; + } + return block; +} +/** + * `a XOR b`, running in-place on `a`. + * @param a left operand and output + * @param b right operand + * @returns `a` (for chaining) + */ +function xorBlock(a, b) { + if (a.length !== b.length) + throw new Error('xorBlock: blocks must have same length'); + for (let i = 0; i < a.length; i++) { + a[i] = a[i] ^ b[i]; + } + return a; +} +/** + * xorend as defined in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}. + * + * ``` + * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B) + * ``` + * + * Mutates `a` in place so the left prefix stays untouched and only the + * rightmost `len(B)` bytes are xored with `b`. + */ +function xorend(a, b) { + if (b.length > a.length) { + throw new Error('xorend: len(B) must be less than or equal to len(A)'); + } + // keep leftmost part of `a` unchanged + // and xor only the rightmost part: + const offset = a.length - b.length; + for (let i = 0; i < b.length; i++) { + a[offset + i] = a[offset + i] ^ b[i]; + } + return a; +} +/** + * Internal CMAC class. + */ +class _CMAC { + blockLen = BLOCK_SIZE; + outputLen = BLOCK_SIZE; + // CMAC can only decide between `K1` and `K2` once the true final block is known, + // so updates process older blocks eagerly but keep one pending block buffered. + buffer; + pos; + finished; + destroyed; + k1; + k2; + x; + xk; + constructor(key) { + abytes(key); + validateKeyLength(key); + this.xk = expandKeyLE(key); + this.buffer = new Uint8Array(BLOCK_SIZE); + this.pos = 0; + this.finished = false; + this.destroyed = false; + this.x = new Uint8Array(BLOCK_SIZE); + // L = AES_encrypt(K, const_Zero) + const L = new Uint8Array(BLOCK_SIZE); + encryptBlock(this.xk, L); + // Generate subkeys K1 and K2 from the main key according to + // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3} + // K1 + this.k1 = dbl(L); + this.k2 = dbl(new Uint8Array(this.k1)); + } + process(data) { + // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y). + xorBlock(this.x, data); + encryptBlock(this.xk, this.x); + } + update(data) { + if (this.destroyed) + throw new Error('Hash instance has been destroyed'); + if (this.finished) + throw new Error('Hash#digest() has already been called'); + abytes(data); + let pos = 0; + if (this.pos) { + const take = Math.min(BLOCK_SIZE - this.pos, data.length); + this.buffer.set(data.subarray(0, take), this.pos); + this.pos += take; + pos = take; + if (this.pos === BLOCK_SIZE && pos < data.length) { + this.process(this.buffer); + this.pos = 0; + } + } + // Keep one complete block buffered: an exact 16-byte tail may still be + // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2. + while (pos + BLOCK_SIZE < data.length) { + this.process(data.subarray(pos, pos + BLOCK_SIZE)); + pos += BLOCK_SIZE; + } + if (pos < data.length) { + this.buffer.set(data.subarray(pos), 0); + this.pos = data.length - pos; + } + return this; + } + // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}. + digestInto(out) { + if (this.destroyed) + throw new Error('Hash instance has been destroyed'); + if (this.finished) + throw new Error('Hash#digest() has already been called'); + // `digestInto(out)` is the no-allocation fast path, so AES block re-use below + // requires a 32-bit-aligned caller buffer instead of hidden temp copies. + aoutput(out, this, true); + this.finished = true; + // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag. + const view = out.subarray(0, this.outputLen); + let last = new Uint8Array(BLOCK_SIZE); + if (this.pos === BLOCK_SIZE) { + // M_last := M_n XOR K1; + last.set(this.buffer); + xorBlock(last, this.k1); + } + else { + // M_last := padding(M_n) XOR K2; + // + // [...] padding(x) is the concatenation of x and a single '1', + // followed by the minimum number of '0's, so that the total length is + // equal to 128 bits. + last.set(this.buffer.subarray(0, this.pos)); + last[this.pos] = 0x80; // single '1' bit + xorBlock(last, this.k2); + } + view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1}) + xorBlock(view, last); // Y := X XOR M_last + encryptBlock(this.xk, view); // T := AES-128(K, Y) + clean(last); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy out before destroy() wipes the internal digest buffer in place. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + destroy() { + const { buffer, destroyed, x, xk, k1, k2 } = this; + if (destroyed) + return; + this.destroyed = true; + // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys. + clean(buffer, x, xk, k1, k2); + } +} +/** + * AES-CMAC (Cipher-based Message Authentication Code). + * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}. + * @param msg - Message bytes to authenticate. + * @param key - AES key bytes. + * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as + * the other keyed helpers in this repo, including `blockLen`, + * `outputLen`, `digestInto()` and `destroy()`. + * @example + * Authenticates a message with AES-CMAC and a fresh key. + * + * ```ts + * import { cmac } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * cmac(new Uint8Array(), key); + * ``` + */ +// The 16-byte probe key is only used to read static metadata; runtime CMAC +// still accepts AES-128/192/256 keys. +export const cmac = /* @__PURE__ */ wrapMacConstructor(16, (key) => new _CMAC(key)); +/** + * S2V (Synthetic Initialization Vector) function as described in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}. + * + * ``` + * S2V(K, S1, ..., Sn) { + * if n = 0 then + * return V = AES-CMAC(K, ) + * fi + * D = AES-CMAC(K, ) + * for i = 1 to n-1 do + * D = dbl(D) xor AES-CMAC(K, Si) + * done + * if len(Sn) >= 128 then + * T = Sn xorend D + * else + * T = dbl(D) xor pad(Sn) + * fi + * return V = AES-CMAC(K, T) + * } + * ``` + * + * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string. + * The S2V function is used to generate a synthetic IV for AES-SIV. + * + * @param key - AES key (128, 192, or 256 bits) + * @param strings - Array of byte arrays to process + * @returns 128-bit synthetic IV + */ +function s2v(key, strings) { + validateKeyLength(key); + const len = strings.length; + if (len > 127) { + // RFC 5297 §7 only proves S2V secure for at most 127 components; SIV + // spends one of those on the plaintext, leaving at most 126 AAD inputs. + throw new Error('s2v: number of input strings must be less than or equal to 127'); + } + if (len === 0) + return cmac(ONE_BLOCK, key); + // D = AES-CMAC(K, ) + let d = cmac(EMPTY_BLOCK, key); + // for i = 1 to n-1 do + // D = dbl(D) xor AES-CMAC(K, Si) + for (let i = 0; i < len - 1; i++) { + dbl(d); + const cmacResult = cmac(strings[i], key); + xorBlock(d, cmacResult); + clean(cmacResult); + } + const s_n = strings[len - 1]; + // Earlier components are validated through cmac(...); validate the final one explicitly because + // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently. + abytes(s_n); + let t; + // if len(Sn) >= 128 then + if (s_n.byteLength >= BLOCK_SIZE) { + // T = Sn xorend D + t = xorend(Uint8Array.from(s_n), d); + } + else { + // pad(Sn): + const paddedSn = new Uint8Array(BLOCK_SIZE); + paddedSn.set(s_n); + paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros + // T = dbl(D) xor pad(Sn) + t = xorBlock(dbl(d), paddedSn); + clean(paddedSn); + } + // V = AES-CMAC(K, T) + const result = cmac(t, key); + clean(d, t); + return result; +} +/** + * Use `gcmsiv` or `aessiv`. + * @returns Never; always throws with the migration hint. + * @throws If called; `siv()` is a removed v1 alias. {@link Error} + * @example + * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const siv = () => { + throw new Error('"siv" from v1 is now "gcmsiv"'); +}; +/** + * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption + * Nonce is derived from the plaintext and AAD using the S2V function. + * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by + * passing the nonce as the final AAD component before the plaintext. + * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}. + * @param key - 32-byte, 48-byte, or 64-byte key. + * @param AAD - Additional authenticated data chunks (up to 126). + * @returns AEAD cipher instance. + * @example + * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces. + * + * ```ts + * import { aessiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const cipher = aessiv(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const aessiv = /* @__PURE__ */ wrapCipher({ blockSize: 16, tagLength: 16 }, function aessiv(key, ...AAD) { + // From RFC 5297: Section 6.1, 6.2, 6.3: + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16); + if (AAD.length > 126) { + // RFC 5297 §2.6 / §2.7 / §7: SIV passes the plaintext as the last S2V + // component, so callers only get 126 associated-data components. + throw new Error('"AAD" number of elements must be less than or equal to 126'); + } + AAD.forEach((aad) => abytes(aad)); + abytes(key); + if (![32, 48, 64].includes(key.length)) + throw new Error('"aes key" expected Uint8Array of length 32/48/64, got length=' + key.length); + // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and + // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR. + // This borrows caller key/AAD buffers by reference; mutating them after + // construction changes future encrypt/decrypt results. + const k1 = key.subarray(0, key.length / 2); + const k2 = key.subarray(key.length / 2); + return { + // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6} + encrypt(plaintext) { + PLAIN_LIMIT(plaintext.length); + const v = s2v(k1, [...AAD, plaintext]); + // clear out the 31st and 63rd (rightmost) bit: + const q = Uint8Array.from(v); + q[8] &= 0x7f; + q[12] &= 0x7f; + // encrypt: + const c = ctr(k2, q).encrypt(plaintext); + return concatBytes(v, c); + }, + // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7} + decrypt(ciphertext) { + CIPHER_LIMIT(ciphertext.length); + const v = ciphertext.subarray(0, BLOCK_SIZE); + const c = ciphertext.subarray(BLOCK_SIZE); + // clear out the 31st and 63rd (rightmost) bit: + const q = Uint8Array.from(v); + q[8] &= 0x7f; + q[12] &= 0x7f; + // decrypt: + const p = ctr(k2, q).decrypt(c); + // verify tag: + const t = s2v(k1, [...AAD, p]); + if (equalBytes(t, v)) { + return p; + } + else { + throw new Error('invalid siv tag'); + } + }, + }; +}); +//#endregion +/** + * Unsafe low-level internal methods. May change at any time. + * Callers are expected to use reviewed expanded-key outputs, pass mutable and + * aligned 16-byte blocks where required, and treat several helpers as in-place + * mutations of their input buffers or counters. + */ +export const unsafe = /* @__PURE__ */ Object.freeze({ + expandKeyLE, + expandKeyDecLE, + encrypt, + decrypt, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, + dbl, + xorBlock, + xorend, + s2v, +}); +export const __TESTS = /* @__PURE__ */ Object.freeze({ + incBytes: incBytes, +}); +//# sourceMappingURL=aes.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/aes.js.map b/node_modules/@noble/ciphers/aes.js.map new file mode 100644 index 0000000..3a71e27 --- /dev/null +++ b/node_modules/@noble/ciphers/aes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aes.js","sourceRoot":"","sources":["src/aes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AAC/C,kBAAkB;AAClB,OAAO,EACL,MAAM,EAAE,OAAO,EAAE,OAAO,EACxB,QAAQ,EACR,KAAK,EAAE,mBAAmB,EAAE,WAAW,EACvC,SAAS,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EACzD,IAAI,EACJ,YAAY,EACZ,UAAU,EACV,SAAS,EACT,GAAG,EAAE,UAAU,EAAE,EAAE,EAAE,UAAU,EAAE,kBAAkB,EAIpD,MAAM,YAAY,CAAC;AAEpB,MAAM,UAAU,GAAG,EAAE,CAAC;AACtB,uDAAuD;AACvD,MAAM,YAAY,GAA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YACX,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YAEhC,cAAc;YACd,MAAM,CAAC,GAAG,GAAG,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;gBACrB,OAAO,CAAqB,CAAC;YAC/B,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;YACrC,CAAC;QACH,CAAC;KACc,CAAC;AACpB,CAAC,CACF,CAAC;AACF,YAAY;AAEZ;;;;;GAKG;AACH,MAAM,CAAC,MAAM,MAAM,GAaf,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IAChC,WAAW;IACX,cAAc;IACd,OAAO;IACP,OAAO;IACP,YAAY;IACZ,YAAY;IACZ,UAAU;IACV,KAAK;IACL,GAAG;IACH,QAAQ;IACR,MAAM;IACN,GAAG;CACJ,CAAC,CAAC;AAEH,MAAM,CAAC,MAAM,OAAO,GAAkC,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IAClF,QAAQ,EAAE,QAAQ;CACnB,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.d.ts b/node_modules/@noble/ciphers/chacha.d.ts new file mode 100644 index 0000000..55c5983 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.d.ts @@ -0,0 +1,249 @@ +/** + * ChaCha stream cipher, released + * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round. + * It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and + * is now used in TLS 1.3. + * + * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20} + * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with + * randomly-generated nonces. + * + * Check out + * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and + * {@link https://cr.yp.to/chacha.html | website}. + * + * @module + */ +import { type XorPRG } from './_arx.ts'; +import { type ARXCipher, type CipherWithOutput, type TArg, type TRet, type XorStream } from './utils.ts'; +/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */ +declare const chachaCore_small: typeof chachaCore; +/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */ +declare function chachaCore(s: TArg, k: TArg, n: TArg, out: TArg, cnt: number, rounds?: number): void; +/** + * hchacha hashes key and nonce into key' and nonce' for xchacha20. + * Algorithmically identical to `hchacha_small`, but this exported path + * normalizes word order on big-endian hosts. + * Need to find a way to merge it with `chachaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XChaCha subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hchacha(sigma, key, nonce, out); + * ``` + */ +export declare function hchacha(s: TArg, k: TArg, i: TArg, out: TArg): void; +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce. + * + * ```ts + * import { chacha20orig } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * chacha20orig(key, nonce, new Uint8Array(4)); + * ``` + */ +export declare const chacha20orig: TRet; +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce. + * + * ```ts + * import { chacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export declare const chacha20: TRet; +/** + * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 32-byte key. + * @param nonce - 24-byte extended nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xchacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export declare const xchacha20: TRet; +/** + * Reduced 8-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha8(key, nonce, new Uint8Array(4)); + * ``` + */ +export declare const chacha8: TRet; +/** + * Reduced 12-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha12 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha12(key, nonce, new Uint8Array(4)); + * ``` + */ +export declare const chacha12: TRet; +export declare const __TESTS: { + chachaCore_small: typeof chachaCore_small; + chachaCore: typeof chachaCore; +}; +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them, but it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export declare const _poly1305_aead: (xorStream: TArg) => (key: TArg, nonce: TArg, AAD?: TArg) => CipherWithOutput; +/** + * ChaCha20-Poly1305 from RFC 8439. + * + * Unsafe to use random nonces under the same key, due to collision chance. + * Prefer XChaCha instead. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce. + * + * ```ts + * import { chacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * const cipher = chacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const chacha20poly1305: TRet; +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * + * Can be safely used with random nonces (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xchacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const xchacha20poly1305: TRet; +/** + * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 40-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the test-only ChaCha20 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha20(seed); + * prg.randomBytes(8); + * ``` + */ +export declare const rngChacha20: TRet; +/** + * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Faster than `rngChacha20`. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 44-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the faster test-only ChaCha8 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha8(seed); + * prg.randomBytes(8); + * ``` + */ +export declare const rngChacha8: TRet; +export {}; +//# sourceMappingURL=chacha.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.d.ts.map b/node_modules/@noble/ciphers/chacha.d.ts.map new file mode 100644 index 0000000..4d37373 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"chacha.d.ts","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,KAAK,MAAM,EAAiC,MAAM,WAAW,CAAC;AAEvE,OAAO,EACL,KAAK,SAAS,EACd,KAAK,gBAAgB,EACrB,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EASf,MAAM,YAAY,CAAC;AAkEpB,sFAAsF;AAEtF,QAAA,MAAM,gBAAgB,EAAE,OAAO,UAE8C,CAAC;AAK9E,gFAAgF;AAEhF,iBAAS,UAAU,CACjB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,SAAK,GACjH,IAAI,CA6DN;AACD;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,wBAAgB,OAAO,CACrB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CAqDN;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,SAAS,CAIvC,CAAC;AACH;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,SAAS,CAKpC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAIlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAInC,CAAC;AAGH,eAAO,MAAM,OAAO,EAAE;IACpB,gBAAgB,EAAE,OAAO,gBAAgB,CAAC;IAC1C,UAAU,EAAE,OAAO,UAAU,CAAC;CACmC,CAAC;AA0CpE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GACxB,WAAW,IAAI,CAAC,SAAS,CAAC,MAC1B,KAAK,IAAI,CAAC,UAAU,CAAC,EAAE,OAAO,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,IAAI,CAAC,UAAU,CAAC,KAAG,gBA+CzE,CAAC;AAEJ;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAG5C,CAAC;AACF;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,SAAS,CAG7C,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,MAAM,CAAsD,CAAC;AAC5F;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,MAAM,CAAkD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.js b/node_modules/@noble/ciphers/chacha.js new file mode 100644 index 0000000..97ecca2 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.js @@ -0,0 +1,575 @@ +/** + * ChaCha stream cipher, released + * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round. + * It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and + * is now used in TLS 1.3. + * + * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20} + * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with + * randomly-generated nonces. + * + * Check out + * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and + * {@link https://cr.yp.to/chacha.html | website}. + * + * @module + */ +import { createCipher, createPRG, rotl } from "./_arx.js"; +import { poly1305 } from "./_poly1305.js"; +import { abytes, clean, equalBytes, getOutput, swap8IfBE, swap32IfBE, u64Lengths, wrapCipher, } from "./utils.js"; +/** + * ChaCha core function. It is implemented twice: + * 1. Simple loop (chachaCore_small, hchacha_small) + * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read + * The specific implementation is selected in `createCipher` below. + */ +/** RFC 8439 §2.1 quarter round on words a, b, c, d. */ +// prettier-ignore +function chachaQR(x, a, b, c, d) { + x[a] = (x[a] + x[b]) | 0; + x[d] = rotl(x[d] ^ x[a], 16); + x[c] = (x[c] + x[d]) | 0; + x[b] = rotl(x[b] ^ x[c], 12); + x[a] = (x[a] + x[b]) | 0; + x[d] = rotl(x[d] ^ x[a], 8); + x[c] = (x[c] + x[d]) | 0; + x[b] = rotl(x[b] ^ x[c], 7); +} +/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */ +function chachaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + // RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds. + chachaQR(x, 0, 4, 8, 12); + chachaQR(x, 1, 5, 9, 13); + chachaQR(x, 2, 6, 10, 14); + chachaQR(x, 3, 7, 11, 15); + chachaQR(x, 0, 5, 10, 15); + chachaQR(x, 1, 6, 11, 12); + chachaQR(x, 2, 7, 8, 13); + chachaQR(x, 3, 4, 9, 14); + } +} +// Shared scratch for the auditability-only helper below; only the test-only +// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant. +const ctmp = /* @__PURE__ */ new Uint32Array(16); +/** Small version of chacha without loop unrolling. Unused, provided for auditability. */ +// prettier-ignore +function chacha(s, k, i, out, isHChacha = true, rounds = 20) { + // `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block + // function or the full 128-bit nonce prefix for the HChaCha subkey path. + // Create initial array using common pattern + const y = Uint32Array.from([ + s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k" + k[0], k[1], k[2], k[3], // Key Key Key Key + k[4], k[5], k[6], k[7], // Key Key Key Key + i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce + ]); + const x = ctmp; + x.set(y); + chachaRound(x, rounds); + // HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha + // block path adds the original state word-by-word. + if (isHChacha) { + const xindexes = [0, 1, 2, 3, 12, 13, 14, 15]; + for (let i = 0; i < 8; i++) + out[i] = x[xindexes[i]]; + } + else { + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; + } +} +/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */ +// @ts-ignore +const chachaCore_small = (s, k, n, out, cnt, rounds) => +// Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha(). +chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds); +/** Identical to `hchacha`. Unused. */ +// @ts-ignore +const hchacha_small = chacha; +/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */ +// prettier-ignore +function chachaCore(s, k, n, out, cnt, rounds = 20) { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k" + y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key + y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key + y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce + // Save state to temporary variables + 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; + for (let r = 0; r < rounds; r += 2) { + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 7); + } + // RFC 8439 §2.3 / §2.3.1: add the original state words back in state order. + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hchacha hashes key and nonce into key' and nonce' for xchacha20. + * Algorithmically identical to `hchacha_small`, but this exported path + * normalizes word order on big-endian hosts. + * Need to find a way to merge it with `chachaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XChaCha subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hchacha(sigma, key, nonce, out); + * ``` + */ +// prettier-ignore +export function hchacha(s, k, i, out) { + let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]); + for (let r = 0; r < 20; r += 2) { + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; + x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; + x04 = rotl(x04 ^ x08, 7); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; + x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; + x05 = rotl(x05 ^ x09, 7); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; + x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; + x06 = rotl(x06 ^ x10, 7); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; + x15 = rotl(x15 ^ x03, 8); + x11 = (x11 + x15) | 0; + x07 = rotl(x07 ^ x11, 7); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; + x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; + x05 = rotl(x05 ^ x10, 7); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; + x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; + x06 = rotl(x06 ^ x11, 7); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; + x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; + x07 = rotl(x07 ^ x08, 7); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 16); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; + x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; + x04 = rotl(x04 ^ x09, 7); + } + // HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds. + let oi = 0; + out[oi++] = x00; + out[oi++] = x01; + out[oi++] = x02; + out[oi++] = x03; + out[oi++] = x12; + out[oi++] = x13; + out[oi++] = x14; + out[oi++] = x15; + swap32IfBE(out); +} +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce. + * + * ```ts + * import { chacha20orig } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * chacha20orig(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha20orig = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + allowShortKeys: true, +}); +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce. + * + * ```ts + * import { chacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false, +}); +/** + * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 32-byte key. + * @param nonce - 24-byte extended nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xchacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false, +}); +/** + * Reduced 8-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha8(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha8 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); +/** + * Reduced 12-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha12 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha12(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha12 = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); +// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core. +export const __TESTS = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore }); +// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding. +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes. +const updatePadded = (h, msg) => { + h.update(msg); + const leftover = msg.length % 16; + if (leftover) + h.update(ZEROS16.subarray(leftover)); +}; +// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key +// generation only needs 32 zero bytes. +const ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag(fn, key, nonce, ciphertext, AAD) { + if (AAD !== undefined) + abytes(AAD, undefined, 'AAD'); + // RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0, + // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext). + const authKey = fn(key, nonce, ZEROS32); + const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); + // Methods below can be replaced with + // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD) + const h = poly1305.create(authKey); + if (AAD) + updatePadded(h, AAD); + updatePadded(h, ciphertext); + h.update(lengths); + const res = h.digest(); + clean(authKey, lengths); + return res; +} +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them, but it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export const _poly1305_aead = (xorStream) => (key, nonce, AAD) => { + // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction + // changes future encrypt/decrypt results. + const tagLength = 16; + return { + encrypt(plaintext, output) { + const plength = plaintext.length; + output = getOutput(plength + tagLength, output, false); + output.set(plaintext); + const oPlain = output.subarray(0, -tagLength); + // RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK. + xorStream(key, nonce, oPlain, oPlain, 1); + const tag = computeTag(xorStream, key, nonce, oPlain, AAD); + output.set(tag, plength); // append tag + clean(tag); + return output; + }, + decrypt(ciphertext, output) { + output = getOutput(ciphertext.length - tagLength, output, false); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag(xorStream, key, nonce, data, AAD); + // RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with + // the constant-time equalBytes() helper rather than decrypting speculative plaintext first. + if (!equalBytes(passedTag, tag)) { + clean(tag); + throw new Error('invalid tag'); + } + output.set(ciphertext.subarray(0, -tagLength)); + // Actual decryption + xorStream(key, nonce, output, output, 1); // start stream with i=1 + clean(tag); + return output; + }, + }; +}; +/** + * ChaCha20-Poly1305 from RFC 8439. + * + * Unsafe to use random nonces under the same key, due to collision chance. + * Prefer XChaCha instead. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce. + * + * ```ts + * import { chacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * const cipher = chacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const chacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 12, tagLength: 16 }, +/* @__PURE__ */ _poly1305_aead(chacha20)); +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * + * Can be safely used with random nonces (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xchacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, +/* @__PURE__ */ _poly1305_aead(xchacha20)); +/** + * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 40-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the test-only ChaCha20 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha20(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngChacha20 = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8); +/** + * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Faster than `rngChacha20`. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 44-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the faster test-only ChaCha8 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha8(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngChacha8 = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12); +//# sourceMappingURL=chacha.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/chacha.js.map b/node_modules/@noble/ciphers/chacha.js.map new file mode 100644 index 0000000..349a252 --- /dev/null +++ b/node_modules/@noble/ciphers/chacha.js.map @@ -0,0 +1 @@ +{"version":3,"file":"chacha.js","sourceRoot":"","sources":["src/chacha.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAe,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACvE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1C,OAAO,EAML,MAAM,EACN,KAAK,EACL,UAAU,EACV,SAAS,EACT,SAAS,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GAoBG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAoB,eAAe,CAAC,UAAU,CAC1E,EAAE,SAAS,EAAE,EAAE,EAAE,WAAW,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE;AACjD,eAAe,CAAC,cAAc,CAAC,SAAS,CAAC,CAC1C,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,MAAM,WAAW,GAAiB,eAAe,CAAC,SAAS,CAAC,YAAY,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC;AAC5F;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,MAAM,UAAU,GAAiB,eAAe,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.d.ts b/node_modules/@noble/ciphers/ff1.d.ts new file mode 100644 index 0000000..7eadb87 --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.d.ts @@ -0,0 +1,40 @@ +import { type Cipher, type TArg, type TRet } from './utils.ts'; +/** + * FPE-FF1 format-preserving encryption. + * @param radix - Alphabet size for each input digit. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over digit arrays. + * @example + * Encrypts decimal digits without changing their format, using a fresh AES key. + * + * ```ts + * import { FF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = FF1(10, key); + * ff1.encrypt([1, 2, 3]); + * ``` + */ +export declare function FF1(radix: number, key: TArg, tweak?: TArg): { + encrypt(x: number[]): number[]; + decrypt(x: number[]): number[]; +}; +/** + * Binary FPE-FF1 wrapper over byte arrays. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over byte arrays. + * @example + * Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key. + * + * ```ts + * import { BinaryFF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = BinaryFF1(key); + * ff1.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function BinaryFF1(key: TArg, tweak?: TArg): TRet; +//# sourceMappingURL=ff1.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.d.ts.map b/node_modules/@noble/ciphers/ff1.d.ts.map new file mode 100644 index 0000000..f2ae60f --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ff1.d.ts","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAMA,OAAO,EAML,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAqGpB;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,GAAG,CACjB,KAAK,EAAE,MAAM,EACb,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC;IAAE,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;CAAE,CAkCpE;AAsBD;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,GAAE,IAAI,CAAC,UAAU,CAAa,GAClC,IAAI,CAAC,MAAM,CAAC,CAQd"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.js b/node_modules/@noble/ciphers/ff1.js new file mode 100644 index 0000000..79679ba --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.js @@ -0,0 +1,204 @@ +/** + * FPE-FF1 (Format-preserving encryption algorithm) specified in + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}. + * @module + */ +import { unsafe } from "./aes.js"; +import { abytes, anumber, bytesToNumberBE, clean, numberToBytesBE, } from "./utils.js"; +// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file +// reuses the reviewed AES key schedule and single-block encryption helpers. +// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow +const { expandKeyLE, encryptBlock } = unsafe; +// Format-preserving encryption algorithm (FPE-FF1) specified in +// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}. +const BLOCK_LEN = 16; +function mod(a, b) { + const result = a % b; + return result >= 0 ? result : b + result; +} +function NUMradix(radix, data) { + let res = BigInt(0); + for (let i of data) + res = res * BigInt(radix) + BigInt(i); + return res; +} +function getRound(radix, key, tweak, x) { + if (radix > 2 ** 16 - 1) + throw new Error('invalid radix ' + radix); + // radix**minlen ≥ 100 + const minLen = Math.ceil(Math.log(100) / Math.log(radix)); + const maxLen = 2 ** 32 - 1; + // 2 ≤ minlen ≤ maxlen < 2**32 + if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32) + throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32'); + if (!Array.isArray(x)) + throw new Error('invalid X'); + if (x.length < minLen || x.length > maxLen) + throw new Error('X is outside minLen..maxLen bounds'); + // SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail + // before NUMradix(...) or round splitting can reinterpret them as a different numeral string. + for (const i of x) { + if (!Number.isSafeInteger(i) || i < 0 || i >= radix) + throw new Error('invalid X: digit outside radix'); + } + const u = Math.floor(x.length / 2); + const v = x.length - u; + const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8); + const d = 4 * Math.ceil(b / 4) + 4; + const padding = mod(-tweak.length - b - 1, 16); + // P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4. + const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]); + const view = new DataView(P.buffer); + // NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as + // 0x00 || uint16_be(radix). + view.setUint16(4, radix, false); + view.setUint32(8, x.length, false); + view.setUint32(12, tweak.length, false); + // Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b. + const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b); + PQ.set(P); + clean(P); + PQ.set(tweak, P.length); + const xk = expandKeyLE(key); + const round = (A, B, i, decrypt = false) => { + // Q = ... || [i]1 || [NUMradix(B)]b. + PQ[PQ.length - b - 1] = i; + if (b) + PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b); + // NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128. + let r = new Uint8Array(16); + for (let j = 0; j < PQ.length / BLOCK_LEN; j++) { + for (let i = 0; i < BLOCK_LEN; i++) + r[i] ^= PQ[j * BLOCK_LEN + i]; + encryptBlock(xk, r); + } + // Let S be the first d bytes of the following string of ⎡d/16⎤ blocks: + // R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16). + let s = Array.from(r); + for (let j = 1; s.length < d; j++) { + const block = numberToBytesBE(BigInt(j), 16); + for (let k = 0; k < BLOCK_LEN; k++) + block[k] ^= r[k]; + s.push(...Array.from(encryptBlock(xk, block))); + } + let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d))); + s.fill(0); + if (decrypt) + y = -y; + const m = i % 2 === 0 ? u : v; + let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m)); + // STR(radix, m, c) + const C = Array(m).fill(0); + for (let i = 0; i < m; i++, c /= BigInt(radix)) + C[m - 1 - i] = Number(c % BigInt(radix)); + A.fill(0); + A = B; + B = C; + return [A, B]; + }; + const destroy = () => { + clean(xk, PQ); + }; + return { u, round, destroy }; +} +const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of(); +/** + * FPE-FF1 format-preserving encryption. + * @param radix - Alphabet size for each input digit. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over digit arrays. + * @example + * Encrypts decimal digits without changing their format, using a fresh AES key. + * + * ```ts + * import { FF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = FF1(10, key); + * ff1.encrypt([1, 2, 3]); + * ``` + */ +export function FF1(radix, key, tweak = EMPTY_BUF) { + anumber(radix); + abytes(key); + abytes(tweak); + // This borrows caller key/tweak buffers by reference through the bound closure; mutating them + // after construction changes later encrypt/decrypt outputs. + const PQ = getRound.bind(null, radix, key, tweak); + return { + encrypt(x) { + const { u, round, destroy } = PQ(x); + let [A, B] = [x.slice(0, u), x.slice(u)]; + for (let i = 0; i < 10; i++) + [A, B] = round(A, B, i); + destroy(); + const res = A.concat(B); + A.fill(0); + B.fill(0); + return res; + }, + decrypt(x) { + const { u, round, destroy } = PQ(x); + // The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm; + // the differences are in Step 6, where: + // 1) the order of the indices is reversed, + // 2) the roles of A and B are swapped + // 3) modular addition is replaced by modular subtraction, in Step 6vi. + let [B, A] = [x.slice(0, u), x.slice(u)]; + for (let i = 9; i >= 0; i--) + [A, B] = round(A, B, i, true); + destroy(); + const res = B.concat(A); + A.fill(0); + B.fill(0); + return res; + }, + }; +} +// Binary wrapper uses little-endian bit order within each byte so bit 0 stays +// in the first numeral slot for this library-defined byte-array surface. +const binLE = { + encode(bytes) { + const x = []; + for (let i = 0; i < bytes.length; i++) { + for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) + x.push(tmp & 1); + } + return x; + }, + decode(b) { + if (!Array.isArray(b) || b.length % 8) + throw new Error('Invalid binary string'); + const res = new Uint8Array(b.length / 8); + for (let i = 0, j = 0; i < res.length; i++) { + res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3); + res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7); + } + return res; + }, +}; +/** + * Binary FPE-FF1 wrapper over byte arrays. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over byte arrays. + * @example + * Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key. + * + * ```ts + * import { BinaryFF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = BinaryFF1(key); + * ff1.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export function BinaryFF1(key, tweak = EMPTY_BUF) { + const ff1 = FF1(2, key, tweak); + return { + encrypt: (x) => binLE.decode(ff1.encrypt(binLE.encode(x))), + decrypt: (x) => binLE.decode(ff1.decrypt(binLE.encode(x))), + }; +} +//# sourceMappingURL=ff1.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/ff1.js.map b/node_modules/@noble/ciphers/ff1.js.map new file mode 100644 index 0000000..8a4131a --- /dev/null +++ b/node_modules/@noble/ciphers/ff1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ff1.js","sourceRoot":"","sources":["src/ff1.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAClC,OAAO,EACL,MAAM,EACN,OAAO,EACP,eAAe,EACf,KAAK,EACL,eAAe,GAIhB,MAAM,YAAY,CAAC;AAEpB,6FAA6F;AAC7F,4EAA4E;AAC5E,8FAA8F;AAC9F,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;AAE7C,gEAAgE;AAChE,wHAAwH;AAExH,MAAM,SAAS,GAAG,EAAE,CAAC;AAMrB,SAAS,GAAG,CAAC,CAAM,EAAE,CAAM;IACz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,CAAC,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QAC1E,CAAC;QACD,OAAO,GAAuB,CAAC;IACjC,CAAC;CACF,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,SAAS,CACvB,GAAqB,EACrB,QAA0B,SAAS;IAEnC,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;IAC/B,OAAO;QACL,OAAO,EAAE,CAAC,CAAmB,EAAoB,EAAE,CACjD,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAqB;QAChE,OAAO,EAAE,CAAC,CAAmB,EAAoB,EAAE,CACjD,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAqB;KACjD,CAAC;AACpB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.d.ts b/node_modules/@noble/ciphers/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/node_modules/@noble/ciphers/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.d.ts.map b/node_modules/@noble/ciphers/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/ciphers/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.js b/node_modules/@noble/ciphers/index.js new file mode 100644 index 0000000..c531a41 --- /dev/null +++ b/node_modules/@noble/ciphers/index.js @@ -0,0 +1,27 @@ +/** + * Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules. + * @example +```js +import { gcm, aessiv } from '@noble/ciphers/aes.js'; +import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; +import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305 +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js'; + +// Unauthenticated encryption: make sure to use HMAC or similar +import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js'; +import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js'; +import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js'; + +// KW +import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; + +// Utilities +import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js'; +import { poly1305 } from '@noble/ciphers/_poly1305.js'; +import { ghash, polyval } from '@noble/ciphers/_polyval.js'; +``` + * @module + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/index.js.map b/node_modules/@noble/ciphers/index.js.map new file mode 100644 index 0000000..b4a5484 --- /dev/null +++ b/node_modules/@noble/ciphers/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/package.json b/node_modules/@noble/ciphers/package.json new file mode 100644 index 0000000..2f17685 --- /dev/null +++ b/node_modules/@noble/ciphers/package.json @@ -0,0 +1,85 @@ +{ + "name": "@noble/ciphers", + "version": "2.2.0", + "description": "Audited & minimal JS implementation of Salsa20, ChaCha and AES", + "files": [ + "src", + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map" + ], + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "@scure/base": "2.0.0", + "@types/node": "25.3.0", + "fast-check": "4.2.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "node test/benchmark/noble.ts", + "bench:compare": "cd test/benchmark; npm install; node compare.ts", + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'", + "test": "node test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts", + "test:node20": "cd test; npx tsc; node compiled/test/index.js", + "test:slow": "node test/crosstest.test.ts slow" + }, + "exports": { + ".": "./index.js", + "./_arx.js": "./_arx.js", + "./_poly1305.js": "./_poly1305.js", + "./_polyval.js": "./_polyval.js", + "./aes.js": "./aes.js", + "./chacha.js": "./chacha.js", + "./ff1.js": "./ff1.js", + "./salsa.js": "./salsa.js", + "./utils.js": "./utils.js", + "./webcrypto.js": "./webcrypto.js" + }, + "engines": { + "node": ">= 20.19.0" + }, + "keywords": [ + "salsa20", + "chacha", + "aes", + "cryptography", + "crypto", + "noble", + "cipher", + "ciphers", + "xsalsa20", + "xchacha20", + "poly1305", + "xsalsa20poly1305", + "chacha20poly1305", + "xchacha20poly1305", + "secretbox", + "rijndael", + "siv", + "ff1" + ], + "homepage": "https://paulmillr.com/noble/", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-ciphers.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@noble/ciphers/salsa.d.ts b/node_modules/@noble/ciphers/salsa.d.ts new file mode 100644 index 0000000..a56e465 --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.d.ts @@ -0,0 +1,115 @@ +import { type ARXCipher, type TArg, type TRet, type XorStream } from './utils.ts'; +/** + * hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20. + * Identical to `hsalsa_small`. + * Need to find a way to merge it with `salsaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hsalsa(sigma, key, nonce, out); + * ``` + */ +export declare function hsalsa(s: TArg, k: TArg, i: TArg, out: TArg): void; +/** + * Salsa20 from original paper. 8-byte nonce. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * Only the low 32 bits of Salsa20's 64-bit counter state are exposed here; + * the high word stays zero and the implementation still caps the public + * value to 32 bits. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher. + * + * ```ts + * import { salsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * salsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export declare const salsa20: TRet; +/** + * XSalsa20 extended-nonce salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * @param key - 32-byte key. + * This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode. + * @param nonce - 24-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XSalsa20 and a random 24-byte nonce. + * + * ```ts + * import { xsalsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export declare const xsalsa20: TRet; +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * Also known as `secretbox` from libsodium / nacl. + * No AAD input is supported here. Caller-provided `output` buffers for + * `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the + * implementation uses a 32-byte leading scratch area before returning `+16`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with XSalsa20-Poly1305. + * + * ```ts + * import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xsalsa20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const xsalsa20poly1305: TRet; +/** + * Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl. + * Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium} + * for `crypto_box`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @returns Wrapper with `seal()` and `open()` helpers. + * @example + * Uses the libsodium-style `seal()` and `open()` wrapper. + * + * ```ts + * import { secretbox } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const box = secretbox(key, nonce); + * box.seal(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function secretbox(key: TArg, nonce: TArg): TRet<{ + seal: (plaintext: TArg, output?: TArg) => TRet; + open: (ciphertext: TArg, output?: TArg) => TRet; +}>; +//# sourceMappingURL=salsa.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.d.ts.map b/node_modules/@noble/ciphers/salsa.d.ts.map new file mode 100644 index 0000000..de0f2e0 --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"salsa.d.ts","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAqBA,OAAO,EAQL,KAAK,SAAS,EAEd,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,SAAS,EACf,MAAM,YAAY,CAAC;AAuHpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH,wBAAgB,MAAM,CACpB,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,WAAW,CAAC,GACvF,IAAI,CA8BN;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,SAAS,CAGlC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,CAGnC,CAAC;AAEH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,SAAS,CAwD5C,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,SAAS,CACvB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC;IACN,IAAI,EAAE,CAAC,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IACnF,IAAI,EAAE,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;CACrF,CAAC,CAMD"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.js b/node_modules/@noble/ciphers/salsa.js new file mode 100644 index 0000000..8574db2 --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.js @@ -0,0 +1,371 @@ +/** + * Salsa20 stream cipher, released in 2005. + * Salsa's goal was to implement AES replacement that does not rely on S-Boxes, + * which are hard to implement in a constant-time manner. + * Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones. + * + * - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20}, + * extended-nonce + * variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits, + * and became safe to be picked at random. + * - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305. + * We provide the alias and corresponding seal / open methods. + * "crypto_box" and "sealedbox" are available in package + * {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}. + * - Check out + * {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF} + * and {@link https://cr.yp.to/snuffle.html | website}. + * @module + */ +import { createCipher, rotl } from "./_arx.js"; +import { poly1305 } from "./_poly1305.js"; +import { abytes, clean, equalBytes, getOutput, swap32IfBE, swap8IfBE, wrapCipher, } from "./utils.js"; +/** + * Salsa20 core function. It is implemented twice: + * 1. Simple loop (salsaCore_small, hsalsa_small) + * 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read + * The specific implementation is selected in `createCipher` below. + * Performance numbers for 1MB inputs: + * * default x 779 ops/sec @ 1ms/op + * * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op + * * small x 132 ops/sec @ 7ms/op + */ +/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */ +function salsaQR(x, a, b, c, d) { + x[b] ^= rotl((x[a] + x[d]) | 0, 7); + x[c] ^= rotl((x[b] + x[a]) | 0, 9); + x[d] ^= rotl((x[c] + x[b]) | 0, 13); + x[a] ^= rotl((x[d] + x[c]) | 0, 18); +} +/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */ +function salsaRound(x, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + salsaQR(x, 0, 4, 8, 12); + salsaQR(x, 5, 9, 13, 1); + salsaQR(x, 10, 14, 2, 6); + salsaQR(x, 15, 3, 7, 11); + salsaQR(x, 0, 1, 2, 3); + salsaQR(x, 5, 6, 7, 4); + salsaQR(x, 10, 11, 8, 9); + salsaQR(x, 15, 12, 13, 14); + } +} +// Shared scratch for the unused auditability helper below; it would be +// non-reentrant under overlapping/nested calls, but current code doesn't invoke it. +const stmp = /* @__PURE__ */ new Uint32Array(16); +/** Small version of salsa without loop unrolling. Unused, provided for auditability. */ +// prettier-ignore +function salsa(s, k, i, out, isHSalsa = true, rounds = 20) { + // Create initial array using common pattern + const y = Uint32Array.from([ + s[0], k[0], k[1], k[2], // "expa" Key Key Key + k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce + i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key + k[5], k[6], k[7], s[3], // Key Key Key "te k" + ]); + const x = stmp; + x.set(y); + // const x = y.slice(); + salsaRound(x, rounds); + // hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state. + if (isHSalsa) { + const xindexes = [0, 5, 10, 15, 6, 7, 8, 9]; + for (let i = 0; i < 8; i++) + out[i] = x[xindexes[i]]; + } + else { + for (let i = 0; i < 16; i++) + out[i] = (y[i] + x[i]) | 0; + } +} +/** Identical to `salsaCore`. Unused. */ +// @ts-ignore +const salsaCore_small = (s, k, n, out, cnt, rounds) => salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds); +/** Identical to `hsalsa`. Unused. */ +// @ts-ignore +const hsalsa_small = salsa; +/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */ +// prettier-ignore +function salsaCore(s, k, n, out, cnt, rounds = 20) { + // Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero. + // Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}. + let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key + y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce + y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key + y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k" + // Save state to temporary variables + 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; + for (let r = 0; r < rounds; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +/** + * hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20. + * Identical to `hsalsa_small`. + * Need to find a way to merge it with `salsaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hsalsa(sigma, key, nonce, out); + * ``` + */ +// prettier-ignore +export function hsalsa(s, k, i, out) { + let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]); + for (let r = 0; r < 20; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + let oi = 0; + // XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material. + out[oi++] = x00; + out[oi++] = x05; + out[oi++] = x10; + out[oi++] = x15; + out[oi++] = x06; + out[oi++] = x07; + out[oi++] = x08; + out[oi++] = x09; + swap32IfBE(out); +} +/** + * Salsa20 from original paper. 8-byte nonce. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * Only the low 32 bits of Salsa20's 64-bit counter state are exposed here; + * the high word stays zero and the implementation still caps the public + * value to 32 bits. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher. + * + * ```ts + * import { salsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * salsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export const salsa20 = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); +/** + * XSalsa20 extended-nonce salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * @param key - 32-byte key. + * This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode. + * @param nonce - 24-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XSalsa20 and a random 24-byte nonce. + * + * ```ts + * import { xsalsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export const xsalsa20 = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * Also known as `secretbox` from libsodium / nacl. + * No AAD input is supported here. Caller-provided `output` buffers for + * `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the + * implementation uses a 32-byte leading scratch area before returning `+16`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with XSalsa20-Poly1305. + * + * ```ts + * import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xsalsa20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const xsalsa20poly1305 = /* @__PURE__ */ wrapCipher({ blockSize: 64, nonceLength: 24, tagLength: 16 }, (key, nonce) => { + // This borrows caller key/nonce buffers by reference; mutating them after construction changes + // later encrypt/decrypt outputs. + return { + encrypt(plaintext, output) { + // xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption. + // Unfortunately, makes it hard to separate tag calculation & encryption itself, + // because 32 bytes is half-block of 64-byte salsa. + // Need 32 extra bytes up front for the auth-key scratch area described above. + output = getOutput(plaintext.length + 32, output, false); + // output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext. + const authKey = output.subarray(0, 32); + const ciphPlaintext = output.subarray(32); + output.set(plaintext, 32); + // authKey is produced by xoring the first 32 bytes with zeros. + clean(authKey); + // output = stream ^ output; authKey = stream ^ zeros(32) + xsalsa20(key, nonce, output, output); + const tag = poly1305(ciphPlaintext, authKey); + output.set(tag, 16); + // Clean up auth-key remnants and the temporary tag copy. + clean(output.subarray(0, 16), tag); + // Return output[16..]. + return output.subarray(16); + }, + decrypt(ciphertext, output) { + // tmp part passed tag ciphertext + // [0..32] [32..48] [48..] + // Authenticate the ciphertext before decrypting it; on tag failure the scratch/output + // buffer may already contain copied ciphertext and derived auth-key material. + abytes(ciphertext); + output = getOutput(ciphertext.length + 32, output, false); + // output[0..32] is auth-key scratch, output[32..48] is passed tag, + // output[48..] is ciphertext then plaintext. + const tmp = output.subarray(0, 32); + const passedTag = output.subarray(32, 48); + const ciphPlaintext = output.subarray(48); + output.set(ciphertext, 32); + // authKey is produced by xoring the scratch area with zeros. + clean(tmp); + const authKey = xsalsa20(key, nonce, tmp, tmp); + const tag = poly1305(ciphPlaintext, authKey); + if (!equalBytes(passedTag, tag)) { + clean(output); + throw new Error('invalid tag'); + } + // output = stream ^ output[16..] + xsalsa20(key, nonce, output.subarray(16), output.subarray(16)); + clean(tmp, passedTag, tag); + // Return output[48..], skipping zeroized output[0..48]. + return ciphPlaintext; + }, + }; +}); +/** + * Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl. + * Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium} + * for `crypto_box`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @returns Wrapper with `seal()` and `open()` helpers. + * @example + * Uses the libsodium-style `seal()` and `open()` wrapper. + * + * ```ts + * import { secretbox } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const box = secretbox(key, nonce); + * box.seal(new Uint8Array([1, 2, 3])); + * ``` + */ +export function secretbox(key, nonce) { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt }; +} +//# sourceMappingURL=salsa.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/salsa.js.map b/node_modules/@noble/ciphers/salsa.js.map new file mode 100644 index 0000000..6a801a1 --- /dev/null +++ b/node_modules/@noble/ciphers/salsa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"salsa.js","sourceRoot":"","sources":["src/salsa.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAC1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,OAAO,CAAC,CAAC;YAC7C,IAAI,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,CAAC,EAAE,CAAC;gBAChC,KAAK,CAAC,MAAM,CAAC,CAAC;gBACd,MAAM,IAAI,KAAK,CAAC,aAAa,CAAC,CAAC;YACjC,CAAC;YACD,iCAAiC;YACjC,QAAQ,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,CAAC;YAC/D,KAAK,CAAC,GAAG,EAAE,SAAS,EAAE,GAAG,CAAC,CAAC;YAC3B,wDAAwD;YACxD,OAAO,aAAiC,CAAC;QAC3C,CAAC;KACwB,CAAC;AAC9B,CAAC,CACF,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,SAAS,CACvB,GAAqB,EACrB,KAAuB;IAKvB,MAAM,EAAE,GAAG,gBAAgB,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,EAGzC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/src/_arx.ts b/node_modules/@noble/ciphers/src/_arx.ts new file mode 100644 index 0000000..fd43e94 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_arx.ts @@ -0,0 +1,499 @@ +/** + * Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers. + +RFC8439 requires multi-step cipher stream, where +authKey starts with counter: 0, actual msg with counter: 1. + +For this, we need a way to re-use nonce / counter: + + const counter = new Uint8Array(4); + chacha(..., counter, ...); // counter is now 1 + chacha(..., counter, ...); // counter is now 2 + +This is complicated: + +- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB +- Original papers don't allow mutating counters +- Counter overflow is undefined [^1] +- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it +- Caveat: Cannot be re-used through all cases: +- * chacha has (counter | nonce) +- * xchacha has (nonce16 | counter | nonce16) +- Idea B: separate nonce / counter and provide separate API for counter re-use +- Caveat: there are different counter sizes depending on an algorithm. +- salsa & chacha also differ in structures of key & sigma: + salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3] + chacha: s(4) | k(8) | cnt(1) | nonce(3) + chacha20orig: s(4) | k(8) | cnt(2) | nonce(2) +- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)` +- Caveat: we can't re-use counter array + +xchacha uses the subkey and remaining 8 byte nonce with ChaCha20 as normal +(prefixed by 4 NUL bytes, since RFC8439 specifies a 12-byte nonce). +Counter overflow is undefined; see {@link https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/ | the CFRG thread}. +Current noble policy is strict non-wrap for the shared 32-bit counter path: +exported ARX ciphers reject initial `0xffffffff` and stop before any implicit +wrap back to zero. +See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2 | the XChaCha appendix} for the extended-nonce construction. + + * @module + */ +import { + type PRG, + type TArg, + type TRet, + type XorStream, + abool, + abytes, + anumber, + checkOpts, + clean, + copyBytes, + getOutput, + isAligned32, + isLE, + randomBytes, + swap32IfBE, + u32, +} from './utils.ts'; + +// Replaces `TextEncoder` for ASCII literals, which is enough for sigma constants. +// Non-ASCII input would not match UTF-8 `TextEncoder` output. +const encodeStr = (str: string) => Uint8Array.from(str.split(''), (c) => c.charCodeAt(0)); +// Raw `createCipher(...)` exports consume these native-endian `u32(...)` views directly. +// Public `wrapCipher(...)` APIs reject non-little-endian platforms before reaching this path. +// RFC 8439 §2.3 / RFC 7539 §2.3 only define the 256-bit-key constants; this 16-byte sigma is +// kept for legacy allowShortKeys Salsa/ChaCha variants. +const sigma16_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 16-byte k'))))(); +// RFC 8439 §2.3 / RFC 7539 §2.3 define words 0-3 as +// `0x61707865 0x3320646e 0x79622d32 0x6b206574`, i.e. `expand 32-byte k`. +const sigma32_32 = /* @__PURE__ */ (() => swap32IfBE(u32(encodeStr('expand 32-byte k'))))(); + +/** + * Rotates a 32-bit word left. + * @param a - Input word. + * @param b - Rotation count in bits. + * @returns Rotated 32-bit word. + * @example + * Moves the top byte of `0x12345678` into the low byte position. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export function rotl(a: number, b: number): number { + return (a << b) | (a >>> (32 - b)); +} + +/** + * ARX core function operating on 32-bit words. Ciphers must use u32 for efficiency. + * @param sigma - Sigma constants for the selected cipher layout. + * @param key - Expanded key words. + * @param nonce - Nonce and counter words prepared for the round function. + * @param output - Output block written in place. + * @param counter - Block counter value. + * @param rounds - Optional round count override. + */ +export type CipherCoreFn = ( + sigma: TArg, + key: TArg, + nonce: TArg, + output: TArg, + counter: number, + rounds?: number +) => void; + +/** + * Nonce-extension function used by XChaCha and XSalsa. + * @param sigma - Sigma constants for the selected cipher layout. + * @param key - Expanded key words. + * @param input - Input nonce words used for subkey derivation. + * @param output - Output buffer written with the derived nonce words. + */ +export type ExtendNonceFn = ( + sigma: TArg, + key: TArg, + input: TArg, + output: TArg +) => void; + +/** ARX cipher options. + * * `allowShortKeys` for 16-byte keys + * * `counterLength` in bytes + * * `counterRight`: right: `nonce|counter`; left: `counter|nonce` + * */ +export type CipherOpts = { + /** Whether 16-byte keys are accepted for legacy Salsa and ChaCha variants. */ + allowShortKeys?: boolean; + /** Optional nonce-expansion hook used by extended-nonce variants. */ + extendNonceFn?: ExtendNonceFn; + /** Counter length in bytes inside the nonce/counter layout. */ + counterLength?: number; + /** Whether the layout is `nonce|counter` instead of `counter|nonce`. */ + counterRight?: boolean; + /** Number of core rounds to execute. */ + rounds?: number; +}; + +// Salsa and Chacha block length is always 512-bit +const BLOCK_LEN = 64; +// RFC 8439 §2.2 / RFC 7539 §2.2: the ChaCha state has 16 32-bit words. +const BLOCK_LEN32 = 16; + +// Counter policy for the shared public `counter` argument: +// - RFC/IETF ChaCha20 uses a 32-bit counter. +// - OpenSSL/Node `chacha20` instead treat the full 16-byte IV as a 128-bit +// counter state and carry into the next word. +// - Raw `chacha20orig`, `salsa20`, `xsalsa20`, and `xchacha20` use 64-bit counters in libsodium +// and libtomcrypt, while some libs (for example libtomcrypt's RFC/IETF path) reject the max +// boundary instead of carrying. +// - AEAD wrappers diverge too: libsodium `xchacha20poly1305` uses the IETF payload counter from +// block 1, while `secretstream_xchacha20poly1305` is a different protocol with rekey/reset. +// Noble intentionally throws instead of silently picking one wrap model for users. In the default +// path, even a 32-bit boundary would take 2^32 blocks * 64 bytes = 256 GiB, which is practically +// unreachable for normal JS callers; advanced users who pass `counter` explicitly can implement +// whatever wider carry / wrap policy they need on top. +const MAX_COUNTER = /* @__PURE__ */ (() => 2 ** 32 - 1)(); +const U32_EMPTY = /* @__PURE__ */ Uint32Array.of(); +function runCipher( + core: TArg, + sigma: TArg, + key: TArg, + nonce: TArg, + data: TArg, + output: TArg, + counter: number, + rounds: number +): void { + const len = data.length; + const block = new Uint8Array(BLOCK_LEN); + const b32 = u32(block); + // Make sure that buffers aligned to 4 bytes + const isAligned = isLE && isAligned32(data) && isAligned32(output); + const d32 = isAligned ? u32(data) : U32_EMPTY; + const o32 = isAligned ? u32(output) : U32_EMPTY; + // RFC 8439 §2.4.1 / RFC 7539 §2.4.1 allow XORing one keystream block at a time and + // truncating the final partial block instead of materializing the whole keystream. + if (!isLE) { + for (let pos = 0; pos < len; counter++) { + core( + sigma as TRet, + key as TRet, + nonce as TRet, + b32, + counter, + rounds + ); + // RFC 8439 §2.4 / RFC 7539 §2.4 serialize keystream words in little-endian order. + swap32IfBE(b32); + if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } + return; + } + for (let pos = 0; pos < len; counter++) { + core( + sigma as TRet, + key as TRet, + nonce as TRet, + b32, + counter, + rounds + ); + // See MAX_COUNTER policy note above: never silently wrap the shared public counter. + if (counter >= MAX_COUNTER) throw new Error('arx: counter overflow'); + const take = Math.min(BLOCK_LEN, len - pos); + // aligned to 4 bytes + if (isAligned && take === BLOCK_LEN) { + const pos32 = pos / 4; + if (pos % 4 !== 0) throw new Error('arx: invalid block position'); + for (let j = 0, posj: number; j < BLOCK_LEN32; j++) { + posj = pos32 + j; + o32[posj] = d32[posj] ^ b32[j]; + } + pos += BLOCK_LEN; + continue; + } + for (let j = 0, posj; j < take; j++) { + posj = pos + j; + output[posj] = data[posj] ^ block[j]; + } + pos += take; + } +} + +/** + * Creates an ARX stream cipher from a 32-bit core permutation. + * Used internally to build the exported Salsa and ChaCha stream ciphers. + * @param core - Core function that fills one keystream block. + * @param opts - Cipher layout and nonce-extension options. See {@link CipherOpts}. + * @returns Stream cipher function over byte arrays. + * @throws If the core callback, key size, counter, or output sizing is invalid. {@link Error} + */ +export function createCipher(core: TArg, opts: TArg): TRet { + const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts( + { allowShortKeys: false, counterLength: 8, counterRight: false, rounds: 20 }, + opts + ); + if (typeof core !== 'function') throw new Error('core must be a function'); + anumber(counterLength); + anumber(rounds); + abool(counterRight); + abool(allowShortKeys); + return ( + key: TArg, + nonce: TArg, + data: TArg, + output?: TArg, + counter = 0 + ): TRet => { + abytes(key, undefined, 'key'); + abytes(nonce, undefined, 'nonce'); + abytes(data, undefined, 'data'); + const len = data.length; + // Raw XorStream APIs return ciphertext/plaintext bytes directly, so caller-provided outputs + // must match the logical result length exactly instead of returning an oversized workspace. + output = getOutput(len, output, false); + anumber(counter); + // See MAX_COUNTER policy note above: reject advanced explicit-counter requests before any wrap. + if (counter < 0 || counter >= MAX_COUNTER) throw new Error('arx: counter overflow'); + const toClean = []; + + // Key & sigma + // key=16 -> sigma16, k=key|key + // key=32 -> sigma32, k=key + let l = key.length; + let k: Uint8Array; + let sigma: Uint32Array; + if (l === 32) { + // Copy caller keys too: big-endian normalization, extended-nonce subkey derivation, and + // final clean(...) all mutate or wipe the temporary buffer in place. + toClean.push((k = copyBytes(key))); + sigma = sigma32_32; + } else if (l === 16 && allowShortKeys) { + k = new Uint8Array(32); + k.set(key); + k.set(key, 16); + sigma = sigma16_32; + toClean.push(k); + } else { + abytes(key, 32, 'arx key'); + throw new Error('invalid key size'); + // throw new Error(`"arx key" expected Uint8Array of length 32, got length=${l}`); + } + + // Nonce + // salsa20: 8 (8-byte counter) + // chacha20orig: 8 (8-byte counter) + // chacha20: 12 (4-byte counter) + // xsalsa20: 24 (16 -> hsalsa, 8 -> old nonce) + // xchacha20: 24 (16 -> hchacha, 8 -> old nonce) + // Copy before taking u32(...) views on misaligned inputs, and on big-endian so later + // swap32IfBE(...) never mutates caller nonce bytes in place. + if (!isLE || !isAligned32(nonce)) toClean.push((nonce = copyBytes(nonce))); + + let k32 = u32(k); + // hsalsa & hchacha: handle extended nonce + if (extendNonceFn) { + if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`); + const n16 = nonce.subarray(0, 16); + if (isLE) extendNonceFn(sigma as TRet, k32, u32(n16), k32); + else { + const sigmaRaw = swap32IfBE(Uint32Array.from(sigma)); + extendNonceFn(sigmaRaw, k32, u32(n16), k32); + clean(sigmaRaw); + swap32IfBE(k32); + } + nonce = nonce.subarray(16); + } else if (!isLE) swap32IfBE(k32); + + // Handle nonce counter + const nonceNcLen = 16 - counterLength; + if (nonceNcLen !== nonce.length) + throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`); + + // Normalize 64-bit-nonce layouts to the 12-byte core input: ChaCha/XChaCha prefix 4 zero + // counter bytes, while Salsa/XSalsa append them after the nonce words. + if (nonceNcLen !== 12) { + const nc = new Uint8Array(12); + nc.set(nonce, counterRight ? 0 : 12 - nonce.length); + nonce = nc; + toClean.push(nonce); + } + const n32 = swap32IfBE(u32(nonce)); + // Ensure temporary key/nonce copies are wiped even if the remaining + // runtime guard in runCipher(...) throws on counter overflow. + try { + runCipher(core, sigma, k32, n32, data, output, counter, rounds); + return output as TRet; + } finally { + clean(...toClean); + } + }; +} + +/** Internal class which wraps chacha20 or chacha8 to create CSPRNG. */ +export class _XorStreamPRG implements PRG { + readonly blockLen: number; + readonly keyLen: number; + readonly nonceLen: number; + private state: TRet; + private buf: TRet; + private key: TRet; + private nonce: TRet; + private pos: number; + private ctr: number; + private cipher: TArg; + constructor( + cipher: TArg, + blockLen: number, + keyLen: number, + nonceLen: number, + seed: TArg + ) { + this.cipher = cipher; + this.blockLen = blockLen; + this.keyLen = keyLen; + this.nonceLen = nonceLen; + this.state = new Uint8Array(this.keyLen + this.nonceLen) as TRet; + this.reseed(seed); + this.ctr = 0; + this.pos = this.blockLen; + this.buf = new Uint8Array(this.blockLen) as TRet; + // Keep a single key||nonce backing buffer so reseed/addEntropy/clean update the live cipher + // inputs in place through these subarray views. + this.key = this.state.subarray(0, this.keyLen) as TRet; + this.nonce = this.state.subarray(this.keyLen) as TRet; + } + private reseed(seed: TArg) { + abytes(seed); + if (!seed || seed.length === 0) throw new Error('entropy required'); + // Mix variable-length entropy cyclically across the whole key||nonce state, then restart the + // keystream so buffered leftovers from the previous state are never reused. + for (let i = 0; i < seed.length; i++) this.state[i % this.state.length] ^= seed[i]; + this.ctr = 0; + this.pos = this.blockLen; + } + addEntropy(seed: TArg): void { + // Reject empty entropy before re-keying, otherwise a throwing call would still advance state. + abytes(seed); + if (seed.length === 0) throw new Error('entropy required'); + // Re-key from the current stream first, then mix external entropy into the fresh key||nonce + // state through reseed() so stale buffered bytes are discarded. + this.state.set(this.randomBytes(this.state.length)); + this.reseed(seed); + } + randomBytes(len: number): TRet { + anumber(len); + if (len === 0) return new Uint8Array(0) as TRet; + const avail = this.pos < this.blockLen ? this.blockLen - this.pos : 0; + const blocks = Math.ceil(Math.max(0, len - avail) / this.blockLen); + // Preflight overflow so failed reads don't partially consume keystream + // and leave the PRG repeating blocks. + if (blocks > 0 && this.ctr > MAX_COUNTER - blocks) throw new Error('arx: counter overflow'); + const out = new Uint8Array(len); + let outPos = 0; + // `out` starts zero-filled, and `buf.fill(0)` below does the same for leftovers: XOR-stream + // ciphers then emit raw keystream bytes directly into those buffers. + // Serve buffered leftovers first so split reads stay identical to one larger read. + if (this.pos < this.blockLen) { + const take = Math.min(len, this.blockLen - this.pos); + out.set(this.buf.subarray(this.pos, this.pos + take), 0); + this.pos += take; + outPos += take; + if (outPos === len) return out as TRet; // fast path + } + // Full blocks directly to out + const full = Math.floor((len - outPos) / this.blockLen); + if (full > 0) { + const blockBytes = full * this.blockLen; + const b = out.subarray(outPos, outPos + blockBytes); + this.cipher(this.key, this.nonce, b as TRet, b as TRet, this.ctr); + this.ctr += full; + outPos += blockBytes; + } + // Save leftovers + const left = len - outPos; + if (left > 0) { + this.buf.fill(0); + // NOTE: cipher will handle overflow + this.cipher( + this.key, + this.nonce, + this.buf as TRet, + this.buf as TRet, + this.ctr++ + ); + out.set(this.buf.subarray(0, left), outPos); + this.pos = left; + } + return out as TRet; + } + // Clone seeds the new instance from this stream, so the source PRG advances too. + clone(): _XorStreamPRG { + return new _XorStreamPRG( + this.cipher, + this.blockLen, + this.keyLen, + this.nonceLen, + this.randomBytes(this.state.length) + ); + } + // Zeroes the current state and leftover buffer, but does not make the instance unusable: + // Later reads first drain zeros from the cleared buffer and then continue + // from zero key||nonce state. + clean(): void { + this.pos = 0; + this.ctr = 0; + this.buf.fill(0); + this.state.fill(0); + } +} + +/** + * PRG constructor backed by an ARX stream cipher. + * @param seed - Optional seed bytes mixed into the initial state. When omitted, exactly 32 + * random bytes are mixed in by default: larger states keep a zero tail, while smaller states + * wrap those bytes through `reseed()`'s XOR schedule. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + */ +export type XorPRG = (seed?: TArg) => TRet<_XorStreamPRG>; + +/** + * Creates a PRG constructor from a stream cipher. + * @param cipher - Stream cipher used to fill output blocks. + * @param blockLen - Keystream block length in bytes. + * @param keyLen - Internal key length in bytes. + * @param nonceLen - Internal nonce length in bytes. + * @returns PRG factory for seeded concrete `_XorStreamPRG` instances. + * @example + * Builds a PRG from XChaCha20 and reads bytes from a randomly seeded instance. + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { createPRG } from '@noble/ciphers/_arx.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const init = createPRG(xchacha20, 64, 32, 24); + * const prg = init(seed); + * prg.randomBytes(8); + * ``` + */ +export const createPRG = ( + cipher: TArg, + blockLen: number, + keyLen: number, + nonceLen: number +): TRet => { + return ((seed: TArg = randomBytes(32)): TRet<_XorStreamPRG> => + new _XorStreamPRG( + cipher, + blockLen, + keyLen, + nonceLen, + seed + ) as TRet<_XorStreamPRG>) as TRet; +}; diff --git a/node_modules/@noble/ciphers/src/_poly1305.ts b/node_modules/@noble/ciphers/src/_poly1305.ts new file mode 100644 index 0000000..351a479 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_poly1305.ts @@ -0,0 +1,399 @@ +/** + * Poly1305 ({@link https://cr.yp.to/mac/poly1305-20050329.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Poly1305 | wiki}) + * is a fast and parallel secret-key message-authentication code suitable for + * a wide variety of applications. It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and is now used in TLS 1.3. + * + * Polynomial MACs are not perfect for every situation: + * they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes. + * See {@link https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/ | the invisible salamanders attack writeup}. + * To combat invisible salamanders, `hash(key)` can be included in ciphertext, + * however, this would violate ciphertext indistinguishability: + * an attacker would know which key was used - so `HKDF(key, i)` + * could be used instead. + * + * Check out the {@link https://cr.yp.to/mac.html | original website}. + * Based on public-domain {@link https://github.com/floodyberry/poly1305-donna | poly1305-donna}. + * @module + */ +// prettier-ignore +import { + abytes, aexists, aoutput, bytesToHex, + clean, concatBytes, copyBytes, hexToNumber, numberToBytesBE, + wrapMacConstructor, type CMac, type IHash2, type TArg, type TRet +} from './utils.ts'; + +// Little-endian 2-byte load used by the Poly1305 limb decomposition. +function u8to16(a: TArg, i: number) { + return (a[i++] & 0xff) | ((a[i++] & 0xff) << 8); +} + +function bytesToNumberLE(bytes: TArg): bigint { + return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse())); +} + +/** Small version of `poly1305` without loop unrolling. Unused, provided for auditability. */ +function poly1305_small(msg: TArg, key: TArg): TRet { + abytes(msg); + abytes(key, 32, 'key'); + const POW_2_130_5 = BigInt(2) ** BigInt(130) - BigInt(5); // 2^130-5 + const POW_2_128_1 = BigInt(2) ** BigInt(128) - BigInt(1); // 2^128-1 + const CLAMP_R = BigInt('0x0ffffffc0ffffffc0ffffffc0fffffff'); + const r = bytesToNumberLE(key.subarray(0, 16)) & CLAMP_R; + const s = bytesToNumberLE(key.subarray(16)); + // Process by 16 byte chunks + let acc = BigInt(0); + for (let i = 0; i < msg.length; i += 16) { + const m = msg.subarray(i, i + 16); + // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 append [0x01] to each chunk before multiplying by r. + const n = bytesToNumberLE(m) | (BigInt(1) << BigInt(8 * m.length)); + acc = ((acc + n) * r) % POW_2_130_5; + } + const res = (acc + s) & POW_2_128_1; + // RFC 8439 §2.5 / RFC 7539 §2.5 serialize the low 128 bits in little-endian order. + return numberToBytesBE(res, 16).reverse() as TRet; // LE +} + +// Can be used to replace `computeTag` in chacha.ts. Unused, provided for auditability. +// @ts-expect-error +function poly1305_computeTag_small( + authKey: TArg, + // AEAD trailer must already be the 16-byte length block: + // 8-byte little-endian AAD length || 8-byte little-endian ciphertext length. + lengths: TArg, + ciphertext: TArg, + AAD?: TArg +): TRet { + // RFC 8439 §2.8.1 / RFC 7539 §2.8.1 MAC input is + // AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || lengths. + const res = []; + const updatePadded2 = (msg: TArg) => { + res.push(msg); + const leftover = msg.length % 16; + // RFC 8439 §2.8.1 / RFC 7539 §2.8.1: pad16(x) is empty for aligned + // inputs, else 16-(len%16) zero bytes. + if (leftover) res.push(new Uint8Array(16).slice(leftover)); + }; + if (AAD) updatePadded2(AAD); + updatePadded2(ciphertext); + res.push(lengths); + return poly1305_small(concatBytes(...res), authKey); +} + +/** + * Incremental Poly1305 MAC state. + * Prefer `poly1305()` for one-shot use. + * @param key - 32-byte Poly1305 one-time key. + * @example + * Feeds one chunk into an incremental Poly1305 state with a fresh one-time key. + * + * ```ts + * import { Poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const mac = new Poly1305(key); + * mac.update(new Uint8Array([1, 2, 3])); + * mac.digest(); + * ``` + */ +export class Poly1305 implements IHash2 { + readonly blockLen = 16; + readonly outputLen = 16; + private buffer = new Uint8Array(16); + private r = new Uint16Array(10); // Allocating 1 array with .subarray() here is slower than 3 + private h = new Uint16Array(10); + private pad = new Uint16Array(8); + private pos = 0; + protected finished = false; + protected destroyed = false; + + // Can be speed-up using BigUint64Array, at the cost of complexity + constructor(key: TArg) { + key = copyBytes(abytes(key, 32, 'key')); + const t0 = u8to16(key, 0); + const t1 = u8to16(key, 2); + const t2 = u8to16(key, 4); + const t3 = u8to16(key, 6); + const t4 = u8to16(key, 8); + const t5 = u8to16(key, 10); + const t6 = u8to16(key, 12); + const t7 = u8to16(key, 14); + + // RFC 8439 §2.5.1 / RFC 7539 §2.5.1 clamp r before multiplication. + // These masks unpack that clamped value into 13-bit limbs, while pad + // keeps the raw s half for finalize(). + // {@link https://github.com/floodyberry/poly1305-donna/blob/e6ad6e091d30d7f4ec2d4f978be1fcfcbce72781/poly1305-donna-16.h#L47 | poly1305-donna reference} + this.r[0] = t0 & 0x1fff; + this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff; + this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03; + this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff; + this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff; + this.r[5] = (t4 >>> 1) & 0x1ffe; + this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff; + this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81; + this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff; + this.r[9] = (t7 >>> 5) & 0x007f; + for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i); + } + + private process(data: TArg, offset: number, isLast = false) { + // RFC 8439 §2.5 / §2.5.1 and RFC 7539 §2.5 / §2.5.1 add an extra high + // bit to every full 16-byte block. The final partial block gets its + // explicit `1` byte during digestInto(), so `hibit` stays zero there. + const hibit = isLast ? 0 : 1 << 11; + const { h, r } = this; + const r0 = r[0]; + const r1 = r[1]; + const r2 = r[2]; + const r3 = r[3]; + const r4 = r[4]; + const r5 = r[5]; + const r6 = r[6]; + const r7 = r[7]; + const r8 = r[8]; + const r9 = r[9]; + + const t0 = u8to16(data, offset + 0); + const t1 = u8to16(data, offset + 2); + const t2 = u8to16(data, offset + 4); + const t3 = u8to16(data, offset + 6); + const t4 = u8to16(data, offset + 8); + const t5 = u8to16(data, offset + 10); + const t6 = u8to16(data, offset + 12); + const t7 = u8to16(data, offset + 14); + + let h0 = h[0] + (t0 & 0x1fff); + let h1 = h[1] + (((t0 >>> 13) | (t1 << 3)) & 0x1fff); + let h2 = h[2] + (((t1 >>> 10) | (t2 << 6)) & 0x1fff); + let h3 = h[3] + (((t2 >>> 7) | (t3 << 9)) & 0x1fff); + let h4 = h[4] + (((t3 >>> 4) | (t4 << 12)) & 0x1fff); + let h5 = h[5] + ((t4 >>> 1) & 0x1fff); + let h6 = h[6] + (((t4 >>> 14) | (t5 << 2)) & 0x1fff); + let h7 = h[7] + (((t5 >>> 11) | (t6 << 5)) & 0x1fff); + let h8 = h[8] + (((t6 >>> 8) | (t7 << 8)) & 0x1fff); + let h9 = h[9] + ((t7 >>> 5) | hibit); + + let c = 0; + + let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6); + c = d0 >>> 13; + d0 &= 0x1fff; + d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1); + c += d0 >>> 13; + d0 &= 0x1fff; + + let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7); + c = d1 >>> 13; + d1 &= 0x1fff; + d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2); + c += d1 >>> 13; + d1 &= 0x1fff; + + let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8); + c = d2 >>> 13; + d2 &= 0x1fff; + d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3); + c += d2 >>> 13; + d2 &= 0x1fff; + + let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9); + c = d3 >>> 13; + d3 &= 0x1fff; + d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4); + c += d3 >>> 13; + d3 &= 0x1fff; + + let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0; + c = d4 >>> 13; + d4 &= 0x1fff; + d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5); + c += d4 >>> 13; + d4 &= 0x1fff; + + let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1; + c = d5 >>> 13; + d5 &= 0x1fff; + d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6); + c += d5 >>> 13; + d5 &= 0x1fff; + + let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2; + c = d6 >>> 13; + d6 &= 0x1fff; + d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7); + c += d6 >>> 13; + d6 &= 0x1fff; + + let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3; + c = d7 >>> 13; + d7 &= 0x1fff; + d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8); + c += d7 >>> 13; + d7 &= 0x1fff; + + let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4; + c = d8 >>> 13; + d8 &= 0x1fff; + d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9); + c += d8 >>> 13; + d8 &= 0x1fff; + + let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5; + c = d9 >>> 13; + d9 &= 0x1fff; + d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0; + c += d9 >>> 13; + d9 &= 0x1fff; + + c = ((c << 2) + c) | 0; + c = (c + d0) | 0; + d0 = c & 0x1fff; + c = c >>> 13; + d1 += c; + + h[0] = d0; + h[1] = d1; + h[2] = d2; + h[3] = d3; + h[4] = d4; + h[5] = d5; + h[6] = d6; + h[7] = d7; + h[8] = d8; + h[9] = d9; + } + + private finalize() { + const { h, pad } = this; + const g = new Uint16Array(10); + let c = h[1] >>> 13; + h[1] &= 0x1fff; + for (let i = 2; i < 10; i++) { + h[i] += c; + c = h[i] >>> 13; + h[i] &= 0x1fff; + } + h[0] += c * 5; + c = h[0] >>> 13; + h[0] &= 0x1fff; + h[1] += c; + c = h[1] >>> 13; + h[1] &= 0x1fff; + h[2] += c; + + // RFC 8439 §2.5 / RFC 7539 §2.5 reduce modulo 2^130-5 before repacking + // to 16-bit words and adding the raw s half. + g[0] = h[0] + 5; + c = g[0] >>> 13; + g[0] &= 0x1fff; + for (let i = 1; i < 10; i++) { + g[i] = h[i] + c; + c = g[i] >>> 13; + g[i] &= 0x1fff; + } + g[9] -= 1 << 13; + + let mask = (c ^ 1) - 1; + for (let i = 0; i < 10; i++) g[i] &= mask; + mask = ~mask; + for (let i = 0; i < 10; i++) h[i] = (h[i] & mask) | g[i]; + h[0] = (h[0] | (h[1] << 13)) & 0xffff; + h[1] = ((h[1] >>> 3) | (h[2] << 10)) & 0xffff; + h[2] = ((h[2] >>> 6) | (h[3] << 7)) & 0xffff; + h[3] = ((h[3] >>> 9) | (h[4] << 4)) & 0xffff; + h[4] = ((h[4] >>> 12) | (h[5] << 1) | (h[6] << 14)) & 0xffff; + h[5] = ((h[6] >>> 2) | (h[7] << 11)) & 0xffff; + h[6] = ((h[7] >>> 5) | (h[8] << 8)) & 0xffff; + h[7] = ((h[8] >>> 8) | (h[9] << 5)) & 0xffff; + + let f = h[0] + pad[0]; + h[0] = f & 0xffff; + for (let i = 1; i < 8; i++) { + f = (((h[i] + pad[i]) | 0) + (f >>> 16)) | 0; + h[i] = f & 0xffff; + } + clean(g); + } + update(data: TArg): this { + aexists(this); + abytes(data); + data = copyBytes(data); + const { buffer, blockLen } = this; + const len = data.length; + + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path: we have at least one block in input + if (take === blockLen) { + for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(buffer, 0, false); + this.pos = 0; + } + } + return this; + } + destroy(): void { + // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too. + this.destroyed = true; + clean(this.h, this.r, this.buffer, this.pad); + } + digestInto(out: TArg): void { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, h } = this; + let { pos } = this; + if (pos) { + // RFC 8439 §2.5 / RFC 7539 §2.5: the final short block appends a + // single `0x01` byte and zero-fills the remaining bytes before the + // last multiplication step. + buffer[pos++] = 1; + for (; pos < 16; pos++) buffer[pos] = 0; + this.process(buffer, 0, true); + } + this.finalize(); + let opos = 0; + for (let i = 0; i < 8; i++) { + out[opos++] = h[i] >>> 0; + out[opos++] = h[i] >>> 8; + } + } + digest(): TRet { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy out before destroy() zeroes the internal buffer. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res as TRet; + } +} + +/** One-shot keyed hash helper with `.create()`. */ +export type CHash = CMac; + +/** + * Poly1305 MAC from RFC 8439. + * @param msg - Message bytes to authenticate. + * @param key - 32-byte Poly1305 one-time key. + * @returns 16-byte authentication tag. + * @example + * Authenticates one message with a one-shot Poly1305 call and a fresh key. + * + * ```ts + * import { poly1305 } from '@noble/ciphers/_poly1305.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * poly1305(new Uint8Array(), key); + * ``` + */ +export const poly1305: TRet = /* @__PURE__ */ wrapMacConstructor( + 32, + (key: TArg) => new Poly1305(key) +); diff --git a/node_modules/@noble/ciphers/src/_polyval.ts b/node_modules/@noble/ciphers/src/_polyval.ts new file mode 100644 index 0000000..f94b885 --- /dev/null +++ b/node_modules/@noble/ciphers/src/_polyval.ts @@ -0,0 +1,381 @@ +/** + * GHash from AES-GCM and its little-endian "mirror image" Polyval from AES-SIV. + * + * Implemented in terms of GHash with conversion function for keys + * GCM GHASH from + * {@link https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf | NIST SP800-38d}, + * SIV from + * {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * + * GHASH modulo: x^128 + x^7 + x^2 + x + 1 + * POLYVAL modulo: x^128 + x^127 + x^126 + x^121 + 1 + * + * @module + */ +import { + abytes, + aexists, + aoutput, + clean, + copyBytes, + createView, + swap32IfBE, + swap8IfBE, + u32, + wrapMacConstructor, + type CMac, + type IHash2, + type TArg, + type TRet, +} from './utils.ts'; + +const BLOCK_SIZE = 16; +// TODO: rewrite +// temporary padding buffer +// ZEROS32 aliases these bytes, so clean(ZEROS32) also resets this shared tail-padding scratch. +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +const ZEROS32 = /* @__PURE__ */ u32(ZEROS16); +// GHASH reduces modulo x^128 + x^7 + x^2 + x + 1, so the low-degree terms +// x^7 + x^2 + x + 1 become bits `11100001` = 0xe1 in R = 0xe1 || 0^120. +const POLY = 0xe1; + +// v = 2*v % POLY +// NOTE: because x + x = 0 (add/sub is same), mul2(x) != x+x +// Montgomery ladder can multiply any field element with this doubling step; +// addition stays simple xor. +const mul2 = (s0: number, s1: number, s2: number, s3: number) => { + const hiBit = s3 & 1; + return { + s3: (s2 << 31) | (s3 >>> 1), + s2: (s1 << 31) | (s2 >>> 1), + s1: (s0 << 31) | (s1 >>> 1), + // NIST SP 800-38D §6.3 applies `V >> 1` and XORs R on carry. In this + // 4x32-bit split, R = 0xe1 || 0^120 lives in the top byte of s0. + s0: (s0 >>> 1) ^ ((POLY << 24) & -(hiBit & 1)), // reduce % poly + }; +}; + +// Per-word part of RFC 8452 `ByteReverse`; callers also reverse the 32-bit word order. +const swapLE = (n: number) => + (((n >>> 0) & 0xff) << 24) | + (((n >>> 8) & 0xff) << 16) | + (((n >>> 16) & 0xff) << 8) | + ((n >>> 24) & 0xff) | + 0; +// POLYVAL first applies RFC 8452's per-word byte reversal, then re-normalizes +// host-endian u32 loads to the little-endian word value `_updateBlock()` expects. +const swap8IfLE = (n: number) => swap8IfBE(swapLE(n)); + +/** + * `mulX_GHASH(ByteReverse(H))` from RFC 8452 Appendix A. + * @param k mutated in place + */ +export function _toGHASHKey(k: TArg): TRet { + // The input is the original POLYVAL key H; reverse() materializes + // RFC 8452's `ByteReverse(H)` before the GHASH mulX step. + k.reverse(); + const hiBit = k[15] & 1; + // k >>= 1 + let carry = 0; + for (let i = 0; i < k.length; i++) { + const t = k[i]; + k[i] = (t >>> 1) | carry; + carry = (t & 1) << 7; + } + k[0] ^= -hiBit & 0xe1; // if (hiBit) n ^= 0xe1000000000000000000000000000000; + return k as TRet; +} + +type Value = { s0: number; s1: number; s2: number; s3: number }; + +// Precompute-window heuristic only: larger inputs trade memory for fewer table lookups. +// Any caller-provided length hint still collapses to one of the supported windows {2, 4, 8}. +const estimateWindow = (bytes: number) => { + if (bytes > 64 * 1024) return 8; + if (bytes > 1024) return 4; + return 2; +}; + +/** + * Incremental GHASH state for AES-GCM. + * @param key - 16-byte GHASH key. + * @param expectedLength - Expected message length for table sizing. + * Chunking is segment-based, not hash-streaming: every `update()` call is zero-padded + * to the next 16-byte boundary before it is absorbed. This matches the internal AES/GCM + * use where AAD, payload, and length block are separate padded segments. + * @example + * Feeds one ciphertext block into an incremental GHASH state with a fresh hash key. + * + * ```ts + * import { GHASH } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new GHASH(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export class GHASH implements IHash2 { + readonly blockLen: number = BLOCK_SIZE; + readonly outputLen: number = BLOCK_SIZE; + protected s0 = 0; + protected s1 = 0; + protected s2 = 0; + protected s3 = 0; + protected finished = false; + protected destroyed = false; + protected t: Value[]; + private W: number; + private windowSize: number; + // We select bits per window adaptively based on expectedLength + constructor(key: TArg, expectedLength?: number) { + abytes(key, 16, 'key'); + key = copyBytes(key); + const kView = createView(key); + let k0 = kView.getUint32(0, false); + let k1 = kView.getUint32(4, false); + let k2 = kView.getUint32(8, false); + let k3 = kView.getUint32(12, false); + // generate table of doubled keys (half of montgomery ladder) + const doubles: Value[] = []; + for (let i = 0; i < 128; i++) { + doubles.push({ s0: swapLE(k0), s1: swapLE(k1), s2: swapLE(k2), s3: swapLE(k3) }); + ({ s0: k0, s1: k1, s2: k2, s3: k3 } = mul2(k0, k1, k2, k3)); + } + const W = estimateWindow(expectedLength || 1024); + if (![1, 2, 4, 8].includes(W)) + throw new Error('ghash: invalid window size, expected 2, 4 or 8'); + this.W = W; + const bits = 128; // always 128 bits; + const windows = bits / W; + const windowSize = (this.windowSize = 2 ** W); + const items: Value[] = []; + // Create precompute table for window of W bits + for (let w = 0; w < windows; w++) { + // truth table: 00, 01, 10, 11 + for (let byte = 0; byte < windowSize; byte++) { + // prettier-ignore + let s0 = 0, s1 = 0, s2 = 0, s3 = 0; + for (let j = 0; j < W; j++) { + const bit = (byte >>> (W - j - 1)) & 1; + if (!bit) continue; + const { s0: d0, s1: d1, s2: d2, s3: d3 } = doubles[W * w + j]; + ((s0 ^= d0), (s1 ^= d1), (s2 ^= d2), (s3 ^= d3)); + } + items.push({ s0, s1, s2, s3 }); + } + } + this.t = items; + } + protected _updateBlock(s0: number, s1: number, s2: number, s3: number): void { + ((s0 ^= this.s0), (s1 ^= this.s1), (s2 ^= this.s2), (s3 ^= this.s3)); + const { W, t, windowSize } = this; + // prettier-ignore + let o0 = 0, o1 = 0, o2 = 0, o3 = 0; + const mask = (1 << W) - 1; // 2**W will kill performance. + let w = 0; + // NIST SP 800-38D §6.3 interprets blocks as little-endian polynomials, + // so the lookup walk consumes each word byte-by-byte from + // least-significant to most-significant bits. + for (const num of [s0, s1, s2, s3]) { + for (let bytePos = 0; bytePos < 4; bytePos++) { + const byte = (num >>> (8 * bytePos)) & 0xff; + for (let bitPos = 8 / W - 1; bitPos >= 0; bitPos--) { + const bit = (byte >>> (W * bitPos)) & mask; + const { s0: e0, s1: e1, s2: e2, s3: e3 } = t[w * windowSize + bit]; + ((o0 ^= e0), (o1 ^= e1), (o2 ^= e2), (o3 ^= e3)); + w += 1; + } + } + } + this.s0 = o0; + this.s1 = o1; + this.s2 = o2; + this.s3 = o3; + } + update(data: TArg): this { + aexists(this); + abytes(data); + data = copyBytes(data); + const b32 = u32(data); + const blocks = Math.floor(data.length / BLOCK_SIZE); + const left = data.length % BLOCK_SIZE; + for (let i = 0; i < blocks; i++) { + this._updateBlock( + swap8IfBE(b32[i * 4 + 0]), + swap8IfBE(b32[i * 4 + 1]), + swap8IfBE(b32[i * 4 + 2]), + swap8IfBE(b32[i * 4 + 3]) + ); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + // Tail blocks go through the shared ZEROS32 scratch, so they need the same host-endian + // normalization as full blocks; otherwise segmented GHASH/POLYVAL updates diverge on BE. + this._updateBlock( + swap8IfBE(ZEROS32[0]), + swap8IfBE(ZEROS32[1]), + swap8IfBE(ZEROS32[2]), + swap8IfBE(ZEROS32[3]) + ); + clean(ZEROS32); // clean tmp buffer + } + return this; + } + destroy(): void { + // `aexists(this)` guards update/digest paths, so destroy must mark the instance unusable too. + this.destroyed = true; + const { t } = this; + // Wipe the key-derived precompute table; scalar accumulator words remain, + // but the destroyed guard blocks further use. + // clean precompute table + for (const elm of t) { + ((elm.s0 = 0), (elm.s1 = 0), (elm.s2 = 0), (elm.s3 = 0)); + } + } + digestInto(out: TArg): void { + aexists(this); + // `digestInto(out)` is the no-allocation fast path, so callers must pass a + // 32-bit-aligned buffer before we reinterpret it with `u32(out)`. + aoutput(out, this, true); + this.finished = true; + // NIST SP 800-38D §6.4 returns the final 128-bit block Y_m. + // `digestInto()` follows the relaxed `aoutput()` contract, so only + // out[0..15] may be touched. + const { s0, s1, s2, s3 } = this; + const o32 = u32(out); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + swap32IfBE(o32); + } + digest(): TRet { + const res = new Uint8Array(BLOCK_SIZE); + this.digestInto(res); + // `res` is independent of internal state, so it stays valid after destroy() wipes the table. + this.destroy(); + return res as TRet; + } +} + +/** + * Incremental POLYVAL state for AES-SIV. + * @param key - 16-byte POLYVAL key. + * @param expectedLength - Expected message length for table sizing. + * Inherits GHASH's segment-padded `update()` behavior: each call is padded + * independently to a 16-byte boundary before absorption. + * @example + * Feeds one block into an incremental POLYVAL state with a fresh hash key. + * + * ```ts + * import { Polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const mac = new Polyval(key); + * mac.update(new Uint8Array(16)); + * mac.digest(); + * ``` + */ +export class Polyval extends GHASH { + constructor(key: TArg, expectedLength?: number) { + abytes(key); + // RFC 8452 Appendix A converts the POLYVAL key with + // `mulX_GHASH(ByteReverse(H))`; copy first because `_toGHASHKey(...)` + // mutates in place. + const ghKey = _toGHASHKey(copyBytes(key)); + super(ghKey, expectedLength); + clean(ghKey); + } + update(data: TArg): this { + aexists(this); + abytes(data); + data = copyBytes(data); + const b32 = u32(data); + const left = data.length % BLOCK_SIZE; + const blocks = Math.floor(data.length / BLOCK_SIZE); + for (let i = 0; i < blocks; i++) { + // RFC 8452 Appendix A feeds `ByteReverse(X_i)` into GHASH, so POLYVAL + // reverses the 32-bit word order in addition to the per-word byte swap. + this._updateBlock( + swap8IfLE(b32[i * 4 + 3]), + swap8IfLE(b32[i * 4 + 2]), + swap8IfLE(b32[i * 4 + 1]), + swap8IfLE(b32[i * 4 + 0]) + ); + } + if (left) { + ZEROS16.set(data.subarray(blocks * BLOCK_SIZE)); + this._updateBlock( + swap8IfLE(ZEROS32[3]), + swap8IfLE(ZEROS32[2]), + swap8IfLE(ZEROS32[1]), + swap8IfLE(ZEROS32[0]) + ); + clean(ZEROS32); + } + return this; + } + digestInto(out: TArg): void { + aexists(this); + // `digestInto(out)` is the no-allocation fast path, so callers must pass a + // 32-bit-aligned buffer before we reinterpret the output prefix with `u32(view)`. + aoutput(out, this, true); + this.finished = true; + // RFC 8452 Appendix A maps POLYVAL output back through `ByteReverse(...)`. + // `digestInto()` follows the relaxed `aoutput()` contract, so only out[0..15] may be touched. + const view = out.subarray(0, this.outputLen); + const { s0, s1, s2, s3 } = this; + const o32 = u32(view); + o32[0] = s0; + o32[1] = s1; + o32[2] = s2; + o32[3] = s3; + swap32IfBE(o32); + view.reverse(); + } +} + +/** + * GHash MAC for AES-GCM. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte GHASH key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with GHASH and a fresh hash key. + * + * ```ts + * import { ghash } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * ghash(new Uint8Array(), key); + * ``` + */ +export const ghash: TRet> = + /* @__PURE__ */ wrapMacConstructor( + 16, + (key: TArg, expectedLength?: number) => new GHASH(key, expectedLength), + (msg: TArg): [expectedLength?: number] => [msg.length] + ); + +/** + * POLYVAL MAC for AES-SIV. + * @param msg - Message bytes to authenticate. + * @param key - 16-byte POLYVAL key. + * @returns 16-byte authentication tag. + * @example + * Authenticates a short message with POLYVAL and a fresh hash key. + * + * ```ts + * import { polyval } from '@noble/ciphers/_polyval.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * polyval(new Uint8Array(), key); + * ``` + */ +export const polyval: TRet> = + /* @__PURE__ */ wrapMacConstructor( + 16, + (key: TArg, expectedLength?: number) => new Polyval(key, expectedLength), + (msg: TArg): [expectedLength?: number] => [msg.length] + ); diff --git a/node_modules/@noble/ciphers/src/aes.ts b/node_modules/@noble/ciphers/src/aes.ts new file mode 100644 index 0000000..960d67c --- /dev/null +++ b/node_modules/@noble/ciphers/src/aes.ts @@ -0,0 +1,2018 @@ +/** + * {@link https://en.wikipedia.org/wiki/Advanced_Encryption_Standard | AES} + * a.k.a. Advanced Encryption Standard + * is a variant of Rijndael block cipher, standardized by NIST in 2001. + * We provide the fastest available pure JS implementation. + * + * `cipher = encrypt(block, key)` + * + * Data is split into 128-bit blocks. + * Encrypted in 10/12/14 rounds (128/192/256 bits). In every round: + * 1. **S-box**, table substitution + * 2. **Shift rows**, cyclic shift left of all rows of data array + * 3. **Mix columns**, multiplying every column by fixed polynomial + * 4. **Add round key**, round_key xor i-th column of array + * + * Check out + * {@link https://csrc.nist.gov/files/pubs/fips/197/final/docs/fips-197.pdf | FIPS-197}, + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}, + * and {@link https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf | original proposal}. + * @module + */ +import { ghash, polyval } from './_polyval.ts'; +// prettier-ignore +import { + abytes, anumber, aoutput, + byteSwap, + clean, complexOverlapBytes, concatBytes, + copyBytes, createView, equalBytes, getOutput, isAligned32, + isLE, + overlapBytes, + swap32IfBE, + swap8IfBE, + u32, u64Lengths, u8, wrapCipher, wrapMacConstructor, + type Cipher, type CipherWithOutput, + type CMac, type IHash2, + type PRG, type TArg, type TRet, type Uint8ArrayBuffer +} from './utils.ts'; + +const BLOCK_SIZE = 16; +// AES operates on 16-byte blocks, i.e. 4 32-bit words. +const BLOCK_SIZE32 = 4; +// Shared zero block (`0^128`) used by GCM's `H = CIPH_K(0^128)` / J0 scratch +// and by CMAC / SIV helpers; callers take `.slice()` before mutating it. +const EMPTY_BLOCK = /* @__PURE__ */ new Uint8Array(BLOCK_SIZE); +// RFC 5297 §2.1 / §2.4: S2V uses ` = 0^127 || 1` for the `n = 0` special case. +const ONE_BLOCK = /* @__PURE__ */ Uint8Array.from([ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, +]); +const POLY = 0x11b; // 1 + x + x**3 + x**4 + x**8 +// Validates plain AES key sizes only; AES-SIV's doubled-key contract is checked elsewhere. +function validateKeyLength(key: TArg) { + if (![16, 24, 32].includes(key.length)) + throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key.length); +} + +// TODO: remove multiplication, binary ops only +// Doubles one GF(2^8) field element; callers are expected to stay in byte range. +// FIPS 197 upd1 §4.3 equation (4.5): XTIMES(b) left-shifts by one and, when +// b7=1, reduces by m(x); using POLY=0x11b here yields the same byte result +// as XORing with {1b} after the shift. +function mul2(n: number) { + return (n << 1) ^ (POLY & -(n >> 7)); +} + +// Shift-and-add multiplication in GF(2^8); callers are expected to pass byte values. +// FIPS 197 upd1 §4.3 equation (4.7): general products are XORs of repeated +// XTIMES() multiples, e.g. {57}•{13} = {57}⊕{ae}⊕{07}. +function mul(a: number, b: number) { + let res = 0; + for (; b > 0; b >>= 1) { + // Usual shift-and-add step in GF(2^8), not a scalar-multiplication ladder. + res ^= a & -(b & 1); // if (b&1) res ^=a (but const-time). + a = mul2(a); // a = 2*a + } + return res; +} + +/** + * Increments a counter block with wrap around. + * AES call sites here currently use the big-endian branch, but the helper supports both layouts. + * NIST SP 800-38A Appendix B.1 and SP 800-38D §6.2 increment the + * least-significant/rightmost bits. + * `isLE=false` matches that standard counter-block layout, while `isLE=true` + * is a generic extension for non-AES callers. + * The implementation keeps a 32-bit bitwise carry path, so `carry` is capped at `0xffffff00`; + * larger values throw instead of silently overflowing before the next-byte propagation step. + */ +// Keep the helper explicitly typed so `--isolatedDeclarations` can expose it +// through the test-only `__TESTS` export without inference errors. +const incBytes: (data: TArg, isLE: boolean, carry?: number) => void = ( + data: TArg, + isLE: boolean, + carry: number = 1 +): void => { + // Keep `carry + byte <= 0xffffffff` so the `| 0` / `>>> 8` path below + // never truncates a real carry bit. + if (!Number.isSafeInteger(carry) || carry > 0xffffff00) + throw new Error('incBytes: wrong carry ' + carry); + abytes(data); + for (let i = 0; i < data.length; i++) { + const pos = !isLE ? data.length - 1 - i : i; + carry = (carry + (data[pos] & 0xff)) | 0; + data[pos] = carry & 0xff; + carry >>>= 8; + } +}; + +// AES S-box is generated using finite field inversion, +// an affine transform, and xor of a constant 0x63. +const sbox = /* @__PURE__ */ (() => { + const t = new Uint8Array(256); + // Repeated multiplication by {03} walks all 255 nonzero field elements + // once, so t[255 - i] is the multiplicative inverse of t[i] for the + // affine step. + for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x)) t[i] = x; + const box = new Uint8Array(256); + // FIPS 197 upd1 §5.1.1: SBOX({00}) = {63} because the inverse step leaves + // {00} at {00}, then the affine transform xors in c = {63}. + box[0] = 0x63; + for (let i = 0; i < 255; i++) { + let x = t[255 - i]; + x |= x << 8; + box[t[i]] = (x ^ (x >> 4) ^ (x >> 5) ^ (x >> 6) ^ (x >> 7) ^ 0x63) & 0xff; + } + clean(t); + return box; +})(); + +// FIPS 197 upd1 §5.3.2: INVSBOX() is derived from SBOX() by swapping input +// and output roles (Table 6). +// `indexOf` is only used once at module init, so the quadratic setup cost stays off hot paths. +const invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j)); + +// FIPS 197 upd1 §5.2: ROTWORD([a0,a1,a2,a3]) = [a1,a2,a3,a0]; with this LE +// word packing that is a right rotate by 8 bits. +const rotr32_8 = (n: number) => (n << 24) | (n >>> 8); +// LE T-table helper: rotates one precomputed word by one byte so T1/T2/T3 +// reuse T0's substitution/mix result in the other byte lanes. +const rotl32_8 = (n: number) => (n << 8) | (n >>> 24); +// T-table is optimization suggested in 5.2 of original proposal (missed from FIPS-197). Changes: +// - LE instead of BE +// - bigger tables: T0 and T1 are merged into T01 table and T2 & T3 into T23; +// so index is u16, instead of u8. This speeds up things, unexpectedly +function genTtable(sbox: TArg, fn: (n: number) => number) { + if (sbox.length !== 256) throw new Error('Wrong sbox length'); + const T0 = new Uint32Array(256).map((_, j) => fn(sbox[j])); + const T1 = T0.map(rotl32_8); + const T2 = T1.map(rotl32_8); + const T3 = T2.map(rotl32_8); + // Pre-xor adjacent lanes so apply0123/applySbox can fetch two substituted + // byte lanes per lookup in the LE round layout. + const T01 = new Uint32Array(256 * 256); + const T23 = new Uint32Array(256 * 256); + const sbox2 = new Uint16Array(256 * 256); + for (let i = 0; i < 256; i++) { + for (let j = 0; j < 256; j++) { + const idx = i * 256 + j; + T01[idx] = T0[i] ^ T1[j]; + T23[idx] = T2[i] ^ T3[j]; + sbox2[idx] = (sbox[i] << 8) | sbox[j]; + } + } + return { sbox, sbox2, T0, T1, T2, T3, T01, T23 }; +} + +// Forward round precompute: the packed word stores the MIXCOLUMNS row +// [{02},{01},{01},{03}] in LE byte-lane order, and the returned `sbox2` +// is also reused by key expansion and the final round. +const tableEncoding = /* @__PURE__ */ genTtable( + sbox, + (s: number) => (mul(s, 3) << 24) | (s << 16) | (s << 8) | mul(s, 2) +); +// Inverse round precompute: the packed word stores the INVMIXCOLUMNS row +// [{0e},{09},{0d},{0b}] in LE byte-lane order, and the tables are reused +// by decrypt() and expandKeyDecLE(). +const tableDecoding = /* @__PURE__ */ genTtable( + invSbox, + (s) => (mul(s, 11) << 24) | (mul(s, 13) << 16) | (mul(s, 9) << 8) | mul(s, 14) +); + +// FIPS 197 upd1 §5.2 Table 5: left-most bytes of Rcon[j] = x^(j-1), generated by repeated XTIMES(). +const xPowers = /* @__PURE__ */ (() => { + const p = new Uint8Array(16); + for (let i = 0, x = 1; i < 16; i++, x = mul2(x)) p[i] = x; + return p; +})(); + +/** Forward AES key expansion used across ECB/CBC/CTR/GCM/CMAC/KW-style paths. */ +function expandKeyLE(key: TArg): TRet { + abytes(key); + const len = key.length; + validateKeyLength(key); + const { sbox2 } = tableEncoding; + const toClean = []; + // Copy on BE or misaligned inputs so the LE word normalization below never + // mutates caller key bytes in place. + if (!isLE || !isAligned32(key)) toClean.push((key = copyBytes(key))); + const k32 = swap32IfBE(u32(key)); + const Nk = k32.length; + // `applySbox` normally reads one byte lane from each argument; repeating + // `n` across all four lanes turns it into SUBWORD(n). + const subByte = (n: number) => applySbox(sbox2, n, n, n, n); + // AES key sizes are 16/24/32 bytes, so len + 28 yields the 44/52/60 + // schedule words from FIPS 197 §5.2 / Table 3. + const xk = new Uint32Array(len + 28); // expanded key + xk.set(k32); + // 4.3.1 Key expansion + for (let i = Nk; i < xk.length; i++) { + let t = xk[i - 1]; + if (i % Nk === 0) t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1]; + else if (Nk > 6 && i % Nk === 4) t = subByte(t); + xk[i] = xk[i - Nk] ^ t; + } + clean(...toClean); + return xk as TRet; +} + +function expandKeyDecLE(key: TArg): TRet { + const encKey = expandKeyLE(key); + const xk = encKey.slice(); + const Nk = encKey.length; + const { sbox2 } = tableEncoding; + const { T0, T1, T2, T3 } = tableDecoding; + // Local decrypt() walks round keys forward from xk[0], so reverse the + // encryption round-key blocks first before applying the equivalent-inverse + // middle-round transform. + for (let i = 0; i < Nk; i += 4) { + for (let j = 0; j < 4; j++) xk[i + j] = encKey[Nk - i - 4 + j]; + } + clean(encKey); + // Apply InvMixColumn to the reversed round keys using the same LE sbox2 + // packing as the forward path. + // apply InvMixColumn except first & last round + for (let i = 4; i < Nk - 4; i++) { + const x = xk[i]; + const w = applySbox(sbox2, x, x, x, x); + xk[i] = T0[w & 0xff] ^ T1[(w >>> 8) & 0xff] ^ T2[(w >>> 16) & 0xff] ^ T3[w >>> 24]; + } + return xk as TRet; +} + +// Apply tables +function apply0123( + T01: TArg, + T23: TArg, + s0: number, + s1: number, + s2: number, + s3: number +) { + // `T01` takes the low byte lane from `s0` plus the next lane from `s1`; + // `T23` does the same for `s2`/`s3`. + // Equivalent to `T0[s0&0xff] ^ T1[(s1>>>8)&0xff] ^ T2[(s2>>>16)&0xff] ^ + // T3[s3>>>24]`, but with two merged-table fetches. + return ( + T01[((s0 << 8) & 0xff00) | ((s1 >>> 8) & 0xff)] ^ + T23[((s2 >>> 8) & 0xff00) | ((s3 >>> 24) & 0xff)] + ); +} + +function applySbox(sbox2: TArg, s0: number, s1: number, s2: number, s3: number) { + // `sbox2` packs two substituted byte lanes at a time in the same LE + // layout used by the round code. + // Equivalent to `SBOX(byte0(s0)) | SBOX(byte1(s1))<<8 | + // SBOX(byte2(s2))<<16 | SBOX(byte3(s3))<<24`. + return ( + sbox2[(s0 & 0xff) | (s1 & 0xff00)] | + (sbox2[((s2 >>> 16) & 0xff) | ((s3 >>> 16) & 0xff00)] << 16) + ); +} + +function encrypt( + xk: TArg, + s0: number, + s1: number, + s2: number, + s3: number +): { s0: number; s1: number; s2: number; s3: number } { + const { sbox2, T01, T23 } = tableEncoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // `xk` has Nr+1 round-key blocks, so after the initial AddRoundKey and the + // final S-box-only round there are Nr-1 full table/MixColumns rounds left. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // last round (without mixcolumns, so using SBOX2 table) + const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3); + const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0); + const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1); + const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} + +// Can't be merged with encrypt: arg positions for apply0123 / applySbox are different +function decrypt( + xk: TArg, + s0: number, + s1: number, + s2: number, + s3: number +): { + s0: number; + s1: number; + s2: number; + s3: number; +} { + const { sbox2, T01, T23 } = tableDecoding; + let k = 0; + ((s0 ^= xk[k++]), (s1 ^= xk[k++]), (s2 ^= xk[k++]), (s3 ^= xk[k++])); + // With `expandKeyDecLE()` the round keys are already reversed and middle + // rounds are InvMixColumns-adjusted, so this loop follows the equivalent + // inverse cipher order directly. + const rounds = xk.length / 4 - 2; + for (let i = 0; i < rounds; i++) { + const t0 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1); + const t1 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2); + const t2 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3); + const t3 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0); + ((s0 = t0), (s1 = t1), (s2 = t2), (s3 = t3)); + } + // Final equivalent-inverse round omits InvMixColumns, so use inverse + // S-box lanes in InvShiftRows order. + const t0: number = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1); + const t1: number = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2); + const t2: number = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3); + const t3: number = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0); + return { s0: t0, s1: t1, s2: t2, s3: t3 }; +} + +function ctrCounter( + xk: TArg, + nonce: TArg, + src: TArg, + dst?: TArg +): TRet { + abytes(nonce, BLOCK_SIZE, 'nonce'); + abytes(src); + const srcLen = src.length; + dst = getOutput(srcLen, dst); + complexOverlapBytes(src, dst); + // Internal helper: mutate `nonce` in place as the live counter block so + // each encrypted block uses the next CTR value. + const ctr = nonce; + const c32 = u32(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + // Fill block (empty, ctr=0) + let { s0, s1, s2, s3 } = encrypt( + xk, + swap8IfBE(c32[0]), + swap8IfBE(c32[1]), + swap8IfBE(c32[2]), + swap8IfBE(c32[3]) + ); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0); + dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1); + dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2); + dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3); + incBytes(ctr, false, 1); // Full 128 bit counter with wrap around + ({ s0, s1, s2, s3 } = encrypt( + xk, + swap8IfBE(c32[0]), + swap8IfBE(c32[1]), + swap8IfBE(c32[2]), + swap8IfBE(c32[3]) + )); + } + // NIST SP 800-38A CTR mode uses the leading `u` bits of the next output + // block for the final short block. + // It's possible to handle > u32 fast, but is it worth it? + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(b32); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + // Unsafe mutable-counter API only advances whole blocks. Callers that want to + // resume after consuming part of this block must re-run from the same counter + // with left-padding and strip the already-consumed prefix themselves. + return dst as TRet; +} + +// AES CTR with overflowing 32 bit counter +// It's possible to do 32le significantly simpler (and probably faster) by using u32. +// But, we need both, and perf bottleneck is in ghash anyway. +// Unsafe 32-bit CTR helper: mutates `nonce` in place, expects aligned `src`/`dst`, +// and uses `isLE` to choose which 32-bit counter word is incremented. +function ctr32( + xk: TArg, + isLE: boolean, + nonce: TArg, + src: TArg, + dst?: TArg +): TRet { + abytes(nonce, BLOCK_SIZE, 'nonce'); + abytes(src); + dst = getOutput(src.length, dst); + const ctr = nonce; // write new value to nonce, so it can be re-used + const c32 = u32(ctr); + const view = createView(ctr); + const src32 = u32(src); + const dst32 = u32(dst); + // NIST SP 800-38D GCTR increments the rightmost 32 bits of J0, while + // RFC 8452 AES-GCM-SIV increments the first 32 bits as a little-endian u32. + const ctrPos = isLE ? 0 : 12; + const srcLen = src.length; + // Fill block (empty, ctr=0) + let ctrNum = view.getUint32(ctrPos, isLE); // read current counter value + let { s0, s1, s2, s3 } = encrypt( + xk, + swap8IfBE(c32[0]), + swap8IfBE(c32[1]), + swap8IfBE(c32[2]), + swap8IfBE(c32[3]) + ); + // process blocks + for (let i = 0; i + 4 <= src32.length; i += 4) { + dst32[i + 0] = src32[i + 0] ^ swap8IfBE(s0); + dst32[i + 1] = src32[i + 1] ^ swap8IfBE(s1); + dst32[i + 2] = src32[i + 2] ^ swap8IfBE(s2); + dst32[i + 3] = src32[i + 3] ^ swap8IfBE(s3); + ctrNum = (ctrNum + 1) >>> 0; // u32 wrap + view.setUint32(ctrPos, ctrNum, isLE); + ({ s0, s1, s2, s3 } = encrypt( + xk, + swap8IfBE(c32[0]), + swap8IfBE(c32[1]), + swap8IfBE(c32[2]), + swap8IfBE(c32[3]) + )); + } + // leftovers (less than a block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + const b32 = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(b32); + const buf = u8(b32); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + clean(b32); + } + // Same unsafe contract as ctrCounter(): only full blocks advance the stored + // mutable counter state; partial-block continuation is caller-managed. + return dst as TRet; +} + +/** + * **CTR** (Counter Mode): turns a block cipher into a stream cipher using a + * full 16-byte counter block. + * Efficient and parallelizable. Requires a unique nonce per encryption. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block, incremented as a full AES block. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short payload with a fresh AES key and counter block. + * + * ```ts + * import { ctr } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ctr: TRet< + ((key: TArg, nonce: TArg) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function aesctr(key: TArg, nonce: TArg): TRet { + function processCtr(buf: TArg, dst?: TArg): TRet { + abytes(buf); + if (dst !== undefined) { + abytes(dst); + // Optional output buffers must stay 4-byte aligned because + // ctrCounter() reinterprets them as Uint32Array words. + if (!isAligned32(dst)) throw new Error('unaligned destination'); + } + const xk = expandKeyLE(key); + // Public CTR keeps caller nonce bytes immutable even though ctrCounter() + // advances the live 16-byte counter block in place. + const n = copyBytes(nonce); // align + avoid changing + const toClean = [xk, n]; + if (!isAligned32(buf)) toClean.push((buf = copyBytes(buf))); + const out = ctrCounter(xk, n, buf, dst); + clean(...toClean); + return out as TRet; + } + return { + encrypt: (plaintext: TArg, dst?: TArg) => processCtr(plaintext, dst), + decrypt: (ciphertext: TArg, dst?: TArg) => + processCtr(ciphertext, dst), + } as TRet; + } +); + +function validateBlockDecrypt(data: TArg) { + abytes(data); + // ECB/CBC decryption always consumes whole ciphertext blocks; PKCS#7/CMS + // padding, when enabled, is removed only after decrypting the final block. + if (data.length % BLOCK_SIZE !== 0) { + throw new Error( + 'aes-(cbc/ecb).decrypt ciphertext should consist of blocks with size ' + BLOCK_SIZE + ); + } +} + +// ECB/CBC core modes operate on whole blocks; `pkcs5` enables the library's +// PKCS#7/CMS-compatible final-block padding convenience before encryption. +function validateBlockEncrypt(plaintext: TArg, pkcs5: boolean, dst?: TArg) { + abytes(plaintext); + let outLen = plaintext.length; + const remaining = outLen % BLOCK_SIZE; + if (!pkcs5 && remaining !== 0) + throw new Error('aec/(cbc-ecb): unpadded plaintext with disabled padding'); + if (pkcs5) { + let left = BLOCK_SIZE - remaining; + // RFC 5652 pads even already-aligned inputs, so a full extra block is + // appended when the plaintext length is already a multiple of 16 bytes. + if (!left) left = BLOCK_SIZE; // if no bytes left, create empty padding block + outLen = outLen + left; + } + dst = getOutput(outLen, dst); + complexOverlapBytes(plaintext, dst); + // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization never + // mutates caller plaintext bytes in place before ECB/CBC processing. + if (!isLE || !isAligned32(plaintext)) plaintext = copyBytes(plaintext); + const b = u32(plaintext); + swap32IfBE(b); + const o = u32(dst); + return { b, o, out: dst }; +} + +// `pkcs5` is the historical option name; for AES's 16-byte block this is the +// generic PKCS#7/CMS-style block-padding rule on decrypt. +function validatePKCS(data: TArg, pkcs5: boolean): TRet { + if (!pkcs5) return data as TRet; + + const len = data.length; + // RFC 5652 pads even empty / already-aligned inputs, so a valid padded + // ECB/CBC ciphertext is never empty when PKCS#7/CMS unpadding is enabled. + // AES-CBC/ECB ciphertext should be full blocks before unpadding + if (len === 0) throw new Error('aes/pkcs7: empty ciphertext not allowed'); + const lastByte = data[len - 1]; + let valid = 1; + valid &= ((lastByte - 1) >>> 31) ^ 1; // pad >= 1 + valid &= ((16 - lastByte) >>> 31) ^ 1; // pad <= 16 + // Check exactly 16 tail bytes in constant-shape loop + // For i < pad: byte must equal pad + // For i >= pad: ignore byte + for (let i = 0; i < 16; i++) { + // const b = data[len - 1 - i]; + const shouldCheck = (i - lastByte) >>> 31; // 1 if i < pad else 0 + const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0; // 1 if equal + valid &= eq | (shouldCheck ^ 1); // pass if equal OR not checked + } + + // if (invalidLen) throw new Error('aes/pkcs7: ciphertext length must be multiple of 16'); + if (!valid) throw new Error('aes/pkcs7: wrong padding'); + return data.subarray(0, len - lastByte) as TRet; +} + +// ECB/CBC callers only pass the final short block here, so `left.length` is +// 0..15 and the helper always emits exactly one padded 16-byte block. +function padPCKS(left: TArg): TRet { + const tmp = new Uint8Array(16); + const tmp32 = u32(tmp); + tmp.set(left); + const paddingByte = BLOCK_SIZE - left.length; + // RFC 5652 §6.3 fills the whole suffix with the padding length byte: + // e.g. `aa 0f..0f` for a 1-byte tail, or `10..10` for a full extra block. + for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++) tmp[i] = paddingByte; + return tmp32; +} + +/** Options for ECB and CBC. */ +export type BlockOpts = { + /** Disable the library's PKCS#7 padding/unpadding layer and require exact-block inputs. */ + disablePadding?: boolean; +}; + +/** + * **ECB** (Electronic Codebook): Deterministic encryption; identical plaintext blocks yield + * identical ciphertexts. Not secure due to pattern leakage. + * See {@link https://words.filippo.io/the-ecb-penguin/ | the AES Penguin}. + * @param key - AES key bytes. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Shows the basic ECB encrypt call shape with a fresh key; avoid ECB in new designs. + * + * ```ts + * import { ecb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const cipher = ecb(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ecb: TRet< + ((key: TArg, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16 }, + function aesecb(key: TArg, opts: BlockOpts = {}): TRet { + const pkcs5 = !opts.disablePadding; + return { + encrypt(plaintext: TArg, dst?: TArg): TRet { + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst); + const xk = expandKeyLE(key); + let i = 0; + for (; i + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + if (pkcs5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + swap32IfBE(tmp32); + const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(xk); + return _out as TRet; + }, + decrypt(ciphertext: TArg, dst?: TArg): TRet { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + dst = getOutput(ciphertext.length, dst); + const toClean: (Uint8Array | Uint32Array)[] = [xk]; + complexOverlapBytes(ciphertext, dst); + // Copy on BE or misaligned ciphertext so u32()/swap32IfBE() + // normalization never mutates caller bytes in place before decrypt(). + if (!isLE || !isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32(ciphertext); + const o = u32(dst); + swap32IfBE(b); + for (let i = 0; i + 4 <= b.length; ) { + const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(...toClean); + return validatePKCS(dst, pkcs5) as TRet; + }, + } as TRet; + } +); + +/** + * **CBC** (Cipher Block Chaining): Each plaintext block is XORed with the + * previous block of ciphertext before encryption. + * Hard to use: requires proper padding and an unpredictable IV. Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @param opts - Padding options. See {@link BlockOpts}. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a padded message with a fresh key and 16-byte IV. + * + * ```ts + * import { cbc } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const cbc: TRet< + ((key: TArg, iv: TArg, opts?: BlockOpts) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function aescbc( + key: TArg, + iv: TArg, + opts: BlockOpts = {} + ): TRet { + const pkcs5 = !opts.disablePadding; + return { + encrypt(plaintext: TArg, dst?: TArg): TRet { + const xk = expandKeyLE(key); + const { b, o, out: _out } = validateBlockEncrypt(plaintext, pkcs5, dst); + let _iv = iv; + const toClean: (Uint8Array | Uint32Array)[] = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + let i = 0; + for (; i + 4 <= b.length; ) { + ((s0 ^= b[i + 0]), (s1 ^= b[i + 1]), (s2 ^= b[i + 2]), (s3 ^= b[i + 3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + if (pkcs5) { + const tmp32 = padPCKS(plaintext.subarray(i * 4)); + swap32IfBE(tmp32); + ((s0 ^= tmp32[0]), (s1 ^= tmp32[1]), (s2 ^= tmp32[2]), (s3 ^= tmp32[3])); + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + ((o[i++] = s0), (o[i++] = s1), (o[i++] = s2), (o[i++] = s3)); + } + swap32IfBE(o); + clean(...toClean); + return _out as TRet; + }, + decrypt(ciphertext: TArg, dst?: TArg): TRet { + validateBlockDecrypt(ciphertext); + const xk = expandKeyDecLE(key); + let _iv = iv; + const toClean: (Uint8Array | Uint32Array)[] = [xk]; + // Copy on BE or misaligned inputs so IV normalization and the mutable + // local chaining state never write back into caller IV bytes. + if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv))); + const n32 = u32(_iv); + swap32IfBE(n32); + dst = getOutput(ciphertext.length, dst); + complexOverlapBytes(ciphertext, dst); + // Copy on BE or misaligned ciphertext so u32()/swap32IfBE() + // normalization never mutates caller bytes in place before decrypt(). + if (!isLE || !isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext))); + const b = u32(ciphertext); + const o = u32(dst); + swap32IfBE(b); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= b.length; ) { + // prettier-ignore + const ps0 = s0, ps1 = s1, ps2 = s2, ps3 = s3; + ((s0 = b[i + 0]), (s1 = b[i + 1]), (s2 = b[i + 2]), (s3 = b[i + 3])); + const { s0: o0, s1: o1, s2: o2, s3: o3 } = decrypt(xk, s0, s1, s2, s3); + ((o[i++] = o0 ^ ps0), (o[i++] = o1 ^ ps1), (o[i++] = o2 ^ ps2), (o[i++] = o3 ^ ps3)); + } + swap32IfBE(o); + clean(...toClean); + return validatePKCS(dst, pkcs5) as TRet; + }, + } as TRet; + } +); + +/** + * CFB (CFB-128): Cipher Feedback Mode with 128-bit segments. The input for the + * block cipher is the previous cipher output. + * Unauthenticated: needs MAC. + * @param key - AES key bytes. + * @param iv - 16-byte unpredictable initialization vector. + * @returns Cipher instance with `encrypt()` and `decrypt()`. + * @example + * Encrypts a short message with feedback mode and a fresh key/IV pair. + * + * ```ts + * import { cfb } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cfb(key, iv); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const cfb: TRet< + ((key: TArg, iv: TArg) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, nonceLength: 16 }, + function aescfb(key: TArg, iv: TArg): TRet { + function processCfb( + src: TArg, + isEncrypt: boolean, + dst?: TArg + ): TRet { + abytes(src); + const srcLen = src.length; + dst = getOutput(srcLen, dst); + // CFB feeds back previous ciphertext, so overlapping src/dst could + // overwrite bytes that are still needed as the next feedback block. + if (overlapBytes(src, dst)) throw new Error('overlapping src and dst not supported.'); + const xk = expandKeyLE(key); + let _iv = iv; + const toClean: (Uint8Array | Uint32Array)[] = [xk]; + // Copy on BE or misaligned inputs so u32()/swap32IfBE() normalization + // never mutates caller IV/src bytes in place before CFB processing. + if (!isLE || !isAligned32(_iv)) toClean.push((_iv = copyBytes(_iv))); + if (!isLE || !isAligned32(src)) toClean.push((src = copyBytes(src))); + const src32 = u32(src); + const dst32 = u32(dst); + // NIST SP 800-38A §6.3 feeds back the previous ciphertext segment in + // both directions: encrypt reuses freshly written dst words, decrypt + // reuses the source ciphertext words. + const next32 = isEncrypt ? dst32 : src32; + const n32 = u32(_iv); + swap32IfBE(src32); + swap32IfBE(n32); + // prettier-ignore + let s0 = n32[0], s1 = n32[1], s2 = n32[2], s3 = n32[3]; + for (let i = 0; i + 4 <= src32.length; ) { + const { s0: e0, s1: e1, s2: e2, s3: e3 } = encrypt(xk, s0, s1, s2, s3); + dst32[i + 0] = src32[i + 0] ^ e0; + dst32[i + 1] = src32[i + 1] ^ e1; + dst32[i + 2] = src32[i + 2] ^ e2; + dst32[i + 3] = src32[i + 3] ^ e3; + ((s0 = next32[i++]), (s1 = next32[i++]), (s2 = next32[i++]), (s3 = next32[i++])); + } + // leftovers (less than block) + const start = BLOCK_SIZE * Math.floor(src32.length / BLOCK_SIZE32); + if (start < srcLen) { + // Byte-oriented API: for a final short tail, reuse the next CFB-128 + // output block and XOR only the needed prefix. RFC 3826 §3.1.3 / + // §3.1.4 describes the same no-padding rule at bit granularity for a + // final r<=128 segment. + ({ s0, s1, s2, s3 } = encrypt(xk, s0, s1, s2, s3)); + const tmp = new Uint32Array([s0, s1, s2, s3]); + swap32IfBE(tmp); + const buf = u8(tmp); + for (let i = start, pos = 0; i < srcLen; i++, pos++) dst[i] = src[i] ^ buf[pos]; + clean(buf); + } + swap32IfBE(dst32); + clean(...toClean); + return dst as TRet; + } + return { + encrypt: (plaintext: TArg, dst?: TArg) => + processCfb(plaintext, true, dst), + decrypt: (ciphertext: TArg, dst?: TArg) => + processCfb(ciphertext, false, dst), + } as TRet; + } +); + +// TODO: merge with chacha, however gcm has bitLen while chacha has byteLen +// `data` is the payload covered by the polynomial MAC: ciphertext for GCM, +// plaintext for GCM-SIV. Keep AAD/data/length as separate updates because +// GHASH/POLYVAL pad each call to block boundaries, so the chunks must match the +// spec-defined segments instead of arbitrary concatenation boundaries. +function computeTag( + fn: typeof ghash, + isLE: boolean, + key: TArg, + data: TArg, + AAD?: TArg +): TRet { + const aadLength = AAD ? AAD.length : 0; + const h = fn.create(key, data.length + aadLength); + if (AAD) h.update(AAD); + // u64Lengths() takes (dataBits, aadBits) but still serializes the final + // block as len(AAD) || len(data), matching both GCM and GCM-SIV. + const num = u64Lengths(8 * data.length, 8 * aadLength, isLE); + h.update(data); + h.update(num); + const res = h.digest(); + clean(num); + return res; +} + +/** + * **GCM** (Galois/Counter Mode): Combines CTR mode with polynomial MAC. Efficient and widely used. + * Not perfect: + * a) conservative key wear-out is `2**32` (4B) msgs. + * b) key wear-out under random nonces is even smaller: `2**23` (8M) messages for `2**-50` chance. + * c) MAC can be forged: see Poly1305 documentation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes (12 recommended, minimum 8; other lengths use GHASH J0 derivation). + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance with a fixed 16-byte tag. + * @example + * Encrypts and authenticates plaintext with a fresh key and 12-byte nonce. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcm: TRet< + ((key: TArg, nonce: TArg, AAD?: TArg) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; + varSizeNonce: true; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, + function aesgcm( + key: TArg, + nonce: TArg, + AAD?: TArg + ): TRet { + // SP 800-38D lets implementations narrow supported IV lengths. + // This wrapper intentionally requires at least 8 bytes; OpenSSL accepts shorter IVs too. + // 12-byte nonces take the fast path; other allowed lengths use GHASH to derive J0. + if (nonce.length < 8) throw new Error('aes/gcm: invalid nonce length'); + const tagLength = 16; + function _computeTag( + authKey: TArg, + tagMask: TArg, + data: TArg + ): TRet { + const tag = computeTag(ghash, false, authKey, data, AAD); + for (let i = 0; i < tagMask.length; i++) tag[i] ^= tagMask[i]; + return tag; + } + function deriveKeys() { + const xk = expandKeyLE(key); + const authKey = EMPTY_BLOCK.slice(); + const counter = EMPTY_BLOCK.slice(); + ctr32(xk, false, counter, counter, authKey); + // NIST 800-38d, page 15: different behavior for 96-bit and non-96-bit nonces + if (nonce.length === 12) { + counter.set(nonce); + } else { + const nonceLen = EMPTY_BLOCK.slice(); + const view = createView(nonceLen); + view.setBigUint64(8, BigInt(nonce.length * 8), false); + // GHASH.update() pads each call to 16 bytes, so + // update(nonce).update(nonceLen) realizes + // IV || 0^s || 0^64 || [len(IV)]_64 for non-96-bit nonces. + // ghash(nonce || u64be(0) || u64be(nonceLen*8)) + const g = ghash.create(authKey).update(nonce).update(nonceLen); + g.digestInto(counter); // digestInto doesn't trigger '.destroy' + g.destroy(); + } + // GCTR_K(J0, 0^128) = E_K(J0); reusing ctr32() here extracts that tag + // mask and leaves `counter` advanced to inc32(J0) for payload GCTR. + const tagMask = ctr32(xk, false, counter, EMPTY_BLOCK); + return { xk, authKey, counter, tagMask }; + } + return { + encrypt(plaintext: TArg): TRet { + const { xk, authKey, counter, tagMask } = deriveKeys(); + const out = new Uint8Array(plaintext.length + tagLength); + const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, counter, tagMask]; + if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext))); + ctr32(xk, false, counter, plaintext, out.subarray(0, plaintext.length)); + const tag = _computeTag(authKey, tagMask, out.subarray(0, out.length - tagLength)); + toClean.push(tag); + out.set(tag, plaintext.length); + clean(...toClean); + return out as TRet; + }, + decrypt(ciphertext: TArg): TRet { + const { xk, authKey, counter, tagMask } = deriveKeys(); + const toClean: (Uint8Array | Uint32Array)[] = [xk, authKey, tagMask, counter]; + if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext))); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = _computeTag(authKey, tagMask, data); + toClean.push(tag); + // NIST SP 800-38D §7.2 permits equivalent step orderings; verify the + // tag before CTR so unauthenticated plaintext is never materialized. + if (!equalBytes(tag, passedTag)) { + clean(...toClean); + throw new Error('aes/gcm: invalid ghash tag'); + } + const out = ctr32(xk, false, counter, data); + clean(...toClean); + return out as TRet; + }, + } as TRet; + } +); + +const limit = (name: string, min: number, max: number) => (value: number) => { + // Current AES-SIV/GCM-SIV callers pass protocol limits from RFC 8452 / RFC 5297, + // not arbitrary library-preference bounds. + // Callers feed Uint8Array.length values here, so safe-integer rejection + // does not exclude any representable input even when an RFC bound is larger. + if (!Number.isSafeInteger(value) || min > value || value > max) { + const minmax = '[' + min + '..' + max + ']'; + throw new Error('' + name + ': expected value in range ' + minmax + ', got ' + value); + } +}; + +/** + * **SIV** (Synthetic IV): GCM with nonce-misuse resistance. + * Repeating nonces reveal only the fact plaintexts are identical. + * Also suffers from GCM issues: key wear-out limits & MAC forging. + * See {@link https://www.rfc-editor.org/rfc/rfc8452 | RFC 8452}. + * RFC 8452 defines 16-byte and 32-byte AES keys for this mode. + * This implementation also accepts 24-byte AES-192 keys as a local + * extension; see the inline comment next to `validateKeyLength(key)` below + * for the exact scope note. + * @param key - AES key bytes. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce, while tolerating reuse. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcmsiv: TRet< + ((key: TArg, nonce: TArg, AAD?: TArg) => Cipher) & { + blockSize: number; + nonceLength: number; + tagLength: number; + varSizeNonce: true; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, nonceLength: 12, tagLength: 16, varSizeNonce: true }, + function aessiv( + key: TArg, + nonce: TArg, + AAD?: TArg + ): TRet { + const tagLength = 16; + // From RFC 8452: Section 6 + const AAD_LIMIT = limit('AAD', 0, 2 ** 36); + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 36); + const NONCE_LIMIT = limit('nonce', 12, 12); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 36 + 16); + abytes(key); + // RFC 8452 only standardizes 16-byte and 32-byte key-generating keys. + // The accepted 24-byte path is a local AES-192 extension outside the RFC-defined AEADs. + validateKeyLength(key); + NONCE_LIMIT(nonce.length); + if (AAD !== undefined) AAD_LIMIT(AAD.length); + function deriveKeys() { + const xk = expandKeyLE(key); + const encKey = new Uint8Array(key.length); + const authKey = new Uint8Array(16); + const toClean: (Uint8Array | Uint32Array)[] = [xk, encKey]; + let _nonce = nonce; + // Copy on BE or misaligned nonce so u32()/swap32IfBE() normalization + // never mutates caller nonce bytes before RFC 8452 key derivation. + if (!isLE || !isAligned32(_nonce)) toClean.push((_nonce = copyBytes(_nonce))); + const n32 = u32(_nonce); + swap32IfBE(n32); + // prettier-ignore + let s0 = 0, s1 = n32[0], s2 = n32[1], s3 = n32[2]; + let counter = 0; + for (const derivedKey of [authKey, encKey].map(u32)) { + const d32 = u32(derivedKey); + for (let i = 0; i < d32.length; i += 2) { + // aes(u32le(0) || nonce)[:8] || aes(u32le(1) || nonce)[:8] ... + const { s0: o0, s1: o1 } = encrypt(xk, s0, s1, s2, s3); + d32[i + 0] = o0; + d32[i + 1] = o1; + s0 = ++counter; // increment counter inside state + } + swap32IfBE(d32); + } + const res = { authKey, encKey: expandKeyLE(encKey) }; + // Cleanup + clean(...toClean); + return res; + } + function _computeTag( + encKey: TArg, + authKey: TArg, + data: TArg + ): TRet { + const tag = computeTag(polyval, true, authKey, data, AAD); + // Compute the expected tag by XORing S_s and the nonce, clearing the + // most significant bit of the last byte and encrypting with the + // message-encryption key. + for (let i = 0; i < 12; i++) tag[i] ^= nonce[i]; + tag[15] &= 0x7f; // Clear the highest bit + // encrypt tag as block + const t32 = u32(tag); + swap32IfBE(t32); + // prettier-ignore + let s0 = t32[0], s1 = t32[1], s2 = t32[2], s3 = t32[3]; + ({ s0, s1, s2, s3 } = encrypt(encKey, s0, s1, s2, s3)); + ((t32[0] = s0), (t32[1] = s1), (t32[2] = s2), (t32[3] = s3)); + swap32IfBE(t32); + return tag; + } + // actual decrypt/encrypt of message. + function processSiv( + encKey: TArg, + tag: TArg, + input: TArg + ): TRet { + let block = copyBytes(tag); + // RFC 8452 §4 / §5 use the tag with the highest bit of the last byte + // forced to one as the initial AES-CTR counter block. + block[15] |= 0x80; // Force highest bit + const res = ctr32(encKey, true, block, input); + // Cleanup + clean(block); + return res; + } + return { + encrypt(plaintext: TArg): TRet { + PLAIN_LIMIT(plaintext.length); + const { encKey, authKey } = deriveKeys(); + const tag = _computeTag(encKey, authKey, plaintext); + const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey, tag]; + if (!isAligned32(plaintext)) toClean.push((plaintext = copyBytes(plaintext))); + const out = new Uint8Array(plaintext.length + tagLength); + out.set(tag, plaintext.length); + out.set(processSiv(encKey, tag, plaintext)); + // Cleanup + clean(...toClean); + return out as TRet; + }, + decrypt(ciphertext: TArg): TRet { + CIPHER_LIMIT(ciphertext.length); + const tag = ciphertext.subarray(-tagLength); + const { encKey, authKey } = deriveKeys(); + const toClean: (Uint8Array | Uint32Array)[] = [encKey, authKey]; + if (!isAligned32(ciphertext)) toClean.push((ciphertext = copyBytes(ciphertext))); + const plaintext = processSiv(encKey, tag, ciphertext.subarray(0, -tagLength)); + const expectedTag = _computeTag(encKey, authKey, plaintext); + toClean.push(expectedTag); + // RFC 8452 §5: plaintext is unauthenticated here and MUST NOT be + // returned until the expected-tag check completes successfully. + if (!equalBytes(tag, expectedTag)) { + clean(...toClean); + throw new Error('invalid polyval tag'); + } + // Cleanup + clean(...toClean); + return plaintext as TRet; + }, + } as TRet; + } +); + +function isBytes32(a: unknown): a is Uint32Array { + // Plain `instanceof Uint32Array` is too strict for cross-realm expanded-key views. + // This is only a best-effort unsafe-export guard, not a provenance proof for `expandKeyLE`. + return ( + a instanceof Uint32Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint32Array') + ); +} + +// Unsafe single-block helpers: mutate `block` in place and require its 16-byte +// Uint8Array view to be 4-byte aligned because `u32(block)` reinterprets it. +function encryptBlock(xk: TArg, block: TArg): TRet { + abytes(block, 16, 'block'); + if (!isBytes32(xk)) throw new Error('_encryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + swap32IfBE(b32); + let { s0, s1, s2, s3 } = encrypt(xk, b32[0], b32[1], b32[2], b32[3]); + ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3)); + swap32IfBE(b32); + return block as TRet; +} + +function decryptBlock(xk: TArg, block: TArg): TRet { + abytes(block, 16, 'block'); + if (!isBytes32(xk)) throw new Error('_decryptBlock accepts result of expandKeyLE'); + const b32 = u32(block); + swap32IfBE(b32); + let { s0, s1, s2, s3 } = decrypt(xk, b32[0], b32[1], b32[2], b32[3]); + ((b32[0] = s0), (b32[1] = s1), (b32[2] = s2), (b32[3] = s3)); + swap32IfBE(b32); + return block as TRet; +} + +/** + * AES-W (base for AESKW/AESKWP). + * Specs: + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | SP800-38F}, + * {@link https://www.rfc-editor.org/rfc/rfc3394 | RFC 3394}, + * {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}. + * Shared core mutates `out` in place; callers are responsible for prepending + * the right IV/AIV and checking the recovered value after decrypt. + */ +const AESW = { + /* + High-level pseudocode: + ``` + A: u64 = IV + out = [] + for (let i=0, ctr = 0; i<6; i++) { + for (const chunk of chunks(plaintext, 8)) { + A ^= swapEndianess(ctr++) + [A, res] = chunks(encrypt(A || chunk), 8); + out ||= res + } + } + out = A || out + ``` + Decrypt is the same, but reversed. + */ + encrypt(kek: TArg, out: TArg) { + // Current implementation keeps RFC 3394/5649 `t` in a u32-shaped counter, + // so the shared core caps plaintext below 4 GiB even though the specs allow more. + if (out.length >= 2 ** 32) throw new Error('plaintext should be less than 4gb'); + const xk = expandKeyLE(kek); + // 16-byte `S = A || P[1]` is the RFC 5649 KWP special case for n=1; + // KW callers never reach it because KW requires at least two plaintext semiblocks. + if (out.length === 16) encryptBlock(xk, out); + else { + const o32 = u32(out); + swap32IfBE(o32); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = 1; j < 6; j++) { + for (let pos = 2; pos < o32.length; pos += 2, ctr++) { + const { s0, s1, s2, s3 } = encrypt(xk, a0, a1, o32[pos], o32[pos + 1]); + // A = MSB(64, B) ^ t where t = (n*j)+i. Under the 32-bit length cap + // above, `t` fits in the low half of `[t]_64`, so xor only the low + // 32 bits of A after converting `ctr` to network order. + ((a0 = s0), (a1 = s1 ^ byteSwap(ctr)), (o32[pos] = s2), (o32[pos + 1] = s3)); + } + } + ((o32[0] = a0), (o32[1] = a1)); // out = A || out + swap32IfBE(o32); + } + xk.fill(0); + }, + decrypt(kek: TArg, out: TArg) { + // Same implementation cap on the recovered plaintext length after + // removing the 8-byte A/IV prefix. + if (out.length - 8 >= 2 ** 32) throw new Error('ciphertext should be less than 4gb'); + const xk = expandKeyDecLE(kek); + const chunks = out.length / 8 - 1; // first chunk is IV + // `n = 2` semiblocks is the RFC 5649 KWP special case; KW ciphertexts + // always have at least three semiblocks and therefore use the W^-1 loop. + if (chunks === 1) decryptBlock(xk, out); + else { + const o32 = u32(out); + swap32IfBE(o32); + // prettier-ignore + let a0 = o32[0], a1 = o32[1]; // A + for (let j = 0, ctr = chunks * 6; j < 6; j++) { + for (let pos = chunks * 2; pos >= 1; pos -= 2, ctr--) { + a1 ^= byteSwap(ctr); + const { s0, s1, s2, s3 } = decrypt(xk, a0, a1, o32[pos], o32[pos + 1]); + ((a0 = s0), (a1 = s1), (o32[pos] = s2), (o32[pos + 1] = s3)); + } + } + ((o32[0] = a0), (o32[1] = a1)); + swap32IfBE(o32); + } + xk.fill(0); + }, +}; + +// RFC 3394 §2.2.3.1 / NIST SP 800-38F Algorithm 3 / Algorithm 4: KW prepends +// the default 64-bit ICV1 and unwrap must verify the same value. +const AESKW_IV = /* @__PURE__ */ new Uint8Array(8).fill(0xa6); // A6A6A6A6A6A6A6A6 + +/** + * AES-KW (key-wrap). Injects static IV into plaintext, adds counter, encrypts 6 times. + * Reduces block size from 16 to 8 bytes. + * Plaintext must be a non-empty multiple of 8 bytes with minimum 16 bytes. + * 8-byte inputs use aeskwp. + * Wrapped ciphertext must be a multiple of 8 bytes with minimum 24 bytes. + * For padded version, use aeskwp. + * See {@link https://www.rfc-editor.org/rfc/rfc3394/ | RFC 3394} and + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf | NIST SP 800-38F}. + * @param kek - AES key-encryption key. + * @returns Key-wrap cipher instance. + * As with other `wrapCipher(...)` wrappers, `encrypt()` is single-use per + * instance. + * @example + * Wraps a 128-bit content-encryption key with a fresh key-encryption key. + * + * ```ts + * import { aeskw } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const cek = randomBytes(16); + * const wrap = aeskw(kek); + * wrap.encrypt(cek); + * ``` + */ +export const aeskw: TRet< + ((kek: TArg) => Cipher) & { + blockSize: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 8 }, + (kek: TArg): TRet => + ({ + encrypt(plaintext: TArg): TRet { + if (!plaintext.length || plaintext.length % 8 !== 0) + throw new Error('invalid plaintext length'); + // RFC 3394 / NIST SP 800-38F define KW only for >=2 plaintext + // semiblocks; the 1-semiblock case belongs to RFC 5649 KWP. + if (plaintext.length === 8) + throw new Error('8-byte keys not allowed in AESKW, use AESKWP instead'); + const out = concatBytes(AESKW_IV, plaintext); + AESW.encrypt(kek, out); + return out; + }, + decrypt(ciphertext: TArg): TRet { + // ciphertext must be at least 24 bytes and a multiple of 8 bytes + // 24 because should have at least two block (1 iv + 2). + // Replace with 16 to enable '8-byte keys' + if (ciphertext.length % 8 !== 0 || ciphertext.length < 3 * 8) + throw new Error('invalid ciphertext length'); + // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext + // immutable across the unwrap, ICV1 check, and IV scrubbing below. + const out = copyBytes(ciphertext); + AESW.decrypt(kek, out); + if (!equalBytes(out.subarray(0, 8), AESKW_IV)) throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8) as TRet; + }, + }) as TRet +); + +/* +We don't support 8-byte keys. The rabbit hole: + +- Wycheproof says: "NIST SP 800-38F does not define the wrapping of 8 byte keys. + RFC 3394 Section 2 on the other hand specifies that 8 byte keys are wrapped + by directly encrypting one block with AES." + - {@link https://github.com/C2SP/wycheproof/blob/master/doc/key_wrap.md | Wycheproof key-wrap note} + - "RFC 3394 specifies in Section 2, that the input for the key wrap + algorithm must be at least two blocks and otherwise the constant + field and key are simply encrypted with ECB as a single block" +- What RFC 3394 actually says (in Section 2): + - "Before being wrapped, the key data is parsed into n blocks of 64 bits. + The only restriction the key wrap algorithm places on n is that n be + at least two" + - "For key data with length less than or equal to 64 bits, the constant + field used in this specification and the key data form a single + 128-bit codebook input making this key wrap unnecessary." +- Which means "assert(n >= 2)" and "use something else for 8 byte keys" +- NIST SP800-38F actually prohibits 8-byte in "5.3.1 Mandatory Limits". + It states that plaintext for KW should be "2 to 2^54 -1 semiblocks". +- So, where does "directly encrypt single block with AES" come from? + - Not RFC 3394. Pseudocode of key wrap in 2.2 explicitly uses + loop of 6 for any code path + - There is a weird W3C spec: + {@link https://www.w3.org/TR/2002/REC-xmlenc-core-20021210/Overview.html#kw-aes128 | XML Encryption AES key-wrap section} + - This spec is outdated, as admitted by Wycheproof authors + - There is RFC 5649 for padded key wrap, which is padding construction on + top of AESKW. In '4.1.2' it says: "If the padded plaintext contains exactly + eight octets, then prepend the AIV as defined in Section 3 above to P[1] and + encrypt the resulting 128-bit block using AES in ECB mode [Modes] with key + K (the KEK). In this case, the output is two 64-bit blocks C[0] and C[1]:" + - Browser subtle crypto is actually crashes on wrapping keys less than 16 bytes: + `Error: error:1C8000E6:Provider routines::invalid input length] + { opensslErrorStack: [ 'error:030000BD:digital envelope routines::update error' ]` + +In the end, seems like a bug in Wycheproof. +The 8-byte check can be easily disabled inside of AES_W. +*/ + +// RFC 5649 §3 / NIST SP 800-38F Algorithm 5 / Algorithm 6: KWP uses ICV2 as +// the high 32 bits of the AIV; the low 32 bits carry the MLI in network order. +const AESKWP_IV = 0xa65959a6; // single u32le value + +/** + * AES-KW, but with padding and allows random keys. + * Uses the RFC 5649 alternative initial value; the second u32 stores the + * 32-bit MLI in network order. + * Wrapped ciphertext must be at least 16 bytes; malformed lengths are + * rejected during AIV/padding checks. + * See {@link https://www.rfc-editor.org/rfc/rfc5649 | RFC 5649}. + * @param kek - AES key-encryption key. + * @returns Padded key-wrap cipher instance. + * @example + * Wraps a short key blob using the padded variant and a fresh key-encryption key. + * + * ```ts + * import { aeskwp } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const kek = randomBytes(16); + * const wrap = aeskwp(kek); + * wrap.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const aeskwp: TRet< + ((kek: TArg) => Cipher) & { + blockSize: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 8 }, + (kek: TArg): TRet => + ({ + encrypt(plaintext: TArg): TRet { + if (!plaintext.length) throw new Error('invalid plaintext length'); + const padded = Math.ceil(plaintext.length / 8) * 8; + const out = new Uint8Array(8 + padded); + out.set(plaintext, 8); + const out32 = u32(out); + out32[0] = swap8IfBE(AESKWP_IV); + // RFC 5649 §3: the low 32 bits of the AIV carry the octet-length MLI in + // network order, even though this buffer is addressed through LE u32s. + out32[1] = swap8IfBE(byteSwap(plaintext.length)); + AESW.encrypt(kek, out); + return out as TRet; + }, + decrypt(ciphertext: TArg): TRet { + // 16 because should have at least one block + if (ciphertext.length < 16) throw new Error('invalid ciphertext length'); + // AESW.decrypt() mutates its buffer in place, so keep caller ciphertext + // immutable across the unwrap, AIV checks, and IV scrubbing below. + const out = copyBytes(ciphertext); + const o32 = u32(out); + AESW.decrypt(kek, out); + const len = byteSwap(swap8IfBE(o32[1])) >>> 0; + const padded = Math.ceil(len / 8) * 8; + if (swap8IfBE(o32[0]) !== AESKWP_IV || out.length - 8 !== padded) + throw new Error('integrity check failed'); + // RFC 5649 §3 / NIST SP 800-38F Algorithm 6: recovered padding length + // must be in [0,7], and every recovered pad octet must be zero. + for (let i = len; i < padded; i++) + if (out[8 + i] !== 0) throw new Error('integrity check failed'); + out.subarray(0, 8).fill(0); // ciphertext.subarray(0, 8) === IV, but we clean it anyway + return out.subarray(8, 8 + len) as TRet; + }, + }) as TRet +); + +class _AesCtrDRBG implements PRG { + readonly blockLen: number; + private key: TRet; + private nonce: TRet; + private state: TRet; + private reseedCnt: number; + constructor(keyLen: number, seed: TArg, personalization?: TArg) { + this.blockLen = ctr.blockSize; + const keyLenBytes = keyLen / 8; + const nonceLen = 16; + // Store the full seedlen state as key || V so CTR_DRBG_Update-style steps + // can rewrite the entire internal state in place. + this.state = new Uint8Array(keyLenBytes + nonceLen) as TRet; + this.key = this.state.subarray(0, keyLenBytes) as TRet; + this.nonce = this.state.subarray(keyLenBytes, keyLenBytes + nonceLen) as TRet; + this.reseedCnt = 1; + // Keep the stored counter one step ahead of SP 800-90A's formal V so + // ctr(key, nonce) uses the next counter block directly. + incBytes(this.nonce, false, 1); + this.addEntropy(seed, personalization); + } + private update(data?: TArg) { + // cannot re-use state here, because we will wipe current key + ctr(this.key, this.nonce).encrypt(new Uint8Array(this.state.length), this.state); + if (data) { + abytes(data); + // CTR_DRBG without a derivation function pads shorter additional_input + // with zeros to seedlen, so XOR only the provided prefix here. + for (let i = 0; i < data.length; i++) this.state[i] ^= data[i]; + } + // Keep storing V+1 so the next ctr(key, nonce) call starts from the + // spec's post-update counter state. + incBytes(this.nonce, false, 1); + } + // Optional `info` is additional input XORed into the reseed block and is + // limited to the internal state width. + addEntropy(seed: TArg, info?: TArg): void { + abytes(seed, this.state.length, 'seed'); + // Copy caller entropy before XORing in personalization/additional input, + // then wipe the mixed seed material after CTR_DRBG_Update consumes it. + const _seed = seed.slice(); + if (info) { + abytes(info); + if (info.length > _seed.length) throw new Error('info length is too big'); + for (let i = 0; i < info.length; i++) _seed[i] ^= info[i]; + } + this.update(_seed); + _seed.fill(0); + this.reseedCnt = 1; + } + // Optional `info` is additional input for the pre/post-update steps; bytes + // SP 800-90A Rev. 1 CTR_DRBG without a derivation function limits + // additional_input to seedlen, which is exactly this internal state width. + randomBytes(len: number, info?: TArg): TRet { + anumber(len); + // SP 800-90A Table 3 caps AES CTR_DRBG requests at 2^16 bits = 65536 bytes. + if (len > 2 ** 16) throw new Error('requested output is too big'); + // The spec allows generate while reseed_counter == reseed_interval and increments afterwards. + if (this.reseedCnt > 2 ** 48) throw new Error('entropy exhausted'); + if (info) { + abytes(info); + if (info.length > this.state.length) throw new Error('info length is too big'); + this.update(info); + } + const res = new Uint8Array(len); + ctr(this.key, this.nonce).encrypt(res, res); + incBytes(this.nonce, false, Math.ceil(len / this.blockLen)); + this.update(info); + this.reseedCnt++; + return res as TRet; + } + // Zeroes the current state and resets the counter, but does not make the + // instance unusable: later calls continue from the zeroed state. + clean(): void { + // `key` and `nonce` alias this backing buffer, so one fill wipes the full + // secret state in place. + this.state.fill(0); + this.reseedCnt = 0; + } +} + +/** + * Factory for AES-CTR DRBG instances. + * @param seed - Initial entropy input. + * @param personalization - Optional personalization string mixed into the state. + * @returns Seeded AES-CTR DRBG instance. + */ +export type AesCtrDrbg = ( + seed: TArg, + personalization?: TArg +) => TRet<_AesCtrDRBG>; + +// Internal helper for the exported 128-bit and 256-bit aliases; other key +// lengths are not validated here. +const createAesDrbg: (keyLen: number) => TRet = (keyLen) => { + return (seed, personalization = undefined) => + new _AesCtrDRBG(keyLen, seed, personalization) as TRet<_AesCtrDRBG>; +}; + +/** + * AES-CTR DRBG 128-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 32-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg128 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngAesCtrDrbg128(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngAesCtrDrbg128: TRet = /* @__PURE__ */ createAesDrbg(128); +/** + * AES-CTR DRBG 256-bit - CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * @param seed - Initial 48-byte entropy input. + * @param personalization - Optional personalization string. + * @returns Seeded DRBG instance. The concrete methods also accept optional additional-input bytes. + * @example + * Seeds the test-only AES-CTR DRBG from fresh entropy and reads bytes from it. + * + * ```ts + * import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(48); + * const prg = rngAesCtrDrbg256(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngAesCtrDrbg256: TRet = /* @__PURE__ */ createAesDrbg(256); + +//#region CMAC + +/** + * Left-shift by one bit and conditionally XOR with 0x87: + * ``` + * if MSB(L) is equal to 0 + * then K1 := L << 1; + * else K1 := (L << 1) XOR const_Rb; + * ``` + * + * Specs: + * {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3}, + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.3 | RFC 5297 Section 2.3} + * + * @returns modified `block` (for chaining) + */ +function dbl(block: T): T { + let carry = 0; + + // Left shift by 1 bit + for (let i = BLOCK_SIZE - 1; i >= 0; i--) { + const newCarry = (block[i] & 0x80) >>> 7; + block[i] = (block[i] << 1) | carry; + carry = newCarry; + } + + // XOR with 0x87 if there was a carry from the most significant bit + if (carry) { + // RFC 4493 §2.3 / RFC 5297 §2.1: 0x87 is const_Rb for doubling in the + // CMAC/S2V finite field with primitive polynomial x^128 + x^7 + x^2 + x + 1. + block[BLOCK_SIZE - 1] ^= 0x87; + } + + return block; +} + +/** + * `a XOR b`, running in-place on `a`. + * @param a left operand and output + * @param b right operand + * @returns `a` (for chaining) + */ +function xorBlock>(a: T, b: TArg): T { + if (a.length !== b.length) throw new Error('xorBlock: blocks must have same length'); + for (let i = 0; i < a.length; i++) { + a[i] = a[i] ^ b[i]; + } + return a; +} + +/** + * xorend as defined in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.1 | RFC 5297 Section 2.1}. + * + * ``` + * leftmost(A, len(A)-len(B)) || (rightmost(A, len(B)) xor B) + * ``` + * + * Mutates `a` in place so the left prefix stays untouched and only the + * rightmost `len(B)` bytes are xored with `b`. + */ +function xorend>(a: T, b: TArg): T { + if (b.length > a.length) { + throw new Error('xorend: len(B) must be less than or equal to len(A)'); + } + // keep leftmost part of `a` unchanged + // and xor only the rightmost part: + const offset = a.length - b.length; + for (let i = 0; i < b.length; i++) { + a[offset + i] = a[offset + i] ^ b[i]; + } + return a; +} + +/** + * Internal CMAC class. + */ +class _CMAC implements IHash2 { + readonly blockLen: number = BLOCK_SIZE; + readonly outputLen: number = BLOCK_SIZE; + // CMAC can only decide between `K1` and `K2` once the true final block is known, + // so updates process older blocks eagerly but keep one pending block buffered. + private buffer: Uint8Array; + private pos: number; + private finished: boolean; + private destroyed: boolean; + private k1: Uint8Array; + private k2: Uint8Array; + private x: Uint8Array; + private xk: Uint32Array; + + constructor(key: TArg) { + abytes(key); + validateKeyLength(key); + this.xk = expandKeyLE(key); + this.buffer = new Uint8Array(BLOCK_SIZE); + this.pos = 0; + this.finished = false; + this.destroyed = false; + this.x = new Uint8Array(BLOCK_SIZE); + // L = AES_encrypt(K, const_Zero) + const L = new Uint8Array(BLOCK_SIZE); + encryptBlock(this.xk, L); + // Generate subkeys K1 and K2 from the main key according to + // {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.3 | RFC 4493 Section 2.3} + // K1 + this.k1 = dbl(L); + this.k2 = dbl(new Uint8Array(this.k1)); + } + + private process(data: TArg): void { + // RFC 4493 §2.4 step 6 loop body: Y := X XOR M_i; X := AES-128(K, Y). + xorBlock(this.x, data); + encryptBlock(this.xk, this.x); + } + + update(data: TArg): this { + if (this.destroyed) throw new Error('Hash instance has been destroyed'); + if (this.finished) throw new Error('Hash#digest() has already been called'); + abytes(data); + let pos = 0; + if (this.pos) { + const take = Math.min(BLOCK_SIZE - this.pos, data.length); + this.buffer.set(data.subarray(0, take), this.pos); + this.pos += take; + pos = take; + if (this.pos === BLOCK_SIZE && pos < data.length) { + this.process(this.buffer); + this.pos = 0; + } + } + // Keep one complete block buffered: an exact 16-byte tail may still be + // M_n, and digestInto() must decide there whether RFC 4493 uses K1 or K2. + while (pos + BLOCK_SIZE < data.length) { + this.process(data.subarray(pos, pos + BLOCK_SIZE)); + pos += BLOCK_SIZE; + } + if (pos < data.length) { + this.buffer.set(data.subarray(pos), 0); + this.pos = data.length - pos; + } + return this; + } + + // See {@link https://www.rfc-editor.org/rfc/rfc4493.html#section-2.4 | RFC 4493 Section 2.4}. + digestInto(out: TArg): void { + if (this.destroyed) throw new Error('Hash instance has been destroyed'); + if (this.finished) throw new Error('Hash#digest() has already been called'); + // `digestInto(out)` is the no-allocation fast path, so AES block re-use below + // requires a 32-bit-aligned caller buffer instead of hidden temp copies. + aoutput(out, this, true); + this.finished = true; + // `digestInto()` accepts out.length >= outputLen, so only the first block stores the tag. + const view = out.subarray(0, this.outputLen); + let last = new Uint8Array(BLOCK_SIZE); + if (this.pos === BLOCK_SIZE) { + // M_last := M_n XOR K1; + last.set(this.buffer); + xorBlock(last, this.k1); + } else { + // M_last := padding(M_n) XOR K2; + // + // [...] padding(x) is the concatenation of x and a single '1', + // followed by the minimum number of '0's, so that the total length is + // equal to 128 bits. + last.set(this.buffer.subarray(0, this.pos)); + last[this.pos] = 0x80; // single '1' bit + xorBlock(last, this.k2); + } + view.set(this.x); // X := AES_CBC(K, M_1..M_{n-1}) + xorBlock(view, last); // Y := X XOR M_last + encryptBlock(this.xk, view); // T := AES-128(K, Y) + clean(last); + } + + digest(): Uint8ArrayBuffer { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy out before destroy() wipes the internal digest buffer in place. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + + destroy(): void { + const { buffer, destroyed, x, xk, k1, k2 } = this; + if (destroyed) return; + this.destroyed = true; + // Wipe the buffered tail, chaining value, expanded AES key, and both CMAC subkeys. + clean(buffer, x, xk, k1, k2); + } +} + +/** + * AES-CMAC (Cipher-based Message Authentication Code). + * Specs: {@link https://www.rfc-editor.org/rfc/rfc4493.html | RFC 4493}. + * @param msg - Message bytes to authenticate. + * @param key - AES key bytes. + * @returns 16-byte authentication tag. `cmac.create(...)` follows the same incremental MAC shape as + * the other keyed helpers in this repo, including `blockLen`, + * `outputLen`, `digestInto()` and `destroy()`. + * @example + * Authenticates a message with AES-CMAC and a fresh key. + * + * ```ts + * import { cmac } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * cmac(new Uint8Array(), key); + * ``` + */ +// The 16-byte probe key is only used to read static metadata; runtime CMAC +// still accepts AES-128/192/256 keys. +export const cmac: TRet> = /* @__PURE__ */ wrapMacConstructor( + 16, + (key: TArg) => new _CMAC(key) +); + +/** + * S2V (Synthetic Initialization Vector) function as described in + * {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.4 | RFC 5297 Section 2.4}. + * + * ``` + * S2V(K, S1, ..., Sn) { + * if n = 0 then + * return V = AES-CMAC(K, ) + * fi + * D = AES-CMAC(K, ) + * for i = 1 to n-1 do + * D = dbl(D) xor AES-CMAC(K, Si) + * done + * if len(Sn) >= 128 then + * T = Sn xorend D + * else + * T = dbl(D) xor pad(Sn) + * fi + * return V = AES-CMAC(K, T) + * } + * ``` + * + * S2V takes a key and a vector of strings S1, S2, ..., Sn and returns a 128-bit string. + * The S2V function is used to generate a synthetic IV for AES-SIV. + * + * @param key - AES key (128, 192, or 256 bits) + * @param strings - Array of byte arrays to process + * @returns 128-bit synthetic IV + */ +function s2v(key: TArg, strings: TArg): TRet { + validateKeyLength(key); + const len = strings.length; + if (len > 127) { + // RFC 5297 §7 only proves S2V secure for at most 127 components; SIV + // spends one of those on the plaintext, leaving at most 126 AAD inputs. + throw new Error('s2v: number of input strings must be less than or equal to 127'); + } + + if (len === 0) return cmac(ONE_BLOCK, key); + + // D = AES-CMAC(K, ) + let d = cmac(EMPTY_BLOCK, key); + + // for i = 1 to n-1 do + // D = dbl(D) xor AES-CMAC(K, Si) + for (let i = 0; i < len - 1; i++) { + dbl(d); + const cmacResult = cmac(strings[i], key); + xorBlock(d, cmacResult); + clean(cmacResult); + } + + const s_n = strings[len - 1]; + // Earlier components are validated through cmac(...); validate the final one explicitly because + // the Uint8Array.from()/set() paths below would otherwise coerce array-like inputs silently. + abytes(s_n); + let t: Uint8Array; + + // if len(Sn) >= 128 then + if (s_n.byteLength >= BLOCK_SIZE) { + // T = Sn xorend D + t = xorend(Uint8Array.from(s_n), d); + } else { + // pad(Sn): + const paddedSn = new Uint8Array(BLOCK_SIZE); + paddedSn.set(s_n); + paddedSn[s_n.length] = 0x80; // padding: 0x80 followed by zeros + + // T = dbl(D) xor pad(Sn) + t = xorBlock(dbl(d), paddedSn); + clean(paddedSn); + } + + // V = AES-CMAC(K, T) + const result = cmac(t, key); + clean(d, t); + return result; +} + +/** + * Use `gcmsiv` or `aessiv`. + * @returns Never; always throws with the migration hint. + * @throws If called; `siv()` is a removed v1 alias. {@link Error} + * @example + * `siv()` was removed in v2; use `gcmsiv()` for nonce-based SIV instead. + * + * ```ts + * import { gcmsiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcmsiv(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const siv: () => never = () => { + throw new Error('"siv" from v1 is now "gcmsiv"'); +}; + +/** + * **SIV**: Synthetic Initialization Vector (SIV) Authenticated Encryption + * Nonce is derived from the plaintext and AAD using the S2V function. + * Supports at most 126 AAD components. RFC 5297 nonce-based use is expressed by + * passing the nonce as the final AAD component before the plaintext. + * See {@link https://datatracker.ietf.org/doc/html/rfc5297.html | RFC 5297}. + * @param key - 32-byte, 48-byte, or 64-byte key. + * @param AAD - Additional authenticated data chunks (up to 126). + * @returns AEAD cipher instance. + * @example + * Authenticates and encrypts plaintext with a fresh key without requiring unique nonces. + * + * ```ts + * import { aessiv } from '@noble/ciphers/aes.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const cipher = aessiv(key); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const aessiv: TRet< + ((key: TArg, ...AAD: TArg) => Cipher) & { + blockSize: number; + tagLength: number; + } +> = /* @__PURE__ */ wrapCipher( + { blockSize: 16, tagLength: 16 }, + function aessiv(key: TArg, ...AAD: TArg): TRet { + // From RFC 5297: Section 6.1, 6.2, 6.3: + const PLAIN_LIMIT = limit('plaintext', 0, 2 ** 132); + const CIPHER_LIMIT = limit('ciphertext', 16, 2 ** 132 + 16); + if (AAD.length > 126) { + // RFC 5297 §2.6 / §2.7 / §7: SIV passes the plaintext as the last S2V + // component, so callers only get 126 associated-data components. + throw new Error('"AAD" number of elements must be less than or equal to 126'); + } + AAD.forEach((aad) => abytes(aad)); + abytes(key); + if (![32, 48, 64].includes(key.length)) + throw new Error('"aes key" expected Uint8Array of length 32/48/64, got length=' + key.length); + + // The key is split into equal halves, K1 = leftmost(K, len(K)/2) and + // K2 = rightmost(K, len(K)/2). K1 is used for S2V and K2 is used for CTR. + // This borrows caller key/AAD buffers by reference; mutating them after + // construction changes future encrypt/decrypt results. + const k1 = key.subarray(0, key.length / 2); + const k2 = key.subarray(key.length / 2); + + return { + // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.6 | RFC 5297 Section 2.6} + encrypt(plaintext: TArg): TRet { + PLAIN_LIMIT(plaintext.length); + + const v = s2v(k1, [...AAD, plaintext]); + + // clear out the 31st and 63rd (rightmost) bit: + const q = Uint8Array.from(v); + q[8] &= 0x7f; + q[12] &= 0x7f; + + // encrypt: + const c = ctr(k2, q).encrypt(plaintext); + + return concatBytes(v, c); + }, + // {@link https://datatracker.ietf.org/doc/html/rfc5297.html#section-2.7 | RFC 5297 Section 2.7} + decrypt(ciphertext: TArg): TRet { + CIPHER_LIMIT(ciphertext.length); + const v = ciphertext.subarray(0, BLOCK_SIZE); + const c = ciphertext.subarray(BLOCK_SIZE); + + // clear out the 31st and 63rd (rightmost) bit: + const q = Uint8Array.from(v); + q[8] &= 0x7f; + q[12] &= 0x7f; + + // decrypt: + const p = ctr(k2, q).decrypt(c); + + // verify tag: + const t = s2v(k1, [...AAD, p]); + + if (equalBytes(t, v)) { + return p as TRet; + } else { + throw new Error('invalid siv tag'); + } + }, + } as TRet; + } +); +//#endregion + +/** + * Unsafe low-level internal methods. May change at any time. + * Callers are expected to use reviewed expanded-key outputs, pass mutable and + * aligned 16-byte blocks where required, and treat several helpers as in-place + * mutations of their input buffers or counters. + */ +export const unsafe: { + expandKeyLE: typeof expandKeyLE; + expandKeyDecLE: typeof expandKeyDecLE; + encrypt: typeof encrypt; + decrypt: typeof decrypt; + encryptBlock: typeof encryptBlock; + decryptBlock: typeof decryptBlock; + ctrCounter: typeof ctrCounter; + ctr32: typeof ctr32; + dbl: typeof dbl; + xorBlock: typeof xorBlock; + xorend: typeof xorend; + s2v: typeof s2v; +} = /* @__PURE__ */ Object.freeze({ + expandKeyLE, + expandKeyDecLE, + encrypt, + decrypt, + encryptBlock, + decryptBlock, + ctrCounter, + ctr32, + dbl, + xorBlock, + xorend, + s2v, +}); + +export const __TESTS: { incBytes: typeof incBytes } = /* @__PURE__ */ Object.freeze({ + incBytes: incBytes, +}); diff --git a/node_modules/@noble/ciphers/src/chacha.ts b/node_modules/@noble/ciphers/src/chacha.ts new file mode 100644 index 0000000..7b1d7c3 --- /dev/null +++ b/node_modules/@noble/ciphers/src/chacha.ts @@ -0,0 +1,579 @@ +/** + * ChaCha stream cipher, released + * in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round. + * It was standardized in + * {@link https://www.rfc-editor.org/rfc/rfc8439 | RFC 8439} and + * is now used in TLS 1.3. + * + * {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | XChaCha20} + * extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with + * randomly-generated nonces. + * + * Check out + * {@link http://cr.yp.to/chacha/chacha-20080128.pdf | PDF}, + * {@link https://en.wikipedia.org/wiki/Salsa20 | wiki}, and + * {@link https://cr.yp.to/chacha.html | website}. + * + * @module + */ +import { type XorPRG, createCipher, createPRG, rotl } from './_arx.ts'; +import { poly1305 } from './_poly1305.ts'; +import { + type ARXCipher, + type CipherWithOutput, + type TArg, + type TRet, + type XorStream, + abytes, + clean, + equalBytes, + getOutput, + swap8IfBE, + swap32IfBE, + u64Lengths, + wrapCipher, +} from './utils.ts'; + +/** + * ChaCha core function. It is implemented twice: + * 1. Simple loop (chachaCore_small, hchacha_small) + * 2. Unrolled loop (chachaCore, hchacha) - 4x faster, but larger & harder to read + * The specific implementation is selected in `createCipher` below. + */ + +/** RFC 8439 §2.1 quarter round on words a, b, c, d. */ +// prettier-ignore +function chachaQR(x: TArg, a: number, b: number, c: number, d: number) { + x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 16); + x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 12); + x[a] = (x[a] + x[b]) | 0; x[d] = rotl(x[d] ^ x[a], 8); + x[c] = (x[c] + x[d]) | 0; x[b] = rotl(x[b] ^ x[c], 7); +} + +/** Repeated ChaCha double rounds; callers are expected to pass an even round count. */ +function chachaRound(x: TArg, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + // RFC 8439 §2.3 / §2.3.1 inner_block: four column rounds, then four diagonal rounds. + chachaQR(x, 0, 4, 8, 12); + chachaQR(x, 1, 5, 9, 13); + chachaQR(x, 2, 6, 10, 14); + chachaQR(x, 3, 7, 11, 15); + chachaQR(x, 0, 5, 10, 15); + chachaQR(x, 1, 6, 11, 12); + chachaQR(x, 2, 7, 8, 13); + chachaQR(x, 3, 4, 9, 14); + } +} + +// Shared scratch for the auditability-only helper below; only the test-only +// __TESTS.chachaCore_small hook reaches it, so production exports stay reentrant. +const ctmp = /* @__PURE__ */ new Uint32Array(16); + +/** Small version of chacha without loop unrolling. Unused, provided for auditability. */ +// prettier-ignore +function chacha( + s: TArg, k: TArg, i: TArg, out: TArg, + isHChacha: boolean = true, rounds: number = 20 +): void { + // `i` is either `[counter, nonce0, nonce1, nonce2]` for the ChaCha block + // function or the full 128-bit nonce prefix for the HChaCha subkey path. + // Create initial array using common pattern + const y = Uint32Array.from([ + s[0], s[1], s[2], s[3], // "expa" "nd 3" "2-by" "te k" + k[0], k[1], k[2], k[3], // Key Key Key Key + k[4], k[5], k[6], k[7], // Key Key Key Key + i[0], i[1], i[2], i[3], // Counter Counter Nonce Nonce + ]); + const x = ctmp; + x.set(y); + chachaRound(x, rounds); + + // HChaCha writes words 0..3 and 12..15 after the rounds; the ChaCha + // block path adds the original state word-by-word. + if (isHChacha) { + const xindexes = [0, 1, 2, 3, 12, 13, 14, 15]; + for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]]; + } else { + for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0; + } +} + +/** Identical to `chachaCore`. Reached only through the test-only `__TESTS` export. */ +// @ts-ignore +const chachaCore_small: typeof chachaCore = (s, k, n, out, cnt, rounds) => + // Keep the reference wrapper on the same [counter, nonce0, nonce1, nonce2] layout as chacha(). + chacha(s, k, Uint32Array.from([cnt, n[0], n[1], n[2]]), out, false, rounds); +/** Identical to `hchacha`. Unused. */ +// @ts-ignore +const hchacha_small: typeof hchacha = chacha; + +/** RFC 8439 §2.3 block core for `state = constants | key | counter | nonce`. */ +// prettier-ignore +function chachaCore( + s: TArg, k: TArg, n: TArg, out: TArg, cnt: number, rounds = 20 +): void { + let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], // "expa" "nd 3" "2-by" "te k" + y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], // Key Key Key Key + y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], // Key Key Key Key + y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2]; // Counter Nonce Nonce Nonce + // Save state to temporary variables + 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; + for (let r = 0; r < rounds; r += 2) { + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7); + + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7); + + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7); + + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8) + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7); + + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7); + + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7); + + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7); + + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16) + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7); + } + // RFC 8439 §2.3 / §2.3.1: add the original state words back in state order. + let oi = 0; + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} +/** + * hchacha hashes key and nonce into key' and nonce' for xchacha20. + * Algorithmically identical to `hchacha_small`, but this exported path + * normalizes word order on big-endian hosts. + * Need to find a way to merge it with `chachaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XChaCha subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hchacha(sigma, key, nonce, out); + * ``` + */ +// prettier-ignore +export function hchacha( + s: TArg, k: TArg, i: TArg, out: TArg +): void { + let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(s[1]), x02 = swap8IfBE(s[2]), x03 = swap8IfBE(s[3]), + x04 = swap8IfBE(k[0]), x05 = swap8IfBE(k[1]), x06 = swap8IfBE(k[2]), x07 = swap8IfBE(k[3]), + x08 = swap8IfBE(k[4]), x09 = swap8IfBE(k[5]), x10 = swap8IfBE(k[6]), x11 = swap8IfBE(k[7]), + x12 = swap8IfBE(i[0]), x13 = swap8IfBE(i[1]), x14 = swap8IfBE(i[2]), x15 = swap8IfBE(i[3]); + for (let r = 0; r < 20; r += 2) { + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 16); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 12); + x00 = (x00 + x04) | 0; x12 = rotl(x12 ^ x00, 8); + x08 = (x08 + x12) | 0; x04 = rotl(x04 ^ x08, 7); + + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 16); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 12); + x01 = (x01 + x05) | 0; x13 = rotl(x13 ^ x01, 8); + x09 = (x09 + x13) | 0; x05 = rotl(x05 ^ x09, 7); + + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 16); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 12); + x02 = (x02 + x06) | 0; x14 = rotl(x14 ^ x02, 8); + x10 = (x10 + x14) | 0; x06 = rotl(x06 ^ x10, 7); + + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 16); + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 12); + x03 = (x03 + x07) | 0; x15 = rotl(x15 ^ x03, 8) + x11 = (x11 + x15) | 0; x07 = rotl(x07 ^ x11, 7); + + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 16); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 12); + x00 = (x00 + x05) | 0; x15 = rotl(x15 ^ x00, 8); + x10 = (x10 + x15) | 0; x05 = rotl(x05 ^ x10, 7); + + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 16); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 12); + x01 = (x01 + x06) | 0; x12 = rotl(x12 ^ x01, 8); + x11 = (x11 + x12) | 0; x06 = rotl(x06 ^ x11, 7); + + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 16); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 12); + x02 = (x02 + x07) | 0; x13 = rotl(x13 ^ x02, 8); + x08 = (x08 + x13) | 0; x07 = rotl(x07 ^ x08, 7); + + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 16) + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 12); + x03 = (x03 + x04) | 0; x14 = rotl(x14 ^ x03, 8); + x09 = (x09 + x14) | 0; x04 = rotl(x04 ^ x09, 7); + } + // HChaCha derives the subkey from state words 0..3 and 12..15 after 20 rounds. + let oi = 0; + out[oi++] = x00; out[oi++] = x01; + out[oi++] = x02; out[oi++] = x03; + out[oi++] = x12; out[oi++] = x13; + out[oi++] = x14; out[oi++] = x15; + swap32IfBE(out); +} + +/** + * Original, non-RFC chacha20 from DJB. 8-byte nonce, 8-byte counter. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce ChaCha variant and a fresh key/nonce. + * + * ```ts + * import { chacha20orig } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * chacha20orig(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha20orig: TRet = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + allowShortKeys: true, +}); +/** + * ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the RFC 8439 ChaCha20 stream cipher and a fresh key/nonce. + * + * ```ts + * import { chacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + allowShortKeys: false, +}); + +/** + * XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * The nonce/counter layout still reserves 8 counter bytes internally, but the shared public + * `counter` argument follows noble's strict non-wrapping 32-bit policy. See `src/_arx.ts` + * near `MAX_COUNTER` for the full counter-policy rationale. + * @param key - 32-byte key. + * @param nonce - 24-byte extended nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XChaCha20 using a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xchacha20(key, nonce, new Uint8Array(4)); + * ``` + */ +export const xchacha20: TRet = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 8, + extendNonceFn: hchacha, + allowShortKeys: false, +}); + +/** + * Reduced 8-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 8-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha8(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha8: TRet = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 8, +}); + +/** + * Reduced 12-round chacha, described in original paper. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Uses the reduced 12-round variant for non-critical workloads with a fresh key/nonce. + * + * ```ts + * import { chacha12 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * chacha12(key, nonce, new Uint8Array(4)); + * ``` + */ +export const chacha12: TRet = /* @__PURE__ */ createCipher(chachaCore, { + counterRight: false, + counterLength: 4, + rounds: 12, +}); + +// Test-only hooks for keeping the simple/reference core aligned with the unrolled production core. +export const __TESTS: { + chachaCore_small: typeof chachaCore_small; + chachaCore: typeof chachaCore; +} = /* @__PURE__ */ Object.freeze({ chachaCore_small, chachaCore }); + +// RFC 8439 §2.8.1 pad16(x): shared zero block for AAD/ciphertext padding. +const ZEROS16 = /* @__PURE__ */ new Uint8Array(16); +// RFC 8439 §2.8 / §2.8.1: aligned inputs add nothing, otherwise append 16-(len%16) zero bytes. +const updatePadded = (h: ReturnType, msg: TArg) => { + h.update(msg); + const leftover = msg.length % 16; + if (leftover) h.update(ZEROS16.subarray(leftover)); +}; + +// RFC 8439 §2.6.1 poly1305_key_gen returns `block[0..31]`, so AEAD key +// generation only needs 32 zero bytes. +const ZEROS32 = /* @__PURE__ */ new Uint8Array(32); +function computeTag( + fn: TArg, + key: TArg, + nonce: TArg, + ciphertext: TArg, + AAD?: TArg +): TRet { + if (AAD !== undefined) abytes(AAD, undefined, 'AAD'); + // RFC 8439 §2.6 / §2.8: derive the Poly1305 one-time key from counter 0, + // then MAC AAD || pad16(AAD) || ciphertext || pad16(ciphertext) || len(AAD) || len(ciphertext). + const authKey = fn( + key as TRet, + nonce as TRet, + ZEROS32 as TRet + ); + const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true); + + // Methods below can be replaced with + // return poly1305_computeTag_small(authKey, lengths, ciphertext, AAD) + const h = poly1305.create(authKey); + if (AAD) updatePadded(h, AAD); + updatePadded(h, ciphertext); + h.update(lengths); + const res = h.digest(); + clean(authKey, lengths); + return res; +} + +/** + * AEAD algorithm from RFC 8439. + * Salsa20 and chacha (RFC 8439) use poly1305 differently. + * We could have composed them, but it's hard because of authKey: + * In salsa20, authKey changes position in salsa stream. + * In chacha, authKey can't be computed inside computeTag, it modifies the counter. + */ +export const _poly1305_aead = + (xorStream: TArg) => + (key: TArg, nonce: TArg, AAD?: TArg): CipherWithOutput => { + // This borrows caller key/nonce/AAD buffers by reference; mutating them after construction + // changes future encrypt/decrypt results. + const tagLength = 16; + return { + encrypt(plaintext: TArg, output?: TArg): TRet { + const plength = plaintext.length; + output = getOutput(plength + tagLength, output, false); + output.set(plaintext); + const oPlain = output.subarray(0, -tagLength); + // RFC 8439 §2.8: payload encryption starts at counter 1 because counter 0 produced the OTK. + xorStream( + key as TRet, + nonce as TRet, + oPlain as TRet, + oPlain as TRet, + 1 + ); + const tag = computeTag(xorStream, key, nonce, oPlain, AAD); + output.set(tag, plength); // append tag + clean(tag); + return output as TRet; + }, + decrypt(ciphertext: TArg, output?: TArg): TRet { + output = getOutput(ciphertext.length - tagLength, output, false); + const data = ciphertext.subarray(0, -tagLength); + const passedTag = ciphertext.subarray(-tagLength); + const tag = computeTag(xorStream, key, nonce, data, AAD); + // RFC 8439 §2.8 / §4: authenticate ciphertext before decrypting it, and compare tags with + // the constant-time equalBytes() helper rather than decrypting speculative plaintext first. + if (!equalBytes(passedTag, tag)) { + clean(tag); + throw new Error('invalid tag'); + } + output.set(ciphertext.subarray(0, -tagLength)); + // Actual decryption + xorStream( + key as TRet, + nonce as TRet, + output as TRet, + output as TRet, + 1 + ); // start stream with i=1 + clean(tag); + return output as TRet; + }, + }; + }; + +/** + * ChaCha20-Poly1305 from RFC 8439. + * + * Unsafe to use random nonces under the same key, due to collision chance. + * Prefer XChaCha instead. + * @param key - 32-byte key. + * @param nonce - 12-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and nonce. + * + * ```ts + * import { chacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(12); + * const cipher = chacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const chacha20poly1305: TRet = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 12, tagLength: 16 }, + /* @__PURE__ */ _poly1305_aead(chacha20) +); +/** + * XChaCha20-Poly1305 extended-nonce chacha. + * + * Can be safely used with random nonces (CSPRNG). + * See {@link https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha | the IRTF draft}. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Additional authenticated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with a fresh key and random 24-byte nonce. + * + * ```ts + * import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xchacha20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const xchacha20poly1305: TRet = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + /* @__PURE__ */ _poly1305_aead(xchacha20) +); + +/** + * Chacha20 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Compatible with libtomcrypt. It does not have a specification, so unclear how secure it is. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 40-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the test-only ChaCha20 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha20 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha20(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngChacha20: TRet = /* @__PURE__ */ createPRG(chacha20orig, 64, 32, 8); +/** + * Chacha20/8 CSPRNG (cryptographically secure pseudorandom number generator). + * It's best to limit usage to non-production, non-critical cases: for example, test-only. + * Faster than `rngChacha20`. + * @param seed - Optional seed bytes mixed into the internal `key || nonce` state. When omitted, + * only 32 random bytes are mixed into the 44-byte state. + * @returns Seeded concrete `_XorStreamPRG` instance, including `clone()`. + * @example + * Seeds the faster test-only ChaCha8 DRBG from fresh entropy. + * + * ```ts + * import { rngChacha8 } from '@noble/ciphers/chacha.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const seed = randomBytes(32); + * const prg = rngChacha8(seed); + * prg.randomBytes(8); + * ``` + */ +export const rngChacha8: TRet = /* @__PURE__ */ createPRG(chacha8, 64, 32, 12); diff --git a/node_modules/@noble/ciphers/src/ff1.ts b/node_modules/@noble/ciphers/src/ff1.ts new file mode 100644 index 0000000..45a178e --- /dev/null +++ b/node_modules/@noble/ciphers/src/ff1.ts @@ -0,0 +1,221 @@ +/** + * FPE-FF1 (Format-preserving encryption algorithm) specified in + * {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST 800-38G}. + * @module + */ +import { unsafe } from './aes.ts'; +import { + abytes, + anumber, + bytesToNumberBE, + clean, + numberToBytesBE, + type Cipher, + type TArg, + type TRet, +} from './utils.ts'; + +// NIST SP 800-38G §4.3 / §5.1 Algorithm 7: FF1's designated CIPH_K here is AES, so this file +// reuses the reviewed AES key schedule and single-block encryption helpers. +// NOTE: no point in inlining encrypt instead of encryptBlock, since BigInt stuff will be slow +const { expandKeyLE, encryptBlock } = unsafe; + +// Format-preserving encryption algorithm (FPE-FF1) specified in +// {@link https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38G.pdf | NIST Special Publication 800-38G}. + +const BLOCK_LEN = 16; + +// FF1 step 6vi needs mathematical modulo in [0, b); JS `%` is remainder, so decrypt rounds must +// map negative intermediate values back into that range. +function mod(a: number, b: number): number; +function mod(a: bigint, b: bigint): bigint; +function mod(a: any, b: any): number | bigint { + const result = a % b; + return result >= 0 ? result : b + result; +} + +function NUMradix(radix: number, data: number[]): bigint { + let res = BigInt(0); + for (let i of data) res = res * BigInt(radix) + BigInt(i); + return res; +} + +function getRound(radix: number, key: TArg, tweak: TArg, x: number[]) { + if (radix > 2 ** 16 - 1) throw new Error('invalid radix ' + radix); + // radix**minlen ≥ 100 + const minLen = Math.ceil(Math.log(100) / Math.log(radix)); + const maxLen = 2 ** 32 - 1; + // 2 ≤ minlen ≤ maxlen < 2**32 + if (2 > minLen || minLen > maxLen || maxLen >= 2 ** 32) + throw new Error('Invalid radix: 2 ≤ minlen ≤ maxlen < 2**32'); + if (!Array.isArray(x)) throw new Error('invalid X'); + if (x.length < minLen || x.length > maxLen) throw new Error('X is outside minLen..maxLen bounds'); + // SP 800-38G defines FF1 over numeral strings in base `radix`; out-of-range digits must fail + // before NUMradix(...) or round splitting can reinterpret them as a different numeral string. + for (const i of x) { + if (!Number.isSafeInteger(i) || i < 0 || i >= radix) + throw new Error('invalid X: digit outside radix'); + } + const u = Math.floor(x.length / 2); + const v = x.length - u; + const b = Math.ceil(Math.ceil(v * Math.log2(radix)) / 8); + const d = 4 * Math.ceil(b / 4) + 4; + const padding = mod(-tweak.length - b - 1, 16); + // P = [1]1 || [2]1 || [1]1 || [radix]3 || [10]1 || [u mod 256]1 || [n]4 || [t]4. + const P = Uint8Array.from([1, 2, 1, 0, 0, 0, 10, u, 0, 0, 0, 0, 0, 0, 0, 0]); + const view = new DataView(P.buffer); + // NIST SP 800-38G §5.1 bounds radix <= 2^16, so the 24-bit [radix]3 field is encoded here as + // 0x00 || uint16_be(radix). + view.setUint16(4, radix, false); + view.setUint32(8, x.length, false); + view.setUint32(12, tweak.length, false); + // Q = T || [0](−t−b−1) mod 16 || [i]1 || [NUMradix(B)]b. + const PQ = new Uint8Array(P.length + tweak.length + padding + 1 + b); + PQ.set(P); + clean(P); + PQ.set(tweak, P.length); + const xk = expandKeyLE(key); + const round = (A: number[], B: number[], i: number, decrypt = false) => { + // Q = ... || [i]1 || [NUMradix(B)]b. + PQ[PQ.length - b - 1] = i; + if (b) PQ.set(numberToBytesBE(NUMradix(radix, B), b), PQ.length - b); + // NIST SP 800-38G Algorithm 6 PRF: Y_j = CIPH_K(Y_(j-1) xor X_j) starting from Y_0 = 0^128. + let r = new Uint8Array(16); + for (let j = 0; j < PQ.length / BLOCK_LEN; j++) { + for (let i = 0; i < BLOCK_LEN; i++) r[i] ^= PQ[j * BLOCK_LEN + i]; + encryptBlock(xk, r); + } + // Let S be the first d bytes of the following string of ⎡d/16⎤ blocks: + // R || CIPHK(R ⊕[1]16) || CIPHK(R ⊕[2]16) ...CIPHK(R ⊕[⎡d / 16⎤ – 1]16). + let s = Array.from(r); + for (let j = 1; s.length < d; j++) { + const block = numberToBytesBE(BigInt(j), 16); + for (let k = 0; k < BLOCK_LEN; k++) block[k] ^= r[k]; + s.push(...Array.from(encryptBlock(xk, block))); + } + let y = bytesToNumberBE(Uint8Array.from(s.slice(0, d))); + s.fill(0); + if (decrypt) y = -y; + const m = i % 2 === 0 ? u : v; + let c = mod(NUMradix(radix, A) + y, BigInt(radix) ** BigInt(m)); + // STR(radix, m, c) + const C = Array(m).fill(0); + for (let i = 0; i < m; i++, c /= BigInt(radix)) C[m - 1 - i] = Number(c % BigInt(radix)); + A.fill(0); + A = B; + B = C; + return [A, B]; + }; + const destroy = () => { + clean(xk, PQ); + }; + return { u, round, destroy }; +} + +const EMPTY_BUF = /* @__PURE__ */ Uint8Array.of(); + +/** + * FPE-FF1 format-preserving encryption. + * @param radix - Alphabet size for each input digit. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over digit arrays. + * @example + * Encrypts decimal digits without changing their format, using a fresh AES key. + * + * ```ts + * import { FF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = FF1(10, key); + * ff1.encrypt([1, 2, 3]); + * ``` + */ +export function FF1( + radix: number, + key: TArg, + tweak: TArg = EMPTY_BUF +): { encrypt(x: number[]): number[]; decrypt(x: number[]): number[] } { + anumber(radix); + abytes(key); + abytes(tweak); + // This borrows caller key/tweak buffers by reference through the bound closure; mutating them + // after construction changes later encrypt/decrypt outputs. + const PQ = getRound.bind(null, radix, key, tweak); + return { + encrypt(x: number[]): number[] { + const { u, round, destroy } = PQ(x); + let [A, B] = [x.slice(0, u), x.slice(u)]; + for (let i = 0; i < 10; i++) [A, B] = round(A, B, i); + destroy(); + const res = A.concat(B); + A.fill(0); + B.fill(0); + return res; + }, + decrypt(x: number[]): number[] { + const { u, round, destroy } = PQ(x); + // The FF1.Decrypt algorithm is similar to the FF1.Encrypt algorithm; + // the differences are in Step 6, where: + // 1) the order of the indices is reversed, + // 2) the roles of A and B are swapped + // 3) modular addition is replaced by modular subtraction, in Step 6vi. + let [B, A] = [x.slice(0, u), x.slice(u)]; + for (let i = 9; i >= 0; i--) [A, B] = round(A, B, i, true); + destroy(); + const res = B.concat(A); + A.fill(0); + B.fill(0); + return res; + }, + }; +} +// Binary wrapper uses little-endian bit order within each byte so bit 0 stays +// in the first numeral slot for this library-defined byte-array surface. +const binLE = { + encode(bytes: TArg): number[] { + const x = []; + for (let i = 0; i < bytes.length; i++) { + for (let j = 0, tmp = bytes[i]; j < 8; j++, tmp >>= 1) x.push(tmp & 1); + } + return x; + }, + decode(b: number[]): TRet { + if (!Array.isArray(b) || b.length % 8) throw new Error('Invalid binary string'); + const res = new Uint8Array(b.length / 8); + for (let i = 0, j = 0; i < res.length; i++) { + res[i] = b[j++] | (b[j++] << 1) | (b[j++] << 2) | (b[j++] << 3); + res[i] |= (b[j++] << 4) | (b[j++] << 5) | (b[j++] << 6) | (b[j++] << 7); + } + return res as TRet; + }, +}; + +/** + * Binary FPE-FF1 wrapper over byte arrays. + * @param key - AES key bytes. + * @param tweak - Optional tweak bytes. + * @returns Encrypt/decrypt helpers over byte arrays. + * @example + * Encrypts raw bytes through FF1's binary alphabet wrapper with a fresh AES key. + * + * ```ts + * import { BinaryFF1 } from '@noble/ciphers/ff1.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const ff1 = BinaryFF1(key); + * ff1.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export function BinaryFF1( + key: TArg, + tweak: TArg = EMPTY_BUF +): TRet { + const ff1 = FF1(2, key, tweak); + return { + encrypt: (x: TArg): TRet => + binLE.decode(ff1.encrypt(binLE.encode(x))) as TRet, + decrypt: (x: TArg): TRet => + binLE.decode(ff1.decrypt(binLE.encode(x))) as TRet, + } as TRet; +} diff --git a/node_modules/@noble/ciphers/src/index.ts b/node_modules/@noble/ciphers/src/index.ts new file mode 100644 index 0000000..466af82 --- /dev/null +++ b/node_modules/@noble/ciphers/src/index.ts @@ -0,0 +1,25 @@ +/** + * Audited & minimal JS implementation of Salsa20, ChaCha and AES. Check out individual modules. + * @example +```js +import { gcm, aessiv } from '@noble/ciphers/aes.js'; +import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; +import { secretbox } from '@noble/ciphers/salsa.js'; // == xsalsa20poly1305 +import { chacha20poly1305, xchacha20poly1305 } from '@noble/ciphers/chacha.js'; + +// Unauthenticated encryption: make sure to use HMAC or similar +import { ctr, cfb, cbc, ecb } from '@noble/ciphers/aes.js'; +import { salsa20, xsalsa20 } from '@noble/ciphers/salsa.js'; +import { chacha20, xchacha20, chacha8, chacha12 } from '@noble/ciphers/chacha.js'; + +// KW +import { aeskw, aeskwp } from '@noble/ciphers/aes.js'; + +// Utilities +import { managedNonce, randomBytes, bytesToHex, hexToBytes } from '@noble/ciphers/utils.js'; +import { poly1305 } from '@noble/ciphers/_poly1305.js'; +import { ghash, polyval } from '@noble/ciphers/_polyval.js'; +``` + * @module + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/node_modules/@noble/ciphers/src/salsa.ts b/node_modules/@noble/ciphers/src/salsa.ts new file mode 100644 index 0000000..840fbc1 --- /dev/null +++ b/node_modules/@noble/ciphers/src/salsa.ts @@ -0,0 +1,374 @@ +/** + * Salsa20 stream cipher, released in 2005. + * Salsa's goal was to implement AES replacement that does not rely on S-Boxes, + * which are hard to implement in a constant-time manner. + * Salsa20 is usually faster than AES, a big deal on slow, budget mobile phones. + * + * - {@link https://cr.yp.to/snuffle/xsalsa-20110204.pdf | XSalsa20}, + * extended-nonce + * variant was released in 2008. It extends Salsa20's 64-bit nonce to 192 bits, + * and became safe to be picked at random. + * - Nacl / Libsodium popularized term "secretbox", - which is just xsalsa20poly1305. + * We provide the alias and corresponding seal / open methods. + * "crypto_box" and "sealedbox" are available in package + * {@link https://github.com/serenity-kit/noble-sodium | noble-sodium}. + * - Check out + * {@link https://cr.yp.to/snuffle/salsafamily-20071225.pdf | PDF} + * and {@link https://cr.yp.to/snuffle.html | website}. + * @module + */ +import { createCipher, rotl } from './_arx.ts'; +import { poly1305 } from './_poly1305.ts'; +import { + abytes, + clean, + equalBytes, + getOutput, + swap32IfBE, + swap8IfBE, + wrapCipher, + type ARXCipher, + type CipherWithOutput, + type TArg, + type TRet, + type XorStream, +} from './utils.ts'; + +/** + * Salsa20 core function. It is implemented twice: + * 1. Simple loop (salsaCore_small, hsalsa_small) + * 2. Unrolled loop (salsaCore, hsalsa) - 4x faster, but larger & harder to read + * The specific implementation is selected in `createCipher` below. + * Performance numbers for 1MB inputs: + * * default x 779 ops/sec @ 1ms/op + * * if salsa+hsalsa are merged x 459 ops/sec @ 2ms/op + * * small x 132 ops/sec @ 7ms/op + */ + +/** RFC 7914 §3 Salsa20/8 core quarter-round on words a, b, c, d. */ +function salsaQR(x: TArg, a: number, b: number, c: number, d: number) { + x[b] ^= rotl((x[a] + x[d]) | 0, 7); + x[c] ^= rotl((x[b] + x[a]) | 0, 9); + x[d] ^= rotl((x[c] + x[b]) | 0, 13); + x[a] ^= rotl((x[d] + x[c]) | 0, 18); +} + +/** RFC 7914 §3 double-round schedule: four column rounds, then four row rounds. */ +function salsaRound(x: TArg, rounds = 20) { + for (let r = 0; r < rounds; r += 2) { + salsaQR(x, 0, 4, 8, 12); + salsaQR(x, 5, 9, 13, 1); + salsaQR(x, 10, 14, 2, 6); + salsaQR(x, 15, 3, 7, 11); + salsaQR(x, 0, 1, 2, 3); + salsaQR(x, 5, 6, 7, 4); + salsaQR(x, 10, 11, 8, 9); + salsaQR(x, 15, 12, 13, 14); + } +} + +// Shared scratch for the unused auditability helper below; it would be +// non-reentrant under overlapping/nested calls, but current code doesn't invoke it. +const stmp = /* @__PURE__ */ new Uint32Array(16); + +/** Small version of salsa without loop unrolling. Unused, provided for auditability. */ +// prettier-ignore +function salsa( + s: TArg, k: TArg, i: TArg, out: TArg, + isHSalsa: boolean = true, rounds: number = 20 +): void { + // Create initial array using common pattern + const y = Uint32Array.from([ + s[0], k[0], k[1], k[2], // "expa" Key Key Key + k[3], s[1], i[0], i[1], // Key "nd 3" Nonce Nonce + i[2], i[3], s[2], k[4], // Pos. Pos. "2-by" Key + k[5], k[6], k[7], s[3], // Key Key Key "te k" + ]); + const x = stmp; + x.set(y); + // const x = y.slice(); + salsaRound(x, rounds); + + // hsalsa extracts 8 specific words for the 32-byte subkey; salsa adds the original state. + if (isHSalsa) { + const xindexes = [0, 5, 10, 15, 6, 7, 8, 9]; + for (let i = 0; i < 8; i++) out[i] = x[xindexes[i]]; + } else { + for (let i = 0; i < 16; i++) out[i] = (y[i] + x[i]) | 0; + } +} +/** Identical to `salsaCore`. Unused. */ +// @ts-ignore +const salsaCore_small: typeof salsaCore = (s, k, n, out, cnt, rounds) => + salsa(s, k, Uint32Array.from([n[0], n[1], cnt, 0]), out, false, rounds); +/** Identical to `hsalsa`. Unused. */ +// @ts-ignore +const hsalsa_small: typeof hsalsa = salsa; + +/** Identical to `salsaCore_small`. Uses only the low 32 bits of Salsa20's 64-bit counter state. */ +// prettier-ignore +function salsaCore( + s: TArg, k: TArg, n: TArg, out: TArg, cnt: number, rounds = 20 +): void { + // Public wrappers expose only the low 32 bits of Salsa20's 64-bit counter; y09 stays zero. + // Based on {@link https://cr.yp.to/salsa20.html | the Salsa20 reference page}. + let y00 = s[0], y01 = k[0], y02 = k[1], y03 = k[2], // "expa" Key Key Key + y04 = k[3], y05 = s[1], y06 = n[0], y07 = n[1], // Key "nd 3" Nonce Nonce + y08 = cnt, y09 = 0, y10 = s[2], y11 = k[4], // Pos. Pos. "2-by" Key + y12 = k[5], y13 = k[6], y14 = k[7], y15 = s[3]; // Key Key Key "te k" + // Save state to temporary variables + 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; + for (let r = 0; r < rounds; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output + let oi = 0; + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +/** + * hsalsa hashes key and nonce-prefix words into the 32-byte subkey used by XSalsa20. + * Identical to `hsalsa_small`. + * Need to find a way to merge it with `salsaCore` without 25% performance hit. + * @param s - Sigma constants as 32-bit words. + * @param k - Key words. + * @param i - Nonce-prefix words. + * @param out - Output buffer for the derived subkey. + * @example + * Derives the XSalsa20 subkey from sigma, key, and nonce-prefix words. + * + * ```ts + * const sigma = new Uint32Array(4); + * const key = new Uint32Array(8); + * const nonce = new Uint32Array(4); + * const out = new Uint32Array(8); + * hsalsa(sigma, key, nonce, out); + * ``` + */ +// prettier-ignore +export function hsalsa( + s: TArg, k: TArg, i: TArg, out: TArg +): void { + let x00 = swap8IfBE(s[0]), x01 = swap8IfBE(k[0]), x02 = swap8IfBE(k[1]), x03 = swap8IfBE(k[2]), + x04 = swap8IfBE(k[3]), x05 = swap8IfBE(s[1]), x06 = swap8IfBE(i[0]), x07 = swap8IfBE(i[1]), + x08 = swap8IfBE(i[2]), x09 = swap8IfBE(i[3]), x10 = swap8IfBE(s[2]), x11 = swap8IfBE(k[4]), + x12 = swap8IfBE(k[5]), x13 = swap8IfBE(k[6]), x14 = swap8IfBE(k[7]), x15 = swap8IfBE(s[3]); + for (let r = 0; r < 20; r += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + let oi = 0; + // XSalsa20 takes words 0,5,10,15 and 6,7,8,9 as the 32-byte subkey material. + out[oi++] = x00; out[oi++] = x05; + out[oi++] = x10; out[oi++] = x15; + out[oi++] = x06; out[oi++] = x07; + out[oi++] = x08; out[oi++] = x09; + swap32IfBE(out); +} + +/** + * Salsa20 from original paper. 8-byte nonce. + * With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance. + * @param key - 16-byte or 32-byte key. + * @param nonce - 8-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * Only the low 32 bits of Salsa20's 64-bit counter state are exposed here; + * the high word stays zero and the implementation still caps the public + * value to 32 bits. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with the original 8-byte-nonce Salsa20 stream cipher. + * + * ```ts + * import { salsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(8); + * salsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export const salsa20: TRet = /* @__PURE__ */ createCipher(salsaCore, { + allowShortKeys: true, + counterRight: true, +}); + +/** + * XSalsa20 extended-nonce salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * @param key - 32-byte key. + * This XSalsa20 wrapper does not enable Salsa20's 16-byte legacy key mode. + * @param nonce - 24-byte nonce. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Initial block counter. + * @returns Encrypted or decrypted bytes. + * @example + * Encrypts bytes with XSalsa20 and a random 24-byte nonce. + * + * ```ts + * import { xsalsa20 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * xsalsa20(key, nonce, new Uint8Array([1, 2, 3, 4])); + * ``` + */ +export const xsalsa20: TRet = /* @__PURE__ */ createCipher(salsaCore, { + counterRight: true, + extendNonceFn: hsalsa, +}); + +/** + * xsalsa20-poly1305 eXtended-nonce (24 bytes) salsa. + * With 24-byte nonce, it's safe to make it random (CSPRNG). + * Also known as `secretbox` from libsodium / nacl. + * No AAD input is supported here. Caller-provided `output` buffers for + * `encrypt()` / `decrypt()` must be `input.length + 32` bytes because the + * implementation uses a 32-byte leading scratch area before returning `+16`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @param AAD - Must be omitted; XSalsa20-Poly1305 secretbox does not support associated data. + * @returns AEAD cipher instance. + * @example + * Encrypts and authenticates plaintext with XSalsa20-Poly1305. + * + * ```ts + * import { xsalsa20poly1305 } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const cipher = xsalsa20poly1305(key, nonce); + * cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const xsalsa20poly1305: TRet = /* @__PURE__ */ wrapCipher( + { blockSize: 64, nonceLength: 24, tagLength: 16 }, + (key: TArg, nonce: TArg): TRet => { + // This borrows caller key/nonce buffers by reference; mutating them after construction changes + // later encrypt/decrypt outputs. + return { + encrypt(plaintext: TArg, output?: TArg): TRet { + // xsalsa20poly1305 optimizes by calculating auth key during the same call as encryption. + // Unfortunately, makes it hard to separate tag calculation & encryption itself, + // because 32 bytes is half-block of 64-byte salsa. + // Need 32 extra bytes up front for the auth-key scratch area described above. + output = getOutput(plaintext.length + 32, output, false); + // output[0..32] = Poly1305 auth key, output[32..] = plaintext then ciphertext. + const authKey = output.subarray(0, 32); + const ciphPlaintext = output.subarray(32); + output.set(plaintext, 32); + // authKey is produced by xoring the first 32 bytes with zeros. + clean(authKey); + // output = stream ^ output; authKey = stream ^ zeros(32) + xsalsa20(key, nonce, output, output); + const tag = poly1305(ciphPlaintext, authKey); + output.set(tag, 16); + // Clean up auth-key remnants and the temporary tag copy. + clean(output.subarray(0, 16), tag); + // Return output[16..]. + return output.subarray(16) as TRet; + }, + decrypt(ciphertext: TArg, output?: TArg): TRet { + // tmp part passed tag ciphertext + // [0..32] [32..48] [48..] + // Authenticate the ciphertext before decrypting it; on tag failure the scratch/output + // buffer may already contain copied ciphertext and derived auth-key material. + abytes(ciphertext); + output = getOutput(ciphertext.length + 32, output, false); + // output[0..32] is auth-key scratch, output[32..48] is passed tag, + // output[48..] is ciphertext then plaintext. + const tmp = output.subarray(0, 32); + const passedTag = output.subarray(32, 48); + const ciphPlaintext = output.subarray(48); + output.set(ciphertext, 32); + // authKey is produced by xoring the scratch area with zeros. + clean(tmp); + const authKey = xsalsa20(key, nonce, tmp, tmp); + const tag = poly1305(ciphPlaintext, authKey); + if (!equalBytes(passedTag, tag)) { + clean(output); + throw new Error('invalid tag'); + } + // output = stream ^ output[16..] + xsalsa20(key, nonce, output.subarray(16), output.subarray(16)); + clean(tmp, passedTag, tag); + // Return output[48..], skipping zeroized output[0..48]. + return ciphPlaintext as TRet; + }, + } as TRet; + } +); + +/** + * Alias to `xsalsa20poly1305`, for compatibility with libsodium / nacl. + * Check out {@link https://github.com/serenity-kit/noble-sodium | noble-sodium} + * for `crypto_box`. + * @param key - 32-byte key. + * @param nonce - 24-byte nonce. + * @returns Wrapper with `seal()` and `open()` helpers. + * @example + * Uses the libsodium-style `seal()` and `open()` wrapper. + * + * ```ts + * import { secretbox } from '@noble/ciphers/salsa.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(32); + * const nonce = randomBytes(24); + * const box = secretbox(key, nonce); + * box.seal(new Uint8Array([1, 2, 3])); + * ``` + */ +export function secretbox( + key: TArg, + nonce: TArg +): TRet<{ + seal: (plaintext: TArg, output?: TArg) => TRet; + open: (ciphertext: TArg, output?: TArg) => TRet; +}> { + const xs = xsalsa20poly1305(key, nonce); + return { seal: xs.encrypt, open: xs.decrypt } as TRet<{ + seal: (plaintext: TArg, output?: TArg) => TRet; + open: (ciphertext: TArg, output?: TArg) => TRet; + }>; +} diff --git a/node_modules/@noble/ciphers/src/utils.ts b/node_modules/@noble/ciphers/src/utils.ts new file mode 100644 index 0000000..08b6d0d --- /dev/null +++ b/node_modules/@noble/ciphers/src/utils.ts @@ -0,0 +1,1191 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ + +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array + ? BigInt64Array + : T extends BigUint64Array + ? BigUint64Array + : T extends Float32Array + ? Float32Array + : T extends Float64Array + ? Float64Array + : T extends Int16Array + ? Int16Array + : T extends Int32Array + ? Int32Array + : T extends Int8Array + ? Int8Array + : T extends Uint16Array + ? Uint16Array + : T extends Uint32Array + ? Uint32Array + : T extends Uint8ClampedArray + ? Uint8ClampedArray + : T extends Uint8Array + ? Uint8Array + : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array + ? ReturnType + : T extends BigUint64Array + ? ReturnType + : T extends Float32Array + ? ReturnType + : T extends Float64Array + ? ReturnType + : T extends Int16Array + ? ReturnType + : T extends Int32Array + ? ReturnType + : T extends Int8Array + ? ReturnType + : T extends Uint16Array + ? ReturnType + : T extends Uint32Array + ? ReturnType + : T extends Uint8ClampedArray + ? ReturnType + : T extends Uint8Array + ? ReturnType + : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = + | T + | ([TypedArg] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TRet }) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; + } + : T extends [infer A, ...infer R] + ? [TArg, ...{ [K in keyof R]: TArg }] + : T extends readonly [infer A, ...infer R] + ? readonly [TArg, ...{ [K in keyof R]: TArg }] + : T extends (infer A)[] + ? TArg[] + : T extends readonly (infer A)[] + ? readonly TArg[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TArg } + : T + : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown + ? T & + ([TypedRet] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TArg }) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; + } + : T extends [infer A, ...infer R] + ? [TRet, ...{ [K in keyof R]: TRet }] + : T extends readonly [infer A, ...infer R] + ? readonly [TRet, ...{ [K in keyof R]: TRet }] + : T extends (infer A)[] + ? TRet[] + : T extends readonly (infer A)[] + ? readonly TRet[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TRet } + : T + : TypedRet) + : never; + +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - Value to inspect. + * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`. + * @example + * Guards a value before treating it as raw key material. + * + * ```ts + * isBytes(new Uint8Array()); + * ``` + */ +export function isBytes(a: unknown): a is Uint8Array { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / + // cross-realm cases. The fallback still requires a real ArrayBuffer view + // so plain JSON-deserialized `{ constructor: ... }` + // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return ( + a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1) + ); +} + +/** + * Asserts something is boolean. + * @param b - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validates a boolean option before branching on it. + * + * ```ts + * abool(true); + * ``` + */ +export function abool(b: boolean): void { + if (typeof b !== 'boolean') throw new TypeError(`boolean expected, not ${b}`); +} + +/** + * Asserts something is a non-negative safe integer. + * @param n - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validates a non-negative length or counter. + * + * ```ts + * anumber(1); + * ``` + */ +export function anumber(n: number): void { + if (typeof n !== 'number') throw new TypeError('number expected, got ' + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError('positive integer expected, got ' + n); +} + +/** + * Asserts something is Uint8Array. + * @param value - Value to validate. + * @param length - Expected byte length. + * @param title - Optional label used in error messages. + * @returns The validated byte array. + * On Node, `Buffer` is accepted too because it is a Uint8Array view. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument lengths. {@link RangeError} + * @example + * Validates a fixed-length nonce or key buffer. + * + * ```ts + * abytes(new Uint8Array([1, 2]), 2); + * ``` + */ +export function abytes( + value: TArg, + length?: number, + title: string = '' +): TRet { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== undefined; + if (!bytes || (needsLen && len !== length)) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ''; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) throw new TypeError(message); + throw new RangeError(message); + } + return value as TRet; +} + +/** + * Asserts a hash- or MAC-like instance has not been destroyed or finished. + * @param instance - Stateful instance to validate. + * @param checkFinished - Whether to reject finished instances. + * When `false`, only `destroyed` is checked. + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Guards against calling `update()` or `digest()` on a finished hash. + * + * ```ts + * aexists({ destroyed: false, finished: false }); + * ``` + */ +export function aexists(instance: any, checkFinished = true): void { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} + +/** + * Asserts output is a properly-sized byte array. + * @param out - Output buffer to validate. + * @param instance - Hash-like instance providing `outputLen`. + * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`, + * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths. + * @throws On wrong argument types. {@link TypeError} + * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views. + * @throws On wrong output buffer lengths. {@link RangeError} + * @throws On wrong output buffer alignment. {@link Error} + * @example + * Verifies that a caller-provided output buffer is large enough. + * + * ```ts + * aoutput(new Uint8Array(16), { outputLen: 16 }); + * ``` + */ +export function aoutput(out: any, instance: any, onlyAligned = false): void { + abytes(out, undefined, 'output'); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('digestInto() expects output buffer of length at least ' + min); + } + if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned'); +} + +/** One-shot hash helper with `.create()`. */ +export type IHash = { + (data: string | TArg): TRet; + /** Input block size in bytes. */ + blockLen: number; + /** Digest size in bytes. */ + outputLen: number; + /** Creates a fresh incremental hash instance of the same algorithm. */ + create: any; +}; + +/** One-shot MAC helper with `.create()`. */ +export type CMac = { + (msg: TArg, key: TArg): TRet; + /** Input block size in bytes. */ + blockLen: number; + /** Digest size in bytes. */ + outputLen: number; + /** + * Creates a fresh incremental MAC instance of the same algorithm. + * @param key - MAC key bytes. + * @param args - Additional constructor arguments, when the MAC wrapper needs them. + * @returns Fresh incremental MAC instance. + */ + create(key: TArg, ...args: A): H; +}; + +/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */ +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +/** + * Casts a typed-array view to Uint8Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint8Array view over the same bytes. + * @example + * Views 32-bit words as raw bytes without copying. + * + * ```ts + * u8(new Uint32Array([1])); + * ``` + */ +export function u8(arr: TArg): TRet { + return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet; +} + +/** + * Casts a typed-array view to Uint32Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint32Array view over the same bytes. Callers are expected to provide a + * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped. + * @example + * Views a byte buffer as 32-bit words for block processing. + * + * ```ts + * u32(new Uint8Array(4)); + * ``` + */ +export function u32(arr: TArg): TRet { + return new Uint32Array( + arr.buffer, + arr.byteOffset, + Math.floor(arr.byteLength / 4) + ) as TRet; +} + +/** + * Zeroizes typed arrays in place. + * Warning: JS provides no guarantees. + * @param arrays - Arrays to wipe. + * @example + * Wipes a temporary key buffer after use. + * + * ```ts + * const bytes = new Uint8Array([1]); + * clean(bytes); + * ``` + */ +export function clean(...arrays: TArg): void { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +/** + * Creates a DataView for byte-level manipulation. + * @param arr - Typed-array view to wrap. + * @returns DataView over the same bytes. + * @example + * Creates an endian-aware view for length encoding. + * + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export function createView(arr: TArg): DataView { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} + +/** + * Whether the current platform is little-endian. + * Most are; some IBM systems are not. + */ +export const isLE: boolean = /* @__PURE__ */ (() => + new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); + +/** + * Reverses byte order of one 32-bit word. + * @param word - Unsigned 32-bit word to swap. + * @returns The same word with bytes reversed. + * @example + * Swaps a big-endian word into little-endian byte order. + * + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export const byteSwap = (word: number): number => + ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); + +/** + * Normalizes one 32-bit word to the little-endian representation expected by cipher cores. + * @param n - Unsigned 32-bit word to normalize. + * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged. + * @example + * Normalizes a host-endian word before passing it into an ARX/AES core. + * + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export const swap8IfBE: (n: number) => number = isLE + ? (n: number) => n + : (n: number) => byteSwap(n) >>> 0; + +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - Uint32Array whose words should be swapped. + * @returns The same array after in-place byte swapping. + * @example + * Swaps every 32-bit word in a word-view buffer. + * + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export const byteSwap32 = (arr: TArg): TRet => { + for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]); + return arr as TRet; +}; + +/** + * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores. + * @param u - Word view to normalize in place. + * @returns Little-endian normalized word view. + * @example + * Normalizes a word-view buffer before block processing. + * + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export const swap32IfBE: (u: TArg) => TRet = isLE + ? (u: TArg) => u as TRet + : byteSwap32; + +// Built-in hex conversion: +// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry} +const hasHexBuiltin: boolean = /* @__PURE__ */ (() => + // @ts-ignore + typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); + +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); + +/** + * Convert byte array to hex string. Uses built-in function, when available. + * @param bytes - Bytes to encode. + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Formats ciphertext bytes for logs or test vectors. + * + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export function bytesToHex(bytes: TArg): string { + abytes(bytes); + // @ts-ignore + if (hasHexBuiltin) return bytes.toHex(); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const; +function asciiToBase16(ch: number): number | undefined { + if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48 + if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10) + if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10) + return; +} + +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - Hexadecimal string to decode. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On malformed hexadecimal input. {@link RangeError} + * @example + * Parses a hex test vector into bytes. + * + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export function hexToBytes(hex: string): TRet { + if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex); + if (hasHexBuiltin) { + try { + return (Uint8Array as any).fromHex(hex); + } catch (error) { + if (error instanceof SyntaxError) throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError( + 'hex string expected, got non-hex character "' + char + '" at index ' + hi + ); + } + array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163 + } + return array as TRet; +} + +// Used in micro +/** + * Converts a big-endian hex string into bigint. + * @param hex - Hexadecimal string without `0x`. + * @returns Parsed bigint value. The empty string is treated as `0n`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parses a big-endian field element or counter from hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex); + return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian +} + +// Used in ff1 +// BE: Big Endian, LE: Little Endian +/** + * Converts big-endian bytes into bigint. + * @param bytes - Big-endian bytes. + * @returns Parsed bigint value. Empty input is treated as `0n`. + * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError} + * @example + * Reads a big-endian integer from serialized bytes. + * + * ```ts + * bytesToNumberBE(new Uint8Array([1, 0])); + * ``` + */ +export function bytesToNumberBE(bytes: TArg): bigint { + return hexToNumber(bytesToHex(bytes)); +} + +// Used in micro, ff1 +/** + * Converts a number into big-endian bytes of fixed length. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Big-endian bytes padded to `len`. + * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`, + * and values that do not fit surface through the downstream hex parser instead of a + * dedicated range guard here. + * @throws On wrong argument types. {@link TypeError} + * @throws If the requested output length cannot represent the encoded value. {@link RangeError} + * @example + * Encodes a counter as fixed-width big-endian bytes. + * + * ```ts + * numberToBytesBE(1, 2); + * ``` + */ +export function numberToBytesBE(n: number | bigint, len: number): TRet { + // Reject coercible non-numeric inputs before string/hex conversion changes behavior. + if (typeof n === 'number') anumber(n); + else if (typeof n !== 'bigint') throw new TypeError(`number or bigint expected, got ${typeof n}`); + anumber(len); + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} + +// Global symbols, but ts doesn't see them: +// {@link https://github.com/microsoft/TypeScript/issues/31535 | TypeScript issue 31535} +declare const TextEncoder: any; +declare const TextDecoder: any; + +/** + * Converts string to bytes using UTF8 encoding. + * @param str - String to encode. + * @returns UTF-8 bytes in a detached fresh Uint8Array copy. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encodes application text before encryption or MACing. + * + * ```ts + * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99]) + * ``` + */ +export function utf8ToBytes(str: string): TRet { + if (typeof str !== 'string') throw new TypeError('string expected'); + return new Uint8Array(new TextEncoder().encode(str)) as TRet; // {@link https://bugzil.la/1681809 | Firefox bug 1681809} +} + +/** + * Converts bytes to string using UTF8 encoding. + * @param bytes - UTF-8 bytes. + * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed + * UTF-8 is replacement-decoded instead of rejected. + * @example + * Decodes UTF-8 plaintext back into a string. + * + * ```ts + * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc' + * ``` + */ +export function bytesToUtf8(bytes: TArg): string { + return new TextDecoder().decode(bytes); +} + +/** + * Checks if two U8A use same underlying buffer and overlaps. + * This is invalid and can corrupt data. + * @param a - First byte view. + * @param b - Second byte view. + * @returns `true` when the views overlap in memory. + * @example + * Detects whether two slices alias the same backing buffer. + * + * ```ts + * overlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export function overlapBytes(a: TArg, b: TArg): boolean { + // Zero-length views cannot overwrite anything, even if their offset sits inside another range. + if (!a.byteLength || !b.byteLength) return false; + return ( + a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy + a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end + b.byteOffset < a.byteOffset + a.byteLength // b starts before a end + ); +} + +/** + * If input and output overlap and input starts before output, we will overwrite end of input before + * we start processing it, so this is not supported for most ciphers + * (except chacha/salsa, which were designed for this) + * @param input - Input bytes. + * @param output - Output bytes. + * @throws If the output view would overwrite unread input bytes. {@link Error} + * @example + * Rejects an in-place layout that would overwrite unread input bytes. + * + * ```ts + * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export function complexOverlapBytes(input: TArg, output: TArg): void { + // This is very cursed. It works somehow, but I'm completely unsure, + // reasoning about overlapping aligned windows is very hard. + if (overlapBytes(input, output) && input.byteOffset < output.byteOffset) + throw new Error('complex overlap of input and output is not supported'); +} + +/** + * Copies several Uint8Arrays into one. + * @param arrays - Byte arrays to concatenate. + * @returns Combined byte array. + * @throws On wrong argument types inside the byte-array list. {@link TypeError} + * @example + * Builds a `nonce || ciphertext` style buffer. + * + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export function concatBytes(...arrays: TArg): TRet { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res as TRet; +} + +// Used in ARX only +type EmptyObj = {}; +/** + * Merges user options into defaults. + * @param defaults - Default option values. + * @param opts - User-provided overrides. + * @returns Combined options object. + * The merge mutates `defaults` in place and returns the same object. + * @throws If options are missing or not an object. {@link Error} + * @example + * Applies user overrides to the default cipher options. + * + * ```ts + * checkOpts({ rounds: 20 }, { rounds: 8 }); + * ``` + */ +export function checkOpts( + defaults: T1, + opts: T2 +): T1 & T2 { + if (opts == null || typeof opts !== 'object') throw new Error('options must be defined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +/** + * Compares two byte arrays in kinda constant time once lengths already match. + * @param a - First byte array. + * @param b - Second byte array. + * @returns `true` when the arrays contain the same bytes. Different lengths still return early. + * @example + * Compares an expected authentication tag with the received one. + * + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export function equalBytes(a: TArg, b: TArg): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; + return diff === 0; +} + +// TODO: remove +/** Incremental hash interface used internally. */ +export interface IHash2 { + /** Bytes processed per compression block. */ + blockLen: number; + /** Bytes produced by the final digest. */ + outputLen: number; + /** + * Absorbs one more chunk into the hash state. + * @param buf - Data chunk to hash. + * @returns The same hash instance for chaining. + */ + update(buf: string | TArg): this; + /** + * Writes the final digest into a caller-provided buffer. + * @param buf - Destination buffer for the digest bytes. + * @returns Nothing. Implementations write into `buf` in place. + */ + digestInto(buf: TArg): void; + /** + * Finalizes the hash and returns a fresh digest buffer. + * @returns Digest bytes. + */ + digest(): TRet; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + destroy(): void; +} + +/** + * Wraps a keyed MAC constructor into a one-shot helper with `.create()`. + * @param keyLen - Valid probe-key length used to read static metadata once. + * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes + * can pass any representative size as long as those values stay fixed. + * @param macCons - Keyed MAC constructor or factory. + * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message. + * @returns Callable MAC helper with `.create()`. + */ +export function wrapMacConstructor( + keyLen: number, + macCons: TArg<(key: Uint8Array, ...args: A) => H>, + fromMsg?: TArg<(msg: Uint8Array) => A> +): TRet> { + const mac = macCons as (key: TArg, ...args: A) => H; + const getArgs = (fromMsg || (() => [] as unknown as A)) as (msg: TArg) => A; + const macC: any = (msg: TArg, key: TArg): TRet => + mac(key, ...getArgs(msg)) + .update(msg) + .digest(); + const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); + macC.outputLen = tmp.outputLen; + macC.blockLen = tmp.blockLen; + macC.create = (key: TArg, ...args: A) => mac(key, ...args); + return macC as TRet>; +} + +// This will allow to re-use with composable things like packed & base encoders +// Also, we probably can make tags composable + +/** Sync cipher: takes byte array and returns byte array. */ +export type Cipher = { + /** + * Encrypts plaintext bytes. + * @param plaintext - Data to encrypt. + * @returns Ciphertext bytes. + */ + encrypt(plaintext: TArg): TRet; + /** + * Decrypts ciphertext bytes. + * @param ciphertext - Data to decrypt. + * @returns Plaintext bytes. + */ + decrypt(ciphertext: TArg): TRet; +}; + +/** Async cipher e.g. from built-in WebCrypto. */ +export type AsyncCipher = { + /** + * Encrypts plaintext bytes. + * @param plaintext - Data to encrypt. + * @returns Promise resolving to ciphertext bytes. + */ + encrypt(plaintext: TArg): Promise>; + /** + * Decrypts ciphertext bytes. + * @param ciphertext - Data to decrypt. + * @returns Promise resolving to plaintext bytes. + */ + decrypt(ciphertext: TArg): Promise>; +}; + +/** Cipher with `output` argument which can optimize by doing 1 less allocation. */ +export type CipherWithOutput = Cipher & { + /** + * Encrypts plaintext bytes into an optional caller-provided buffer. + * @param plaintext - Data to encrypt. + * @param output - Optional destination buffer. + * @returns Ciphertext bytes. + */ + encrypt(plaintext: TArg, output?: TArg): TRet; + /** + * Decrypts ciphertext bytes into an optional caller-provided buffer. + * @param ciphertext - Data to decrypt. + * @param output - Optional destination buffer. + * @returns Plaintext bytes. + */ + decrypt(ciphertext: TArg, output?: TArg): TRet; +}; + +/** + * Params are outside of return type, so it is accessible before calling constructor. + * If function support multiple nonceLength's, we return the best one. + */ +export type CipherParams = { + /** Cipher block size in bytes. */ + blockSize: number; + /** Nonce length in bytes when the cipher uses a fixed nonce size. */ + nonceLength?: number; + /** Authentication-tag length in bytes for AEAD modes. */ + tagLength?: number; + /** Whether nonce length is variable at runtime. */ + varSizeNonce?: boolean; +}; +/** + * ARX AEAD cipher, like salsa or chacha. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param AAD - Optional associated data. + * @returns Cipher instance with caller-managed output buffers. + */ +export type ARXCipher = (( + key: TArg, + nonce: TArg, + AAD?: TArg +) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * Cipher constructor signature. + * @param key - Secret key bytes. + * @param args - Additional constructor arguments, such as nonce or IV. + * @returns Cipher instance. + */ +export type CipherCons = (key: TArg, ...args: T) => Cipher; +/** + * Wraps a cipher: validates args, ensures encrypt() can only be called once. + * Used internally by the exported cipher constructors. + * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt` + * arity (`fn.length === 2`), and tag-bearing constructors are expected to use + * `args[1]` for optional AAD. + * @__NO_SIDE_EFFECTS__ + * @param params - Static cipher metadata. See {@link CipherParams}. + * @param constructor - Cipher constructor. + * @returns Wrapped constructor with validation. + */ +export const wrapCipher = , P extends CipherParams>( + params: P, + constructor: C +): C & P => { + function wrappedCipher(key: TArg, ...args: any[]): TRet { + // Validate key + abytes(key, undefined, 'key'); + + // Validate nonce if nonceLength is present + if (params.nonceLength !== undefined) { + const nonce = args[0]; + abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce'); + } + + // Validate AAD if tagLength present + const tagl = params.tagLength; + if (tagl && args[1] !== undefined) abytes(args[1], undefined, 'AAD'); + + const cipher = constructor(key, ...args); + const checkOutput = (fnLength: number, output?: TArg) => { + if (output !== undefined) { + if (fnLength !== 2) throw new Error('cipher output not supported'); + abytes(output, undefined, 'output'); + } + }; + // Create wrapped cipher with validation and single-use encryption + let called = false; + const wrCipher = { + encrypt(data: TArg, output?: TArg) { + if (called) throw new Error('cannot encrypt() twice with same key + nonce'); + called = true; + abytes(data); + checkOutput(cipher.encrypt.length, output); + return (cipher as CipherWithOutput).encrypt(data, output); + }, + decrypt(data: TArg, output?: TArg) { + abytes(data); + if (tagl && data.length < tagl) + throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); + checkOutput(cipher.decrypt.length, output); + return (cipher as CipherWithOutput).decrypt(data, output); + }, + }; + + return wrCipher as TRet; + } + + Object.assign(wrappedCipher, params); + return wrappedCipher as C & P; +}; + +/** + * Represents a Salsa or ChaCha xor stream. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Optional starting block counter. + * @returns Output bytes. + */ +export type XorStream = ( + key: TArg, + nonce: TArg, + data: TArg, + output?: TArg, + counter?: number +) => TRet; + +/** + * By default, returns u8a of length. + * When out is available, it checks it for validity and uses it. + * @param expectedLength - Required output length. + * @param out - Optional destination buffer. + * @param onlyAligned - Whether `out` must be 4-byte aligned. + * @returns Output buffer ready for writing. + * @throws On wrong argument types. {@link TypeError} + * @throws If the provided output buffer has the wrong size or alignment. {@link Error} + * @example + * Reuses a caller-provided output buffer when lengths match. + * + * ```ts + * getOutput(16, new Uint8Array(16)); + * ``` + */ +export function getOutput( + expectedLength: number, + out?: TArg, + onlyAligned = true +): TRet { + if (out === undefined) return new Uint8Array(expectedLength) as TRet; + // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object. + abytes(out, undefined, 'output'); + if (out.length !== expectedLength) + throw new Error( + '"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length + ); + if (onlyAligned && !isAligned32(out)) throw new Error('invalid output, must be aligned'); + return out as TRet; +} + +/** + * Encodes data and AAD bit lengths into a 16-byte buffer. + * @param dataLength - Data length in bits. + * @param aadLength - AAD length in bits. + * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305 + * conventions even though the helper parameter order is `(dataLength, aadLength)`. + * @param isLE - Whether to encode lengths as little-endian. + * @returns 16-byte length block. + * @throws On wrong argument types passed to the endian validator. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Builds the length block appended by GCM and Poly1305. + * + * ```ts + * u64Lengths(16, 8, true); + * ``` + */ +export function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet { + // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them. + anumber(dataLength); + anumber(aadLength); + abool(isLE); + const num = new Uint8Array(16); + const view = createView(num); + view.setBigUint64(0, BigInt(aadLength), isLE); + view.setBigUint64(8, BigInt(dataLength), isLE); + return num as TRet; +} + +/** + * Checks whether a byte array is aligned to a 4-byte offset. + * @param bytes - Byte array to inspect. + * @returns `true` when the view is 4-byte aligned. + * @example + * Checks whether a buffer can be safely viewed as Uint32Array. + * + * ```ts + * isAligned32(new Uint8Array(4)); + * ``` + */ +export function isAligned32(bytes: TArg): boolean { + return bytes.byteOffset % 4 === 0; +} + +/** + * Copies bytes into a new Uint8Array. + * @param bytes - Bytes to copy. + * @returns Copied byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Copies input into an aligned Uint8Array before block processing. + * + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export function copyBytes(bytes: TArg): TRet { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)) as TRet; +} + +/** + * Cryptographically secure PRNG. + * Uses internal OS-level `crypto.getRandomValues`. + * @param bytesLength - Number of bytes to produce. + * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so + * non-integers, negative lengths, and oversize requests surface backend/runtime errors. + * @returns Random byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error} + * @example + * Generates a fresh nonce or key. + * + * ```ts + * randomBytes(16); + * ``` + */ +export function randomBytes(bytesLength = 32): TRet { + // Validate upfront so fractional / coercible lengths do not silently + // truncate through Uint8Array(). + anumber(bytesLength); + const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + return cr.getRandomValues(new Uint8Array(bytesLength)) as TRet; +} + +/** + * The pseudorandom number generator doesn't wipe current state: + * instead, it generates new one based on previous state + entropy. + * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes, + * which is in fact `reseed`, since it changes counter too. + */ +export interface PRG { + /** + * Mixes fresh entropy into the current generator state. + * @param seed - Entropy bytes to absorb. + */ + addEntropy(seed: TArg): void; + /** + * Produces a requested number of pseudorandom bytes. + * @param bytesLength - Number of bytes to generate. + * @returns Random byte array. + */ + randomBytes(bytesLength: number): TRet; + /** Destroys the generator state. */ + clean(): void; +} + +/** Removes the nonce argument from a cipher constructor type. */ +export type RemoveNonce any> = T extends ( + arg0: any, + arg1: any, + ...rest: infer R +) => infer Ret + ? (key: TArg, ...args: R) => Ret + : never; +/** + * Cipher constructor that requires a nonce argument. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param args - Additional cipher-specific arguments. + * @returns Cipher instance. + */ +export type CipherWithNonce = (( + key: TArg, + nonce: TArg, + ...args: any[] +) => Cipher | AsyncCipher) & { + nonceLength: number; +}; + +/** + * Uses CSPRNG for nonce, nonce injected in ciphertext. + * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and + * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext + * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext` + * buffer on encrypt and intentionally does not support caller-provided destination buffers. + * Too-short decrypt inputs are split into short/empty nonce views and then delegated + * to the wrapped cipher instead of being rejected here first. + * + * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha + * should be limited to `2**23` (8M) messages to get a collision chance of + * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to + * `2**-33`, still negligible but creeping up. + * @param fn - Cipher constructor that expects a nonce. + * @param randomBytes_ - Random-byte source used for nonce generation. + * @returns Cipher constructor that prepends the nonce to ciphertext. + * @throws On wrong argument types. {@link TypeError} + * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError} + * @example + * Prepends a fresh random nonce to every ciphertext. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js'; + * const wrapped = managedNonce(gcm); + * const key = randomBytes(16); + * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3])); + * wrapped(key).decrypt(ciphertext); + * ``` + */ +export function managedNonce( + fn: T, + randomBytes_: typeof randomBytes = randomBytes +): TRet> { + const { nonceLength } = fn; + anumber(nonceLength); + const addNonce = ( + nonce: TArg, + ciphertext: TArg, + plaintext: TArg + ) => { + const out = concatBytes(nonce, ciphertext); + // Wrapped ciphers may alias caller plaintext on encrypt(); never zero + // caller-owned buffers here. + if (!overlapBytes(plaintext, ciphertext)) ciphertext.fill(0); + return out; + }; + // NOTE: we cannot support DST here, it would be mistake: + // - we don't know how much dst length cipher requires + // - nonce may unalign dst and break everything + // - we create new u8a anyway (concatBytes) + // - previously we passed all args to cipher, but that was mistake! + const res = ((key: TArg, ...args: any[]): any => ({ + encrypt(plaintext: TArg) { + abytes(plaintext); + const nonce = randomBytes_(nonceLength); + const encrypted = fn(key, nonce, ...args).encrypt(plaintext); + // @ts-ignore + if (encrypted instanceof Promise) + return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); + return addNonce(nonce, encrypted, plaintext); + }, + decrypt(ciphertext: TArg) { + abytes(ciphertext); + const nonce = ciphertext.subarray(0, nonceLength); + const decrypted = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(decrypted); + }, + })) as RemoveNonce & { blockSize?: number; tagLength?: number }; + // Auto-nonce wrappers still preserve the wrapped payload geometry. + if ('blockSize' in fn) res.blockSize = (fn as any).blockSize; + if ('tagLength' in fn) res.tagLength = (fn as any).tagLength; + return res as TRet>; +} + +/** `Uint8Array.of()` return type helper for TS 5.9. */ +export type Uint8ArrayBuffer = TRet; diff --git a/node_modules/@noble/ciphers/src/webcrypto.ts b/node_modules/@noble/ciphers/src/webcrypto.ts new file mode 100644 index 0000000..889d91e --- /dev/null +++ b/node_modules/@noble/ciphers/src/webcrypto.ts @@ -0,0 +1,226 @@ +/** + * WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`. + * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. + * @module + */ +import { abytes, anumber, type AsyncCipher, type TArg, type TRet } from './utils.ts'; + +function getWebcryptoSubtle(): any { + const cr = typeof globalThis !== 'undefined' && (globalThis as any).crypto; + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} + +type WebcryptoUtils = { + encrypt( + key: TArg, + keyParams: unknown, + cryptParams: unknown, + plaintext: TArg + ): Promise>; + decrypt( + key: TArg, + keyParams: unknown, + cryptParams: unknown, + ciphertext: TArg + ): Promise>; +}; +/** + * Internal webcrypto utils. Can be overridden if crypto.subtle is not present, + * for example in React Native. + * Raw keys are re-imported on every call; this wrapper intentionally does not + * cache `CryptoKey` objects between operations. + */ +export const utils: TRet = { + async encrypt( + key: TArg, + keyParams: any, + cryptParams: any, + plaintext: TArg + ): Promise> { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']); + const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext); + return new Uint8Array(ciphertext) as TRet; + }, + async decrypt( + key: TArg, + keyParams: any, + cryptParams: any, + ciphertext: TArg + ): Promise> { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']); + const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext); + return new Uint8Array(plaintext) as TRet; + }, +}; + +const mode = { + CBC: 'AES-CBC', + CTR: 'AES-CTR', + GCM: 'AES-GCM', +} as const; +type BlockMode = (typeof mode)[keyof typeof mode]; + +function getCryptParams(algo: BlockMode, nonce: TArg, AAD?: TArg) { + if (algo === mode.CBC) return { name: mode.CBC, iv: nonce }; + // WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap. + if (algo === mode.CTR) return { name: mode.CTR, counter: nonce, length: 128 }; + if (algo === mode.GCM) { + // Rely on the backend default tag length (128 bits) instead of setting it explicitly. + if (AAD) return { name: mode.GCM, iv: nonce, additionalData: AAD }; + else return { name: mode.GCM, iv: nonce }; + } + + throw new Error('unknown aes block mode'); +} + +function generate( + algo: BlockMode, + nonceLength: number +): TRet< + ((key: TArg, nonce: TArg, AAD?: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; + } +> { + anumber(nonceLength); + const res = ( + key: TArg, + nonce: TArg, + AAD?: TArg + ): TRet => { + abytes(key); + abytes(nonce); + // Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD". + if (AAD !== undefined) abytes(AAD, undefined, 'AAD'); + // Exact nonce-length enforcement and WebCrypto-specific AAD normalization are + // delegated to the backend; locally we only require byte-array inputs here. + // Keep caller key/nonce/AAD by reference; mutating them after + // construction changes later operations. + const keyParams = { name: algo, length: key.length * 8 }; + const cryptParams = getCryptParams(algo, nonce, AAD); + let consumed = false; + return { + // keyLength, + encrypt(plaintext: TArg): Promise> { + abytes(plaintext); + if (consumed) throw new Error('Cannot encrypt() twice with same key / nonce'); + consumed = true; + return utils.encrypt(key, keyParams, cryptParams, plaintext); + }, + decrypt(ciphertext: TArg): Promise> { + abytes(ciphertext); + return utils.decrypt(key, keyParams, cryptParams, ciphertext); + }, + } as TRet; + }; + res.nonceLength = nonceLength; + res.blockSize = 16; // always for AES + return res as TRet< + ((key: TArg, nonce: TArg, AAD?: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; + } + >; +} + +/** + * AES-CBC implemented with WebCrypto. + * Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are + * delegated to the backend instead of local `abytes(..., 16)` validation. + * @param key - AES key bytes. + * @param iv - 16-byte initialization vector. + * @returns Async cipher instance. + * @example + * Encrypts a block with the browser or Node WebCrypto backend. + * + * ```ts + * import { cbc } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * await cipher.encrypt(new Uint8Array(16)); + * ``` + */ +export const cbc: TRet< + ((key: TArg, iv: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ (() => generate(mode.CBC, 16))(); +/** + * AES-CTR implemented with WebCrypto. + * Uses WebCrypto's full 128-bit counter-length setting so the whole + * 16-byte counter block is incremented, matching sync `aes.ts:ctr`. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block incremented as a full big-endian AES counter block. + * @returns Async cipher instance. + * @example + * Encrypts a short payload with WebCrypto AES-CTR. + * + * ```ts + * import { ctr } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ctr: TRet< + ((key: TArg, nonce: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ (() => generate(mode.CTR, 16))(); +/** + * AES-GCM implemented with WebCrypto. + * AAD type normalization and nonce-shape enforcement beyond raw bytes are left + * to the backend WebCrypto implementation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes. + * @param AAD - Additional authenticated data. + * @returns Async cipher instance. + * @example + * Encrypts and authenticates plaintext with WebCrypto AES-GCM. + * + * ```ts + * import { gcm } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcm: TRet< + ((key: TArg, nonce: TArg, AAD?: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; + } +> = /* @__PURE__ */ (() => generate(mode.GCM, 12))(); + +// // Type tests +// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts'; +// import { xsalsa20poly1305 } from '../salsa.ts'; +// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts'; + +// const wsiv = managedNonce(siv); +// const wgcm = managedNonce(gcm); +// const wctr = managedNonce(ctr); +// const wcbc = managedNonce(cbc); +// const wsalsapoly = managedNonce(xsalsa20poly1305); +// const wchacha = managedNonce(chacha20poly1305); +// const wxchacha = managedNonce(xchacha20poly1305); + +// // should fail +// const wcbc2 = managedNonce(managedNonce(cbc)); +// const wctr = managedNonce(ctr); +// import { gcm as gcmSync } from '../aes.ts'; +// const x1 = managedNonce(gcmSync); +// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher +// const x2 = managedNonce(gcm); +// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher diff --git a/node_modules/@noble/ciphers/utils.d.ts b/node_modules/@noble/ciphers/utils.d.ts new file mode 100644 index 0000000..2aee9df --- /dev/null +++ b/node_modules/@noble/ciphers/utils.d.ts @@ -0,0 +1,717 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - Value to inspect. + * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`. + * @example + * Guards a value before treating it as raw key material. + * + * ```ts + * isBytes(new Uint8Array()); + * ``` + */ +export declare function isBytes(a: unknown): a is Uint8Array; +/** + * Asserts something is boolean. + * @param b - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validates a boolean option before branching on it. + * + * ```ts + * abool(true); + * ``` + */ +export declare function abool(b: boolean): void; +/** + * Asserts something is a non-negative safe integer. + * @param n - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validates a non-negative length or counter. + * + * ```ts + * anumber(1); + * ``` + */ +export declare function anumber(n: number): void; +/** + * Asserts something is Uint8Array. + * @param value - Value to validate. + * @param length - Expected byte length. + * @param title - Optional label used in error messages. + * @returns The validated byte array. + * On Node, `Buffer` is accepted too because it is a Uint8Array view. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument lengths. {@link RangeError} + * @example + * Validates a fixed-length nonce or key buffer. + * + * ```ts + * abytes(new Uint8Array([1, 2]), 2); + * ``` + */ +export declare function abytes(value: TArg, length?: number, title?: string): TRet; +/** + * Asserts a hash- or MAC-like instance has not been destroyed or finished. + * @param instance - Stateful instance to validate. + * @param checkFinished - Whether to reject finished instances. + * When `false`, only `destroyed` is checked. + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Guards against calling `update()` or `digest()` on a finished hash. + * + * ```ts + * aexists({ destroyed: false, finished: false }); + * ``` + */ +export declare function aexists(instance: any, checkFinished?: boolean): void; +/** + * Asserts output is a properly-sized byte array. + * @param out - Output buffer to validate. + * @param instance - Hash-like instance providing `outputLen`. + * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`, + * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths. + * @throws On wrong argument types. {@link TypeError} + * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views. + * @throws On wrong output buffer lengths. {@link RangeError} + * @throws On wrong output buffer alignment. {@link Error} + * @example + * Verifies that a caller-provided output buffer is large enough. + * + * ```ts + * aoutput(new Uint8Array(16), { outputLen: 16 }); + * ``` + */ +export declare function aoutput(out: any, instance: any, onlyAligned?: boolean): void; +/** One-shot hash helper with `.create()`. */ +export type IHash = { + (data: string | TArg): TRet; + /** Input block size in bytes. */ + blockLen: number; + /** Digest size in bytes. */ + outputLen: number; + /** Creates a fresh incremental hash instance of the same algorithm. */ + create: any; +}; +/** One-shot MAC helper with `.create()`. */ +export type CMac = { + (msg: TArg, key: TArg): TRet; + /** Input block size in bytes. */ + blockLen: number; + /** Digest size in bytes. */ + outputLen: number; + /** + * Creates a fresh incremental MAC instance of the same algorithm. + * @param key - MAC key bytes. + * @param args - Additional constructor arguments, when the MAC wrapper needs them. + * @returns Fresh incremental MAC instance. + */ + create(key: TArg, ...args: A): H; +}; +/** Generic type encompassing 8/16/32-bit typed arrays, but not 64-bit. */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +/** + * Casts a typed-array view to Uint8Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint8Array view over the same bytes. + * @example + * Views 32-bit words as raw bytes without copying. + * + * ```ts + * u8(new Uint32Array([1])); + * ``` + */ +export declare function u8(arr: TArg): TRet; +/** + * Casts a typed-array view to Uint32Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint32Array view over the same bytes. Callers are expected to provide a + * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped. + * @example + * Views a byte buffer as 32-bit words for block processing. + * + * ```ts + * u32(new Uint8Array(4)); + * ``` + */ +export declare function u32(arr: TArg): TRet; +/** + * Zeroizes typed arrays in place. + * Warning: JS provides no guarantees. + * @param arrays - Arrays to wipe. + * @example + * Wipes a temporary key buffer after use. + * + * ```ts + * const bytes = new Uint8Array([1]); + * clean(bytes); + * ``` + */ +export declare function clean(...arrays: TArg): void; +/** + * Creates a DataView for byte-level manipulation. + * @param arr - Typed-array view to wrap. + * @returns DataView over the same bytes. + * @example + * Creates an endian-aware view for length encoding. + * + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export declare function createView(arr: TArg): DataView; +/** + * Whether the current platform is little-endian. + * Most are; some IBM systems are not. + */ +export declare const isLE: boolean; +/** + * Reverses byte order of one 32-bit word. + * @param word - Unsigned 32-bit word to swap. + * @returns The same word with bytes reversed. + * @example + * Swaps a big-endian word into little-endian byte order. + * + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export declare const byteSwap: (word: number) => number; +/** + * Normalizes one 32-bit word to the little-endian representation expected by cipher cores. + * @param n - Unsigned 32-bit word to normalize. + * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged. + * @example + * Normalizes a host-endian word before passing it into an ARX/AES core. + * + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export declare const swap8IfBE: (n: number) => number; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - Uint32Array whose words should be swapped. + * @returns The same array after in-place byte swapping. + * @example + * Swaps every 32-bit word in a word-view buffer. + * + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export declare const byteSwap32: (arr: TArg) => TRet; +/** + * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores. + * @param u - Word view to normalize in place. + * @returns Little-endian normalized word view. + * @example + * Normalizes a word-view buffer before block processing. + * + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export declare const swap32IfBE: (u: TArg) => TRet; +/** + * Convert byte array to hex string. Uses built-in function, when available. + * @param bytes - Bytes to encode. + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Formats ciphertext bytes for logs or test vectors. + * + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export declare function bytesToHex(bytes: TArg): string; +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - Hexadecimal string to decode. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On malformed hexadecimal input. {@link RangeError} + * @example + * Parses a hex test vector into bytes. + * + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export declare function hexToBytes(hex: string): TRet; +/** + * Converts a big-endian hex string into bigint. + * @param hex - Hexadecimal string without `0x`. + * @returns Parsed bigint value. The empty string is treated as `0n`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parses a big-endian field element or counter from hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export declare function hexToNumber(hex: string): bigint; +/** + * Converts big-endian bytes into bigint. + * @param bytes - Big-endian bytes. + * @returns Parsed bigint value. Empty input is treated as `0n`. + * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError} + * @example + * Reads a big-endian integer from serialized bytes. + * + * ```ts + * bytesToNumberBE(new Uint8Array([1, 0])); + * ``` + */ +export declare function bytesToNumberBE(bytes: TArg): bigint; +/** + * Converts a number into big-endian bytes of fixed length. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Big-endian bytes padded to `len`. + * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`, + * and values that do not fit surface through the downstream hex parser instead of a + * dedicated range guard here. + * @throws On wrong argument types. {@link TypeError} + * @throws If the requested output length cannot represent the encoded value. {@link RangeError} + * @example + * Encodes a counter as fixed-width big-endian bytes. + * + * ```ts + * numberToBytesBE(1, 2); + * ``` + */ +export declare function numberToBytesBE(n: number | bigint, len: number): TRet; +/** + * Converts string to bytes using UTF8 encoding. + * @param str - String to encode. + * @returns UTF-8 bytes in a detached fresh Uint8Array copy. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encodes application text before encryption or MACing. + * + * ```ts + * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99]) + * ``` + */ +export declare function utf8ToBytes(str: string): TRet; +/** + * Converts bytes to string using UTF8 encoding. + * @param bytes - UTF-8 bytes. + * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed + * UTF-8 is replacement-decoded instead of rejected. + * @example + * Decodes UTF-8 plaintext back into a string. + * + * ```ts + * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc' + * ``` + */ +export declare function bytesToUtf8(bytes: TArg): string; +/** + * Checks if two U8A use same underlying buffer and overlaps. + * This is invalid and can corrupt data. + * @param a - First byte view. + * @param b - Second byte view. + * @returns `true` when the views overlap in memory. + * @example + * Detects whether two slices alias the same backing buffer. + * + * ```ts + * overlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export declare function overlapBytes(a: TArg, b: TArg): boolean; +/** + * If input and output overlap and input starts before output, we will overwrite end of input before + * we start processing it, so this is not supported for most ciphers + * (except chacha/salsa, which were designed for this) + * @param input - Input bytes. + * @param output - Output bytes. + * @throws If the output view would overwrite unread input bytes. {@link Error} + * @example + * Rejects an in-place layout that would overwrite unread input bytes. + * + * ```ts + * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export declare function complexOverlapBytes(input: TArg, output: TArg): void; +/** + * Copies several Uint8Arrays into one. + * @param arrays - Byte arrays to concatenate. + * @returns Combined byte array. + * @throws On wrong argument types inside the byte-array list. {@link TypeError} + * @example + * Builds a `nonce || ciphertext` style buffer. + * + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export declare function concatBytes(...arrays: TArg): TRet; +type EmptyObj = {}; +/** + * Merges user options into defaults. + * @param defaults - Default option values. + * @param opts - User-provided overrides. + * @returns Combined options object. + * The merge mutates `defaults` in place and returns the same object. + * @throws If options are missing or not an object. {@link Error} + * @example + * Applies user overrides to the default cipher options. + * + * ```ts + * checkOpts({ rounds: 20 }, { rounds: 8 }); + * ``` + */ +export declare function checkOpts(defaults: T1, opts: T2): T1 & T2; +/** + * Compares two byte arrays in kinda constant time once lengths already match. + * @param a - First byte array. + * @param b - Second byte array. + * @returns `true` when the arrays contain the same bytes. Different lengths still return early. + * @example + * Compares an expected authentication tag with the received one. + * + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export declare function equalBytes(a: TArg, b: TArg): boolean; +/** Incremental hash interface used internally. */ +export interface IHash2 { + /** Bytes processed per compression block. */ + blockLen: number; + /** Bytes produced by the final digest. */ + outputLen: number; + /** + * Absorbs one more chunk into the hash state. + * @param buf - Data chunk to hash. + * @returns The same hash instance for chaining. + */ + update(buf: string | TArg): this; + /** + * Writes the final digest into a caller-provided buffer. + * @param buf - Destination buffer for the digest bytes. + * @returns Nothing. Implementations write into `buf` in place. + */ + digestInto(buf: TArg): void; + /** + * Finalizes the hash and returns a fresh digest buffer. + * @returns Digest bytes. + */ + digest(): TRet; + /** + * Resets internal state. Makes Hash instance unusable. + * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed + * by user, they will need to manually call `destroy()` when zeroing is necessary. + */ + destroy(): void; +} +/** + * Wraps a keyed MAC constructor into a one-shot helper with `.create()`. + * @param keyLen - Valid probe-key length used to read static metadata once. + * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes + * can pass any representative size as long as those values stay fixed. + * @param macCons - Keyed MAC constructor or factory. + * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message. + * @returns Callable MAC helper with `.create()`. + */ +export declare function wrapMacConstructor(keyLen: number, macCons: TArg<(key: Uint8Array, ...args: A) => H>, fromMsg?: TArg<(msg: Uint8Array) => A>): TRet>; +/** Sync cipher: takes byte array and returns byte array. */ +export type Cipher = { + /** + * Encrypts plaintext bytes. + * @param plaintext - Data to encrypt. + * @returns Ciphertext bytes. + */ + encrypt(plaintext: TArg): TRet; + /** + * Decrypts ciphertext bytes. + * @param ciphertext - Data to decrypt. + * @returns Plaintext bytes. + */ + decrypt(ciphertext: TArg): TRet; +}; +/** Async cipher e.g. from built-in WebCrypto. */ +export type AsyncCipher = { + /** + * Encrypts plaintext bytes. + * @param plaintext - Data to encrypt. + * @returns Promise resolving to ciphertext bytes. + */ + encrypt(plaintext: TArg): Promise>; + /** + * Decrypts ciphertext bytes. + * @param ciphertext - Data to decrypt. + * @returns Promise resolving to plaintext bytes. + */ + decrypt(ciphertext: TArg): Promise>; +}; +/** Cipher with `output` argument which can optimize by doing 1 less allocation. */ +export type CipherWithOutput = Cipher & { + /** + * Encrypts plaintext bytes into an optional caller-provided buffer. + * @param plaintext - Data to encrypt. + * @param output - Optional destination buffer. + * @returns Ciphertext bytes. + */ + encrypt(plaintext: TArg, output?: TArg): TRet; + /** + * Decrypts ciphertext bytes into an optional caller-provided buffer. + * @param ciphertext - Data to decrypt. + * @param output - Optional destination buffer. + * @returns Plaintext bytes. + */ + decrypt(ciphertext: TArg, output?: TArg): TRet; +}; +/** + * Params are outside of return type, so it is accessible before calling constructor. + * If function support multiple nonceLength's, we return the best one. + */ +export type CipherParams = { + /** Cipher block size in bytes. */ + blockSize: number; + /** Nonce length in bytes when the cipher uses a fixed nonce size. */ + nonceLength?: number; + /** Authentication-tag length in bytes for AEAD modes. */ + tagLength?: number; + /** Whether nonce length is variable at runtime. */ + varSizeNonce?: boolean; +}; +/** + * ARX AEAD cipher, like salsa or chacha. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param AAD - Optional associated data. + * @returns Cipher instance with caller-managed output buffers. + */ +export type ARXCipher = ((key: TArg, nonce: TArg, AAD?: TArg) => CipherWithOutput) & { + blockSize: number; + nonceLength: number; + tagLength: number; +}; +/** + * Cipher constructor signature. + * @param key - Secret key bytes. + * @param args - Additional constructor arguments, such as nonce or IV. + * @returns Cipher instance. + */ +export type CipherCons = (key: TArg, ...args: T) => Cipher; +/** + * Wraps a cipher: validates args, ensures encrypt() can only be called once. + * Used internally by the exported cipher constructors. + * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt` + * arity (`fn.length === 2`), and tag-bearing constructors are expected to use + * `args[1]` for optional AAD. + * @__NO_SIDE_EFFECTS__ + * @param params - Static cipher metadata. See {@link CipherParams}. + * @param constructor - Cipher constructor. + * @returns Wrapped constructor with validation. + */ +export declare const wrapCipher: , P extends CipherParams>(params: P, constructor: C) => C & P; +/** + * Represents a Salsa or ChaCha xor stream. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param data - Input bytes to xor with the keystream. + * @param output - Optional destination buffer. + * @param counter - Optional starting block counter. + * @returns Output bytes. + */ +export type XorStream = (key: TArg, nonce: TArg, data: TArg, output?: TArg, counter?: number) => TRet; +/** + * By default, returns u8a of length. + * When out is available, it checks it for validity and uses it. + * @param expectedLength - Required output length. + * @param out - Optional destination buffer. + * @param onlyAligned - Whether `out` must be 4-byte aligned. + * @returns Output buffer ready for writing. + * @throws On wrong argument types. {@link TypeError} + * @throws If the provided output buffer has the wrong size or alignment. {@link Error} + * @example + * Reuses a caller-provided output buffer when lengths match. + * + * ```ts + * getOutput(16, new Uint8Array(16)); + * ``` + */ +export declare function getOutput(expectedLength: number, out?: TArg, onlyAligned?: boolean): TRet; +/** + * Encodes data and AAD bit lengths into a 16-byte buffer. + * @param dataLength - Data length in bits. + * @param aadLength - AAD length in bits. + * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305 + * conventions even though the helper parameter order is `(dataLength, aadLength)`. + * @param isLE - Whether to encode lengths as little-endian. + * @returns 16-byte length block. + * @throws On wrong argument types passed to the endian validator. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Builds the length block appended by GCM and Poly1305. + * + * ```ts + * u64Lengths(16, 8, true); + * ``` + */ +export declare function u64Lengths(dataLength: number, aadLength: number, isLE: boolean): TRet; +/** + * Checks whether a byte array is aligned to a 4-byte offset. + * @param bytes - Byte array to inspect. + * @returns `true` when the view is 4-byte aligned. + * @example + * Checks whether a buffer can be safely viewed as Uint32Array. + * + * ```ts + * isAligned32(new Uint8Array(4)); + * ``` + */ +export declare function isAligned32(bytes: TArg): boolean; +/** + * Copies bytes into a new Uint8Array. + * @param bytes - Bytes to copy. + * @returns Copied byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Copies input into an aligned Uint8Array before block processing. + * + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export declare function copyBytes(bytes: TArg): TRet; +/** + * Cryptographically secure PRNG. + * Uses internal OS-level `crypto.getRandomValues`. + * @param bytesLength - Number of bytes to produce. + * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so + * non-integers, negative lengths, and oversize requests surface backend/runtime errors. + * @returns Random byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error} + * @example + * Generates a fresh nonce or key. + * + * ```ts + * randomBytes(16); + * ``` + */ +export declare function randomBytes(bytesLength?: number): TRet; +/** + * The pseudorandom number generator doesn't wipe current state: + * instead, it generates new one based on previous state + entropy. + * Not reseed/rekey, since AES CTR DRBG does rekey on each randomBytes, + * which is in fact `reseed`, since it changes counter too. + */ +export interface PRG { + /** + * Mixes fresh entropy into the current generator state. + * @param seed - Entropy bytes to absorb. + */ + addEntropy(seed: TArg): void; + /** + * Produces a requested number of pseudorandom bytes. + * @param bytesLength - Number of bytes to generate. + * @returns Random byte array. + */ + randomBytes(bytesLength: number): TRet; + /** Destroys the generator state. */ + clean(): void; +} +/** Removes the nonce argument from a cipher constructor type. */ +export type RemoveNonce any> = T extends (arg0: any, arg1: any, ...rest: infer R) => infer Ret ? (key: TArg, ...args: R) => Ret : never; +/** + * Cipher constructor that requires a nonce argument. + * @param key - Secret key bytes. + * @param nonce - Nonce bytes. + * @param args - Additional cipher-specific arguments. + * @returns Cipher instance. + */ +export type CipherWithNonce = ((key: TArg, nonce: TArg, ...args: any[]) => Cipher | AsyncCipher) & { + nonceLength: number; +}; +/** + * Uses CSPRNG for nonce, nonce injected in ciphertext. + * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and + * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext + * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext` + * buffer on encrypt and intentionally does not support caller-provided destination buffers. + * Too-short decrypt inputs are split into short/empty nonce views and then delegated + * to the wrapped cipher instead of being rejected here first. + * + * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha + * should be limited to `2**23` (8M) messages to get a collision chance of + * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to + * `2**-33`, still negligible but creeping up. + * @param fn - Cipher constructor that expects a nonce. + * @param randomBytes_ - Random-byte source used for nonce generation. + * @returns Cipher constructor that prepends the nonce to ciphertext. + * @throws On wrong argument types. {@link TypeError} + * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError} + * @example + * Prepends a fresh random nonce to every ciphertext. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js'; + * const wrapped = managedNonce(gcm); + * const key = randomBytes(16); + * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3])); + * wrapped(key).decrypt(ciphertext); + * ``` + */ +export declare function managedNonce(fn: T, randomBytes_?: typeof randomBytes): TRet>; +/** `Uint8Array.of()` return type helper for TS 5.9. */ +export type Uint8ArrayBuffer = TRet; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/utils.d.ts.map b/node_modules/@noble/ciphers/utils.d.ts.map new file mode 100644 index 0000000..8242ae7 --- /dev/null +++ b/node_modules/@noble/ciphers/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,uEAAuE;AAEvE;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI,CAAC,SAAS,aAAa,GAC7C,aAAa,GACb,CAAC,SAAS,cAAc,GACtB,cAAc,GACd,CAAC,SAAS,YAAY,GACpB,YAAY,GACZ,CAAC,SAAS,YAAY,GACpB,YAAY,GACZ,CAAC,SAAS,UAAU,GAClB,UAAU,GACV,CAAC,SAAS,UAAU,GAClB,UAAU,GACV,CAAC,SAAS,SAAS,GACjB,SAAS,GACT,CAAC,SAAS,WAAW,GACnB,WAAW,GACX,CAAC,SAAS,WAAW,GACnB,WAAW,GACX,CAAC,SAAS,iBAAiB,GACzB,iBAAiB,GACjB,CAAC,SAAS,UAAU,GAClB,UAAU,GACV,KAAK,CAAC;AAC9B,oEAAoE;AACpE,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI,CAAC,SAAS,aAAa,GAC7C,UAAU,CAAC,OAAO,aAAa,CAAC,EAAE,CAAC,GACnC,CAAC,SAAS,cAAc,GACtB,UAAU,CAAC,OAAO,cAAc,CAAC,EAAE,CAAC,GACpC,CAAC,SAAS,YAAY,GACpB,UAAU,CAAC,OAAO,YAAY,CAAC,EAAE,CAAC,GAClC,CAAC,SAAS,YAAY,GACpB,UAAU,CAAC,OAAO,YAAY,CAA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644 index 0000000..692efa0 --- /dev/null +++ b/node_modules/@noble/ciphers/utils.js @@ -0,0 +1,807 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */ +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - Value to inspect. + * @returns `true` when the value is a Uint8Array view, including Node's `Buffer`. + * @example + * Guards a value before treating it as raw key material. + * + * ```ts + * isBytes(new Uint8Array()); + * ``` + */ +export function isBytes(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / + // cross-realm cases. The fallback still requires a real ArrayBuffer view + // so plain JSON-deserialized `{ constructor: ... }` + // spoofing is rejected, and `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); +} +/** + * Asserts something is boolean. + * @param b - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validates a boolean option before branching on it. + * + * ```ts + * abool(true); + * ``` + */ +export function abool(b) { + if (typeof b !== 'boolean') + throw new TypeError(`boolean expected, not ${b}`); +} +/** + * Asserts something is a non-negative safe integer. + * @param n - Value to validate. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validates a non-negative length or counter. + * + * ```ts + * anumber(1); + * ``` + */ +export function anumber(n) { + if (typeof n !== 'number') + throw new TypeError('number expected, got ' + typeof n); + if (!Number.isSafeInteger(n) || n < 0) + throw new RangeError('positive integer expected, got ' + n); +} +/** + * Asserts something is Uint8Array. + * @param value - Value to validate. + * @param length - Expected byte length. + * @param title - Optional label used in error messages. + * @returns The validated byte array. + * On Node, `Buffer` is accepted too because it is a Uint8Array view. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument lengths. {@link RangeError} + * @example + * Validates a fixed-length nonce or key buffer. + * + * ```ts + * abytes(new Uint8Array([1, 2]), 2); + * ``` + */ +export function abytes(value, length, title = '') { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== undefined; + if (!bytes || (needsLen && len !== length)) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ''; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + return value; +} +/** + * Asserts a hash- or MAC-like instance has not been destroyed or finished. + * @param instance - Stateful instance to validate. + * @param checkFinished - Whether to reject finished instances. + * When `false`, only `destroyed` is checked. + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Guards against calling `update()` or `digest()` on a finished hash. + * + * ```ts + * aexists({ destroyed: false, finished: false }); + * ``` + */ +export function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +/** + * Asserts output is a properly-sized byte array. + * @param out - Output buffer to validate. + * @param instance - Hash-like instance providing `outputLen`. + * This is the relaxed `digestInto()`-style contract: output must be at least `outputLen`, + * unlike one-shot cipher helpers elsewhere in the repo that often require exact lengths. + * @throws On wrong argument types. {@link TypeError} + * @param onlyAligned - Whether `out` must be 4-byte aligned for zero-allocation word views. + * @throws On wrong output buffer lengths. {@link RangeError} + * @throws On wrong output buffer alignment. {@link Error} + * @example + * Verifies that a caller-provided output buffer is large enough. + * + * ```ts + * aoutput(new Uint8Array(16), { outputLen: 16 }); + * ``` + */ +export function aoutput(out, instance, onlyAligned = false) { + abytes(out, undefined, 'output'); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('digestInto() expects output buffer of length at least ' + min); + } + if (onlyAligned && !isAligned32(out)) + throw new Error('invalid output, must be aligned'); +} +/** + * Casts a typed-array view to Uint8Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint8Array view over the same bytes. + * @example + * Views 32-bit words as raw bytes without copying. + * + * ```ts + * u8(new Uint32Array([1])); + * ``` + */ +export function u8(arr) { + return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Casts a typed-array view to Uint32Array. + * @param arr - Typed-array view to reinterpret. + * @returns Uint32Array view over the same bytes. Callers are expected to provide a + * 4-byte-aligned offset; trailing `1..3` bytes are silently dropped. + * @example + * Views a byte buffer as 32-bit words for block processing. + * + * ```ts + * u32(new Uint8Array(4)); + * ``` + */ +export function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +/** + * Zeroizes typed arrays in place. + * Warning: JS provides no guarantees. + * @param arrays - Arrays to wipe. + * @example + * Wipes a temporary key buffer after use. + * + * ```ts + * const bytes = new Uint8Array([1]); + * clean(bytes); + * ``` + */ +export function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +/** + * Creates a DataView for byte-level manipulation. + * @param arr - Typed-array view to wrap. + * @returns DataView over the same bytes. + * @example + * Creates an endian-aware view for length encoding. + * + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Whether the current platform is little-endian. + * Most are; some IBM systems are not. + */ +export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); +/** + * Reverses byte order of one 32-bit word. + * @param word - Unsigned 32-bit word to swap. + * @returns The same word with bytes reversed. + * @example + * Swaps a big-endian word into little-endian byte order. + * + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export const byteSwap = (word) => ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff); +/** + * Normalizes one 32-bit word to the little-endian representation expected by cipher cores. + * @param n - Unsigned 32-bit word to normalize. + * @returns Little-endian normalized word on big-endian hosts, else the input word unchanged. + * @example + * Normalizes a host-endian word before passing it into an ARX/AES core. + * + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export const swap8IfBE = isLE + ? (n) => n + : (n) => byteSwap(n) >>> 0; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - Uint32Array whose words should be swapped. + * @returns The same array after in-place byte swapping. + * @example + * Swaps every 32-bit word in a word-view buffer. + * + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export const byteSwap32 = (arr) => { + for (let i = 0; i < arr.length; i++) + arr[i] = byteSwap(arr[i]); + return arr; +}; +/** + * Normalizes a Uint32Array view to the little-endian representation expected by cipher cores. + * @param u - Word view to normalize in place. + * @returns Little-endian normalized word view. + * @example + * Normalizes a word-view buffer before block processing. + * + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export const swap32IfBE = isLE + ? (u) => u + : byteSwap32; +// Built-in hex conversion: +// {@link https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex | caniuse entry} +const hasHexBuiltin = /* @__PURE__ */ (() => +// @ts-ignore +typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * Convert byte array to hex string. Uses built-in function, when available. + * @param bytes - Bytes to encode. + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Formats ciphertext bytes for logs or test vectors. + * + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export function bytesToHex(bytes) { + abytes(bytes); + // @ts-ignore + if (hasHexBuiltin) + return bytes.toHex(); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; // '2' => 50-48 + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); // 'B' => 66-(65-10) + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); // 'b' => 98-(97-10) + return; +} +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - Hexadecimal string to decode. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On malformed hexadecimal input. {@link RangeError} + * @example + * Parses a hex test vector into bytes. + * + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new TypeError('hex string expected, got ' + typeof hex); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex); + } + catch (error) { + if (error instanceof SyntaxError) + throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163 + } + return array; +} +// Used in micro +/** + * Converts a big-endian hex string into bigint. + * @param hex - Hexadecimal string without `0x`. + * @returns Parsed bigint value. The empty string is treated as `0n`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parses a big-endian field element or counter from hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new TypeError('hex string expected, got ' + typeof hex); + return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian +} +// Used in ff1 +// BE: Big Endian, LE: Little Endian +/** + * Converts big-endian bytes into bigint. + * @param bytes - Big-endian bytes. + * @returns Parsed bigint value. Empty input is treated as `0n`. + * @throws On invalid byte input passed to the internal hex conversion. {@link TypeError} + * @example + * Reads a big-endian integer from serialized bytes. + * + * ```ts + * bytesToNumberBE(new Uint8Array([1, 0])); + * ``` + */ +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +// Used in micro, ff1 +/** + * Converts a number into big-endian bytes of fixed length. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Big-endian bytes padded to `len`. + * Validation is indirect through `hexToBytes(...)`, so negative values, `len = 0`, + * and values that do not fit surface through the downstream hex parser instead of a + * dedicated range guard here. + * @throws On wrong argument types. {@link TypeError} + * @throws If the requested output length cannot represent the encoded value. {@link RangeError} + * @example + * Encodes a counter as fixed-width big-endian bytes. + * + * ```ts + * numberToBytesBE(1, 2); + * ``` + */ +export function numberToBytesBE(n, len) { + // Reject coercible non-numeric inputs before string/hex conversion changes behavior. + if (typeof n === 'number') + anumber(n); + else if (typeof n !== 'bigint') + throw new TypeError(`number or bigint expected, got ${typeof n}`); + anumber(len); + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +/** + * Converts string to bytes using UTF8 encoding. + * @param str - String to encode. + * @returns UTF-8 bytes in a detached fresh Uint8Array copy. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encodes application text before encryption or MACing. + * + * ```ts + * utf8ToBytes('abc'); // new Uint8Array([97, 98, 99]) + * ``` + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new TypeError('string expected'); + return new Uint8Array(new TextEncoder().encode(str)); // {@link https://bugzil.la/1681809 | Firefox bug 1681809} +} +/** + * Converts bytes to string using UTF8 encoding. + * @param bytes - UTF-8 bytes. + * @returns Decoded string. Input validation is delegated to `TextDecoder`, and malformed + * UTF-8 is replacement-decoded instead of rejected. + * @example + * Decodes UTF-8 plaintext back into a string. + * + * ```ts + * bytesToUtf8(new Uint8Array([97, 98, 99])); // 'abc' + * ``` + */ +export function bytesToUtf8(bytes) { + return new TextDecoder().decode(bytes); +} +/** + * Checks if two U8A use same underlying buffer and overlaps. + * This is invalid and can corrupt data. + * @param a - First byte view. + * @param b - Second byte view. + * @returns `true` when the views overlap in memory. + * @example + * Detects whether two slices alias the same backing buffer. + * + * ```ts + * overlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export function overlapBytes(a, b) { + // Zero-length views cannot overwrite anything, even if their offset sits inside another range. + if (!a.byteLength || !b.byteLength) + return false; + return (a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy + a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end + b.byteOffset < a.byteOffset + a.byteLength // b starts before a end + ); +} +/** + * If input and output overlap and input starts before output, we will overwrite end of input before + * we start processing it, so this is not supported for most ciphers + * (except chacha/salsa, which were designed for this) + * @param input - Input bytes. + * @param output - Output bytes. + * @throws If the output view would overwrite unread input bytes. {@link Error} + * @example + * Rejects an in-place layout that would overwrite unread input bytes. + * + * ```ts + * complexOverlapBytes(new Uint8Array(4), new Uint8Array(4)); + * ``` + */ +export function complexOverlapBytes(input, output) { + // This is very cursed. It works somehow, but I'm completely unsure, + // reasoning about overlapping aligned windows is very hard. + if (overlapBytes(input, output) && input.byteOffset < output.byteOffset) + throw new Error('complex overlap of input and output is not supported'); +} +/** + * Copies several Uint8Arrays into one. + * @param arrays - Byte arrays to concatenate. + * @returns Combined byte array. + * @throws On wrong argument types inside the byte-array list. {@link TypeError} + * @example + * Builds a `nonce || ciphertext` style buffer. + * + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +/** + * Merges user options into defaults. + * @param defaults - Default option values. + * @param opts - User-provided overrides. + * @returns Combined options object. + * The merge mutates `defaults` in place and returns the same object. + * @throws If options are missing or not an object. {@link Error} + * @example + * Applies user overrides to the default cipher options. + * + * ```ts + * checkOpts({ rounds: 20 }, { rounds: 8 }); + * ``` + */ +export function checkOpts(defaults, opts) { + if (opts == null || typeof opts !== 'object') + throw new Error('options must be defined'); + const merged = Object.assign(defaults, opts); + return merged; +} +/** + * Compares two byte arrays in kinda constant time once lengths already match. + * @param a - First byte array. + * @param b - Second byte array. + * @returns `true` when the arrays contain the same bytes. Different lengths still return early. + * @example + * Compares an expected authentication tag with the received one. + * + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * Wraps a keyed MAC constructor into a one-shot helper with `.create()`. + * @param keyLen - Valid probe-key length used to read static metadata once. + * The probe key is only used for `outputLen` / `blockLen`, so callers with several valid key sizes + * can pass any representative size as long as those values stay fixed. + * @param macCons - Keyed MAC constructor or factory. + * @param fromMsg - Optional adapter that derives extra constructor args from the one-shot message. + * @returns Callable MAC helper with `.create()`. + */ +export function wrapMacConstructor(keyLen, macCons, fromMsg) { + const mac = macCons; + const getArgs = (fromMsg || (() => [])); + const macC = (msg, key) => mac(key, ...getArgs(msg)) + .update(msg) + .digest(); + const tmp = mac(new Uint8Array(keyLen), ...getArgs(new Uint8Array(0))); + macC.outputLen = tmp.outputLen; + macC.blockLen = tmp.blockLen; + macC.create = (key, ...args) => mac(key, ...args); + return macC; +} +/** + * Wraps a cipher: validates args, ensures encrypt() can only be called once. + * Used internally by the exported cipher constructors. + * Output-buffer support is inferred from the wrapped `encrypt` / `decrypt` + * arity (`fn.length === 2`), and tag-bearing constructors are expected to use + * `args[1]` for optional AAD. + * @__NO_SIDE_EFFECTS__ + * @param params - Static cipher metadata. See {@link CipherParams}. + * @param constructor - Cipher constructor. + * @returns Wrapped constructor with validation. + */ +export const wrapCipher = (params, constructor) => { + function wrappedCipher(key, ...args) { + // Validate key + abytes(key, undefined, 'key'); + // Validate nonce if nonceLength is present + if (params.nonceLength !== undefined) { + const nonce = args[0]; + abytes(nonce, params.varSizeNonce ? undefined : params.nonceLength, 'nonce'); + } + // Validate AAD if tagLength present + const tagl = params.tagLength; + if (tagl && args[1] !== undefined) + abytes(args[1], undefined, 'AAD'); + const cipher = constructor(key, ...args); + const checkOutput = (fnLength, output) => { + if (output !== undefined) { + if (fnLength !== 2) + throw new Error('cipher output not supported'); + abytes(output, undefined, 'output'); + } + }; + // Create wrapped cipher with validation and single-use encryption + let called = false; + const wrCipher = { + encrypt(data, output) { + if (called) + throw new Error('cannot encrypt() twice with same key + nonce'); + called = true; + abytes(data); + checkOutput(cipher.encrypt.length, output); + return cipher.encrypt(data, output); + }, + decrypt(data, output) { + abytes(data); + if (tagl && data.length < tagl) + throw new Error('"ciphertext" expected length bigger than tagLength=' + tagl); + checkOutput(cipher.decrypt.length, output); + return cipher.decrypt(data, output); + }, + }; + return wrCipher; + } + Object.assign(wrappedCipher, params); + return wrappedCipher; +}; +/** + * By default, returns u8a of length. + * When out is available, it checks it for validity and uses it. + * @param expectedLength - Required output length. + * @param out - Optional destination buffer. + * @param onlyAligned - Whether `out` must be 4-byte aligned. + * @returns Output buffer ready for writing. + * @throws On wrong argument types. {@link TypeError} + * @throws If the provided output buffer has the wrong size or alignment. {@link Error} + * @example + * Reuses a caller-provided output buffer when lengths match. + * + * ```ts + * getOutput(16, new Uint8Array(16)); + * ``` + */ +export function getOutput(expectedLength, out, onlyAligned = true) { + if (out === undefined) + return new Uint8Array(expectedLength); + // Keep Buffer/cross-realm Uint8Array support here instead of trusting a shape-compatible object. + abytes(out, undefined, 'output'); + if (out.length !== expectedLength) + throw new Error('"output" expected Uint8Array of length ' + expectedLength + ', got: ' + out.length); + if (onlyAligned && !isAligned32(out)) + throw new Error('invalid output, must be aligned'); + return out; +} +/** + * Encodes data and AAD bit lengths into a 16-byte buffer. + * @param dataLength - Data length in bits. + * @param aadLength - AAD length in bits. + * The serialized block is still `aadLength || dataLength`, matching GCM/Poly1305 + * conventions even though the helper parameter order is `(dataLength, aadLength)`. + * @param isLE - Whether to encode lengths as little-endian. + * @returns 16-byte length block. + * @throws On wrong argument types passed to the endian validator. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Builds the length block appended by GCM and Poly1305. + * + * ```ts + * u64Lengths(16, 8, true); + * ``` + */ +export function u64Lengths(dataLength, aadLength, isLE) { + // Reject coercible non-number lengths like '10' and true before BigInt(...) accepts them. + anumber(dataLength); + anumber(aadLength); + abool(isLE); + const num = new Uint8Array(16); + const view = createView(num); + view.setBigUint64(0, BigInt(aadLength), isLE); + view.setBigUint64(8, BigInt(dataLength), isLE); + return num; +} +/** + * Checks whether a byte array is aligned to a 4-byte offset. + * @param bytes - Byte array to inspect. + * @returns `true` when the view is 4-byte aligned. + * @example + * Checks whether a buffer can be safely viewed as Uint32Array. + * + * ```ts + * isAligned32(new Uint8Array(4)); + * ``` + */ +export function isAligned32(bytes) { + return bytes.byteOffset % 4 === 0; +} +/** + * Copies bytes into a new Uint8Array. + * @param bytes - Bytes to copy. + * @returns Copied byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Copies input into an aligned Uint8Array before block processing. + * + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)); +} +/** + * Cryptographically secure PRNG. + * Uses internal OS-level `crypto.getRandomValues`. + * @param bytesLength - Number of bytes to produce. + * Validation is delegated to `Uint8Array(bytesLength)` and `getRandomValues`, so + * non-integers, negative lengths, and oversize requests surface backend/runtime errors. + * @returns Random byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the runtime does not expose `crypto.getRandomValues`. {@link Error} + * @example + * Generates a fresh nonce or key. + * + * ```ts + * randomBytes(16); + * ``` + */ +export function randomBytes(bytesLength = 32) { + // Validate upfront so fractional / coercible lengths do not silently + // truncate through Uint8Array(). + anumber(bytesLength); + const cr = typeof globalThis === 'object' ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +/** + * Uses CSPRNG for nonce, nonce injected in ciphertext. + * For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and + * prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext + * are treated as nonce. The wrapper always allocates a fresh `nonce || ciphertext` + * buffer on encrypt and intentionally does not support caller-provided destination buffers. + * Too-short decrypt inputs are split into short/empty nonce views and then delegated + * to the wrapped cipher instead of being rejected here first. + * + * NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha + * should be limited to `2**23` (8M) messages to get a collision chance of + * `2**-50`. Stretching to `2**32` (4B) messages would raise that chance to + * `2**-33`, still negligible but creeping up. + * @param fn - Cipher constructor that expects a nonce. + * @param randomBytes_ - Random-byte source used for nonce generation. + * @returns Cipher constructor that prepends the nonce to ciphertext. + * @throws On wrong argument types. {@link TypeError} + * @throws On invalid nonce lengths observed at wrapper construction or use. {@link RangeError} + * @example + * Prepends a fresh random nonce to every ciphertext. + * + * ```ts + * import { gcm } from '@noble/ciphers/aes.js'; + * import { managedNonce, randomBytes } from '@noble/ciphers/utils.js'; + * const wrapped = managedNonce(gcm); + * const key = randomBytes(16); + * const ciphertext = wrapped(key).encrypt(new Uint8Array([1, 2, 3])); + * wrapped(key).decrypt(ciphertext); + * ``` + */ +export function managedNonce(fn, randomBytes_ = randomBytes) { + const { nonceLength } = fn; + anumber(nonceLength); + const addNonce = (nonce, ciphertext, plaintext) => { + const out = concatBytes(nonce, ciphertext); + // Wrapped ciphers may alias caller plaintext on encrypt(); never zero + // caller-owned buffers here. + if (!overlapBytes(plaintext, ciphertext)) + ciphertext.fill(0); + return out; + }; + // NOTE: we cannot support DST here, it would be mistake: + // - we don't know how much dst length cipher requires + // - nonce may unalign dst and break everything + // - we create new u8a anyway (concatBytes) + // - previously we passed all args to cipher, but that was mistake! + const res = ((key, ...args) => ({ + encrypt(plaintext) { + abytes(plaintext); + const nonce = randomBytes_(nonceLength); + const encrypted = fn(key, nonce, ...args).encrypt(plaintext); + // @ts-ignore + if (encrypted instanceof Promise) + return encrypted.then((ct) => addNonce(nonce, ct, plaintext)); + return addNonce(nonce, encrypted, plaintext); + }, + decrypt(ciphertext) { + abytes(ciphertext); + const nonce = ciphertext.subarray(0, nonceLength); + const decrypted = ciphertext.subarray(nonceLength); + return fn(key, nonce, ...args).decrypt(decrypted); + }, + })); + // Auto-nonce wrappers still preserve the wrapped payload geometry. + if ('blockSize' in fn) + res.blockSize = fn.blockSize; + if ('tagLength' in fn) + res.tagLength = fn.tagLength; + return res; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/utils.js.map b/node_modules/@noble/ciphers/utils.js.map new file mode 100644 index 0000000..fd8c6e3 --- /dev/null +++ b/node_modules/@noble/ciphers/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,uEAAuE;AA4GvE;;;;;;;;;;GAUG;AACH,MAAM,UAAU,OAAO,CAAC,CAAU;IAChC,wEAAwE;IACxE,yEAAyE;IACzE,oDAAoD;IACpD,iGAAiG;IACjG,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YACpB,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,YAAY;YACnC,mBAAmB,IAAI,CAAC;YACxB,CAAC,CAAC,iBAAiB,KAAK,CAAC,CAAC,CA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CAAC,SAAS,CAAC,CAAC;YAClB,MAAM,KAAK,GAAG,YAAY,CAAC,WAAW,CAAC,CAAC;YACxC,MAAM,SAAS,GAAG,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;YAC7D,aAAa;YACb,IAAI,SAAS,YAAY,OAAO;gBAC9B,OAAO,SAAS,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC;YAChE,OAAO,QAAQ,CAAC,KAAK,EAAE,SAAS,EAAE,SAAS,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,CAAC,UAA4B;YAClC,MAAM,CAAC,UAAU,CAAC,CAAC;YACnB,MAAM,KAAK,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC;YAClD,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;YACnD,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QACpD,CAAC;KACF,CAAC,CAAgE,CAAC;IACnE,mEAAmE;IACnE,IAAI,WAAW,IAAI,EAAE;QAAE,GAAG,CAAC,SAAS,GAAI,EAAU,CAAC,SAAS,CAAC;IAC7D,IAAI,WAAW,IAAI,EAAE;QAAE,GAAG,CAAC,SAAS,GAAI,EAAU,CAAC,SAAS,CAAC;IAC7D,OAAO,GAA2B,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.d.ts b/node_modules/@noble/ciphers/webcrypto.d.ts new file mode 100644 index 0000000..4f4985f --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.d.ts @@ -0,0 +1,89 @@ +/** + * WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`. + * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. + * @module + */ +import { type AsyncCipher, type TArg, type TRet } from './utils.ts'; +type WebcryptoUtils = { + encrypt(key: TArg, keyParams: unknown, cryptParams: unknown, plaintext: TArg): Promise>; + decrypt(key: TArg, keyParams: unknown, cryptParams: unknown, ciphertext: TArg): Promise>; +}; +/** + * Internal webcrypto utils. Can be overridden if crypto.subtle is not present, + * for example in React Native. + * Raw keys are re-imported on every call; this wrapper intentionally does not + * cache `CryptoKey` objects between operations. + */ +export declare const utils: TRet; +/** + * AES-CBC implemented with WebCrypto. + * Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are + * delegated to the backend instead of local `abytes(..., 16)` validation. + * @param key - AES key bytes. + * @param iv - 16-byte initialization vector. + * @returns Async cipher instance. + * @example + * Encrypts a block with the browser or Node WebCrypto backend. + * + * ```ts + * import { cbc } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * await cipher.encrypt(new Uint8Array(16)); + * ``` + */ +export declare const cbc: TRet<((key: TArg, iv: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; +}>; +/** + * AES-CTR implemented with WebCrypto. + * Uses WebCrypto's full 128-bit counter-length setting so the whole + * 16-byte counter block is incremented, matching sync `aes.ts:ctr`. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block incremented as a full big-endian AES counter block. + * @returns Async cipher instance. + * @example + * Encrypts a short payload with WebCrypto AES-CTR. + * + * ```ts + * import { ctr } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const ctr: TRet<((key: TArg, nonce: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; +}>; +/** + * AES-GCM implemented with WebCrypto. + * AAD type normalization and nonce-shape enforcement beyond raw bytes are left + * to the backend WebCrypto implementation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes. + * @param AAD - Additional authenticated data. + * @returns Async cipher instance. + * @example + * Encrypts and authenticates plaintext with WebCrypto AES-GCM. + * + * ```ts + * import { gcm } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const gcm: TRet<((key: TArg, nonce: TArg, AAD?: TArg) => AsyncCipher) & { + blockSize: number; + nonceLength: number; +}>; +export {}; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.d.ts.map b/node_modules/@noble/ciphers/webcrypto.d.ts.map new file mode 100644 index 0000000..b42e059 --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAmB,KAAK,WAAW,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAQrF,KAAK,cAAc,GAAG;IACpB,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,GAC1B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC7B,OAAO,CACL,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,SAAS,EAAE,OAAO,EAClB,WAAW,EAAE,OAAO,EACpB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;CAC9B,CAAC;AACF;;;;;GAKG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,cAAc,CAuBtC,CAAC;AAwEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC/D,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAClE,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC;AACrD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,GAAG,EAAE,IAAI,CACpB,CAAC,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,WAAW,CAAC,GAAG;IAC1F,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;CACrB,CACiD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.js b/node_modules/@noble/ciphers/webcrypto.js new file mode 100644 index 0000000..78e44a5 --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.js @@ -0,0 +1,167 @@ +/** + * WebCrypto-based AES gcm/ctr/cbc, `managedNonce` and `randomBytes`. + * We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+. + * @module + */ +import { abytes, anumber } from "./utils.js"; +function getWebcryptoSubtle() { + const cr = typeof globalThis !== 'undefined' && globalThis.crypto; + if (cr && typeof cr.subtle === 'object' && cr.subtle != null) + return cr.subtle; + throw new Error('crypto.subtle must be defined'); +} +/** + * Internal webcrypto utils. Can be overridden if crypto.subtle is not present, + * for example in React Native. + * Raw keys are re-imported on every call; this wrapper intentionally does not + * cache `CryptoKey` objects between operations. + */ +export const utils = { + async encrypt(key, keyParams, cryptParams, plaintext) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['encrypt']); + const ciphertext = await cr.encrypt(cryptParams, iKey, plaintext); + return new Uint8Array(ciphertext); + }, + async decrypt(key, keyParams, cryptParams, ciphertext) { + const cr = getWebcryptoSubtle(); + const iKey = await cr.importKey('raw', key, keyParams, true, ['decrypt']); + const plaintext = await cr.decrypt(cryptParams, iKey, ciphertext); + return new Uint8Array(plaintext); + }, +}; +const mode = { + CBC: 'AES-CBC', + CTR: 'AES-CTR', + GCM: 'AES-GCM', +}; +function getCryptParams(algo, nonce, AAD) { + if (algo === mode.CBC) + return { name: mode.CBC, iv: nonce }; + // WebCrypto allows 1..128 counter bits; use the full block to match sync ctr() / Node CTR wrap. + if (algo === mode.CTR) + return { name: mode.CTR, counter: nonce, length: 128 }; + if (algo === mode.GCM) { + // Rely on the backend default tag length (128 bits) instead of setting it explicitly. + if (AAD) + return { name: mode.GCM, iv: nonce, additionalData: AAD }; + else + return { name: mode.GCM, iv: nonce }; + } + throw new Error('unknown aes block mode'); +} +function generate(algo, nonceLength) { + anumber(nonceLength); + const res = (key, nonce, AAD) => { + abytes(key); + abytes(nonce); + // Reject falsy non-byte AAD locally; otherwise false/0/''/null silently become "no AAD". + if (AAD !== undefined) + abytes(AAD, undefined, 'AAD'); + // Exact nonce-length enforcement and WebCrypto-specific AAD normalization are + // delegated to the backend; locally we only require byte-array inputs here. + // Keep caller key/nonce/AAD by reference; mutating them after + // construction changes later operations. + const keyParams = { name: algo, length: key.length * 8 }; + const cryptParams = getCryptParams(algo, nonce, AAD); + let consumed = false; + return { + // keyLength, + encrypt(plaintext) { + abytes(plaintext); + if (consumed) + throw new Error('Cannot encrypt() twice with same key / nonce'); + consumed = true; + return utils.encrypt(key, keyParams, cryptParams, plaintext); + }, + decrypt(ciphertext) { + abytes(ciphertext); + return utils.decrypt(key, keyParams, cryptParams, ciphertext); + }, + }; + }; + res.nonceLength = nonceLength; + res.blockSize = 16; // always for AES + return res; +} +/** + * AES-CBC implemented with WebCrypto. + * Uses WebCrypto's built-in PKCS padding behavior; exact IV-length checks are + * delegated to the backend instead of local `abytes(..., 16)` validation. + * @param key - AES key bytes. + * @param iv - 16-byte initialization vector. + * @returns Async cipher instance. + * @example + * Encrypts a block with the browser or Node WebCrypto backend. + * + * ```ts + * import { cbc } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const iv = randomBytes(16); + * const cipher = cbc(key, iv); + * await cipher.encrypt(new Uint8Array(16)); + * ``` + */ +export const cbc = /* @__PURE__ */ (() => generate(mode.CBC, 16))(); +/** + * AES-CTR implemented with WebCrypto. + * Uses WebCrypto's full 128-bit counter-length setting so the whole + * 16-byte counter block is incremented, matching sync `aes.ts:ctr`. + * @param key - AES key bytes. + * @param nonce - 16-byte counter block incremented as a full big-endian AES counter block. + * @returns Async cipher instance. + * @example + * Encrypts a short payload with WebCrypto AES-CTR. + * + * ```ts + * import { ctr } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(16); + * const cipher = ctr(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const ctr = /* @__PURE__ */ (() => generate(mode.CTR, 16))(); +/** + * AES-GCM implemented with WebCrypto. + * AAD type normalization and nonce-shape enforcement beyond raw bytes are left + * to the backend WebCrypto implementation. + * @param key - AES key bytes. + * @param nonce - Nonce bytes. + * @param AAD - Additional authenticated data. + * @returns Async cipher instance. + * @example + * Encrypts and authenticates plaintext with WebCrypto AES-GCM. + * + * ```ts + * import { gcm } from '@noble/ciphers/webcrypto.js'; + * import { randomBytes } from '@noble/ciphers/utils.js'; + * const key = randomBytes(16); + * const nonce = randomBytes(12); + * const cipher = gcm(key, nonce); + * await cipher.encrypt(new Uint8Array([1, 2, 3])); + * ``` + */ +export const gcm = /* @__PURE__ */ (() => generate(mode.GCM, 12))(); +// // Type tests +// import { siv, gcm, ctr, ecb, cbc } from '../aes.ts'; +// import { xsalsa20poly1305 } from '../salsa.ts'; +// import { chacha20poly1305, xchacha20poly1305 } from '../chacha.ts'; +// const wsiv = managedNonce(siv); +// const wgcm = managedNonce(gcm); +// const wctr = managedNonce(ctr); +// const wcbc = managedNonce(cbc); +// const wsalsapoly = managedNonce(xsalsa20poly1305); +// const wchacha = managedNonce(chacha20poly1305); +// const wxchacha = managedNonce(xchacha20poly1305); +// // should fail +// const wcbc2 = managedNonce(managedNonce(cbc)); +// const wctr = managedNonce(ctr); +// import { gcm as gcmSync } from '../aes.ts'; +// const x1 = managedNonce(gcmSync); +// // const x1: (key: Uint8Array, AAD?: Uint8Array | undefined) => Cipher +// const x2 = managedNonce(gcm); +// // const x2: (key: Uint8Array, AAD?: Uint8Array | undefined) => AsyncCipher +//# sourceMappingURL=webcrypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/ciphers/webcrypto.js.map b/node_modules/@noble/ciphers/webcrypto.js.map new file mode 100644 index 0000000..9c0edf5 --- /dev/null +++ b/node_modules/@noble/ciphers/webcrypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,OAAO,EAA0C,MAAM,YAAY,CAAC;AAErF,SAAS,kBAAkB;IACzB,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,WAAW,IAAK,UAAkB,CAAC,MAAM,CAAC;IAC3E,IAA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;AAEtE,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,kCAAkC;AAClC,qDAAqD;AACrD,kDAAkD;AAClD,oDAAoD;AAEpD,iBAAiB;AACjB,iDAAiD;AACjD,kCAAkC;AAClC,8CAA8C;AAC9C,oCAAoC;AACpC,yEAAyE;AACzE,gCAAgC;AAChC,8EAA8E"} \ No newline at end of file diff --git a/node_modules/@noble/curves/LICENSE b/node_modules/@noble/curves/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@noble/curves/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/curves/README.md b/node_modules/@noble/curves/README.md new file mode 100644 index 0000000..77a998a --- /dev/null +++ b/node_modules/@noble/curves/README.md @@ -0,0 +1,1129 @@ +# noble-curves + +Audited & minimal JS implementation of elliptic curve cryptography. + +- 🔒 [**Audited**](#security) by independent security firms +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🏎 Fast: hand-optimized for caveats of JS engines +- 🔍 Reliable: cross-library / wycheproof tests and fuzzing ensure correctness +- ➰ Weierstrass, Edwards, Montgomery curves; ECDSA, EdDSA, Schnorr, BLS signatures +- ✍️ ECDH, hash-to-curve, OPRF, FROST, Poseidon hash, FFT +- 🔖 Non-repudiation (SUF-CMA, SBS) & consensus-friendliness (ZIP215) in ed25519, ed448 +- 🥈 Optional, friendly wrapper over native WebCrypto +- 🪶 32KB (gzipped) including bundled hashes, 11KB for single-curve build + +Curves have 5kb sister projects +[secp256k1](https://github.com/paulmillr/noble-secp256k1) & [ed25519](https://github.com/paulmillr/noble-ed25519). +They have smaller attack surface, but less features. + +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-curves/discussions) for questions and support. + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out the homepage](https://paulmillr.com/noble/) + for reading resources, documentation, and apps built with noble + +## Usage + +> `npm install @noble/curves` + +> `deno add jsr:@noble/curves` + +We support all major platforms and runtimes. +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file [noble-curves.js](https://github.com/paulmillr/noble-curves/releases) is also available. + +```ts +// import * from '@noble/curves'; // Error: use sub-imports, to ensure small app size +import { secp256k1, schnorr } from '@noble/curves/secp256k1.js'; +import { ed25519, ed25519ph, ed25519ctx, x25519, ristretto255 } from '@noble/curves/ed25519.js'; +import { ed448, ed448ph, x448, decaf448 } from '@noble/curves/ed448.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { bls12_381 } from '@noble/curves/bls12-381.js'; +import { bn254 } from '@noble/curves/bn254.js'; +import { jubjub, babyjubjub, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1 } from '@noble/curves/misc.js'; + +// hash-to-curve +import { secp256k1_hasher } from '@noble/curves/secp256k1.js'; +import { p256_hasher, p384_hasher, p521_hasher } from '@noble/curves/nist.js'; +import { ristretto255_hasher } from '@noble/curves/ed25519.js'; +import { decaf448_hasher } from '@noble/curves/ed448.js'; + +// OPRFs +import { p256_oprf, p384_oprf, p521_oprf } from '@noble/curves/nist.js'; +import { ristretto255_oprf } from '@noble/curves/ed25519.js'; +import { decaf448_oprf } from '@noble/curves/ed448.js'; + +// utils +import { bytesToHex, hexToBytes, concatBytes } from '@noble/curves/utils.js'; +import { Field } from '@noble/curves/abstract/modular.js'; +import { weierstrass, ecdsa } from '@noble/curves/abstract/weierstrass.js'; +import { edwards, eddsa } from '@noble/curves/abstract/edwards.js'; +import { poseidon, poseidonSponge } from '@noble/curves/abstract/poseidon.js'; +import { FFT, poly } from '@noble/curves/abstract/fft.js'; +``` + +- Examples + - [ECDSA, EdDSA, Schnorr signatures](#ecdsa-eddsa-schnorr-signatures) + - [secp256k1, p256, p384, p521, ed25519, ed448, brainpool](#secp256k1-p256-p384-p521-ed25519-ed448-brainpool) + - [ristretto255, decaf448](#ristretto255-decaf448) + - [Prehashed signing](#prehashed-signing) + - [Recovering public keys from signatures](#recovering-public-keys-from-signatures) + - [Hedged ECDSA with noise](#hedged-ecdsa-with-noise) + - [Consensus-friendliness vs e-voting](#consensus-friendliness-vs-e-voting) + - [ECDH: Diffie-Hellman shared secrets](#ecdh-diffie-hellman-shared-secrets) + - [webcrypto: Friendly wrapper](#webcrypto-friendly-wrapper) + - [BLS signatures, bls12-381, bn254 aka alt\_bn128](#bls-signatures-bls12-381-bn254-aka-alt_bn128) + - [Hashing to curve points](#hash-to-curve-hashing-to-curve-points) + - [OPRFs](#oprfs) + - [FROST threshold signatures](#frost-threshold-signatures) + - [Poseidon hash](#poseidon-poseidon-hash) + - [Fast Fourier Transform](#fft-fast-fourier-transform) + - [utils](#utils-byte-shuffling-conversion) +- [Internals](#internals) + - [Elliptic curve Point math](#elliptic-curve-point-math) + - [modular: Modular arithmetics \& finite fields](#modular-modular-arithmetics--finite-fields) + - [weierstrass: Custom Weierstrass curve](#weierstrass-custom-weierstrass-curve) + - [edwards: Custom Edwards curve](#edwards-custom-edwards-curve) + - [Custom ECDSA instance](#custom-ecdsa-instance) +- [Security](#security) +- [Speed](#speed) +- [Contributing & testing](#contributing--testing) +- [Upgrading](#upgrading) + +### ECDSA, EdDSA, Schnorr signatures + +#### secp256k1, p256, p384, p521, ed25519, ed448, brainpool + +```js +import { secp256k1, schnorr } from '@noble/curves/secp256k1.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { ed25519 } from '@noble/curves/ed25519.js'; +import { ed448 } from '@noble/curves/ed448.js'; +import { brainpoolP256r1, brainpoolP384r1, brainpoolP512r1 } from '@noble/curves/misc.js'; +for (const curve of [ + secp256k1, schnorr, + p256, p384, p521, + ed25519, ed448, + brainpoolP256r1, brainpoolP384r1, brainpoolP512r1 +]) { + const { secretKey, publicKey } = curve.keygen(); + const msg = new TextEncoder().encode('hello noble'); + const sig = curve.sign(msg, secretKey); + const isValid = curve.verify(sig, msg, publicKey); + console.log(curve, secretKey, publicKey, sig, isValid); +} + +// Specific private key +import { hexToBytes } from '@noble/curves/utils.js'; +const secret2 = hexToBytes('46c930bc7bb4db7f55da20798697421b98c4175a52c630294d75a84b9c126236'); +const pub2 = secp256k1.getPublicKey(secret2); +``` + +ECDSA signatures use deterministic k, conforming to [RFC 6979](https://www.rfc-editor.org/rfc/rfc6979). +EdDSA conforms to [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032). +Schnorr (secp256k1-only) conforms to [BIP 340](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki). + +Messages are always hashed first. + +#### ristretto255, decaf448 + +```ts +import { ristretto255, ristretto255_hasher, ristretto255_oprf } from '@noble/curves/ed25519.js'; +import { decaf448, decaf448_hasher, decaf448_oprf } from '@noble/curves/ed448.js'; + +console.log(ristretto255.Point, decaf448.Point); +``` + +Check out [RFC 9496](https://www.rfc-editor.org/rfc/rfc9496) more info on ristretto255 & decaf448. +Check out separate documentation for [Point](#elliptic-curve-point-math), [hasher](#hash-to-curve-hashing-to-curve-points) and [oprf](#oprfs). + +#### Prehashed signing + +```js +import { secp256k1 } from '@noble/curves/secp256k1.js'; +import { keccak_256 } from '@noble/hashes/sha3.js'; +const { secretKey } = secp256k1.keygen(); +const msg = new TextEncoder().encode('hello noble'); +// prehash: true (default) - hash using secp256k1.hash (sha256) +const sig = secp256k1.sign(msg, secretKey); +// prehash: false - hash using custom hash +const sigKeccak = secp256k1.sign(keccak_256(msg), secretKey, { prehash: false }); +``` + +Default sign() and verify() behavior (`prehash: true`) applies built-in hash function to message first. +For secp256k1 that's sha256, for p521 that's sha512. + +Providing `prehash: false` allows user to specify their own hash function (e.g. use secp256k1 + keccak_256). + +> [!NOTE] +> Previously, in noble-curves v1, `prehash: false` was the default. +> Some other libraries (like libsecp256k1) have no prehashing. + +#### Recovering public keys from signatures + +```js +import { secp256k1 } from '@noble/curves/secp256k1.js'; +const { secretKey, publicKey } = secp256k1.keygen(); +const msg = new TextEncoder().encode('hello noble'); +const sigRec = secp256k1.sign(msg, secretKey, { format: 'recovered' }); +const publicKey_ = secp256k1.recoverPublicKey(sigRec, msg); // == publicKey + +// recovered sig is compact sig with an extra byte +const sigNoRec = secp256k1.sign(msg, secretKey, { format: 'compact' }); +// sigNoRec == sigRec.slice(1) + +// Signature instance +const sigInstance = secp256k1.Signature.fromBytes(sigRec, 'recovered'); +``` + +Public key recovery - only supported with ECDSA. + +> [!NOTE] +> Key recovery is a simple math operation. +> There are no guarantees the signing was actually done. +> It's possible to forge signature and msg hash (r, s, h), which would +> recover into a random public key, but it's not feasible +> to find m which would lead to this specific forged h. + +#### Hedged ECDSA with noise + +```js +import { secp256k1 } from '@noble/curves/secp256k1.js'; +const { secretKey } = secp256k1.keygen(); +const msg = new TextEncoder().encode('hello noble'); +// extraEntropy: false - default, hedging disabled +const sigNoisy = secp256k1.sign(msg, secretKey); +// extraEntropy: true - fetch 32 random bytes from CSPRNG +const sigNoisyA = secp256k1.sign(msg, secretKey, { extraEntropy: true }); +// extraEntropy: bytes - specific extra entropy +const ent = Uint8Array.from([0xca, 0xfe, 0x01, 0x23]); +const sigNoisy2 = secp256k1.sign(msg, secretKey, { extraEntropy: ent }); +``` + +ECDSA `sign()` allows providing `extraEntropy`, which switches sig generation to hedged mode. + +By default, ECDSA signatures are generated deterministically, +following [RFC 6979](https://www.rfc-editor.org/rfc/rfc6979). +However, purely deterministic signatures are vulnerable to fault attacks. +Newer signature schemes, such as BIP340 schnorr, switched to hedged signatures because of this. +Hedging is basically incorporating some randomness into sig generation process. + +For more info, check out +[Deterministic signatures are not your friends](https://paulmillr.com/posts/deterministic-signatures/), +[RFC 6979](https://www.rfc-editor.org/rfc/rfc6979) section 3.6, +and [cfrg-det-sigs-with-noise draft](https://datatracker.ietf.org/doc/draft-irtf-cfrg-det-sigs-with-noise/). + +#### Consensus-friendliness vs e-voting + +```js +import { ed25519 } from '@noble/curves/ed25519.js'; +const { secretKey, publicKey } = ed25519.keygen(); +const msg = new TextEncoder().encode('hello noble'); +const sig = ed25519.sign(msg, secretKey); +// zip215: true +const isValid = ed25519.verify(sig, msg, publicKey); +// SBS / e-voting / RFC8032 / FIPS 186-5 +const isValidRfc = ed25519.verify(sig, msg, publicKey, { zip215: false }); +``` + +> [!NOTE] +> Most other libraries don't have SUF-CMA & SBS - less optimal choice for their security. + +In ed25519, there is an ability to choose between consensus-friendliness vs e-voting mode. + +* `zip215: true` (default) uses the more permissive, [consensus-friendly](https://hdevalence.ca/blog/2020-10-04-its-25519am) verification rules defined in [ZIP215](https://zips.z.cash/zip-0215). +* `zip215: false` enforces strict [RFC 8032](https://www.rfc-editor.org/rfc/rfc8032) / [FIPS 186-5](https://csrc.nist.gov/publications/detail/fips/186/5/final) verification and adds SBS-based non-repudiation, which is useful for: + * **Contract signing:** prevents a signer from later claiming they signed a different document + * **E-voting:** stops voters from choosing keys that let them repudiate their vote + * **Blockchains:** avoids signatures valid for multiple transactions (e.g., amount X also validating amount Y) + +Both modes have SUF-CMA (strong unforgeability under chosen message attacks). +See [Taming the many EdDSAs](https://eprint.iacr.org/2020/1244) for more info. + +### ECDH: Diffie-Hellman shared secrets + +```js +import { secp256k1 } from '@noble/curves/secp256k1.js'; +import { x25519 } from '@noble/curves/ed25519.js'; +import { x448 } from '@noble/curves/ed448.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; + +for (const curve of [secp256k1, x25519, x448, p256, p384, p521]) { + const alice = curve.keygen(); + const bob = curve.keygen(); + const sharedKey = curve.getSharedSecret(alice.secretKey, bob.publicKey); + console.log('alice', alice, 'bob', bob, 'shared', sharedKey); +} + +// x25519 & x448 specific methods +import { ed25519 } from '@noble/curves/ed25519.js'; +const alice = ed25519.keygen(); +const bob = ed25519.keygen(); +const aliceSecX = ed25519.utils.toMontgomerySecret(alice.secretKey); +const bobPubX = ed25519.utils.toMontgomery(bob.publicKey); +const sharedKey = x25519.getSharedSecret(aliceSecX, bobPubX); +``` + +We provide ECDH over all Weierstrass curves, and over 2 Montgomery curves +X25519 (Curve25519) & X448 (Curve448), conforming to [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748). + +In Weierstrass curves, shared secrets: + +- Include y-parity bytes: use `key.slice(1)` to strip it +- Are not hashed: use hashing or KDF on top, like `sha256(shared)` or `hkdf(shared)` + +#### webcrypto: Friendly wrapper + +> [!NOTE] +> Webcrypto methods are always async. + +##### webcrypto signatures + +```js +import { ed25519, ed448, p256, p384, p521 } from '@noble/curves/webcrypto.js'; + +(async () => { + for (let [name, curve] of Object.entries({ p256, p384, p521, ed25519, ed448 })) { + console.log('curve', name); + if (!await curve.isSupported()) { + console.log('is not supported, skipping'); + continue; + } + const keys = await curve.keygen(); + const msg = new TextEncoder().encode('hello noble'); + const sig = await curve.sign(msg, keys.secretKey); + const isValid = await curve.verify(sig, msg, keys.publicKey); + console.log({ + keys, msg, sig, isValid + }); + } +})(); +``` + +##### webcrypto ecdh + +```js +import { p256, p384, p521, x25519, x448 } from '@noble/curves/webcrypto.js'; + +(async () => { + for (let [name, curve] of Object.entries({ p256, p384, p521, x25519, x448 })) { + console.log('curve', name); + if (!await curve.isSupported()) { + console.log('is not supported, skipping'); + continue; + } + const alice = await curve.keygen(); + const bob = await curve.keygen(); + const shared = await curve.getSharedSecret(alice.secretKey, bob.publicKey); + const shared2 = await curve.getSharedSecret(bob.secretKey, alice.publicKey); + console.log({shared}); + } +})(); +``` + +##### Key conversion from noble to webcrypto and back + +```js +import { p256 as p256n } from '@noble/curves/nist.js'; +import { p256 } from '@noble/curves/webcrypto.js'; +(async () => { + const nobleKeys = p256n.keygen(); + // convert noble keys to webcrypto + const webKeys = { + secretKey: await p256.utils.convertSecretKey(nobleKeys.secretKey, 'raw', 'pkcs8'), + publicKey: await p256.utils.convertPublicKey(nobleKeys.publicKey, 'raw', 'spki') + }; + // convert webcrypto keys to noble + const nobleKeys2 = { + secretKey: await p256.utils.convertSecretKey(webKeys.secretKey, 'pkcs8', 'raw'), + publicKey: await p256.utils.convertPublicKey(webKeys.publicKey, 'spki', 'raw') + }; +})(); +``` + +Check out [micro-key-producer](https://github.com/paulmillr/micro-key-producer) for +pure JS key conversion utils. + +### BLS signatures, bls12-381, bn254 aka alt_bn128 + +```ts +import { bls12_381 } from '@noble/curves/bls12-381.js'; + +// G1 pubkeys, G2 sigs +const blsl = bls12_381.longSignatures; +const { secretKey, publicKey } = blsl.keygen(); +// const publicKey = blsl.getPublicKey(secretKey); +const msg = new TextEncoder().encode('hello noble'); +// default DST +const msgp = blsl.hash(msg); +// custom DST (Ethereum) +const msgpd = blsl.hash(msg, 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_'); +const signature = blsl.sign(msgp, secretKey); +const isValid = blsl.verify(signature, msgp, publicKey); +console.log('long', { publicKey, signature, isValid }); + +// G1 sigs, G2 pubkeys +const blss = bls12_381.shortSignatures; +const publicKey2 = blss.getPublicKey(secretKey); +const msgp2 = blss.hash(msg, 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_'); +const signature2 = blss.sign(msgp2, secretKey); +const isValid2 = blss.verify(signature2, msgp2, publicKey2); +console.log({ publicKey2, signature2, isValid2 }); + +// Aggregation +const aggregatedKey = bls12_381.longSignatures.aggregatePublicKeys([ + blsl.getPublicKey(bls12_381.utils.randomSecretKey()), + blsl.getPublicKey(bls12_381.utils.randomSecretKey()), +]); +// const aggregatedSig = bls.aggregateSignatures(sigs) + +// Pairings, with and without final exponentiation +// bls.pairing(PointG1, PointG2); +// bls.pairing(PointG1, PointG2, false); +// bls.fields.Fp12.finalExponentiate(bls.fields.Fp12.mul(PointG1, PointG2)); + +// Others +// bls.G1.Point.BASE, bls.G2.Point.BASE; +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr; +``` + +See [abstract/bls](#bls-barreto-lynn-scott-curves). +For example usage, check out [the implementation of BLS EVM precompiles](https://github.com/ethereumjs/ethereumjs-monorepo/blob/361f4edbc239e795a411ac2da7e5567298b9e7e5/packages/evm/src/precompiles/bls12_381/noble.ts). + +The BN254 API mirrors [BLS](#bls12-381). The curve was previously called alt_bn128. +The implementation is compatible with [EIP-196](https://eips.ethereum.org/EIPS/eip-196) and +[EIP-197](https://eips.ethereum.org/EIPS/eip-197). + +For BN254 usage, check out [the implementation of bn254 EVM precompiles](https://github.com/paulmillr/noble-curves/blob/3ed792f8ad9932765b84d1064afea8663a255457/test/bn254.test.js#L697). +We don't implement Point methods toBytes. To work around this limitation, has to initialize points on their own from BigInts. Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109). +Points of divergence: + +- Endianness: LE vs BE (byte-swapped) +- Flags as first hex bits (similar to BLS) vs no-flags +- Imaginary part last in G2 vs first (c0, c1 vs c1, c0) + +### hash-to-curve: hashing to curve points + +```ts +import { bls12_381 } from '@noble/curves/bls12-381.js'; +import { ed25519_hasher, ristretto255_hasher } from '@noble/curves/ed25519.js'; +import { decaf448_hasher, ed448_hasher } from '@noble/curves/ed448.js'; +import { p256_hasher, p384_hasher, p521_hasher } from '@noble/curves/nist.js'; +import { secp256k1_hasher } from '@noble/curves/secp256k1.js'; + +const h = { + secp256k1_hasher, + p256_hasher, p384_hasher, p521_hasher, + ed25519_hasher, + ed448_hasher, + ristretto255_hasher, + decaf448_hasher, + bls_G1: bls12_381.G1, + bls_G2: bls12_381.G2 +}; + +const msg = Uint8Array.from([0xca, 0xfe, 0x01, 0x23]); +console.log('msg', msg); +for (let [name, c] of Object.entries(h)) { + const hashToCurve = c.hashToCurve(msg).toHex(); + const hashToCurve_customDST = c.hashToCurve(msg, { DST: 'hello noble' }).toHex(); + const encodeToCurve = 'encodeToCurve' in c ? c.encodeToCurve(msg).toHex() : undefined; + // ristretto255, decaf448 only + const deriveToCurve = 'deriveToCurve' in c ? + c.deriveToCurve!(new Uint8Array(c.Point.Fp.BYTES * 2)).toHex() : undefined; + const hashToScalar = c.hashToScalar(msg); + console.log({ + name, hashToCurve, hashToCurve_customDST, encodeToCurve, deriveToCurve, hashToScalar + }); +} + +// abstract methods +import { expand_message_xmd, expand_message_xof, hash_to_field } from '@noble/curves/abstract/hash-to-curve.js'; +``` + +The module allows to hash arbitrary strings to elliptic curve points. Implements [RFC 9380](https://www.rfc-editor.org/rfc/rfc9380). + +> [!NOTE] +> Why is `p256_hasher` separate from `p256`? +> The methods reside in separate _hasher namespace for tree-shaking: +> this way users who don't need hash-to-curve, won't have it in their builds. + +### OPRFs + +```js +import { p256_oprf, p384_oprf, p521_oprf } from '@noble/curves/nist.js'; +import { ristretto255_oprf } from '@noble/curves/ed25519.js'; +import { decaf448_oprf } from '@noble/curves/ed448.js'; +``` + +We provide OPRFs (oblivious pseudorandom functions), +conforming to [RFC 9497](https://www.rfc-editor.org/rfc/rfc9497). + +OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`: + +- Server cannot calculate Output by itself: it doesn't know Input +- Client cannot calculate Output by itself: it doesn't know server secretKey +- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't + link Input to some value. + +### FROST threshold signatures + +FROST implements [RFC 9591](https://www.rfc-editor.org/rfc/rfc9591) threshold Schnorr signing. +It is similar to multisig from the application point of view: any `min` of `max` participants +can jointly produce one Schnorr signature under a shared public key. +Supported ciphersuites are `p256_FROST`, `ed25519_FROST`, `ed448_FROST`, `ristretto255_FROST`, +`secp256k1_FROST`, and `schnorr_FROST` (Taproot-compatible secp256k1). +Signing has two rounds: selected signers commit first, then produce signature shares. + +> [!WARNING] +> The FROST code is new and has not been audited yet. +> It passes the imported `frost-rs` vectors/examples and local regression tests. + +```js +import { p256_FROST } from '@noble/curves/nist.js'; + +const signers = { min: 2, max: 3 }; +const alice = p256_FROST.Identifier.derive('alice@example.com'); +const bob = p256_FROST.Identifier.derive('bob@example.com'); +const carol = p256_FROST.Identifier.derive('carol@example.com'); +// trusted dealer +const deal = p256_FROST.trustedDealer(signers, [alice, bob, carol]); +for (const id of [alice, bob, carol]) p256_FROST.validateSecret(deal.secretShares[id], deal.public); + +const msg = new TextEncoder().encode('hello threshold'); +// round 1: selected signers commit +const aliceRound1 = p256_FROST.commit(deal.secretShares[alice]); +const bobRound1 = p256_FROST.commit(deal.secretShares[bob]); +const commitmentList = [aliceRound1.commitments, bobRound1.commitments]; +// round 2: signers produce signature shares +const sigShares = { + [alice]: p256_FROST.signShare( + deal.secretShares[alice], + deal.public, + aliceRound1.nonces, + commitmentList, + msg + ), + [bob]: p256_FROST.signShare( + deal.secretShares[bob], + deal.public, + bobRound1.nonces, + commitmentList, + msg + ), +}; +const sig = p256_FROST.aggregate(deal.public, commitmentList, msg, sigShares); +const isValid = p256_FROST.verify(sig, msg, deal.public.commitments[0]); +``` + +Key generation can be done with a trusted dealer or with DKG. +DKG has three rounds: participants commit to key generation, exchange private shares, then derive final participant keys. + +```js +import { p256_FROST } from '@noble/curves/nist.js'; + +const signers = { min: 2, max: 3 }; +const alice = p256_FROST.DKG.round1(p256_FROST.Identifier.fromNumber(1), signers); +const bob = p256_FROST.DKG.round1(p256_FROST.Identifier.fromNumber(2), signers); +const carol = p256_FROST.DKG.round1(p256_FROST.Identifier.fromNumber(3), signers); + +// round 1: participants commit to key generation +const aliceRound2 = p256_FROST.DKG.round2(alice.secret, [bob.public, carol.public]); +const bobRound2 = p256_FROST.DKG.round2(bob.secret, [alice.public, carol.public]); +const carolRound2 = p256_FROST.DKG.round2(carol.secret, [alice.public, bob.public]); + +// round 2: private shares for each recipient +const aliceKey = p256_FROST.DKG.round3(alice.secret, [bob.public, carol.public], [ + bobRound2[p256_FROST.Identifier.fromNumber(1)], + carolRound2[p256_FROST.Identifier.fromNumber(1)], +]); +// round 3: final participant key package +``` + +DKG helpers are intended for interoperable testing and practical key generation. +The library implements the cryptographic steps, not the surrounding application protocol: +callers still need authenticated communication, coordination, retries, session handling, and policy. + +### poseidon: Poseidon hash + +Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash: +permutation and sponge. + +There are many poseidon variants with different constants. +We don't provide them: you should construct them manually. +Check out [scure-starknet](https://github.com/paulmillr/scure-starknet) package for a proper example. + +```ts +import { bn254 } from '@noble/curves/bn254.js'; +import { grainGenConstants, poseidon, poseidonSponge } from '@noble/curves/abstract/poseidon.js'; + +const rate = 2; +const capacity = 1; +const Fp = bn254.fields.Fr; +const { mds, roundConstants } = grainGenConstants({ + Fp, + t: rate + capacity, + roundsFull: 8, + roundsPartial: 31, +}); +const opts = { + Fp, + rate, + capacity, + sboxPower: 17, + mds, + roundConstants, + roundsFull: 8, + roundsPartial: 31, +}; +const permutation = poseidon({ ...opts, t: rate + capacity }); +const sponge = poseidonSponge(opts); // use carefully, not specced +``` + +### fft: Fast Fourier Transform + +```ts +import * as fft from '@noble/curves/abstract/fft.js'; +import { bls12_381 } from '@noble/curves/bls12-381.js'; +const Fr = bls12_381.fields.Fr; +const roots = fft.rootsOfUnity(Fr, 7n); +const fftFr = fft.FFT(roots, Fr); +``` + +Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields. +API may change at any time. The code has not been audited. Feature requests are welcome. + +### utils: byte shuffling, conversion + +```ts +import { bytesToHex, concatBytes, equalBytes, hexToBytes } from '@noble/curves/utils.js'; + +bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); +hexToBytes('cafe0123'); +concatBytes(Uint8Array.from([0xca, 0xfe]), Uint8Array.from([0x01, 0x23])); +equalBytes(Uint8Array.of(0xca), Uint8Array.of(0xca)); +``` + +### Internals + +#### Elliptic curve Point math + +```js +import { pippenger } from '@noble/curves/abstract/curve.js'; +import { secp256k1, schnorr } from '@noble/curves/secp256k1.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { ed25519, ristretto255 } from '@noble/curves/ed25519.js'; +import { ed448, decaf448 } from '@noble/curves/ed448.js'; +import { bls12_381 } from '@noble/curves/bls12-381.js'; +import { bn254 } from '@noble/curves/bn254.js'; +import { jubjub, babyjubjub } from '@noble/curves/misc.js'; + +const curves = [ + secp256k1, schnorr, p256, p384, p521, ed25519, ed448, + ristretto255, decaf448, + bls12_381.G1, bls12_381.G2, bn254.G1, + jubjub, babyjubjub +]; +for (const curve of curves) { + const { Point } = curve; + const { BASE, ZERO, Fp, Fn } = Point; + const info = Point.CURVE?.(); + const p = BASE.multiply(2n); + + // Initialization + if (info?.type === 'weierstrass') { + // projective (homogeneous) coordinates: (X, Y, Z) ∋ (x=X/Z, y=Y/Z) + const p_ = new Point(BASE.X, BASE.Y, BASE.Z); + } else if (info?.type === 'edwards') { + // extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z) + const p_ = new Point(BASE.X, BASE.Y, BASE.Z, BASE.T); + } + + // Math + const p1 = p.add(p); + const p2 = p.double(); + const p3 = p.subtract(p); + const p4 = p.negate(); + const p5 = p.multiply(451n); + + // MSM (multi-scalar multiplication) + const pa = [BASE, BASE.multiply(2n), BASE.multiply(4n), BASE.multiply(8n)]; + const p6 = pippenger(Point, pa, [3n, 5n, 7n, 11n]); + const _true3 = p6.equals(BASE.multiply(129n)); // 129*G + + const pcl = p.clearCofactor(); + const isTorsionFree = p.isTorsionFree(); + + const r1 = p.toBytes(); + const r1_ = Point.fromBytes(r1); + const r2 = p.toAffine(); + const { x, y } = r2; + const r2_ = Point.fromAffine(r2); +} +``` + +#### modular: Modular arithmetics & finite fields + +```js +import { mod, invert, Field } from '@noble/curves/abstract/modular.js'; + +// Finite Field utils +const fp = Field(2n ** 255n - 19n); // Finite field over 2^255-19 +fp.mul(591n, 932n); // multiplication +fp.pow(481n, 11024858120n); // exponentiation +fp.div(5n, 17n); // division: 5/17 mod 2^255-19 == 5 * invert(17) +fp.inv(5n); // modular inverse +fp.sqrt(4n); // square root + +// Non-Field generic utils are also available +mod(21n, 10n); // 21 mod 10 == 1n; fixed version of 21 % 10 +invert(17n, 10n); // invert(17) mod 10; modular multiplicative inverse +``` + +All arithmetics is done with JS bigints over finite fields, +which is defined from `modular` sub-module. + +Field operations are not constant-time: see [security](#security). +The fact is mostly irrelevant, but the important method to keep in mind is `pow`, +which may leak exponent bits, when used naïvely. + +#### weierstrass: Custom Weierstrass curve + +```js +import { weierstrass } from '@noble/curves/abstract/weierstrass.js'; +// NIST secp192r1 aka p192. https://www.secg.org/sec2-v2.pdf +const p192_CURVE = { + p: 0xfffffffffffffffffffffffffffffffeffffffffffffffffn, + n: 0xffffffffffffffffffffffff99def836146bc9b1b4d22831n, + h: 1n, + a: 0xfffffffffffffffffffffffffffffffefffffffffffffffcn, + b: 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1n, + Gx: 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012n, + Gy: 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811n, +}; +const p192_Point = weierstrass(p192_CURVE); +``` + +Short Weierstrass curve's formula is `y² = x³ + ax + b`. `weierstrass` +expects arguments `a`, `b`, field characteristic `p`, curve order `n`, +cofactor `h` and coordinates `Gx`, `Gy` of generator point. + +#### edwards: Custom Edwards curve + +```js +import { edwards } from '@noble/curves/abstract/edwards.js'; +const ed25519_CURVE = { + p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn, + n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn, + h: 8n, + a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn, + d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n, + Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an, + Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n, +}; +const ed25519_Point = edwards(ed25519_CURVE); +``` + +Twisted Edwards curve's formula is `ax² + y² = 1 + dx²y²`. +You must specify `a`, `d`, field characteristic `p`, curve order `n` (sometimes named as `L`), +cofactor `h` and coordinates `Gx`, `Gy` of generator point. + +#### Custom ECDSA instance + +```js +import { weierstrass, ecdsa } from '@noble/curves/abstract/weierstrass.js'; +import { sha224, sha256 } from '@noble/hashes/sha2.js'; +const p192_CURVE = { + p: 0xfffffffffffffffffffffffffffffffeffffffffffffffffn, + n: 0xffffffffffffffffffffffff99def836146bc9b1b4d22831n, + h: 1n, + a: 0xfffffffffffffffffffffffffffffffefffffffffffffffcn, + b: 0x64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1n, + Gx: 0x188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012n, + Gy: 0x07192b95ffc8da78631011ed6b24cdd573f977a11e794811n, +}; +const p192_Point = weierstrass(p192_CURVE); +const p192_sha256 = ecdsa(p192_Point, sha256); +// or +const p192_sha224 = ecdsa(p192_Point, sha224); + +const keys = p192_sha256.keygen(); +const msg = new TextEncoder().encode('custom curve'); +const sig = p192_sha256.sign(msg, keys.secretKey); +const isValid = p192_sha256.verify(sig, msg, keys.publicKey); +``` + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/2.2.0..main) +- at version 1.6.0, in Sep 2024, independently, by [Cure53](https://cure53.de) + - PDFs: [website](https://cure53.de/audit-report_noble-crypto-libs.pdf), [in-repo](./audit/2024-09-cure53-audit-nbl4.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.6.0..main) + - Scope: ed25519, ed448, their add-ons, bls12-381, bn254, + hash-to-curve, low-level primitives bls, tower, edwards, montgomery. + - The audit has been funded by [OpenSats](https://opensats.org) +- at version 1.2.0, in Sep 2023, independently, by [Kudelski Security](https://kudelskisecurity.com) + - PDFs: [in-repo](./audit/2023-09-kudelski-audit-starknet.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/1.2.0..main) + - Scope: [scure-starknet](https://github.com/paulmillr/scure-starknet) and its related + abstract modules of noble-curves: `curve`, `modular`, `poseidon`, `weierstrass` + - The audit has been funded by [Starkware](https://starkware.co) +- at version 0.7.3, in Feb 2023, independently, by [Trail of Bits](https://www.trailofbits.com) + - PDFs: [website](https://github.com/trailofbits/publications/blob/master/reviews/2023-01-ryanshea-noblecurveslibrary-securityreview.pdf), + [in-repo](./audit/2023-01-trailofbits-audit-curves.pdf) + - [Changes since audit](https://github.com/paulmillr/noble-curves/compare/0.7.3..main) + - Scope: abstract modules `curve`, `hash-to-curve`, `modular`, `poseidon`, `utils`, `weierstrass` and + top-level modules `_shortw_utils` and `secp256k1` + - The audit has been funded by [Ryan Shea](https://www.shea.io) + +It is tested against property-based, cross-library and Wycheproof vectors, +and is being fuzzed in [the separate repo](https://github.com/paulmillr/integration-tests). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time" +extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. + +### Memory dumping + +Use low-level languages instead of JS / WASM if your goal is absolute security. + +The library mostly uses Uint8Arrays and bigints. + +- Uint8Arrays have `.fill(0)` which instructs to fill content with zeroes + but there are no guarantees in JS +- bigints are immutable and don't have a method to zeroize their content: + a user needs to wait until the next garbage collection cycle +- hex strings are also immutable: there is no way to zeroize them +- `await fn()` will write all internal variables to memory. With + async functions there are no guarantees when the code + chunk would be executed. Which means attacker can have + plenty of time to read data from memory. + +This means some secrets could stay in memory longer than anticipated. +However, if an attacker can read application memory, it's doomed anyway: +there is no way to guarantee anything about zeroizing sensitive data without +complex tests-suite which will dump process memory and verify that there is +no sensitive data left. For JS it means testing all browsers (including mobile). +And, of course, it will be useless without using the same +test-suite in the actual application that consumes the library. + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there is 1 dependency; and a few dev dependencies: + +- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +### Randomness + +We rely on the built-in +[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), +which is considered a cryptographically secure PRNG. + +Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy. + +### Quantum computers + +Cryptographically relevant quantum computer, if built, will allow to +break elliptic curve cryptography (both ECDSA / EdDSA & ECDH) using Shor's algorithm. + +Consider switching to newer / hybrid algorithms, such as SPHINCS+. They are available in +[noble-post-quantum](https://github.com/paulmillr/noble-post-quantum). + +NIST prohibits classical cryptography (RSA, DSA, ECDSA, ECDH) [after 2035](https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf). Australian ASD prohibits it [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography). + +## Speed + +```sh +npm run bench +``` + +noble-curves spends 10+ ms to generate 20MB+ of base point precomputes. +This is done **one-time** per curve. + +The generation is deferred until any method (pubkey, sign, verify) is called. +User can force precompute generation by manually calling `Point.BASE.precompute(windowSize, false)`. +Check out the source code. + +Benchmark results on Apple M4: + +``` +# secp256k1 +init 10ms +getPublicKey x 9,099 ops/sec @ 109μs/op +sign x 7,182 ops/sec @ 139μs/op +verify x 1,188 ops/sec @ 841μs/op +recoverPublicKey x 1,265 ops/sec @ 790μs/op +getSharedSecret x 735 ops/sec @ 1ms/op +schnorr.sign x 957 ops/sec @ 1ms/op +schnorr.verify x 1,210 ops/sec @ 825μs/op + +# ed25519 +init 14ms +getPublicKey x 14,216 ops/sec @ 70μs/op +sign x 6,849 ops/sec @ 145μs/op +verify x 1,400 ops/sec @ 713μs/op + +# ed448 +init 37ms +getPublicKey x 5,273 ops/sec @ 189μs/op +sign x 2,494 ops/sec @ 400μs/op +verify x 476 ops/sec @ 2ms/op + +# p256 +init 17ms +getPublicKey x 8,977 ops/sec @ 111μs/op +sign x 7,236 ops/sec @ 138μs/op +verify x 877 ops/sec @ 1ms/op + +# p384 +init 42ms +getPublicKey x 4,084 ops/sec @ 244μs/op +sign x 3,247 ops/sec @ 307μs/op +verify x 331 ops/sec @ 3ms/op + +# p521 +init 83ms +getPublicKey x 2,049 ops/sec @ 487μs/op +sign x 1,748 ops/sec @ 571μs/op +verify x 170 ops/sec @ 5ms/op + +# ristretto255 +add x 931,966 ops/sec @ 1μs/op +multiply x 15,444 ops/sec @ 64μs/op +encode x 21,367 ops/sec @ 46μs/op +decode x 21,715 ops/sec @ 46μs/op + +# decaf448 +add x 478,011 ops/sec @ 2μs/op +multiply x 416 ops/sec @ 2ms/op +encode x 8,562 ops/sec @ 116μs/op +decode x 8,636 ops/sec @ 115μs/op + +# ECDH +x25519 x 1,981 ops/sec @ 504μs/op +x448 x 743 ops/sec @ 1ms/op +secp256k1 x 728 ops/sec @ 1ms/op +p256 x 705 ops/sec @ 1ms/op +p384 x 268 ops/sec @ 3ms/op +p521 x 137 ops/sec @ 7ms/op + +# hash-to-curve +hashToPrivateScalar x 1,754,385 ops/sec @ 570ns/op +hash_to_field x 135,703 ops/sec @ 7μs/op +hashToCurve secp256k1 x 3,194 ops/sec @ 313μs/op +hashToCurve p256 x 5,962 ops/sec @ 167μs/op +hashToCurve p384 x 2,230 ops/sec @ 448μs/op +hashToCurve p521 x 1,063 ops/sec @ 940μs/op +hashToCurve ed25519 x 4,047 ops/sec @ 247μs/op +hashToCurve ed448 x 1,691 ops/sec @ 591μs/op +hash_to_ristretto255 x 8,733 ops/sec @ 114μs/op +hash_to_decaf448 x 3,882 ops/sec @ 257μs/op + +# modular over secp256k1 P field +invert a x 866,551 ops/sec @ 1μs/op +invert b x 693,962 ops/sec @ 1μs/op +sqrt p = 3 mod 4 x 25,738 ops/sec @ 38μs/op +sqrt tonneli-shanks x 847 ops/sec @ 1ms/op + +# bls12-381 +init 22ms +getPublicKey x 1,325 ops/sec @ 754μs/op +sign x 80 ops/sec @ 12ms/op +verify x 62 ops/sec @ 15ms/op +pairing x 166 ops/sec @ 6ms/op +pairing10 x 54 ops/sec @ 18ms/op ± 23.48% (15ms..36ms) +MSM 4096 scalars x points 3286ms +aggregatePublicKeys/8 x 173 ops/sec @ 5ms/op +aggregatePublicKeys/32 x 46 ops/sec @ 21ms/op +aggregatePublicKeys/128 x 11 ops/sec @ 84ms/op +aggregatePublicKeys/512 x 2 ops/sec @ 335ms/op +aggregatePublicKeys/2048 x 0 ops/sec @ 1346ms/op +aggregateSignatures/8 x 82 ops/sec @ 12ms/op +aggregateSignatures/32 x 21 ops/sec @ 45ms/op +aggregateSignatures/128 x 5 ops/sec @ 178ms/op +aggregateSignatures/512 x 1 ops/sec @ 705ms/op +aggregateSignatures/2048 x 0 ops/sec @ 2823ms/op +``` + +## Upgrading + +Supported node.js versions: + +- v2 (2025-08): v20.19+ (ESM-only) +- v1 (2023-04): v14.21+ (ESM & CJS) + +### Changelog of curves v1 to curves v2 + +v2 massively simplifies internals, improves security, reduces bundle size and lays path for the future. +We tried to keep v2 as much backwards-compatible as possible. + +To simplify upgrading, upgrade first to curves 1.9.x. It would show deprecations in vscode-like text editor. +Fix them first. + +- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+ +- `.js` extension must be used for all modules + - Old: `@noble/curves/ed25519` + - New: `@noble/curves/ed25519.js` + - This simplifies working in browsers natively without transpilers + +New features: + +- webcrypto: create friendly noble-like wrapper over built-in WebCrypto +- oprf: implement RFC 9497 OPRFs (oblivious pseudorandom functions) + - We support p256, p384, p521, ristretto255 and decaf448 +- weierstrass, edwards: add `isValidSecretKey`, `isValidPublicKey` +- misc: add Brainpool curves: brainpoolP256r1, brainpoolP384r1, brainpoolP512r1 + +Changes: + +- Most methods now expect Uint8Array, string hex inputs are prohibited + - The change simplifies reasoning, improves security and reduces malleability + - `Point.fromHex` now expects string-only hex inputs, use `Point.fromBytes` for Uint8Array +- Many methods were renamed, upgrade to curves v1.9 first to highlight deprecated old names +- Breaking changes of ECDSA (secp256k1, p256, p384...): + - To bring back old behavior, pass `{ prehash: false, lowS: false }` to sign / verify + - sign, verify: Switch to **prehashed messages**. Instead of + messageHash, the methods now expect unhashed message. + To bring back old behavior, use option `{prehash: false}` + - sign, verify: Switch to **lowS signatures** by default. + This change doesn't affect secp256k1, which has been using lowS since beginning. + To bring back old behavior, use option `{lowS: false}` + - sign, verify: Switch to **Uint8Array signatures** (format: 'compact') by default. + - verify: **der format must be explicitly specified** in `{format: 'der'}`. + This reduces malleability + - verify: **prohibit Signature-instance** signature. User must now always do + `signature.toBytes()` +- Breaking changes of BLS signatures (bls12-381, bn254): + - Move getPublicKey, sign, verify, signShortSignature etc into two new namespaces: + bls.longSignatures (G1 pubkeys, G2 sigs) and bls.shortSignatures (G1 sigs, G2 pubkeys). + - verifyBatch now expects array of inputs `{message: ..., publicKey: ...}[]` +- Curve changes: + - Massively simplify curve creation, split it into point creation & sig generator creation + - New methods are `weierstrass() + ecdsa()` / `edwards() + eddsa()` + - weierstrass / edwards expect simplified curve params (Fp became p) + - ecdsa / eddsa expect Point class and hash + - Remove unnecessary Fn argument in `pippenger` +- modular changes: + - Field#fromBytes() now validates elements to be in 0..order-1 range +- Massively improve error messages, make them more descriptive + +Renamings: + +- Module changes + - `p256`, `p384`, `p521` modules have been moved into `nist` + - `jubjub` module has been moved into `misc` +- Point changes + - ExtendedPoint, ProjectivePoint => Point + - Point coordinates (projective / extended) from px/ex, py/ey, pz/ez, et => X, Y, Z, T + - Point.normalizeZ, Point.msm => separate methods in `abstract/curve.js` submodule + - Point.fromPrivateKey() got removed, use `Point.BASE.multiply()` and `Point.Fn.fromBytes(secretKey)` + - toRawBytes, fromRawBytes => toBytes, fromBytes + - RistrettoPoint => ristretto255.Point, DecafPoiont => decaf448.Point +- Signature (ECDSA) changes + - toCompactRawBytes, toDERRawBytes => toBytes('compact'), toBytes('der') + - toCompactHex, toDERHex => toHex('compact'), toHex('der') + - fromCompact, fromDER => fromBytes(format), fromHex(format) +- utils changes + - randomPrivateKey => randomSecretKey + - utils.precompute, Point#_setWindowSize => Point#precompute + - edwardsToMontgomery => utils.toMontgomery + - edwardsToMontgomeryPriv => utils.toMontgomerySecret +- Rename all curve-specific hash-to-curve methods to `*curve*_hasher`. + Example: `secp256k1.hashToCurve` => `secp256k1_hasher.hashToCurve()` +- Massive type renamings and improvements + +Removed features: + +- Point#multiplyAndAddUnsafe, Point#hasEvenY +- `CURVE` property with all kinds of random stuff. Point.CURVE() now replaces it, but only provides + curve parameters +- Remove `pasta`, `bn254_weierstrass` (NOT pairing-based bn254) curves +- utils.normPrivateKeyToScalar - use `Point.Fn.fromBytes` +- Field.MASK + +### secp256k1 v1, ed25519 v1, bls12-381 v1 to curves v1 + +Previously, the library was split into single-feature packages +[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1), +[noble-ed25519](https://github.com/paulmillr/noble-ed25519) and +[noble-bls12-381](https://github.com/paulmillr/noble-bls12-381). + +Curves continue their original work. The single-feature packages changed their +direction towards providing minimal 5kb implementations of cryptography, +which means they have less features. Separate bls package had been deprecated. + +secp256k1: + +- `getPublicKey`: defaults to compressed sigs (use second argument to adjust) +- `sign`: renamed options `canonical` => `lowS`; `der` => `format: 'der'` +- `verify`: renamed option `strict` => `lowS` +- `getSharedSecret`: defaults to compressed sigs (use third argument to adjust) +- `recoverPublicKey(msg, sig, rec)` was changed to `sig.recoverPublicKey(msg)` +- `Point` (2d xy) has been changed to `ProjectivePoint` (3d xyz) + +ed25519: + +- `Signature` was removed in favor of raw bytes +- `getSharedSecret` was moved to `x25519` module + +bls12-381: + +- Renamed PointG1 -> G1.Point, PointG2 -> G2.Point +- Renamed PointG2.fromSignature -> Signature.decode, PointG2.toSignature -> Signature.encode + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run bench` will run benchmarks +- `npm run build:release` will build single file + +See [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +MuSig2 signature scheme and BIP324 ElligatorSwift mapping for secp256k1 +are available [in a separate package](https://github.com/paulmillr/scure-btc-signer). + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/curves/abstract/bls.d.ts b/node_modules/@noble/curves/abstract/bls.d.ts new file mode 100644 index 0000000..1ade638 --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.d.ts @@ -0,0 +1,411 @@ +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two modes of operation: + * - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs). + * - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs). + * @module + **/ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type TArg, type TRet } from '../utils.ts'; +import { type CurveLengths } from './curve.ts'; +import { type H2CHasher, type H2COpts, type MapToCurve } from './hash-to-curve.ts'; +import { type IField } from './modular.ts'; +import type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6Bls } from './tower.ts'; +import { type WeierstrassPoint, type WeierstrassPointCons } from './weierstrass.ts'; +type Fp = bigint; +/** + * Twist convention used by the pairing formulas for a concrete curve family. + * BLS12-381 uses a multiplicative twist, while BN254 uses a divisive one. + */ +export type BlsTwistType = 'multiplicative' | 'divisive'; +/** + * Codec exposed as `curve.shortSignatures.Signature`. + * Use it to parse or serialize G1 signatures in short-signature mode. + * In this mode, public keys live in G2. + */ +export type BlsShortSignatureCoder = { + /** + * Parse a compressed signature from raw bytes. + * @param bytes - Compressed signature bytes. + * @returns Parsed signature point. + */ + fromBytes(bytes: TArg): WeierstrassPoint; + /** + * Parse a compressed signature from a hex string. + * @param hex - Compressed signature hex string. + * @returns Parsed signature point. + */ + fromHex(hex: string): WeierstrassPoint; + /** + * Encode a signature point into compressed bytes. + * @param point - Signature point. + * @returns Compressed signature bytes. + */ + toBytes(point: WeierstrassPoint): TRet; + /** + * Encode a signature point into a hex string. + * @param point - Signature point. + * @returns Compressed signature hex. + */ + toHex(point: WeierstrassPoint): string; +}; +/** + * Codec exposed as `curve.longSignatures.Signature`. + * Use it to parse or serialize G2 signatures in long-signature mode. + * In this mode, public keys live in G1. + */ +export type BlsLongSignatureCoder = { + /** + * Parse a compressed signature from raw bytes. + * @param bytes - Compressed signature bytes. + * @returns Parsed signature point. + */ + fromBytes(bytes: TArg): WeierstrassPoint; + /** + * Parse a compressed signature from a hex string. + * @param hex - Compressed signature hex string. + * @returns Parsed signature point. + */ + fromHex(hex: string): WeierstrassPoint; + /** + * Encode a signature point into compressed bytes. + * @param point - Signature point. + * @returns Compressed signature bytes. + */ + toBytes(point: WeierstrassPoint): TRet; + /** + * Encode a signature point into a hex string. + * @param point - Signature point. + * @returns Compressed signature hex. + */ + toHex(point: WeierstrassPoint): string; +}; +/** Tower fields needed by pairing code, hash-to-curve, and subgroup arithmetic. */ +export type BlsFields = { + /** Base field of G1 coordinates. */ + Fp: IField; + /** Scalar field used for secret scalars and subgroup order arithmetic. */ + Fr: IField; + /** Quadratic extension field used by G2. */ + Fp2: Fp2Bls; + /** Sextic extension field used inside pairing arithmetic. */ + Fp6: Fp6Bls; + /** Degree-12 extension field that contains the GT target group. */ + Fp12: Fp12Bls; +}; +/** + * Callback used by pairing post-processing hooks to add one more G2 point to the Miller-loop state. + * @param Rx - Current projective X coordinate. + * @param Ry - Current projective Y coordinate. + * @param Rz - Current projective Z coordinate. + * @param Qx - G2 affine x coordinate. + * @param Qy - G2 affine y coordinate. + * @returns Updated projective accumulator coordinates. + */ +export type BlsPostPrecomputePointAddFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) => { + Rx: Fp2; + Ry: Fp2; + Rz: Fp2; +}; +/** + * Hook for curve-specific pairing cleanup after the Miller loop precomputes are built. + * @param Rx - Current projective X coordinate. + * @param Ry - Current projective Y coordinate. + * @param Rz - Current projective Z coordinate. + * @param Qx - G2 affine x coordinate. + * @param Qy - G2 affine y coordinate. + * @param pointAdd - Callback used to fold one more point into the accumulator. + */ +export type BlsPostPrecomputeFn = (Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2, pointAdd: BlsPostPrecomputePointAddFn) => void; +/** Low-level pairing helpers shared by BLS curve bundles. */ +export type BlsPairing = { + /** Byte lengths for keys and signatures exposed by this pairing family. */ + lengths: CurveLengths; + /** Scalar field used by the pairing and signing helpers. */ + Fr: IField; + /** Target field used for the GT result of pairings. */ + Fp12: Fp12Bls; + /** + * Build Miller-loop precomputes for one G2 point. + * @param p - G2 point to precompute. + * @returns Pairing precompute table. + */ + calcPairingPrecomputes: (p: WeierstrassPoint) => Precompute; + /** + * Evaluate a batch of Miller loops from precomputed line coefficients. + * @param pairs - Precomputed Miller-loop inputs. + * @returns Accumulated GT value before or after final exponentiation. + */ + millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12; + /** + * Pair one G1 point with one G2 point. + * @param P - G1 point. + * @param Q - G2 point. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. + * @throws If either point is the point at infinity. {@link Error} + */ + pairing: (P: WeierstrassPoint, Q: WeierstrassPoint, withFinalExponent?: boolean) => Fp12; + /** + * Pair many G1/G2 pairs in one batch. + * @param pairs - Point pairs to accumulate. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. Empty input returns the multiplicative identity in GT. + */ + pairingBatch: (pairs: { + g1: WeierstrassPoint; + g2: WeierstrassPoint; + }[], withFinalExponent?: boolean) => Fp12; + /** + * Generate a random secret key for this pairing family. + * @param seed - Optional seed material. + * @returns Secret key bytes. + */ + randomSecretKey: (seed?: TArg) => TRet; +}; +/** + * Parameters that define the Miller-loop shape and twist handling + * for a concrete pairing family. + */ +export type BlsPairingParams = { + /** Signed loop parameter used by the Miller loop. */ + ateLoopSize: bigint; + /** Whether the signed Miller-loop parameter is negative. */ + xNegative: boolean; + /** + * Twist convention used by the pairing formulas. + * BLS12-381 is multiplicative; BN254 is divisive. + */ + twistType: BlsTwistType; + /** + * Optional RNG override used by helper constructors. + * Receives the requested byte length and returns random bytes. + */ + randomBytes?: (len?: number) => TRet; + /** + * Optional hook for curve-specific untwisting after precomputation. + * Used by BN254 after the Miller loop. + */ + postPrecompute?: BlsPostPrecomputeFn; +}; +/** Hash-to-curve settings shared by the G1 and G2 hashers inside a BLS curve bundle. */ +export type BlsHasherParams = { + /** + * Optional map-to-curve override for G1. + * Receives the hash-to-field tuple and returns one affine G1 point. + */ + mapToG1?: MapToCurve; + /** + * Optional map-to-curve override for G2. + * Receives the hash-to-field tuple and returns one affine G2 point. + */ + mapToG2?: MapToCurve; + /** Shared baseline hash-to-curve options. */ + hasherOpts: H2COpts; + /** G1-specific hash-to-curve options merged on top of `hasherOpts`. */ + hasherOptsG1: H2COpts; + /** G2-specific hash-to-curve options merged on top of `hasherOpts`. */ + hasherOptsG2: H2COpts; +}; +type PrecomputeSingle = [Fp2, Fp2, Fp2][]; +type Precompute = PrecomputeSingle[]; +/** + * BLS consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + */ +export interface BlsCurvePair { + /** Byte lengths for keys and signatures exposed by this curve family. */ + lengths: CurveLengths; + /** + * Shared Miller-loop batch evaluator. + * @param pairs - Precomputed Miller-loop inputs. + * @returns Accumulated GT value. + */ + millerLoopBatch: BlsPairing['millerLoopBatch']; + /** + * Pair one G1 point with one G2 point. + * @param P - G1 point. + * @param Q - G2 point. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. + * @throws If either point is the point at infinity. {@link Error} + */ + pairing: BlsPairing['pairing']; + /** + * Pair many G1/G2 pairs in one batch. + * @param pairs - Point pairs to accumulate. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. Empty input returns the multiplicative identity in GT. + */ + pairingBatch: BlsPairing['pairingBatch']; + /** G1 point constructor for the base field subgroup. */ + G1: { + Point: WeierstrassPointCons; + }; + /** G2 point constructor for the twist subgroup. */ + G2: { + Point: WeierstrassPointCons; + }; + /** Tower fields exposed by the pairing implementation. */ + fields: { + Fp: IField; + Fp2: Fp2Bls; + Fp6: Fp6Bls; + Fp12: Fp12Bls; + Fr: IField; + }; + /** Utility helpers shared by hashers and signers. */ + utils: { + randomSecretKey: (seed?: TArg) => TRet; + calcPairingPrecomputes: BlsPairing['calcPairingPrecomputes']; + }; + /** Public pairing parameters exposed for introspection. */ + params: { + ateLoopSize: bigint; + twistType: BlsTwistType; + }; +} +/** BLS curve bundle extended with hash-to-curve helpers for G1 and G2. */ +export interface BlsCurvePairWithHashers extends BlsCurvePair { + /** G1 hasher bundle with RFC 9380 helpers. */ + G1: H2CHasher>; + /** G2 hasher bundle with RFC 9380 helpers. */ + G2: H2CHasher>; +} +/** BLS curve bundle extended with both hashers and signature helpers. */ +export interface BlsCurvePairWithSignatures extends BlsCurvePairWithHashers { + /** Long-signature mode: G1 public keys and G2 signatures. */ + longSignatures: BlsSigs; + /** Short-signature mode: G2 public keys and G1 signatures. */ + shortSignatures: BlsSigs; +} +type BLSInput = TArg; +/** BLS signer helpers for one signature mode. */ +export interface BlsSigs { + /** Byte lengths for secret keys, public keys, and signatures. */ + lengths: CurveLengths; + /** + * Generate a secret/public key pair for this signature mode. + * @param seed - Optional seed material. + * @returns Secret and public key pair. + */ + keygen(seed?: TArg): { + secretKey: TRet; + publicKey: WeierstrassPoint

; + }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public-key point. + */ + getPublicKey(secretKey: TArg): WeierstrassPoint

; + /** + * Sign a message already hashed onto the signature subgroup. + * @param hashedMessage - Message mapped to the signature subgroup. + * @param secretKey - Secret key bytes. + * @returns Signature point. + */ + sign(hashedMessage: WeierstrassPoint, secretKey: TArg): WeierstrassPoint; + /** + * Verify one signature against one public key and hashed message. + * @param signature - Signature point or encoded signature. + * @param message - Hashed message point. + * @param publicKey - Public-key point or encoded key. + * @returns Whether the signature is valid. + */ + verify(signature: WeierstrassPoint | BLSInput, message: WeierstrassPoint, publicKey: WeierstrassPoint

| BLSInput): boolean; + /** + * Verify one aggregated signature against many `(message, publicKey)` pairs. + * @param signature - Aggregated signature. + * @param items - Message/public-key pairs. + * @returns Whether the aggregated signature is valid. Same-message aggregate verification still + * requires proof of possession or another rogue-key defense from the caller. + */ + verifyBatch: (signature: WeierstrassPoint | BLSInput, items: { + message: WeierstrassPoint; + publicKey: WeierstrassPoint

| BLSInput; + }[]) => boolean; + /** + * Add many public keys into one aggregate point. + * @param publicKeys - Public keys to aggregate. + * @returns Aggregated public-key point. This is raw point addition and does not add proof of + * possession or rogue-key protection on its own. + */ + aggregatePublicKeys(publicKeys: (WeierstrassPoint

| BLSInput)[]): WeierstrassPoint

; + /** + * Add many signatures into one aggregate point. + * @param signatures - Signatures to aggregate. + * @returns Aggregated signature point. This is raw point addition and does not change the proof + * of possession requirements of the aggregate-verification scheme. + */ + aggregateSignatures(signatures: (WeierstrassPoint | BLSInput)[]): WeierstrassPoint; + /** + * Hash an arbitrary message onto the signature subgroup. + * @param message - Message bytes. + * @param DST - Optional domain separation tag. + * @returns Curve point on the signature subgroup. + */ + hash(message: TArg, DST?: TArg): WeierstrassPoint; + /** Signature codec for this mode. */ + Signature: BlsLongSignatureCoder; +} +type BlsSignatureCoders = Partial<{ + LongSignature: BlsLongSignatureCoder; + ShortSignature: BlsShortSignatureCoder; +}>; +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while + * empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the + * low-level pairing API fail-closed for BLS-style callers, where identity points usually signal + * broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly + * precomputes the G1 base-point table as a performance side effect. + * @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error} + * @example + * ```ts + * import { blsBasic } from '@noble/curves/abstract/bls.js'; + * import { bn254 } from '@noble/curves/bn254.js'; + * // Pair a G1 point with a G2 point without the higher-level signer helpers. + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +export declare function blsBasic(fields: TArg, G1_Point: WeierstrassPointCons, G2_Point: WeierstrassPointCons, params: TArg): BlsCurvePair; +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}. + * @param signatureCoders - Signature codecs. + * @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs, + * and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate + * verification still requires proof of possession or another rogue-key defense from the caller. + * @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error} + * @example + * ```ts + * import { bls } from '@noble/curves/abstract/bls.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const sigs = bls12_381.longSignatures; + * // Use the full BLS helper set when you need hashing, keygen, signing, and verification. + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = sigs.hash(new TextEncoder().encode('hello noble')); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export declare function bls(fields: TArg, G1_Point: WeierstrassPointCons, G2_Point: WeierstrassPointCons, params: TArg, hasherParams: TArg, signatureCoders: BlsSignatureCoders): BlsCurvePairWithSignatures; +export {}; +//# sourceMappingURL=bls.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.d.ts.map b/node_modules/@noble/curves/abstract/bls.d.ts.map new file mode 100644 index 0000000..55d82eb --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls.d.ts","sourceRoot":"","sources":["../src/abstract/bls.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;IAeI;AACJ,sEAAsE;AACtE,OAAO,EAAuC,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AACxF,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAGL,KAAK,SAAS,EACd,KAAK,OAAO,EACZ,KAAK,UAAU,EAChB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAoC,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAC7E,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACrE,OAAO,EAAE,KAAK,gBAAgB,EAAE,KAAK,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAEpF,KAAK,EAAE,GAAG,MAAM,CAAC;AAKjB;;;GAGG;AACH,MAAM,MAAM,YAAY,GAAG,gBAAgB,GAAG,UAAU,CAAC;AAEzD;;;;GAIG;AACH,MAAM,MAAM,sBAAsB,CAAC,EAAE,IAAI;IACvC;;;;OAIG;IACH,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,EAAE,CAAC,CAAC;IACzD;;;;OAIG;IACH,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,CAAC,EAAE,CAAC,CAAC;IAC3C;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,gBAAgB,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IACv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D,KAAK,kBAAkB,GAAG,OAAO,CAAC;IAChC,aAAa,EAAE,qBAAqB,CAAC,GAAG,CAAC,CAAC;IAC1C,cAAc,EAAE,sBAAsB,CAAC,EAAE,CAAC,CAAC;CAC5C,CAAC,CAAC;AAGH;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,QAAQ,CACtB,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EACvB,QAAQ,EAAE,oBAAoB,CAAC,EAAE,CAAC,EAClC,QAAQ,EAAE,oBAAoB,CAAC,GAAG,CAAC,EACnC,MAAM,EAAE,IAAI,CAAC,gBAAgB,CAAC,GAC7B,YAAY,CAuCd;AAiCD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,GAAG,CACjB,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EACvB,QAAQ,EAAE,oBAAoB,CAAC,EAAE,CAAC,EAClC,QAAQ,EAAE,oBAAoB,CAAC,GAAG,CAAC,EACnC,MAAM,EAAE,IAAI,CAAC,gBAAgB,CAAC,EAC9B,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,EACnC,eAAe,EAAE,kBAAkB,GAClC,0BAA0B,CA0B5B"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.js b/node_modules/@noble/curves/abstract/bls.js new file mode 100644 index 0000000..56e83db --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.js @@ -0,0 +1,432 @@ +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two modes of operation: + * - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs). + * - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs). + * @module + **/ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abytes, notImplemented, randomBytes } from "../utils.js"; +import {} from "./curve.js"; +import { createHasher, } from "./hash-to-curve.js"; +import { getMinHashLength, mapHashToField } from "./modular.js"; +import {} from "./weierstrass.js"; +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); +// Signed non-adjacent decomposition of the spec-defined Miller-loop parameter. +// BN254 benefits most because `6x+2` has multiple adjacent `11` runs, but BLS12-381's +// stored `|x|` still starts with `11`, so the Miller loop must also handle one `-1` digit there. +function NAfDecomposition(a) { + const res = []; + // a>1 because of marker bit + for (; a > _1n; a >>= _1n) { + if ((a & _1n) === _0n) + res.unshift(0); + else if ((a & _3n) === _3n) { + res.unshift(-1); + a += _1n; + } + else + res.unshift(1); + } + return res; +} +function aNonEmpty(arr) { + // Aggregate helpers use this to reject empty variable-length inputs consistently. + // Without the guard, each caller would fall through into a different empty-input / identity + // case and hide missing inputs behind outputs that still look structurally valid. + if (!Array.isArray(arr) || arr.length === 0) + throw new Error('expected non-empty array'); +} +// This should be enough for bn254, no need to export full stuff? +function createBlsPairing(fields, G1, G2, params) { + const { Fr, Fp2, Fp12 } = fields; + const { twistType, ateLoopSize, xNegative, postPrecompute } = params; + // Applies sparse multiplication as line function + let lineFunction; + if (twistType === 'multiplicative') { + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); + } + else if (twistType === 'divisive') { + // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of + // precompute calculations. + lineFunction = (c0, c1, c2, f, Px, Py) => Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); + } + else + throw new Error('bls: unknown twist type'); + const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n)); + function pointDouble(ell, Rx, Ry, Rz) { + const t0 = Fp2.sqr(Ry); // Ry² + const t1 = Fp2.sqr(Rz); // Rz² + const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + const t3 = Fp2.mul(t2, _3n); // 3 * T2 + const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + const c0 = Fp2.sub(t2, t0); // T2 - T0 (i) + const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx² + const c2 = Fp2.neg(t4); // -T4 (-h) + ell.push([c0, c1, c2]); + Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2 + // ((T0 + T3) / 2)² - 3 * T2² + Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); + Rz = Fp2.mul(t0, t4); // T0 * T4 + return { Rx, Ry, Rz }; + } + function pointAdd(ell, Rx, Ry, Rz, Qx, Qy) { + // Addition + const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy + const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry + const c2 = t1; // == Rx - Qx * Rz + ell.push([c0, c1, c2]); + const t2 = Fp2.sqr(t1); // T1² + const t3 = Fp2.mul(t2, t1); // T2 * T1 + const t4 = Fp2.mul(t2, Rx); // T2 * Rx + // T3 - 2 * T4 + T0² * Rz + const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + return { Rx, Ry, Rz }; + } + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine + // add + double in windowed precomputes here, otherwise it would be single op (since X is static) + const ATE_NAF = NAfDecomposition(ateLoopSize); + const calcPairingPrecomputes = (point) => { + const p = point; + const { x, y } = p.toAffine(); + // prettier-ignore + const Qx = x, Qy = y, negQy = Fp2.neg(y); + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; + const ell = []; + for (const bit of ATE_NAF) { + const cur = []; + ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); + if (bit) + ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); + ell.push(cur); + } + if (postPrecompute) { + const last = ell[ell.length - 1]; + postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); + } + return ell; + }; + function millerLoopBatch(pairs, withFinalExponent = false) { + let f12 = Fp12.ONE; + if (pairs.length) { + const ellLen = pairs[0][0].length; + for (let i = 0; i < ellLen; i++) { + f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings + // NOTE: we apply multiple pairings in parallel here + for (const [ell, Px, Py] of pairs) { + for (const [c0, c1, c2] of ell[i]) + f12 = lineFunction(c0, c1, c2, f12, Px, Py); + } + } + } + if (xNegative) + f12 = Fp12.conjugate(f12); + return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; + } + // Calculates product of multiple pairings + // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))` + function pairingBatch(pairs, withFinalExponent = true) { + const res = []; + for (const { g1, g2 } of pairs) { + // Mathematically, a zero pairing term contributes GT.ONE. We still reject it here because + // this API mainly backs BLS verification, where ZERO inputs usually mean broken hash / + // wiring. Silently skipping them would turn those failures into a neutral pairing product. + // Callers that want the algebraic neutral-element behavior can filter ZERO terms first. + if (g1.is0() || g2.is0()) + throw new Error('pairing is not available for ZERO point'); + // This uses toAffine inside + g1.assertValidity(); + g2.assertValidity(); + const Qa = g1.toAffine(); + res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]); + } + return millerLoopBatch(res, withFinalExponent); + } + // Calculates bilinear pairing + function pairing(Q, P, withFinalExponent = true) { + return pairingBatch([{ g1: Q, g2: P }], withFinalExponent); + } + const lengths = { + seed: getMinHashLength(Fr.ORDER), + }; + const rand = params.randomBytes === undefined ? randomBytes : params.randomBytes; + // Seeded calls deterministically reduce exactly `lengths.seed` bytes into `1..Fr.ORDER-1`; + // omitting `seed` just fills that input buffer from the configured RNG first. + const randomSecretKey = (seed) => { + seed = seed === undefined ? rand(lengths.seed) : seed; + abytes(seed, lengths.seed, 'seed'); + return mapHashToField(seed, Fr.ORDER); + }; + Object.freeze(lengths); + return { + lengths, + Fr, + Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12! + millerLoopBatch, + pairing, + pairingBatch, + calcPairingPrecomputes, + randomSecretKey, + }; +} +function createBlsSig(blsPairing, PubPoint, SigPoint, isSigG1, hashToSigCurve, SignatureCoder) { + const { Fr, Fp12, pairingBatch, randomSecretKey, lengths } = blsPairing; + if (!SignatureCoder) { + SignatureCoder = { + fromBytes: notImplemented, + fromHex: notImplemented, + toBytes: notImplemented, + toHex: notImplemented, + }; + } + function normPub(point) { + return point instanceof PubPoint ? point : PubPoint.fromBytes(point); + } + function normSig(point) { + return point instanceof SigPoint ? point : SigPoint.fromBytes(point); + } + // Sign/verify here take points already hashed onto the signature subgroup. + // Raw bytes and points from the other subgroup must fail this constructor-brand + // check before later validity checks run. + function amsg(m) { + if (!(m instanceof SigPoint)) + throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`); + return m; + } + // What matters here is what point pairing API accepts as G1 or G2, not actual size or names + const pair = !isSigG1 + ? (a, b) => ({ g1: a, g2: b }) + : (a, b) => ({ g1: b, g2: a }); + return Object.freeze({ + lengths: Object.freeze({ ...lengths, secretKey: Fr.BYTES }), + keygen(seed) { + const secretKey = randomSecretKey(seed); + const publicKey = this.getPublicKey(secretKey); + return { secretKey, publicKey }; + }, + // P = pk x G + getPublicKey(secretKey) { + let sec; + try { + sec = PubPoint.Fn.fromBytes(secretKey); + } + catch (error) { + // @ts-ignore + throw new Error('invalid private key: ' + typeof secretKey, { cause: error }); + } + return PubPoint.BASE.multiply(sec); + }, + // S = pk x H(m) + sign(message, secretKey, unusedArg) { + if (unusedArg != null) + throw new Error('sign() expects 2 arguments'); + const sec = PubPoint.Fn.fromBytes(secretKey); + amsg(message).assertValidity(); + return message.multiply(sec); + }, + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + // e(S, G) == e(H(m), P) + verify(signature, message, publicKey, unusedArg) { + if (unusedArg != null) + throw new Error('verify() expects 3 arguments'); + signature = normSig(signature); + publicKey = normPub(publicKey); + const P = publicKey.negate(); + const G = PubPoint.BASE; + const Hm = amsg(message); + const S = signature; + // This code was changed in 1.9.x: + // Before it was G.negate() in G2, now it's always pubKey.negate + // e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair). + // We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1 + try { + const exp = pairingBatch([pair(P, Hm), pair(G, S)]); + return Fp12.eql(exp, Fp12.ONE); + } + catch { + return false; + } + }, + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead? + verifyBatch(signature, items) { + aNonEmpty(items); + const sig = normSig(signature); + const nMessages = items.map((i) => i.message); + const nPublicKeys = items.map((i) => normPub(i.publicKey)); + // NOTE: this works only for exact same object + const messagePubKeyMap = new Map(); + for (let i = 0; i < nPublicKeys.length; i++) { + const pub = nPublicKeys[i]; + const msg = nMessages[i]; + let keys = messagePubKeyMap.get(msg); + if (keys === undefined) { + keys = []; + messagePubKeyMap.set(msg, keys); + } + keys.push(pub); + } + const paired = []; + const G = PubPoint.BASE; + try { + for (const [msg, keys] of messagePubKeyMap) { + const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg)); + paired.push(pair(groupPublicKey, msg)); + } + paired.push(pair(G.negate(), sig)); + return Fp12.eql(pairingBatch(paired), Fp12.ONE); + } + catch { + return false; + } + }, + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + aggregatePublicKeys(publicKeys) { + aNonEmpty(publicKeys); + publicKeys = publicKeys.map((pub) => normPub(pub)); + const agg = publicKeys.reduce((sum, p) => sum.add(p), PubPoint.ZERO); + agg.assertValidity(); + return agg; + }, + // Adds a bunch of signature points together. + // pk1 + pk2 + pk3 = pkA + aggregateSignatures(signatures) { + aNonEmpty(signatures); + signatures = signatures.map((sig) => normSig(sig)); + const agg = signatures.reduce((sum, s) => sum.add(s), SigPoint.ZERO); + agg.assertValidity(); + return agg; + }, + hash(messageBytes, DST) { + abytes(messageBytes); + const opts = DST ? { DST } : undefined; + return hashToSigCurve(messageBytes, opts); + }, + Signature: Object.freeze({ ...SignatureCoder }), + }) /*satisfies Signer */; +} +// NOTE: separate function instead of function override, so we don't depend on hasher in bn254. +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while + * empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the + * low-level pairing API fail-closed for BLS-style callers, where identity points usually signal + * broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly + * precomputes the G1 base-point table as a performance side effect. + * @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error} + * @example + * ```ts + * import { blsBasic } from '@noble/curves/abstract/bls.js'; + * import { bn254 } from '@noble/curves/bn254.js'; + * // Pair a G1 point with a G2 point without the higher-level signer helpers. + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +export function blsBasic(fields, G1_Point, G2_Point, params) { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = fields; + // Point on G1 curve: (x, y) + // const G1_Point = weierstrass(CURVE.G1, { Fn: Fr }); + const G1 = { Point: G1_Point }; + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2 = { Point: G2_Point }; + const pairingRes = createBlsPairing(fields, G1_Point, G2_Point, params); + const { millerLoopBatch, pairing, pairingBatch, calcPairingPrecomputes, randomSecretKey, lengths, } = pairingRes; + G1.Point.BASE.precompute(4); + Object.freeze(G1); + Object.freeze(G2); + return Object.freeze({ + lengths: Object.freeze(lengths), + millerLoopBatch, + pairing, + pairingBatch, + G1, + G2, + fields: Object.freeze({ Fr, Fp, Fp2, Fp6, Fp12 }), + params: Object.freeze({ + ateLoopSize: params.ateLoopSize, + twistType: params.twistType, + }), + utils: Object.freeze({ + randomSecretKey, + calcPairingPrecomputes, + }), + }); +} +// We can export this too, but seems there is not much reasons for now? If user wants hasher, they can just create hasher. +function blsHashers(fields, G1_Point, G2_Point, params, hasherParams) { + const base = blsBasic(fields, G1_Point, G2_Point, params); + // Missing map hooks intentionally fail closed via notImplemented on first hash use. + const G1Hasher = createHasher(G1_Point, hasherParams.mapToG1 === undefined ? notImplemented : hasherParams.mapToG1, { + ...hasherParams.hasherOpts, + ...hasherParams.hasherOptsG1, + }); + const G2Hasher = createHasher(G2_Point, hasherParams.mapToG2 === undefined ? notImplemented : hasherParams.mapToG2, { + ...hasherParams.hasherOpts, + ...hasherParams.hasherOptsG2, + }); + return Object.freeze({ ...base, G1: G1Hasher, G2: G2Hasher }); +} +// G1_Point: ProjConstructor, G2_Point: ProjConstructor, +// Rename to blsSignatures? +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}. + * @param signatureCoders - Signature codecs. + * @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs, + * and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate + * verification still requires proof of possession or another rogue-key defense from the caller. + * @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error} + * @example + * ```ts + * import { bls } from '@noble/curves/abstract/bls.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const sigs = bls12_381.longSignatures; + * // Use the full BLS helper set when you need hashing, keygen, signing, and verification. + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = sigs.hash(new TextEncoder().encode('hello noble')); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export function bls(fields, G1_Point, G2_Point, params, hasherParams, signatureCoders) { + const base = blsHashers(fields, G1_Point, G2_Point, params, hasherParams); + const pairingRes = { + ...base, + Fr: base.fields.Fr, + Fp12: base.fields.Fp12, + calcPairingPrecomputes: base.utils.calcPairingPrecomputes, + randomSecretKey: base.utils.randomSecretKey, + }; + const longSignatures = createBlsSig(pairingRes, G1_Point, G2_Point, false, base.G2.hashToCurve, signatureCoders?.LongSignature); + const shortSignatures = createBlsSig(pairingRes, G2_Point, G1_Point, true, base.G1.hashToCurve, signatureCoders?.ShortSignature); + return Object.freeze({ ...base, longSignatures, shortSignatures }); +} +//# sourceMappingURL=bls.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/bls.js.map b/node_modules/@noble/curves/abstract/bls.js.map new file mode 100644 index 0000000..91b4fd8 --- /dev/null +++ b/node_modules/@noble/curves/abstract/bls.js.map @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,MAAM,CAAC,EAAE;QAClB,IAAI,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI;QACtB,sBAAsB,EAAE,IAAI,CAAC,KAAK,CAAC,sBAAsB;QACzD,eAAe,EAAE,IAAI,CAAC,KAAK,CAAC,eAAe;KAC5C,CAAC;IACF,MAAM,cAAc,GAAG,YAAY,CACjC,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,KAAK,EACL,IAAI,CAAC,EAAE,CAAC,WAAW,EACnB,eAAe,EAAE,aAAa,CAC/B,CAAC;IACF,MAAM,eAAe,GAAG,YAAY,CAClC,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,IAAI,EACJ,IAAI,CAAC,EAAE,CAAC,WAAW,EACnB,eAAe,EAAE,cAAc,CAChC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,GAAG,IAAI,EAAE,cAAc,EAAE,eAAe,EAAE,CAAC,CAAC;AACrE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.d.ts b/node_modules/@noble/curves/abstract/curve.d.ts new file mode 100644 index 0000000..8e98ccc --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.d.ts @@ -0,0 +1,442 @@ +/** + * Methods for elliptic curve multiplication by scalars. + * Contains wNAF, pippenger. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type Signer, type TArg, type TRet } from '../utils.ts'; +import { type IField } from './modular.ts'; +/** Affine point coordinates without projective fields. */ +export type AffinePoint = { + /** Affine x coordinate. */ + x: T; + /** Affine y coordinate. */ + y: T; +} & { + Z?: never; +}; +/** Base interface for all elliptic-curve point instances. */ +export interface CurvePoint> { + /** Affine x coordinate. Different from projective / extended X coordinate. */ + x: F; + /** Affine y coordinate. Different from projective / extended Y coordinate. */ + y: F; + /** Projective Z coordinate when the point keeps projective state. */ + Z?: F; + /** + * Double the point. + * @returns Doubled point. + */ + double(): P; + /** + * Negate the point. + * @returns Negated point. + */ + negate(): P; + /** + * Add another point from the same curve. + * @param other - Point to add. + * @returns Sum point. + */ + add(other: P): P; + /** + * Subtract another point from the same curve. + * @param other - Point to subtract. + * @returns Difference point. + */ + subtract(other: P): P; + /** + * Compare two points for equality. + * @param other - Point to compare. + * @returns Whether the points are equal. + */ + equals(other: P): boolean; + /** + * Multiply the point by a scalar in constant time. + * Implementations keep the subgroup-scalar contract strict and may reject + * `0` instead of returning the identity point. + * @param scalar - Scalar multiplier. + * @returns Product point. + */ + multiply(scalar: bigint): P; + /** Assert that the point satisfies the curve equation and subgroup checks. */ + assertValidity(): void; + /** + * Map the point into the prime-order subgroup when the curve requires it. + * @returns Prime-order point. + */ + clearCofactor(): P; + /** + * Check whether the point is the point at infinity. + * @returns Whether the point is zero. + */ + is0(): boolean; + /** + * Check whether the point belongs to the prime-order subgroup. + * @returns Whether the point is torsion-free. + */ + isTorsionFree(): boolean; + /** + * Check whether the point lies in a small torsion subgroup. + * @returns Whether the point has small order. + */ + isSmallOrder(): boolean; + /** + * Multiply the point by a scalar without constant-time guarantees. + * Public-scalar callers that need `0` should use this method instead of + * relying on `multiply(...)` to return the identity point. + * @param scalar - Scalar multiplier. + * @returns Product point. + */ + multiplyUnsafe(scalar: bigint): P; + /** + * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}. + * Cache state lives in internal WeakMaps keyed by point identity, not on the point object. + * Repeating `precompute(...)` for the same point identity replaces the remembered window size + * and forces table regeneration for that point. + * @param windowSize - Precompute window size. + * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()` + * @returns Same point instance with precompute tables attached. + */ + precompute(windowSize?: number, isLazy?: boolean): P; + /** + * Converts point to 2D xy affine coordinates. + * @param invertedZ - Optional inverted Z coordinate for batch normalization. + * @returns Affine x/y coordinates. + */ + toAffine(invertedZ?: F): AffinePoint; + /** + * Encode the point into the curve's canonical byte form. + * @returns Encoded point bytes. + */ + toBytes(): Uint8Array; + /** + * Encode the point into the curve's canonical hex form. + * @returns Encoded point hex. + */ + toHex(): string; +} +/** Base interface for elliptic-curve point constructors. */ +export interface CurvePointCons

> { + /** + * Runtime brand check for points created by this constructor. + * @param item - Value to test. + * @returns Whether the value is a point from this constructor. + */ + [Symbol.hasInstance]: (item: unknown) => boolean; + /** Canonical subgroup generator. */ + BASE: P; + /** Point at infinity. */ + ZERO: P; + /** Field for basic curve math */ + Fp: IField>; + /** Scalar field, for scalars in multiply and others */ + Fn: IField; + /** + * Create one point from affine coordinates. + * Does NOT validate curve, subgroup, or wrapper invariants. + * Use `.assertValidity()` on adversarial inputs. + * @param p - Affine point coordinates. + * @returns Point instance. + */ + fromAffine(p: AffinePoint>): P; + /** + * Decode a point from the canonical byte encoding. + * @param bytes - Encoded point bytes. + * Implementations MUST treat `bytes` as read-only. + * @returns Point instance. + */ + fromBytes(bytes: Uint8Array): P; + /** + * Decode a point from the canonical hex encoding. + * @param hex - Encoded point hex. + * @returns Point instance. + */ + fromHex(hex: string): P; +} +/** Returns the affine field type for a point instance (`P_F

== P.F`). */ +export type P_F

> = P extends CurvePoint ? F : never; +/** Returns the affine field type for a point constructor (`PC_F == PC.P.F`). */ +export type PC_F>> = PC['Fp']['ZERO']; +/** Returns the point instance type for a point constructor (`PC_P == PC.P`). */ +export type PC_P>> = PC['ZERO']; +/** Wide point-constructor type used when the concrete curve is not important. */ +export type PC_ANY = CurvePointCons>>>>>>>>>>; +/** + * Validates the static surface of a point constructor. + * This is only a cheap sanity check for the constructor hooks and fields consumed by generic + * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself. + * @param Point - Runtime point constructor. + * @throws On missing constructor hooks or malformed field metadata. {@link TypeError} + * @example + * Check that one point constructor exposes the static hooks generic helpers need. + * + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { validatePointCons } from '@noble/curves/abstract/curve.js'; + * validatePointCons(ed25519.Point); + * ``` + */ +export declare function validatePointCons

>(Point: CurvePointCons

): void; +/** Byte lengths used by one curve implementation. */ +export interface CurveLengths { + /** Secret-key length in bytes. */ + secretKey?: number; + /** Compressed public-key length in bytes. */ + publicKey?: number; + /** Uncompressed public-key length in bytes. */ + publicKeyUncompressed?: number; + /** Whether public-key encodings include a format prefix byte. */ + publicKeyHasPrefix?: boolean; + /** Signature length in bytes. */ + signature?: number; + /** Seed length in bytes when the curve exposes deterministic keygen from seed. */ + seed?: number; +} +/** Reorders or otherwise remaps a batch while preserving its element type. */ +export type Mapper = (i: T[]) => T[]; +/** + * Computes both candidates first, but the final selection still branches on `condition`, so this + * is not a strict constant-time CMOV primitive. + * @param condition - Whether to negate the point. + * @param item - Point-like value. + * @returns Original or negated value. + * @example + * Keep the point or return its negation based on one boolean branch. + * + * ```ts + * import { negateCt } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const maybeNegated = negateCt(true, p256.Point.BASE); + * ``` + */ +export declare function negateCt T; +}>(condition: boolean, item: T): T; +/** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + * Input points are left unchanged; the normalized points are returned as fresh instances. + * @param c - Point constructor. + * @param points - Projective points. + * @returns Fresh projective points reconstructed from normalized affine coordinates. + * @example + * Batch-normalize projective points with a single shared inversion. + * + * ```ts + * import { normalizeZ } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]); + * ``` + */ +export declare function normalizeZ

, PC extends CurvePointCons

>(c: PC, points: P[]): P[]; +/** + * Elliptic curve multiplication of Point by scalar. Fragile. + * Table generation takes **30MB of ram and 10ms on high-end CPU**, + * but may take much longer on slow devices. Actual generation will happen on + * first call of `multiply()`. By default, `BASE` point is precomputed. + * + * Scalars should always be less than curve order: this should be checked inside of a curve itself. + * Creates precomputation tables for fast multiplication: + * - private scalar is split by fixed size windows of W bits + * - every window point is collected from window's table & added to accumulator + * - since windows are different, same point inside tables won't be accessed more than once per calc + * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) + * - +1 window is neccessary for wNAF + * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication + * + * TODO: research returning a 2d JS array of windows instead of a single window. + * This would allow windows to be in different memory locations. + * @param Point - Point constructor. + * @param bits - Scalar bit length. + * @example + * Elliptic curve multiplication of Point by scalar. + * + * ```ts + * import { wNAF } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS); + * ``` + */ +export declare class wNAF { + private readonly BASE; + private readonly ZERO; + private readonly Fn; + readonly bits: number; + constructor(Point: PC, bits: number); + _unsafeLadder(elm: PC_P, n: bigint, p?: PC_P): PC_P; + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param point - Point instance + * @param W - window size + * @returns precomputed point tables flattened to a single array + */ + private precomputeWindow; + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * More compact implementation: + * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 + * @returns real and fake (for const-time) points + */ + private wNAF; + /** + * Implements unsafe EC multiplication using precomputed tables + * and w-ary non-adjacent form. + * @param acc - accumulator point to add result of multiplication + * @returns point + */ + private wNAFUnsafe; + private getPrecomputes; + cached(point: PC_P, scalar: bigint, transform?: Mapper>): { + p: PC_P; + f: PC_P; + }; + unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P; + createCache(P: PC_P, W: number): void; + hasCache(elm: PC_P): boolean; +} +/** + * Endomorphism-specific multiplication for Koblitz curves. + * Cost: 128 dbl, 0-256 adds. + * @param Point - Point constructor. + * @param point - Input point. + * @param k1 - First non-negative absolute scalar chunk. + * @param k2 - Second non-negative absolute scalar chunk. + * @returns Partial multiplication results. + * @example + * Endomorphism-specific multiplication for Koblitz curves. + * + * ```ts + * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js'; + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n); + * ``` + */ +export declare function mulEndoUnsafe

, PC extends CurvePointCons

>(Point: PC, point: P, k1: bigint, k2: bigint): { + p1: P; + p2: P; +}; +/** + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster than precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param scalars - array of L scalars (aka secret keys / bigints) + * @returns MSM result point. Empty input is accepted and returns the identity. + * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error} + * @example + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { pippenger } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]); + * ``` + */ +export declare function pippenger

, PC extends CurvePointCons

>(c: PC, points: P[], scalars: bigint[]): P; +/** + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param windowSize - Precompute window size. + * @returns Function which multiplies points with scalars. The closure accepts + * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero. + * @throws If the point set or precompute window is invalid. {@link Error} + * @example + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4); + * const point = msm([3n]); + * ``` + */ +export declare function precomputeMSMUnsafe

, PC extends CurvePointCons

>(c: PC, points: P[], windowSize: number): (scalars: bigint[]) => P; +/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */ +export type ValidCurveParams = { + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Cofactor. */ + h: bigint; + /** Curve parameter `a`. */ + a: T; + /** Weierstrass curve parameter `b`. */ + b?: T; + /** Edwards curve parameter `d`. */ + d?: T; + /** Generator x coordinate. */ + Gx: T; + /** Generator y coordinate. */ + Gy: T; +}; +/** Pair of fields used by curve constructors. */ +export type FpFn = { + /** Base field used for curve coordinates. */ + Fp: IField; + /** Scalar field used for secret scalars and subgroup arithmetic. */ + Fn: IField; +}; +/** + * Validates basic CURVE shape and field membership, then creates fields. + * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or + * that the curve equation itself is otherwise sane. + * @param type - Curve family. + * @param CURVE - Curve parameters. + * @param curveOpts - Optional field overrides: + * - `Fp` (optional): Optional base-field override. + * - `Fn` (optional): Optional scalar-field override. + * @param FpFnLE - Whether field encoding is little-endian. + * @returns Frozen curve parameters and fields. + * @throws If the curve parameters or field overrides are invalid. {@link Error} + * @example + * Build curve fields from raw constants before constructing a curve instance. + * + * ```ts + * const curve = createCurveFields('weierstrass', { + * p: 17n, + * n: 19n, + * h: 1n, + * a: 2n, + * b: 2n, + * Gx: 5n, + * Gy: 1n, + * }); + * ``` + */ +export declare function createCurveFields(type: 'weierstrass' | 'edwards', CURVE: ValidCurveParams, curveOpts?: TArg>>, FpFnLE?: boolean): TRet & { + CURVE: ValidCurveParams; +}>; +type KeygenFn = (seed?: Uint8Array, isCompressed?: boolean) => { + secretKey: Uint8Array; + publicKey: Uint8Array; +}; +/** + * @param randomSecretKey - Secret-key generator. + * @param getPublicKey - Public-key derivation helper. + * @returns Keypair generator. + * @example + * Build a `keygen()` helper from existing secret-key and public-key primitives. + * + * ```ts + * import { createKeygen } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey); + * const pair = keygen(); + * ``` + */ +export declare function createKeygen(randomSecretKey: Function, getPublicKey: TArg): TRet; +export {}; +//# sourceMappingURL=curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.d.ts.map b/node_modules/@noble/curves/abstract/curve.d.ts.map new file mode 100644 index 0000000..78f2910 --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.d.ts","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,sEAAsE;AACtE,OAAO,EAAmC,KAAK,MAAM,EAAE,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AACjG,OAAO,EAAuC,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAKhF,0DAA0D;AAC1D,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAC3B,2BAA2B;IAC3B,CAAC,EAAE,CAAC,CAAC;IACL,2BAA2B;IAC3B,CAAC,EAAE,CAAC,CAAC;CACN,GAAG;IAAE,CAAC,CAAC,EAAE,KAAK,CAAA;CAAE,CAAC;AAUlB,6DAA6D;AAC7D,MAAM,WAAW,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,CAAC,CAAC;IACvD,8EAA8E;IAC9E,CAAC,EAAE,CAAC,CAAC;IACL,8EAA8E;IAC9E,CAAC,EAAE,CAAC,CAAC;IACL,qEAAqE;IACrE,CAAC,CAAC,EAAE,CAAC,CAAC;IACN;;;OAGG;IACH,MAAM,IAAI,CAAC,CAAC;IACZ;;;OAG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AE,MAAM,CAAC,MAAM,CAAC,CAAC;CACpB,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,EACjC,IAAI,EAAE,aAAa,GAAG,SAAS,EAC/B,KAAK,EAAE,gBAAgB,CAAC,CAAC,CAAC,EAC1B,SAAS,GAAE,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAM,EACtC,MAAM,CAAC,EAAE,OAAO,GACf,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG;IAAE,KAAK,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAA;CAAE,CAAC,CAmBhD;AAED,KAAK,QAAQ,GAAG,CACd,IAAI,CAAC,EAAE,UAAU,EACjB,YAAY,CAAC,EAAE,OAAO,KACnB;IAAE,SAAS,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,UAAU,CAAA;CAAE,CAAC;AACtD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,YAAY,CAC1B,eAAe,EAAE,QAAQ,EACzB,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC,GACzC,IAAI,CAAC,QAAQ,CAAC,CAKhB"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.js b/node_modules/@noble/curves/abstract/curve.js new file mode 100644 index 0000000..6808517 --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.js @@ -0,0 +1,611 @@ +/** + * Methods for elliptic curve multiplication by scalars. + * Contains wNAF, pippenger. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { bitLen, bitMask, validateObject } from "../utils.js"; +import { Field, FpInvertBatch, validateField } from "./modular.js"; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +/** + * Validates the static surface of a point constructor. + * This is only a cheap sanity check for the constructor hooks and fields consumed by generic + * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself. + * @param Point - Runtime point constructor. + * @throws On missing constructor hooks or malformed field metadata. {@link TypeError} + * @example + * Check that one point constructor exposes the static hooks generic helpers need. + * + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { validatePointCons } from '@noble/curves/abstract/curve.js'; + * validatePointCons(ed25519.Point); + * ``` + */ +export function validatePointCons(Point) { + const pc = Point; + if (typeof pc !== 'function') + throw new TypeError('Point must be a constructor'); + // validateObject only accepts plain objects, so copy the constructor statics into one bag first. + validateObject({ + Fp: pc.Fp, + Fn: pc.Fn, + fromAffine: pc.fromAffine, + fromBytes: pc.fromBytes, + fromHex: pc.fromHex, + }, { + Fp: 'object', + Fn: 'object', + fromAffine: 'function', + fromBytes: 'function', + fromHex: 'function', + }); + validateField(pc.Fp); + validateField(pc.Fn); +} +/** + * Computes both candidates first, but the final selection still branches on `condition`, so this + * is not a strict constant-time CMOV primitive. + * @param condition - Whether to negate the point. + * @param item - Point-like value. + * @returns Original or negated value. + * @example + * Keep the point or return its negation based on one boolean branch. + * + * ```ts + * import { negateCt } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const maybeNegated = negateCt(true, p256.Point.BASE); + * ``` + */ +export function negateCt(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +/** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + * Input points are left unchanged; the normalized points are returned as fresh instances. + * @param c - Point constructor. + * @param points - Projective points. + * @returns Fresh projective points reconstructed from normalized affine coordinates. + * @example + * Batch-normalize projective points with a single shared inversion. + * + * ```ts + * import { normalizeZ } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]); + * ``` + */ +export function normalizeZ(c, points) { + const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z)); + return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); +} +function validateW(W, bits) { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W); +} +function calcWOpts(W, scalarBits) { + validateW(W, scalarBits); + const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero + const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero + const maxNumber = 2 ** W; // W=8 256 + const mask = bitMask(W); // W=8 255 == mask 0b11111111 + const shiftBy = BigInt(W); // W=8 8 + return { windows, windowSize, mask, maxNumber, shiftBy }; +} +function calcOffsets(n, window, wOpts) { + const { windowSize, mask, maxNumber, shiftBy } = wOpts; + let wbits = Number(n & mask); // extract W bits. + let nextN = n >> shiftBy; // shift number by W bits. + // What actually happens here: + // const highestBit = Number(mask ^ (mask >> 1n)); + // let wbits2 = wbits - 1; // skip zero + // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~); + // split if bits > max: +224 => 256-32 + if (wbits > windowSize) { + // we skip zero, which means instead of `>= size-1`, we do `> size` + wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here. + nextN += _1n; // +256 (carry) + } + const offsetStart = window * windowSize; + const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero + const isZero = wbits === 0; // is current window slice a 0? + const isNeg = wbits < 0; // is current window slice negative? + const isNegF = window % 2 !== 0; // fake branch noise only + const offsetF = offsetStart; // fake branch noise only + return { nextN, offset, isZero, isNeg, isNegF, offsetF }; +} +function validateMSMPoints(points, c) { + if (!Array.isArray(points)) + throw new Error('array expected'); + points.forEach((p, i) => { + if (!(p instanceof c)) + throw new Error('invalid point at index ' + i); + }); +} +function validateMSMScalars(scalars, field) { + if (!Array.isArray(scalars)) + throw new Error('array of scalars expected'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) + throw new Error('invalid scalar at index ' + i); + }); +} +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes. +// Allows to make points frozen / immutable. +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); +function getW(P) { + // To disable precomputes: + // return 1; + // `1` is also the uncached sentinel: use the ladder / non-precomputed path. + return pointWindowSizes.get(P) || 1; +} +function assert0(n) { + // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop + // count is inconsistent, not that the original caller provided a bad scalar. + if (n !== _0n) + throw new Error('invalid wNAF'); +} +/** + * Elliptic curve multiplication of Point by scalar. Fragile. + * Table generation takes **30MB of ram and 10ms on high-end CPU**, + * but may take much longer on slow devices. Actual generation will happen on + * first call of `multiply()`. By default, `BASE` point is precomputed. + * + * Scalars should always be less than curve order: this should be checked inside of a curve itself. + * Creates precomputation tables for fast multiplication: + * - private scalar is split by fixed size windows of W bits + * - every window point is collected from window's table & added to accumulator + * - since windows are different, same point inside tables won't be accessed more than once per calc + * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) + * - +1 window is neccessary for wNAF + * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication + * + * TODO: research returning a 2d JS array of windows instead of a single window. + * This would allow windows to be in different memory locations. + * @param Point - Point constructor. + * @param bits - Scalar bit length. + * @example + * Elliptic curve multiplication of Point by scalar. + * + * ```ts + * import { wNAF } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS); + * ``` + */ +export class wNAF { + BASE; + ZERO; + Fn; + bits; + // Parametrized with a given Point class (not individual point) + constructor(Point, bits) { + this.BASE = Point.BASE; + this.ZERO = Point.ZERO; + this.Fn = Point.Fn; + this.bits = bits; + } + // non-const time multiplication ladder + _unsafeLadder(elm, n, p = this.ZERO) { + let d = elm; + while (n > _0n) { + if (n & _1n) + p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + } + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param point - Point instance + * @param W - window size + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(point, W) { + const { windows, windowSize } = calcWOpts(W, this.bits); + const points = []; + let p = point; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // i=1, bc we skip 0 + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * More compact implementation: + * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + // Scalar should be smaller than field order + if (!this.Fn.isValid(n)) + throw new Error('invalid scalar'); + // Accumulators + let p = this.ZERO; + let f = this.BASE; + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise + const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + // bits are 0: add garbage to fake point + // Important part for const-time getPublicKey: add random "noise" point to f. + f = f.add(negateCt(isNegF, precomputes[offsetF])); + } + else { + // bits are 1: add to result point + p = p.add(negateCt(isNeg, precomputes[offset])); + } + } + assert0(n); + // Return both real and fake points so JIT keeps the noise path alive. + // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not, + // which weakens the noise path and leaves this only "less const-time" by about one bigint mul. + return { p, f }; + } + /** + * Implements unsafe EC multiplication using precomputed tables + * and w-ary non-adjacent form. + * @param acc - accumulator point to add result of multiplication + * @returns point + */ + wNAFUnsafe(W, precomputes, n, acc = this.ZERO) { + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + if (n === _0n) + break; // Early-exit, skip 0 value + const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + // Window bits are 0: skip processing. + // Move to next window. + continue; + } + else { + const item = precomputes[offset]; + acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM + } + } + assert0(n); + return acc; + } + getPrecomputes(W, point, transform) { + // Cache key is only point identity plus the remembered window size; callers must not reuse the + // same point with incompatible `transform(...)` layouts and expect a separate cache entry. + let comp = pointPrecomputes.get(point); + if (!comp) { + comp = this.precomputeWindow(point, W); + if (W !== 1) { + // Doing transform outside of if brings 15% perf hit + if (typeof transform === 'function') + comp = transform(comp); + pointPrecomputes.set(point, comp); + } + } + return comp; + } + cached(point, scalar, transform) { + const W = getW(point); + return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar); + } + unsafe(point, scalar, transform, prev) { + const W = getW(point); + if (W === 1) + return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster + return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev); + } + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + createCache(P, W) { + validateW(W, this.bits); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + } + hasCache(elm) { + return getW(elm) !== 1; + } +} +/** + * Endomorphism-specific multiplication for Koblitz curves. + * Cost: 128 dbl, 0-256 adds. + * @param Point - Point constructor. + * @param point - Input point. + * @param k1 - First non-negative absolute scalar chunk. + * @param k2 - Second non-negative absolute scalar chunk. + * @returns Partial multiplication results. + * @example + * Endomorphism-specific multiplication for Koblitz curves. + * + * ```ts + * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js'; + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n); + * ``` + */ +export function mulEndoUnsafe(Point, point, k1, k2) { + let acc = point; + let p1 = Point.ZERO; + let p2 = Point.ZERO; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) + p1 = p1.add(acc); + if (k2 & _1n) + p2 = p2.add(acc); + acc = acc.double(); + k1 >>= _1n; + k2 >>= _1n; + } + return { p1, p2 }; +} +/** + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster than precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param scalars - array of L scalars (aka secret keys / bigints) + * @returns MSM result point. Empty input is accepted and returns the identity. + * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error} + * @example + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { pippenger } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]); + * ``` + */ +export function pippenger(c, points, scalars) { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + const fieldN = c.Fn; + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + const plength = points.length; + const slength = scalars.length; + if (plength !== slength) + throw new Error('arrays of points and scalars must have equal length'); + // if (plength === 0) throw new Error('array must be of length >= 2'); + const zero = c.ZERO; + const wbits = bitLen(BigInt(plength)); + let windowSize = 1; // bits + if (wbits > 12) + windowSize = wbits - 3; + else if (wbits > 4) + windowSize = wbits - 2; + else if (wbits > 0) + windowSize = 2; + const MASK = bitMask(windowSize); + const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j = 0; j < slength; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & MASK); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = zero; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) + for (let j = 0; j < windowSize; j++) + sum = sum.double(); + } + return sum; +} +/** + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param windowSize - Precompute window size. + * @returns Function which multiplies points with scalars. The closure accepts + * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero. + * @throws If the point set or precompute window is invalid. {@link Error} + * @example + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4); + * const point = msm([3n]); + * ``` + */ +export function precomputeMSMUnsafe(c, points, windowSize) { + /** + * Performance Analysis of Window-based Precomputation + * + * Base Case (256-bit scalar, 8-bit window): + * - Standard precomputation requires: + * - 31 additions per scalar × 256 scalars = 7,936 ops + * - Plus 255 summary additions = 8,191 total ops + * Note: Summary additions can be optimized via accumulator + * + * Chunked Precomputation Analysis: + * - Using 32 chunks requires: + * - 255 additions per chunk + * - 256 doublings + * - Total: (255 × 32) + 256 = 8,416 ops + * + * Memory Usage Comparison: + * Window Size | Standard Points | Chunked Points + * ------------|-----------------|--------------- + * 4-bit | 520 | 15 + * 8-bit | 4,224 | 255 + * 10-bit | 13,824 | 1,023 + * 16-bit | 557,056 | 65,535 + * + * Key Advantages: + * 1. Enables larger window sizes due to reduced memory overhead + * 2. More efficient for smaller scalar counts: + * - 16 chunks: (16 × 255) + 256 = 4,336 ops + * - ~2x faster than standard 8,191 ops + * + * Limitations: + * - Not suitable for plain precomputes (requires 256 constant doublings) + * - Performance degrades with larger scalar counts: + * - Optimal for ~256 scalars + * - Less efficient for 4096+ scalars (Pippenger preferred) + */ + const fieldN = c.Fn; + validateW(windowSize, fieldN.BITS); + validateMSMPoints(points, c); + const zero = c.ZERO; + const tableSize = 2 ** windowSize - 1; // table size (without zero) + const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item + const MASK = bitMask(windowSize); + const tables = points.map((p) => { + const res = []; + for (let i = 0, acc = p; i < tableSize; i++) { + res.push(acc); + acc = acc.add(p); + } + return res; + }); + return (scalars) => { + validateMSMScalars(scalars, fieldN); + if (scalars.length > points.length) + throw new Error('array of scalars must be smaller than array of points'); + let res = zero; + for (let i = 0; i < chunks; i++) { + // No need to double if accumulator is still zero. + if (res !== zero) + for (let j = 0; j < windowSize; j++) + res = res.double(); + const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize); + for (let j = 0; j < scalars.length; j++) { + const n = scalars[j]; + const curr = Number((n >> shiftBy) & MASK); + if (!curr) + continue; // skip zero scalars chunks + res = res.add(tables[j][curr - 1]); + } + } + return res; + }; +} +function createField(order, field, isLE) { + if (field) { + // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback + // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov + // behavior. + if (field.ORDER !== order) + throw new Error('Field.ORDER must match order: Fp == p, Fn == n'); + validateField(field); + return field; + } + else { + return Field(order, { isLE }); + } +} +/** + * Validates basic CURVE shape and field membership, then creates fields. + * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or + * that the curve equation itself is otherwise sane. + * @param type - Curve family. + * @param CURVE - Curve parameters. + * @param curveOpts - Optional field overrides: + * - `Fp` (optional): Optional base-field override. + * - `Fn` (optional): Optional scalar-field override. + * @param FpFnLE - Whether field encoding is little-endian. + * @returns Frozen curve parameters and fields. + * @throws If the curve parameters or field overrides are invalid. {@link Error} + * @example + * Build curve fields from raw constants before constructing a curve instance. + * + * ```ts + * const curve = createCurveFields('weierstrass', { + * p: 17n, + * n: 19n, + * h: 1n, + * a: 2n, + * b: 2n, + * Gx: 5n, + * Gy: 1n, + * }); + * ``` + */ +export function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) { + if (FpFnLE === undefined) + FpFnLE = type === 'edwards'; + if (!CURVE || typeof CURVE !== 'object') + throw new Error(`expected valid ${type} CURVE object`); + for (const p of ['p', 'n', 'h']) { + const val = CURVE[p]; + if (!(typeof val === 'bigint' && val > _0n)) + throw new Error(`CURVE.${p} must be positive bigint`); + } + const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); + const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE); + const _b = type === 'weierstrass' ? 'b' : 'd'; + const params = ['Gx', 'Gy', 'a', _b]; + for (const p of params) { + // @ts-ignore + if (!Fp.isValid(CURVE[p])) + throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); + } + CURVE = Object.freeze(Object.assign({}, CURVE)); + return { CURVE, Fp, Fn }; +} +/** + * @param randomSecretKey - Secret-key generator. + * @param getPublicKey - Public-key derivation helper. + * @returns Keypair generator. + * @example + * Build a `keygen()` helper from existing secret-key and public-key primitives. + * + * ```ts + * import { createKeygen } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey); + * const pair = keygen(); + * ``` + */ +export function createKeygen(randomSecretKey, getPublicKey) { + return function keygen(seed) { + const secretKey = randomSecretKey(seed); + return { secretKey, publicKey: getPublicKey(secretKey) }; + }; +} +//# sourceMappingURL=curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/curve.js.map b/node_modules/@noble/curves/abstract/curve.js.map new file mode 100644 index 0000000..a60e315 --- /dev/null +++ b/node_modules/@noble/curves/abstract/curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"curve.js","sourceRoot":"","sources":["../src/abstract/curve.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,EAAqC,MAAM,aAAa,CAAC;AACjG,OAAO,EAAE,KAAK,EAAE,aAAa,EAAE,aAAa,EAAe,MAAM,cAAc,CAAC;AAEhF,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AA8MtC;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,iBAAiB,CAA+B,KAAwB;IACtF,MAAM,EAAE,GAAG,KAAuC,CAAC;IACnD,IAAI,OAAQ,EAAc,KAAK,UAAU;QAAE,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAC;IAC9F,iGAAiG;IACjG,cAAc,CACZ;QACE,EAAE,EAAE,EAAE,CAAC,EAAE;QACT,EAAE,EAAE,EAAE,CAAC,EAAE;QACT,UAAU,EAAE,EAAE,CAAC,UAAU;QACzB,SAAS,EAAE,EAAE,CAAC,SAAS;QACvB,OAAO,EAAE,EAAE,CAAC,OAAO;KACpB,EACD;QACE,EAAE,EAAE,QAAQ;QACZ,EAAE,EAAE,QAAQ;QACZ,UAAU,EAAE,UAAU;QACtB,SAAS,EAAE,UAAU;QACrB,OAAO,EAAE,UAAU;KACpB,CACF,CAAC;IACF,aAAa,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;IACrB,aAAa,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;AACvB,CAAC;AAqBD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAA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wards.d.ts b/node_modules/@noble/curves/abstract/edwards.d.ts new file mode 100644 index 0000000..ccfe3d4 --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.d.ts @@ -0,0 +1,320 @@ +/** + * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y². + * For design rationale of types / exports, see weierstrass module documentation. + * Untwisted Edwards curves exist, but they aren't used in real-world protocols. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type FHash, type TArg, type TRet } from '../utils.ts'; +import { type AffinePoint, type CurveLengths, type CurvePoint, type CurvePointCons } from './curve.ts'; +import { type IField } from './modular.ts'; +/** Extended Edwards point with X/Y/Z/T coordinates. */ +export interface EdwardsPoint extends CurvePoint { + /** extended X coordinate. Different from affine x. */ + readonly X: bigint; + /** extended Y coordinate. Different from affine y. */ + readonly Y: bigint; + /** extended Z coordinate */ + readonly Z: bigint; + /** extended T coordinate */ + readonly T: bigint; +} +/** Constructor and decoding helpers for extended Edwards points. */ +export interface EdwardsPointCons extends CurvePointCons { + /** Create a point from extended X/Y/Z/T coordinates without validation. */ + new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint; + /** + * Return the curve parameters used by this point constructor. + * @returns Curve parameters. + */ + CURVE(): EdwardsOpts; + /** + * Decode a point from bytes, optionally using ZIP-215 rules. + * @param bytes - Encoded point bytes. + * @param zip215 - Whether to accept ZIP-215 encodings. + * @returns Decoded Edwards point. + */ + fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint; + /** + * Decode a point from hex, optionally using ZIP-215 rules. + * @param hex - Encoded point hex. + * @param zip215 - Whether to accept ZIP-215 encodings. + * @returns Decoded Edwards point. + */ + fromHex(hex: string, zip215?: boolean): EdwardsPoint; +} +/** + * Twisted Edwards curve options. + * + * * a: formula param + * * d: formula param + * * p: prime characteristic (order) of finite field, in which arithmetics is done + * * n: order of prime subgroup a.k.a total amount of valid curve points + * * h: cofactor. h*n is group order; n is subgroup order + * * Gx: x coordinate of generator point a.k.a. base point + * * Gy: y coordinate of generator point + */ +export type EdwardsOpts = Readonly<{ + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Curve cofactor. */ + h: bigint; + /** Edwards curve parameter `a`. */ + a: bigint; + /** Edwards curve parameter `d`. */ + d: bigint; + /** Generator x coordinate. */ + Gx: bigint; + /** Generator y coordinate. */ + Gy: bigint; +}>; +/** + * Extra curve options for Twisted Edwards. + * + * * Fp: redefined Field over curve.p + * * Fn: redefined Field over curve.n + * * uvRatio: helper function for decompression, calculating √(u/v) + */ +export type EdwardsExtraOpts = Partial<{ + /** Optional base-field override. */ + Fp: IField; + /** Optional scalar-field override. */ + Fn: IField; + /** Whether field encodings are little-endian. */ + FpFnLE: boolean; + /** Square-root ratio helper used during point decompression. */ + uvRatio: (u: bigint, v: bigint) => { + isValid: boolean; + value: bigint; + }; +}>; +/** + * EdDSA (Edwards Digital Signature algorithm) options. + * + * * hash: hash function used to hash secret keys and messages + * * adjustScalarBytes: clears bits to get valid field element + * * domain: Used for hashing + * * mapToCurve: for hash-to-curve standard + * * prehash: RFC 8032 pre-hashing of messages to sign() / verify() + * * randomBytes: function generating random bytes, used for randomSecretKey + */ +export type EdDSAOpts = Partial<{ + /** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */ + adjustScalarBytes: (bytes: TArg) => TRet; + /** Domain-separation helper for contexts and prehash mode. */ + domain: (data: TArg, ctx: TArg, phflag: boolean) => TRet; + /** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */ + mapToCurve: (scalar: bigint[]) => AffinePoint; + /** Optional prehash function used before signing or verifying messages. */ + prehash: FHash; + /** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */ + zip215: boolean; + /** RNG override used by helper constructors. */ + randomBytes: (bytesLength?: number) => TRet; +}>; +/** + * EdDSA (Edwards Digital Signature algorithm) helper namespace. + * Allows creating and verifying signatures, and deriving public keys. + */ +export interface EdDSA { + /** + * Generate a secret/public key pair. + * @param seed - Optional seed material. + * @returns Secret/public key pair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Encoded public key. + */ + getPublicKey: (secretKey: TArg) => TRet; + /** + * Sign a message with an EdDSA secret key. + * @param message - Message bytes. + * @param secretKey - Secret key bytes. + * @param options - Optional signature tweaks: + * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448. + * @returns Encoded signature bytes. + */ + sign: (message: TArg, secretKey: TArg, options?: TArg<{ + context?: Uint8Array; + }>) => TRet; + /** + * Verify a signature against a message and public key. + * @param sig - Encoded signature bytes. + * @param message - Message bytes. + * @param publicKey - Encoded public key. + * @param options - Optional verification tweaks: + * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448. + * - `zip215` (optional): Whether to accept ZIP-215 encodings. + * @returns Whether the signature is valid. + */ + verify: (sig: TArg, message: TArg, publicKey: TArg, options?: TArg<{ + context?: Uint8Array; + zip215?: boolean; + }>) => boolean; + /** Point constructor used by this signature scheme. */ + Point: EdwardsPointCons; + /** Helper utilities for key validation and Montgomery conversion. */ + utils: { + /** + * Generate a valid random secret key. + * Optional seed bytes are only length-checked and returned unchanged. + */ + randomSecretKey: (seed?: TArg) => TRet; + /** Check whether a secret key has the expected encoding. */ + isValidSecretKey: (secretKey: TArg) => boolean; + /** Check whether a public key decodes to a valid point. */ + isValidPublicKey: (publicKey: TArg, zip215?: boolean) => boolean; + /** + * Converts ed public key to x public key. + * + * There is NO `fromMontgomery`: + * - There are 2 valid ed25519 points for every x25519, with flipped coordinate + * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally* + * accepts inputs on the quadratic twist, which can't be moved to ed25519 + * + * @example + * Converts ed public key to x public key. + * + * ```js + * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey()); + * const someonesPub = ed25519.utils.toMontgomery(someonesPub); + * const aPriv = x25519.utils.randomSecretKey(); + * const shared = x25519.getSharedSecret(aPriv, someonesPub) + * ``` + */ + toMontgomery: (publicKey: TArg) => TRet; + /** + * Converts ed secret key to x secret key. + * @example + * Converts ed secret key to x secret key. + * + * ```js + * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey()); + * const aPriv_ed = ed25519.utils.randomSecretKey(); + * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed); + * const shared = x25519.getSharedSecret(aPriv, someonesPub) + * ``` + */ + toMontgomerySecret: (secretKey: TArg) => TRet; + /** Return the expanded private key components used by RFC8032 signing. */ + getExtendedPublicKey: (key: TArg) => { + head: TRet; + prefix: TRet; + scalar: bigint; + point: EdwardsPoint; + pointBytes: TRet; + }; + }; + /** Byte lengths for keys and signatures exposed by this scheme. */ + lengths: CurveLengths; +} +/** + * @param params - Curve parameters. See {@link EdwardsOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}. + * @returns Edwards point constructor. Generator validation here only checks + * that `(Gx, Gy)` satisfies the affine Edwards equation. + * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0` + * are left to the caller's chosen parameters, since eager subgroup + * validation here adds about 10-15ms to heavyweight imports like ed448. + * The returned constructor also eagerly marks `Point.BASE` for W=8 + * precompute caching. Some code paths still assume + * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here. + * @throws If the curve parameters or Edwards overrides are invalid. {@link Error} + * @example + * ```ts + * import { edwards } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * // Build a point constructor from explicit curve parameters, then use its base point. + * const Point = edwards(jubjub.Point.CURVE()); + * Point.BASE.toHex(); + * ``` + */ +export declare function edwards(params: TArg, extraOpts?: TArg): EdwardsPointCons; +/** + * Base class for prime-order points like Ristretto255 and Decaf448. + * These points eliminate cofactor issues by representing equivalence classes + * of Edwards curve points. Multiple Edwards representatives can describe the + * same abstract wrapper element, so wrapper validity is not the same thing as + * the hidden representative being torsion-free. + * @param ep - Backing Edwards point. + * @example + * Base class for prime-order points like Ristretto255 and Decaf448. + * + * ```ts + * import { ristretto255 } from '@noble/curves/ed25519.js'; + * const point = ristretto255.Point.BASE.multiply(2n); + * ``` + */ +export declare abstract class PrimeEdwardsPoint> implements CurvePoint { + static BASE: PrimeEdwardsPoint; + static ZERO: PrimeEdwardsPoint; + static Fp: IField; + static Fn: IField; + protected readonly ep: EdwardsPoint; + /** + * Wrap one internal Edwards representative directly. + * This is not a canonical encoding boundary: alternate Edwards + * representatives may still describe the same abstract wrapper element. + */ + constructor(ep: EdwardsPoint); + abstract toBytes(): Uint8Array; + abstract equals(other: T): boolean; + static fromBytes(_bytes: Uint8Array): any; + static fromHex(_hex: string): any; + get x(): bigint; + get y(): bigint; + clearCofactor(): T; + assertValidity(): void; + /** + * Return affine coordinates of the current internal Edwards representative. + * This is a convenience helper, not a canonical Ristretto/Decaf encoding. + * Equal abstract elements may expose different `x` / `y`; use + * `toBytes()` / `fromBytes()` for canonical roundtrips. + */ + toAffine(invertedZ?: bigint): AffinePoint; + toHex(): string; + toString(): string; + isTorsionFree(): boolean; + isSmallOrder(): boolean; + add(other: T): T; + subtract(other: T): T; + multiply(scalar: bigint): T; + multiplyUnsafe(scalar: bigint): T; + double(): T; + negate(): T; + precompute(windowSize?: number, isLazy?: boolean): T; + abstract is0(): boolean; + protected abstract assertSame(other: T): void; + protected abstract init(ep: EdwardsPoint): T; +} +/** + * Initializes EdDSA signatures over given Edwards curve. + * @param Point - Edwards point constructor. + * @param cHash - Hash function. + * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}. + * @returns EdDSA helper namespace. + * @throws If the hash function, options, or derived point operations are invalid. {@link Error} + * @example + * Initializes EdDSA signatures over given Edwards curve. + * + * ```ts + * import { eddsa } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * import { sha512 } from '@noble/hashes/sha2.js'; + * const sigs = eddsa(jubjub.Point, sha512); + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export declare function eddsa(Point: EdwardsPointCons, cHash: TArg, eddsaOpts?: TArg): EdDSA; +//# sourceMappingURL=edwards.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.d.ts.map b/node_modules/@noble/curves/abstract/edwards.d.ts.map new file mode 100644 index 0000000..6393e1f --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.d.ts","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EAcL,KAAK,KAAK,EAEV,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAM3C,uDAAuD;AACvD,MAAM,WAAW,YAAa,SAAQ,UAAU,CAAC,MAAM,EAAE,YAAY,CAAC;IACpE,sDAAsD;IACtD,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,sDAAsD;IACtD,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,4BAA4B;IAC5B,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;IACnB,4BAA4B;IAC5B,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;CACpB;AACD,oEAAoE;AACpE,MAAM,WAAW,gBAAiB,SAAQ,cAAc,CAAC,YAAY,CAAC;IACpE,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,YAAY,CAAC;IAC/D;;;O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M,EAAE,MAAM,GAAG,CAAC;IAI3B,cAAc,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC;IAIjC,MAAM,IAAI,CAAC;IAIX,MAAM,IAAI,CAAC;IAIX,UAAU,CAAC,UAAU,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,CAAC;IAQpD,QAAQ,CAAC,GAAG,IAAI,OAAO;IACvB,SAAS,CAAC,QAAQ,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC,GAAG,IAAI;IAC7C,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,YAAY,GAAG,CAAC;CAC7C;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,KAAK,CACnB,KAAK,EAAE,gBAAgB,EACvB,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,EAClB,SAAS,GAAE,IAAI,CAAC,SAAS,CAAM,GAC9B,KAAK,CAuOP"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.js b/node_modules/@noble/curves/abstract/edwards.js new file mode 100644 index 0000000..ee5cefc --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.js @@ -0,0 +1,693 @@ +/** + * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y². + * For design rationale of types / exports, see weierstrass module documentation. + * Untwisted Edwards curves exist, but they aren't used in real-world protocols. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abool, abytes, aInRange, asafenumber, bytesToHex, bytesToNumberLE, concatBytes, copyBytes, hexToBytes, isBytes, notImplemented, validateObject, randomBytes as wcRandomBytes, } from "../utils.js"; +import { createCurveFields, createKeygen, normalizeZ, wNAF, } from "./curve.js"; +import {} from "./modular.js"; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8); +// Affine Edwards-equation check only; this does not prove subgroup membership, canonical +// encoding, prime-order base-point requirements, or identity exclusion. +function isEdValidXY(Fp, CURVE, x, y) { + const x2 = Fp.sqr(x); + const y2 = Fp.sqr(y); + const left = Fp.add(Fp.mul(CURVE.a, x2), y2); + const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2))); + return Fp.eql(left, right); +} +/** + * @param params - Curve parameters. See {@link EdwardsOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}. + * @returns Edwards point constructor. Generator validation here only checks + * that `(Gx, Gy)` satisfies the affine Edwards equation. + * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0` + * are left to the caller's chosen parameters, since eager subgroup + * validation here adds about 10-15ms to heavyweight imports like ed448. + * The returned constructor also eagerly marks `Point.BASE` for W=8 + * precompute caching. Some code paths still assume + * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here. + * @throws If the curve parameters or Edwards overrides are invalid. {@link Error} + * @example + * ```ts + * import { edwards } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * // Build a point constructor from explicit curve parameters, then use its base point. + * const Point = edwards(jubjub.Point.CURVE()); + * Point.BASE.toHex(); + * ``` + */ +export function edwards(params, extraOpts = {}) { + const opts = extraOpts; + const validated = createCurveFields('edwards', params, opts, opts.FpFnLE); + const { Fp, Fn } = validated; + let CURVE = validated.CURVE; + const { h: cofactor } = CURVE; + validateObject(opts, {}, { uvRatio: 'function' }); + // Important: + // There are some places where Fp.BYTES is used instead of nByteLength. + // So far, everything has been tested with curves of Fp.BYTES == nByteLength. + // TODO: test and find curves which behave otherwise. + const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n); + const modP = (n) => Fp.create(n); // Function overrides + // sqrt(u/v) + const uvRatio = opts.uvRatio === undefined + ? (u, v) => { + try { + return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) }; + } + catch (e) { + return { isValid: false, value: _0n }; + } + } + : opts.uvRatio; + // Validate whether the passed curve params are valid. + // equation ax² + y² = 1 + dx²y² should work for generator point. + if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) + throw new Error('bad curve params: generator point'); + /** + * Asserts coordinate is valid: 0 <= n < MASK. + * Coordinates >= Fp.ORDER are allowed for zip215. + */ + function acoord(title, n, banZero = false) { + const min = banZero ? _1n : _0n; + aInRange('coordinate ' + title, n, min, MASK); + return n; + } + function aedpoint(other) { + if (!(other instanceof Point)) + throw new Error('EdwardsPoint expected'); + } + // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point { + // base / generator point + static BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + // zero / infinity / identity point + static ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + // math field + static Fp = Fp; + // scalar field + static Fn = Fn; + X; + Y; + Z; + T; + constructor(X, Y, Z, T) { + this.X = acoord('x', X); + this.Y = acoord('y', Y); + this.Z = acoord('z', Z, true); + this.T = acoord('t', T); + Object.freeze(this); + } + static CURVE() { + return CURVE; + } + /** + * Create one extended Edwards point from affine coordinates. + * Does NOT validate that the point is on-curve or torsion-free. + * Use `.assertValidity()` on adversarial inputs. + */ + static fromAffine(p) { + if (p instanceof Point) + throw new Error('extended point not allowed'); + const { x, y } = p || {}; + acoord('x', x); + acoord('y', y); + return new Point(x, y, _1n, modP(x * y)); + } + // Uses algo from RFC8032 5.1.3. + static fromBytes(bytes, zip215 = false) { + const len = Fp.BYTES; + const { a, d } = CURVE; + bytes = copyBytes(abytes(bytes, len, 'point')); + abool(zip215, 'zip215'); + const normed = copyBytes(bytes); // copy again, we'll manipulate it + const lastByte = bytes[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5. + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('point.y', y, _0n, max); + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) + throw new Error('bad point: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('bad point: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) + x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + static fromHex(hex, zip215 = false) { + return Point.fromBytes(hexToBytes(hex), zip215); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + precompute(windowSize = 8, isLazy = true) { + wnaf.createCache(this, windowSize); + if (!isLazy) + this.multiply(_2n); // random number + return this; + } + // Useful in fromAffine() - not for fromBytes(), which always created valid points. + assertValidity() { + const p = this; + const { a, d } = CURVE; + // Keep generic Edwards validation fail-closed on the neutral point. + // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level + // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids + // silently treating that degenerate state as an ordinary public point. + if (p.is0()) + throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { X, Y, Z, T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) + throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) + throw new Error('bad point: equation left != right (2)'); + } + // Compare one point to another. + equals(other) { + aedpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + is0() { + return this.equals(Point.ZERO); + } + negate() { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T)); + } + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double() { + const { a } = CURVE; + const { X: X1, Y: Y1, Z: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other) { + aedpoint(other); + const { a, d } = CURVE; + const { X: X1, Y: Y1, Z: Z1, T: T1 } = this; + const { X: X2, Y: Y2, Z: Z2, T: T2 } = other; + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + subtract(other) { + // Validate before calling `negate()` so wrong inputs fail with the point guard + // instead of leaking a foreign `negate()` error. + aedpoint(other); + return this.add(other.negate()); + } + // Constant-time multiplication. + multiply(scalar) { + // 1 <= scalar < L + // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO. + // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing, + // and failing closed is safer than silently producing the identity point. + if (!Fn.isValidNot0(scalar)) + throw new RangeError('invalid scalar: expected 1 <= sc < curve.n'); + const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p)); + return normalizeZ(Point, [p, f])[0]; + } + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but + // n and larger values are rejected instead of being reduced mod n to the identity point. + multiplyUnsafe(scalar) { + // 0 <= scalar < L + if (!Fn.isValid(scalar)) + throw new RangeError('invalid scalar: expected 0 <= sc < curve.n'); + if (scalar === _0n) + return Point.ZERO; + if (this.is0() || scalar === _1n) + return this; + return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p)); + } + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Clears cofactor and checks if the result is 0. + isSmallOrder() { + return this.clearCofactor().is0(); + } + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree() { + return wnaf.unsafe(this, CURVE.n).is0(); + } + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(invertedZ) { + const p = this; + let iz = invertedZ; + const { X, Y, Z } = p; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? _8n : Fp.inv(Z); // 8 was chosen arbitrarily + const x = modP(X * iz); + const y = modP(Y * iz); + const zz = Fp.mul(Z, iz); + if (is0) + return { x: _0n, y: _1n }; + if (zz !== _1n) + throw new Error('invZ was invalid'); + return { x, y }; + } + clearCofactor() { + if (cofactor === _1n) + return this; + return this.multiplyUnsafe(cofactor); + } + toBytes() { + const { x, y } = this.toAffine(); + // Fp.toBytes() allows non-canonical encoding of y (>= p). + const bytes = Fp.toBytes(y); + // Each y has 2 valid points: (x, y), (x,-y). + // When compressing, it's enough to store y and use the last byte to encode sign of x + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; + return bytes; + } + toHex() { + return bytesToHex(this.toBytes()); + } + toString() { + return ``; + } + } + const wnaf = new wNAF(Point, Fn.BITS); + // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve + // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports. + // Callers that construct custom curves are responsible for supplying the correct base point. + // try { + // Point.BASE.assertValidity(); + // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + // } catch { + // throw new Error('bad curve params: generator point'); + // } + // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the + // eager W=8 cache there instead of rejecting an otherwise valid constructor. + if (Fn.BITS >= 8) + Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + Object.freeze(Point.prototype); + Object.freeze(Point); + return Point; +} +/** + * Base class for prime-order points like Ristretto255 and Decaf448. + * These points eliminate cofactor issues by representing equivalence classes + * of Edwards curve points. Multiple Edwards representatives can describe the + * same abstract wrapper element, so wrapper validity is not the same thing as + * the hidden representative being torsion-free. + * @param ep - Backing Edwards point. + * @example + * Base class for prime-order points like Ristretto255 and Decaf448. + * + * ```ts + * import { ristretto255 } from '@noble/curves/ed25519.js'; + * const point = ristretto255.Point.BASE.multiply(2n); + * ``` + */ +export class PrimeEdwardsPoint { + static BASE; + static ZERO; + static Fp; + static Fn; + ep; + /** + * Wrap one internal Edwards representative directly. + * This is not a canonical encoding boundary: alternate Edwards + * representatives may still describe the same abstract wrapper element. + */ + constructor(ep) { + this.ep = ep; + } + // Static methods that must be implemented by subclasses + static fromBytes(_bytes) { + notImplemented(); + } + static fromHex(_hex) { + notImplemented(); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + // Common implementations + clearCofactor() { + // no-op for the abstract prime-order wrapper group; this is about the + // wrapper element, not the hidden Edwards representative. + return this; + } + assertValidity() { + // Keep wrapper validity at the abstract-group boundary. Canonical decode + // may choose Edwards representatives that differ by small torsion, so + // checking `this.ep.isTorsionFree()` here would reject valid wrapper points. + this.ep.assertValidity(); + } + /** + * Return affine coordinates of the current internal Edwards representative. + * This is a convenience helper, not a canonical Ristretto/Decaf encoding. + * Equal abstract elements may expose different `x` / `y`; use + * `toBytes()` / `fromBytes()` for canonical roundtrips. + */ + toAffine(invertedZ) { + return this.ep.toAffine(invertedZ); + } + toHex() { + return bytesToHex(this.toBytes()); + } + toString() { + return this.toHex(); + } + isTorsionFree() { + // Abstract Ristretto/Decaf elements are already prime-order even when the + // hidden Edwards representative is not torsion-free. + return true; + } + isSmallOrder() { + return false; + } + add(other) { + this.assertSame(other); + return this.init(this.ep.add(other.ep)); + } + subtract(other) { + this.assertSame(other); + return this.init(this.ep.subtract(other.ep)); + } + multiply(scalar) { + return this.init(this.ep.multiply(scalar)); + } + multiplyUnsafe(scalar) { + return this.init(this.ep.multiplyUnsafe(scalar)); + } + double() { + return this.init(this.ep.double()); + } + negate() { + return this.init(this.ep.negate()); + } + precompute(windowSize, isLazy) { + this.ep.precompute(windowSize, isLazy); + // Keep the wrapper identity stable like the backing Edwards API instead of + // allocating a fresh wrapper around the same cached point. + return this; + } +} +/** + * Initializes EdDSA signatures over given Edwards curve. + * @param Point - Edwards point constructor. + * @param cHash - Hash function. + * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}. + * @returns EdDSA helper namespace. + * @throws If the hash function, options, or derived point operations are invalid. {@link Error} + * @example + * Initializes EdDSA signatures over given Edwards curve. + * + * ```ts + * import { eddsa } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * import { sha512 } from '@noble/hashes/sha2.js'; + * const sigs = eddsa(jubjub.Point, sha512); + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export function eddsa(Point, cHash, eddsaOpts = {}) { + if (typeof cHash !== 'function') + throw new Error('"hash" function param is required'); + const hash = cHash; + const opts = eddsaOpts; + validateObject(opts, {}, { + adjustScalarBytes: 'function', + randomBytes: 'function', + domain: 'function', + prehash: 'function', + zip215: 'boolean', + mapToCurve: 'function', + }); + const { prehash } = opts; + const { BASE, Fp, Fn } = Point; + const outputLen = hash.outputLen; + const expectedLen = 2 * Fp.BYTES; + // When hash metadata is available, reject incompatible EdDSA wrappers at construction time + // instead of deferring the mismatch until the first keygen/sign call. + if (outputLen !== undefined) { + asafenumber(outputLen, 'hash.outputLen'); + if (outputLen !== expectedLen) + throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`); + } + const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes; + const adjustScalarBytes = opts.adjustScalarBytes === undefined + ? (bytes) => bytes + : opts.adjustScalarBytes; + const domain = opts.domain === undefined + ? (data, ctx, phflag) => { + abool(phflag, 'phflag'); + if (ctx.length || phflag) + throw new Error('Contexts/pre-hash are not supported'); + return data; + } + : opts.domain; // NOOP + // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order. + function modN_LE(hash) { + return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit + } + // Get the hashed private scalar per RFC8032 5.1.5 + function getPrivateScalar(key) { + const len = lengths.secretKey; + abytes(key, lengths.secretKey, 'secretKey'); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey'); + // Slice before clamping so in-place adjustors don't corrupt the prefix half. + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + return { head, prefix, scalar }; + } + /** Convenience method that creates public key from scalar. RFC8032 5.1.5 + * Also exposes the derived scalar/prefix tuple and point form reused by sign(). + */ + function getExtendedPublicKey(secretKey) { + const { head, prefix, scalar } = getPrivateScalar(secretKey); + const point = BASE.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toBytes(); + return { head, prefix, scalar, point, pointBytes }; + } + /** Calculates EdDSA pub key. RFC8032 5.1.5. */ + function getPublicKey(secretKey) { + return getExtendedPublicKey(secretKey).pointBytes; + } + // Hash domain-separated chunks into a little-endian scalar modulo the group order. + function hashDomainToScalar(context = Uint8Array.of(), ...msgs) { + const msg = concatBytes(...msgs); + return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash))); + } + /** Signs message with secret key. RFC8032 5.1.6 */ + function sign(msg, secretKey, options = {}) { + msg = abytes(msg, undefined, 'message'); + if (prehash) + msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point + // signature. + // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider + // fails loudly instead of silently producing a degenerate signature. + const R = BASE.multiply(r).toBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L + if (!Fn.isValid(s)) + throw new Error('sign failed: invalid s'); // 0 <= s < L + const rs = concatBytes(R, Fn.toBytes(s)); + return abytes(rs, lengths.signature, 'result'); + } + // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject + // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules. + const verifyOpts = { + zip215: opts.zip215, + }; + /** + * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7. + * A cofactored verification equation is checked. + */ + function verify(sig, msg, publicKey, options = verifyOpts) { + // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts. + const { context } = options; + const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215; + const len = lengths.signature; + sig = abytes(sig, len, 'signature'); + msg = abytes(msg, undefined, 'message'); + publicKey = abytes(publicKey, lengths.publicKey, 'publicKey'); + if (zip215 !== undefined) + abool(zip215, 'zip215'); + if (prehash) + msg = prehash(msg); // for ed25519ph, etc + const mid = len / 2; + const r = sig.subarray(0, mid); + const s = bytesToNumberLE(sig.subarray(mid, len)); + let A, R, SB; + try { + // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that + // explicitly want consensus-style unreduced encoding acceptance. + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + A = Point.fromBytes(publicKey, zip215); + R = Point.fromBytes(r, zip215); + SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside + } + catch (error) { + return false; + } + // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored + // verification equation; they do not add a separate low-order-public-key rejection here. + // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to + // avoid ambiguous verification outcomes where unusual low-order keys can make distinct + // key/signature/message combinations verify. + if (!zip215 && A.isSmallOrder()) + return false; + // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the + // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points. + const k = hashDomainToScalar(context, r, publicKey, msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // Check the cofactored verification equation via the curve cofactor h. + // [h][S]B = [h]R + [h][k]A' + return RkA.subtract(SB).clearCofactor().is0(); + } + const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448 + const lengths = { + secretKey: _size, + publicKey: _size, + signature: 2 * _size, + seed: _size, + }; + function randomSecretKey(seed) { + seed = seed === undefined ? randomBytes(lengths.seed) : seed; + return abytes(seed, lengths.seed, 'seed'); + } + function isValidSecretKey(key) { + return isBytes(key) && key.length === lengths.secretKey; + } + function isValidPublicKey(key, zip215) { + try { + // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too. + return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215); + } + catch (error) { + return false; + } + } + const utils = { + getExtendedPublicKey, + randomSecretKey, + isValidSecretKey, + isValidPublicKey, + /** + * Converts ed public key to x public key. Uses formula: + * - ed25519: + * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * - ed448: + * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + */ + toMontgomery(publicKey) { + const { y } = Point.fromBytes(publicKey); + const size = lengths.publicKey; + const is25519 = size === 32; + if (!is25519 && size !== 57) + throw new Error('only defined for 25519 and 448'); + const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n); + return Fp.toBytes(u); + }, + toMontgomerySecret(secretKey) { + const size = lengths.secretKey; + abytes(secretKey, size); + const hashed = hash(secretKey.subarray(0, size)); + return adjustScalarBytes(hashed).subarray(0, size); + }, + }; + Object.freeze(lengths); + Object.freeze(utils); + return Object.freeze({ + keygen: createKeygen(randomSecretKey, getPublicKey), + getPublicKey, + sign, + verify, + utils, + Point, + lengths, + }); +} +//# sourceMappingURL=edwards.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/edwards.js.map b/node_modules/@noble/curves/abstract/edwards.js.map new file mode 100644 index 0000000..2bba3b7 --- /dev/null +++ b/node_modules/@noble/curves/abstract/edwards.js.map @@ -0,0 +1 @@ +{"version":3,"file":"edwards.js","sourceRoot":"","sources":["../src/abstract/edwards.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EACL,KAAK,EACL,MAAM,EACN,QAAQ,EACR,WAAW,EACX,UAAU,EACV,eAAe,EACf,WAAW,EACX,SAAS,EACT,UAAU,EACV,OAAO,EACP,cAAc,EACd,cAAc,EACd,WAAW,IAAI,aAAa,GAK7B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,IAAI,GAKL,MAAM,YAAY,CAAC;AACpB,OAAO,EAAe,MAAM,cAAc,CAAC;AAE3C,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AAsNzI,yFAAyF;AACzF,wEAAwE;AACxE,SAAS,WAAW,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 index 0000000..de23516 --- /dev/null +++ b/node_modules/@noble/curves/abstract/fft.d.ts @@ -0,0 +1,439 @@ +/** + * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields. + * API may change at any time. The code has not been audited. Feature requests are welcome. + * @module + */ +import type { TArg } from '../utils.ts'; +import type { IField } from './modular.ts'; +/** Array-like coefficient storage that can be mutated in place. */ +export interface MutableArrayLike { + /** Element access by numeric index. */ + [index: number]: T; + /** Current amount of stored coefficients. */ + length: number; + /** + * Return a sliced copy using the same storage shape. + * @param start - Inclusive start index. + * @param end - Exclusive end index. + * @returns Sliced copy. + */ + slice(start?: number, end?: number): this; + /** + * Iterate over stored coefficients in order. + * @returns Coefficient iterator. + */ + [Symbol.iterator](): Iterator; +} +/** + * Concrete polynomial containers accepted by the high-level `poly(...)` helpers. + * Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)` + * intentionally keeps runtime dispatch on plain arrays and typed-array views. + */ +export type PolyStorage = T[] | (MutableArrayLike & ArrayBufferView); +/** + * Checks if integer is in form of `1 << X`. + * @param x - Integer to inspect. + * @returns `true` when the value is a power of two. + * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Validate that an FFT size is a power of two. + * + * ```ts + * isPowerOfTwo(8); + * ``` + */ +export declare function isPowerOfTwo(x: number): boolean; +/** + * @param n - Input value. + * @returns Next power of two within the u32/array-length domain. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Round an integer up to the FFT size it needs. + * + * ```ts + * nextPowerOfTwo(9); + * ``` + */ +export declare function nextPowerOfTwo(n: number): number; +/** + * @param n - Value to reverse. + * @param bits - Number of bits to use. + * @returns Bit-reversed integer. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Reverse the low `bits` bits of one index. + * + * ```ts + * reverseBits(3, 3); + * ``` + */ +export declare function reverseBits(n: number, bits: number): number; +/** + * Similar to `bitLen(x)-1` but much faster for small integers, like indices. + * @param n - Input value. + * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Compute the radix-2 stage count for one transform size. + * + * ```ts + * log2(8); + * ``` + */ +export declare function log2(n: number): number; +/** + * Moves lowest bit to highest position, which at first step splits + * array on even and odd indices, then it applied again to each part, + * which is core of fft + * @param values - Mutable coefficient array. + * @returns Mutated input array. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Reorder coefficients into bit-reversed order in place. + * + * ```ts + * const values = Uint8Array.from([0, 1, 2, 3]); + * bitReversalInplace(values); + * ``` + */ +export declare function bitReversalInplace>(values: T): T; +/** + * @param values - Input values. + * @returns Reordered copy. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Return a reordered copy instead of mutating the input in place. + * + * ```ts + * const reordered = bitReversalPermutation([0, 1, 2, 3]); + * ``` + */ +export declare function bitReversalPermutation(values: T[]): T[]; +/** Cached roots-of-unity tables derived from one finite field. */ +export type RootsOfUnity = { + /** Generator and 2-adicity metadata for the cached field. */ + info: { + G: bigint; + oddFactor: bigint; + powerOfTwo: number; + }; + /** + * Return the natural-order roots of unity for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Natural-order roots for that size. + */ + roots: (bits: number) => bigint[]; + /** + * Return the bit-reversal permutation of the roots for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Bit-reversed roots. + */ + brp(bits: number): bigint[]; + /** + * Return the inverse roots of unity for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Inverse roots. + */ + inverse(bits: number): bigint[]; + /** + * Return one primitive root used by a radix-2 stage. + * @param bits - Transform size as `log2(N)`. + * @returns Primitive root for that stage. + */ + omega: (bits: number) => bigint; + /** + * Drop all cached root tables. + * @returns Nothing. + */ + clear: () => void; +}; +/** + * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. + * @param field - Field implementation. + * @param generator - Optional generator override. + * @returns Roots-of-unity cache. + * @example + * Cache roots once, then ask for the omega table of one FFT size. + * + * ```ts + * import { rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const roots = rootsOfUnity(Field(17n)); + * const omega = roots.omega(4); + * ``` + */ +export declare function rootsOfUnity(field: TArg>, generator?: bigint): RootsOfUnity; +/** Polynomial coefficient container used by the FFT helpers. */ +export type Polynomial = MutableArrayLike; +/** + * Arithmetic operations used by the generic FFT implementation. + * + * Maps great to Field, but not to Group (EC points): + * - inv from scalar field + * - we need multiplyUnsafe here, instead of multiply for speed + * - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse + */ +export type FFTOpts = { + /** + * Add two coefficients. + * @param a - Left coefficient. + * @param b - Right coefficient. + * @returns Sum coefficient. + */ + add: (a: T, b: T) => T; + /** + * Subtract two coefficients. + * @param a - Left coefficient. + * @param b - Right coefficient. + * @returns Difference coefficient. + */ + sub: (a: T, b: T) => T; + /** + * Multiply one coefficient by a scalar/root factor. + * @param a - Coefficient value. + * @param scalar - Scalar/root factor. + * @returns Scaled coefficient. + */ + mul: (a: T, scalar: R) => T; + /** + * Invert one scalar/root factor. + * @param a - Scalar/root factor. + * @returns Inverse factor. + */ + inv: (a: R) => R; +}; +/** Configuration for one low-level FFT loop. */ +export type FFTCoreOpts = { + /** Transform size. Must be a power of two. */ + N: number; + /** Stage roots for the selected transform size. */ + roots: Polynomial; + /** Whether to run the DIT variant instead of DIF. */ + dit: boolean; + /** Whether to invert butterfly placement for decode-oriented layouts. */ + invertButterflies?: boolean; + /** Number of initial stages to skip. */ + skipStages?: number; + /** Whether to apply bit-reversal permutation at the boundary. */ + brp?: boolean; +}; +/** + * Callable low-level FFT loop over one polynomial storage shape. + * @param values - Polynomial coefficients to transform in place. + * @returns The mutated input polynomial. + */ +export type FFTCoreLoop =

>(values: P) => P; +/** + * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors: + * + * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey + * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande + * + * DIT takes brp input, returns natural output. + * DIF takes natural input, returns brp output. + * + * The output is actually identical. Time / frequence distinction is not meaningful + * for Polynomial multiplication in fields. + * Which means if protocol supports/needs brp output/inputs, then we can skip this step. + * + * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega + * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa + * @param F - Field operations. + * @param coreOpts - FFT configuration: + * - `N`: Transform size. Must be a power of two. + * - `roots`: Stage roots for the selected transform size. + * - `dit`: Whether to run the DIT variant instead of DIF. + * - `invertButterflies` (optional): Whether to invert butterfly placement. + * - `skipStages` (optional): Number of initial stages to skip. + * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary. + * @returns Low-level FFT loop. + * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error} + * @example + * Constructs different flavors of FFT. + * + * ```ts + * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const roots = rootsOfUnity(Fp).roots(2); + * const loop = FFTCore(Fp, { N: 4, roots, dit: true }); + * const values = loop([1n, 2n, 3n, 4n]); + * ``` + */ +export declare const FFTCore: (F: FFTOpts, coreOpts: FFTCoreOpts) => FFTCoreLoop; +/** Forward and inverse FFT helpers for one coefficient domain. */ +export type FFTMethods = { + /** + * Apply the forward transform. + * @param values - Polynomial coefficients to transform. + * @param brpInput - Whether the input is already bit-reversed. + * @param brpOutput - Whether to keep the output bit-reversed. + * @returns Transformed copy. + */ + direct

>(values: P, brpInput?: boolean, brpOutput?: boolean): P; + /** + * Apply the inverse transform. + * @param values - Polynomial coefficients to transform. + * @param brpInput - Whether the input is already bit-reversed. + * @param brpOutput - Whether to keep the output bit-reversed. + * @returns Inverse-transformed copy. + */ + inverse

>(values: P, brpInput?: boolean, brpOutput?: boolean): P; +}; +/** + * NTT aka FFT over finite field (NOT over complex numbers). + * Naming mirrors other libraries. + * @param roots - Roots-of-unity cache. + * @param opts - Field operations. See {@link FFTOpts}. + * @returns Forward and inverse FFT helpers. + * @example + * NTT aka FFT over finite field (NOT over complex numbers). + * + * ```ts + * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const fft = FFT(rootsOfUnity(Fp), Fp); + * const values = fft.direct([1n, 2n, 3n, 4n]); + * ``` + */ +export declare function FFT(roots: RootsOfUnity, opts: FFTOpts): FFTMethods; +/** + * Factory that allocates one polynomial storage container. + * Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted, + * because the quadratic `mul()` / `convolve()` paths and the Kronecker-δ shortcut in + * `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly. + * @param len - Requested amount of coefficients. + * @param elm - Optional fill value. + * @returns Newly allocated polynomial container. + */ +export type CreatePolyFn

, T> = (len: number, elm?: T) => P; +/** High-level polynomial helpers layered on top of FFT and field arithmetic. */ +export type PolyFn

, T> = { + /** Roots-of-unity cache used by the helper namespace. */ + roots: RootsOfUnity; + /** Factory used to allocate new polynomial containers. */ + create: CreatePolyFn; + /** Optional enforced polynomial length. */ + length?: number; + /** + * Compute the polynomial degree. + * @param a - Polynomial coefficients. + * @returns Polynomial degree. + */ + degree: (a: P) => number; + /** + * Extend or truncate one polynomial to a requested length. + * @param a - Polynomial coefficients. + * @param len - Target length. + * @returns Resized polynomial. + */ + extend: (a: P, len: number) => P; + /** + * Add two polynomials coefficient-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Sum polynomial. + */ + add: (a: P, b: P) => P; + /** + * Subtract two polynomials coefficient-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Difference polynomial. + */ + sub: (a: P, b: P) => P; + /** + * Multiply by another polynomial or by one scalar. + * @param a - Left polynomial. + * @param b - Right polynomial or scalar. + * @returns Product polynomial. + */ + mul: (a: P, b: P | T) => P; + /** + * Multiply coefficients point-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Point-wise product polynomial. + */ + dot: (a: P, b: P) => P; + /** + * Multiply two polynomials with convolution. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Convolution product. + */ + convolve: (a: P, b: P) => P; + /** + * Apply a point-wise coefficient shift by powers of one factor. + * @param p - Polynomial coefficients. + * @param factor - Shift factor. + * @returns Shifted polynomial. + */ + shift: (p: P, factor: bigint) => P; + /** + * Clone one polynomial container. + * @param a - Polynomial coefficients. + * @returns Cloned polynomial. + */ + clone: (a: P) => P; + /** + * Evaluate one polynomial on a basis vector. + * @param a - Polynomial coefficients. + * @param basis - Basis vector. + * @returns Evaluated field element. + */ + eval: (a: P, basis: P) => T; + /** Helpers for monomial-basis polynomials. */ + monomial: { + /** Build the monomial basis vector for one evaluation point. */ + basis: (x: T, n: number) => P; + /** Evaluate a polynomial in the monomial basis. */ + eval: (a: P, x: T) => T; + }; + /** Helpers for Lagrange-basis polynomials. */ + lagrange: { + /** Build the Lagrange basis vector for one evaluation point. */ + basis: (x: T, n: number, brp?: boolean) => P; + /** Evaluate a polynomial in the Lagrange basis. */ + eval: (a: P, x: T, brp?: boolean) => T; + }; + /** + * Build the vanishing polynomial for a root set. + * @param roots - Root set. + * @returns Vanishing polynomial. + */ + vanishing: (roots: P) => P; +}; +/** + * Poly wants a cracker. + * + * Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is + * function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways: + * + * - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))` + * - **Basis** is array of functions + * - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers) + * - **Array size** is domain size + * - **Lattice** is matrix (Polynomial of Polynomials) + * @param field - Field implementation. + * @param roots - Roots-of-unity cache. + * @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array` + * and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected. + * @param fft - Optional FFT implementation. + * @param length - Optional fixed polynomial length. + * @returns Polynomial helper namespace. + * @example + * Build polynomial helpers, then convolve two coefficient arrays. + * + * ```ts + * import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const poly17 = poly(Fp, rootsOfUnity(Fp)); + * const product = poly17.convolve([1n, 2n], [3n, 4n]); + * ``` + */ +export declare function poly(field: TArg>, roots: RootsOfUnity, create?: undefined, fft?: FFTMethods, length?: number): PolyFn; +export declare function poly>(field: TArg>, roots: RootsOfUnity, create: CreatePolyFn, fft?: FFTMethods, length?: number): PolyFn; +//# sourceMappingURL=fft.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/fft.d.ts.map b/node_modules/@noble/curves/abstract/fft.d.ts.map new file mode 100644 index 0000000..93d9f62 --- /dev/null +++ b/node_modules/@noble/curves/abstract/fft.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"fft.d.ts","sourceRoot":"","sources":["../src/abstract/fft.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAE3C,mEAAmE;AACnE,MAAM,WAAW,gBAAgB,CAAC,CAAC;IACjC,uCAAuC;IACvC,CAAC,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC;IACnB,6CAA6C;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1C;;;OAGG;IACH,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,CAAC,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,MAAM,MAAM,WAAW,CA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K,CAAC,CAAC;KACzB,CAAC;IACF,8CAA8C;IAC9C,QAAQ,EAAE;QACR,gEAAgE;QAChE,KAAK,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,OAAO,KAAK,CAAC,CAAC;QAC7C,mDAAmD;QACnD,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,EAAE,OAAO,KAAK,CAAC,CAAC;KACxC,CAAC;IACF;;;;OAIG;IACH,SAAS,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,CAAC;CAC5B,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,IAAI,CAAC,CAAC,EACpB,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EACtB,KAAK,EAAE,YAAY,EACnB,MAAM,CAAC,EAAE,SAAS,EAClB,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EACnB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC;AAClB,wBAAgB,IAAI,CAAC,CAAC,EAAE,CAAC,SAAS,WAAW,CAAC,CAAC,CAAC,EAC9C,KAAK,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EACtB,KAAK,EAAE,YAAY,EACnB,MAAM,EAAE,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,EAC1B,GAAG,CAAC,EAAE,UAAU,CAAC,CAAC,CAAC,EACnB,MAAM,CAAC,EAAE,MAAM,GACd,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/fft.js b/node_modules/@noble/curves/abstract/fft.js new file mode 100644 index 0000000..db818e6 --- /dev/null +++ b/node_modules/@noble/curves/abstract/fft.js @@ -0,0 +1,568 @@ +function checkU32(n) { + // 0xff_ff_ff_ff + if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff) + throw new Error('wrong u32 integer:' + n); + return n; +} +/** + * Checks if integer is in form of `1 << X`. + * @param x - Integer to inspect. + * @returns `true` when the value is a power of two. + * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Validate that an FFT size is a power of two. + * + * ```ts + * isPowerOfTwo(8); + * ``` + */ +export function isPowerOfTwo(x) { + checkU32(x); + return (x & (x - 1)) === 0 && x !== 0; +} +/** + * @param n - Input value. + * @returns Next power of two within the u32/array-length domain. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Round an integer up to the FFT size it needs. + * + * ```ts + * nextPowerOfTwo(9); + * ``` + */ +export function nextPowerOfTwo(n) { + checkU32(n); + if (n <= 1) + return 1; + // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result: + // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1. + if (n > 0x8000_0000) + throw new Error('nextPowerOfTwo overflow: result does not fit u32'); + return (1 << (log2(n - 1) + 1)) >>> 0; +} +/** + * @param n - Value to reverse. + * @param bits - Number of bits to use. + * @returns Bit-reversed integer. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Reverse the low `bits` bits of one index. + * + * ```ts + * reverseBits(3, 3); + * ``` + */ +export function reverseBits(n, bits) { + checkU32(n); + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`); + let reversed = 0; + for (let i = 0; i < bits; i++, n >>>= 1) + reversed = (reversed << 1) | (n & 1); + // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain. + return reversed >>> 0; +} +/** + * Similar to `bitLen(x)-1` but much faster for small integers, like indices. + * @param n - Input value. + * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Compute the radix-2 stage count for one transform size. + * + * ```ts + * log2(8); + * ``` + */ +export function log2(n) { + checkU32(n); + return 31 - Math.clz32(n); +} +/** + * Moves lowest bit to highest position, which at first step splits + * array on even and odd indices, then it applied again to each part, + * which is core of fft + * @param values - Mutable coefficient array. + * @returns Mutated input array. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Reorder coefficients into bit-reversed order in place. + * + * ```ts + * const values = Uint8Array.from([0, 1, 2, 3]); + * bitReversalInplace(values); + * ``` + */ +export function bitReversalInplace(values) { + const n = values.length; + // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it. + if (!isPowerOfTwo(n)) + throw new Error('expected positive power-of-two length, got ' + n); + const bits = log2(n); + for (let i = 0; i < n; i++) { + const j = reverseBits(i, bits); + if (i < j) { + const tmp = values[i]; + values[i] = values[j]; + values[j] = tmp; + } + } + return values; +} +/** + * @param values - Input values. + * @returns Reordered copy. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Return a reordered copy instead of mutating the input in place. + * + * ```ts + * const reordered = bitReversalPermutation([0, 1, 2, 3]); + * ``` + */ +export function bitReversalPermutation(values) { + return bitReversalInplace(values.slice()); +} +const _1n = /** @__PURE__ */ BigInt(1); +function findGenerator(field) { + let G = BigInt(2); + for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++) + ; + return G; +} +/** + * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. + * @param field - Field implementation. + * @param generator - Optional generator override. + * @returns Roots-of-unity cache. + * @example + * Cache roots once, then ask for the omega table of one FFT size. + * + * ```ts + * import { rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const roots = rootsOfUnity(Field(17n)); + * const omega = roots.omega(4); + * ``` + */ +export function rootsOfUnity(field, generator) { + // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo + let oddFactor = field.ORDER - _1n; + let powerOfTwo = 0; + for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n) + ; + // Find non quadratic residue + let G = generator !== undefined ? BigInt(generator) : findGenerator(field); + // Powers of generator + const omegas = new Array(powerOfTwo + 1); + omegas[powerOfTwo] = field.pow(G, oddFactor); + for (let i = powerOfTwo; i > 0; i--) + omegas[i - 1] = field.sqr(omegas[i]); + // Compute all roots of unity for powers up to maxPower + const rootsCache = []; + const checkBits = (bits) => { + checkU32(bits); + if (bits > 31 || bits > powerOfTwo) + throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo); + return bits; + }; + const precomputeRoots = (maxPower) => { + checkBits(maxPower); + for (let power = maxPower; power >= 0; power--) { + if (rootsCache[power]) + continue; // Skip if we've already computed roots for this power + const rootsAtPower = []; + for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power])) + rootsAtPower.push(cur); + rootsCache[power] = rootsAtPower; + } + return rootsCache[maxPower]; + }; + const brpCache = new Map(); + const inverseCache = new Map(); + // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only. + // NOTE: we use bits instead of power, because power = 2**bits, + // but power is not neccesary isPowerOfTwo(power)! + return { + info: { G, powerOfTwo, oddFactor }, + roots: (bits) => { + const b = checkBits(bits); + return precomputeRoots(b); + }, + brp(bits) { + const b = checkBits(bits); + if (brpCache.has(b)) + return brpCache.get(b); + else { + const res = bitReversalPermutation(this.roots(b)); + brpCache.set(b, res); + return res; + } + }, + inverse(bits) { + const b = checkBits(bits); + if (inverseCache.has(b)) + return inverseCache.get(b); + else { + const res = field.invertBatch(this.roots(b)); + inverseCache.set(b, res); + return res; + } + }, + omega: (bits) => omegas[checkBits(bits)], + clear: () => { + rootsCache.splice(0, rootsCache.length); + brpCache.clear(); + inverseCache.clear(); + }, + }; +} +/** + * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors: + * + * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey + * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande + * + * DIT takes brp input, returns natural output. + * DIF takes natural input, returns brp output. + * + * The output is actually identical. Time / frequence distinction is not meaningful + * for Polynomial multiplication in fields. + * Which means if protocol supports/needs brp output/inputs, then we can skip this step. + * + * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega + * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa + * @param F - Field operations. + * @param coreOpts - FFT configuration: + * - `N`: Transform size. Must be a power of two. + * - `roots`: Stage roots for the selected transform size. + * - `dit`: Whether to run the DIT variant instead of DIF. + * - `invertButterflies` (optional): Whether to invert butterfly placement. + * - `skipStages` (optional): Number of initial stages to skip. + * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary. + * @returns Low-level FFT loop. + * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error} + * @example + * Constructs different flavors of FFT. + * + * ```ts + * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const roots = rootsOfUnity(Fp).roots(2); + * const loop = FFTCore(Fp, { N: 4, roots, dit: true }); + * const values = loop([1n, 2n, 3n, 4n]); + * ``` + */ +export const FFTCore = (F, coreOpts) => { + const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts; + const bits = log2(N); + if (!isPowerOfTwo(N)) + throw new Error('FFT: Polynomial size should be power of two'); + // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense. + if (roots.length !== N) + throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`); + const isDit = dit !== invertButterflies; + isDit; + return (values) => { + if (values.length !== N) + throw new Error('FFT: wrong Polynomial length'); + if (dit && brp) + bitReversalInplace(values); + for (let i = 0, g = 1; i < bits - skipStages; i++) { + // For each stage s (sub-FFT length m = 2^s) + const s = dit ? i + 1 + skipStages : bits - i; + const m = 1 << s; + const m2 = m >> 1; + const stride = N >> s; + // Loop over each subarray of length m + for (let k = 0; k < N; k += m) { + // Loop over each butterfly within the subarray + for (let j = 0, grp = g++; j < m2; j++) { + const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride; + const i0 = k + j; + const i1 = k + j + m2; + const omega = roots[rootPos]; + const b = values[i1]; + const a = values[i0]; + // Inlining gives us 10% perf in kyber vs functions + if (isDit) { + const t = F.mul(b, omega); // Standard DIT butterfly + values[i0] = F.add(a, t); + values[i1] = F.sub(a, t); + } + else if (invertButterflies) { + values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode) + values[i1] = F.mul(F.sub(b, a), omega); + } + else { + values[i0] = F.add(a, b); // Standard DIF butterfly + values[i1] = F.mul(F.sub(a, b), omega); + } + } + } + } + if (!dit && brp) + bitReversalInplace(values); + return values; + }; +}; +/** + * NTT aka FFT over finite field (NOT over complex numbers). + * Naming mirrors other libraries. + * @param roots - Roots-of-unity cache. + * @param opts - Field operations. See {@link FFTOpts}. + * @returns Forward and inverse FFT helpers. + * @example + * NTT aka FFT over finite field (NOT over complex numbers). + * + * ```ts + * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const fft = FFT(rootsOfUnity(Fp), Fp); + * const values = fft.direct([1n, 2n, 3n, 4n]); + * ``` + */ +export function FFT(roots, opts) { + const getLoop = (N, roots, brpInput = false, brpOutput = false) => { + if (brpInput && brpOutput) { + // we cannot optimize this case, but lets support it anyway + return (values) => FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values)); + } + if (brpInput) + return FFTCore(opts, { N, roots, dit: true, brp: false }); + if (brpOutput) + return FFTCore(opts, { N, roots, dit: false, brp: false }); + return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural + }; + return { + direct(values, brpInput = false, brpOutput = false) { + const N = values.length; + if (!isPowerOfTwo(N)) + throw new Error('FFT: Polynomial size should be power of two'); + const bits = log2(N); + return getLoop(N, roots.roots(bits), brpInput, brpOutput)(values.slice()); + }, + inverse(values, brpInput = false, brpOutput = false) { + const N = values.length; + if (!isPowerOfTwo(N)) + throw new Error('FFT: Polynomial size should be power of two'); + const bits = log2(N); + const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice()); + const ivm = opts.inv(BigInt(values.length)); // scale + // we can get brp output if we use dif instead of dit! + for (let i = 0; i < res.length; i++) + res[i] = opts.mul(res[i], ivm); + // Allows to re-use non-inverted roots, but is VERY fragile + // return [res[0]].concat(res.slice(1).reverse()); + // inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices) + return res; + }, + }; +} +export function poly(field, roots, create, fft, length) { + const F = field; + const _create = create || + ((len, elm) => new Array(len).fill(elm ?? F.ZERO)); + // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted + // polynomial containers concrete instead of trying to support arbitrary wrappers. + const isPoly = (x) => { + if (Array.isArray(x)) + return true; + if (!ArrayBuffer.isView(x)) + return false; + const v = x; + return (typeof v.length === 'number' && + typeof v.slice === 'function' && + typeof v[Symbol.iterator] === 'function'); + }; + const checkLength = (...lst) => { + if (!lst.length) + return 0; + for (const i of lst) + if (!isPoly(i)) + throw new Error('poly: not polynomial: ' + i); + const L = lst[0].length; + for (let i = 1; i < lst.length; i++) + if (lst[i].length !== L) + throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`); + if (length !== undefined && L !== length) + throw new Error(`poly: expected fixed length ${length}, got ${L}`); + return L; + }; + function findOmegaIndex(x, n, brp = false) { + const bits = log2(n); + const omega = brp ? roots.brp(bits) : roots.roots(bits); + for (let i = 0; i < n; i++) + if (F.eql(x, omega[i])) + return i; + return -1; + } + // TODO: mutating versions for mlkem/mldsa + return { + roots, + create: _create, + length, + extend: (a, len) => { + checkLength(a); + const out = _create(len, F.ZERO); + // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep + // `extend()` consistent with typed arrays and with its documented truncate behavior. + for (let i = 0; i < Math.min(a.length, len); i++) + out[i] = a[i]; + return out; + }, + degree: (a) => { + checkLength(a); + for (let i = a.length - 1; i >= 0; i--) + if (!F.is0(a[i])) + return i; + return -1; + }, + add: (a, b) => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) + out[i] = F.add(a[i], b[i]); + return out; + }, + sub: (a, b) => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) + out[i] = F.sub(a[i], b[i]); + return out; + }, + dot: (a, b) => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) + out[i] = F.mul(a[i], b[i]); + return out; + }, + mul: (a, b) => { + if (isPoly(b)) { + const len = checkLength(a, b); + if (fft) { + const A = fft.direct(a, false, true); + const B = fft.direct(b, false, true); + for (let i = 0; i < A.length; i++) + A[i] = F.mul(A[i], B[i]); + return fft.inverse(A, true, false); + } + else { + // NOTE: this is quadratic and mostly for compat tests with FFT + const res = _create(len); + for (let i = 0; i < len; i++) { + for (let j = 0; j < len; j++) { + const k = (i + j) % len; // wrap mod length + res[k] = F.add(res[k], F.mul(a[i], b[j])); + } + } + return res; + } + } + else { + const out = _create(checkLength(a)); + for (let i = 0; i < out.length; i++) + out[i] = F.mul(a[i], b); + return out; + } + }, + convolve(a, b) { + const len = nextPowerOfTwo(a.length + b.length - 1); + return this.mul(this.extend(a, len), this.extend(b, len)); + }, + shift(p, factor) { + const out = _create(checkLength(p)); + out[0] = p[0]; + for (let i = 1, power = F.ONE; i < p.length; i++) { + power = F.mul(power, factor); + out[i] = F.mul(p[i], power); + } + return out; + }, + clone: (a) => { + checkLength(a); + const out = _create(a.length); + for (let i = 0; i < a.length; i++) + out[i] = a[i]; + return out; + }, + eval: (a, basis) => { + checkLength(a, basis); + let acc = F.ZERO; + for (let i = 0; i < a.length; i++) + acc = F.add(acc, F.mul(a[i], basis[i])); + return acc; + }, + monomial: { + basis: (x, n) => { + const out = _create(n); + let pow = F.ONE; + for (let i = 0; i < n; i++) { + out[i] = pow; + pow = F.mul(pow, x); + } + return out; + }, + eval: (a, x) => { + checkLength(a); + // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way + let acc = F.ZERO; + for (let i = a.length - 1; i >= 0; i--) + acc = F.add(F.mul(acc, x), a[i]); + return acc; + }, + }, + lagrange: { + basis: (x, n, brp = false, weights) => { + const bits = log2(n); + const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [ω⁰, ω¹, ..., ωⁿ⁻¹] + const out = _create(n); + // Fast Kronecker-δ shortcut + const idx = findOmegaIndex(x, n, brp); + if (idx !== -1) { + out[idx] = F.ONE; + return out; + } + const tm = F.pow(x, BigInt(n)); + const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n))); // c = (xⁿ - 1)/n + const denom = _create(n); + for (let i = 0; i < n; i++) + denom[i] = F.sub(x, cache[i]); + const inv = F.invertBatch(denom); + for (let i = 0; i < n; i++) + out[i] = F.mul(c, F.mul(cache[i], inv[i])); + return out; + }, + eval(a, x, brp = false) { + checkLength(a); + const idx = findOmegaIndex(x, a.length, brp); + if (idx !== -1) + return a[idx]; // fast path + const L = this.basis(x, a.length, brp); // Lᵢ(x) + let acc = F.ZERO; + for (let i = 0; i < a.length; i++) + if (!F.is0(a[i])) + acc = F.add(acc, F.mul(a[i], L[i])); + return acc; + }, + }, + vanishing(roots) { + checkLength(roots); + const out = _create(roots.length + 1, F.ZERO); + out[0] = F.ONE; + for (const r of roots) { + const neg = F.neg(r); + for (let j = out.length - 1; j > 0; j--) + out[j] = F.add(F.mul(out[j], neg), out[j - 1]); + out[0] = F.mul(out[0], neg); + } + return out; + }, + }; +} +//# sourceMappingURL=fft.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/fft.js.map b/node_modules/@noble/curves/abstract/fft.js.map new file mode 100644 index 0000000..05e32be --- /dev/null +++ b/node_modules/@noble/curves/abstract/fft.js.map @@ -0,0 +1 @@ +{"version":3,"file":"fft.js","sourceRoot":"","sources":["../src/abstract/fft.ts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AAI,CAAC,GAAG,GAAG,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE;oBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBACxF,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;YAC9B,CAAC;YACD,OAAO,GAAG,CAAC;QACb,CAAC;KACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/frost.d.ts b/node_modules/@noble/curves/abstract/frost.d.ts new file mode 100644 index 0000000..9c2b3a6 --- /dev/null +++ b/node_modules/@noble/curves/abstract/frost.d.ts @@ -0,0 +1,293 @@ +import { randomBytes, type TArg, type TRet } from '../utils.ts'; +import { type CurvePoint, type CurvePointCons } from './curve.ts'; +import { type H2CDSTOpts } from './hash-to-curve.ts'; +import { type IField } from './modular.ts'; +export type RNG = typeof randomBytes; +export type Identifier = string; +export type Commitment = Uint8Array; +export type Coefficient = Uint8Array; +export type Signature = Uint8Array; +export type Signers = { + min: number; + max: number; +}; +export type SecretKey = Uint8Array; +export type Bytes = Uint8Array; +type Point = Uint8Array; +export type DKG_Round1 = { + identifier: Identifier; + commitment: TRet; + proofOfKnowledge: TRet; +}; +export type DKG_Round2 = { + identifier: Identifier; + signingShare: TRet; +}; +export type DKG_Secret = { + identifier: bigint; + coefficients?: bigint[]; + commitment: TRet; + signers: Signers; + step?: 1 | 2 | 3; +}; +export type FrostPublic = { + signers: Signers; + commitments: TRet; + verifyingShares: TRet>; +}; +export type FrostSecret = { + identifier: Identifier; + signingShare: TRet; +}; +export type Key = { + public: FrostPublic; + secret: FrostSecret; +}; +export type DealerShares = { + public: FrostPublic; + secretShares: Record; +}; +export type Nonces = { + hiding: TRet; + binding: TRet; +}; +export type NonceCommitments = { + identifier: Identifier; + hiding: TRet; + binding: TRet; +}; +export type GenNonce = { + nonces: Nonces; + commitments: NonceCommitments; +}; +export interface FROSTPoint> extends CurvePoint { + add(rhs: T): T; + multiply(rhs: bigint): T; + equals(rhs: T): boolean; + toBytes(compressed?: boolean): Bytes; + clearCofactor(): T; +} +export interface FROSTPointConstructor> extends CurvePointCons { + fromBytes(a: Bytes): T; + Fn: IField; +} +export type FrostOpts

> = { + readonly name: string; + readonly Point: FROSTPointConstructor

; + readonly Fn?: IField; + /** Optional suite hook that tightens canonical decoding with subgroup / identity checks. */ + readonly validatePoint?: (p: P) => void; + /** Optional public-key parser. Implementations MUST preserve the same subgroup / identity policy + * as `validatePoint`, because this bypasses generic canonical decoding in `parsePoint()`. */ + readonly parsePublicKey?: (bytes: TArg) => P; + readonly hash: (msg: TArg) => TRet; + /** Custom scalar hash hook. Implementations MUST treat `msg` and `options` as read-only. */ + readonly hashToScalar?: (msg: TArg, options?: TArg) => bigint; + readonly adjustScalar?: (n: bigint) => bigint; + readonly adjustPoint?: (n: P) => P; + readonly challenge?: (R: P, PK: P, msg: TArg) => bigint; + readonly adjustNonces?: (PK: P, nonces: TArg) => TRet; + readonly adjustSecret?: (secret: TArg, pub: TArg) => TRet; + readonly adjustPublic?: (pub: TArg) => TRet; + readonly adjustGroupCommitmentShare?: (GC: P, GCShare: P) => P; + readonly adjustTx?: { + readonly encode: (tx: TArg) => TRet; + readonly decode: (tx: TArg) => TRet; + }; + readonly adjustDKG?: (k: TArg) => TRet; + readonly H1?: string; + readonly H2?: string; + readonly H3?: string; + readonly H4?: string; + readonly H5?: string; + readonly HDKG?: string; + readonly HID?: string; +}; +/** + * FROST: Threshold Protocol for Two‑Round Schnorr Signatures + * from [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/). + */ +export type FROST = { + /** + * Methods to construct participant identifiers. + */ + Identifier: { + /** + * Constructs an identifier from a numeric index. + * @param n - A positive integer. + * @returns A canonical serialized Identifier. + */ + fromNumber(n: number): Identifier; + /** + * Derives an identifier deterministically from a string (e.g. an email). + * @param s - Arbitrary string. + * @returns A canonical serialized Identifier. + */ + derive(s: string): Identifier; + }; + /** + * Distributed Key Generation (DKG) protocol interface. + * RFC 9591 leaves DKG out of scope; Appendix C only specifies dealer/VSS key generation. + * These helpers follow the split-round API used by frost-rs for interoperable testing. + */ + DKG: { + /** + * Generates the first round of DKG. + * @param id - Participant's identifier. + * @param signers - Set of all participants (min/max threshold). + * @param secret - Optional initial secret scalar. + * @param rng - Optional RNG for nonce generation. + * @returns Public broadcast and private DKG state. The returned `secret` package is mutable + * round state that will be consumed by `round2()` and `round3()`. + */ + round1: (id: Identifier, signers: Signers, secret?: TArg, rng?: RNG) => { + public: DKG_Round1; + secret: DKG_Secret; + }; + /** + * Executes DKG round 2 given public round1 data from others. + * @param secret - Private DKG state from round1. This mutates `secret.step` in place. + * @param others - Public round1 broadcasts from other participants. + * @returns A map of round2 messages to be sent to others. + */ + round2: (secret: TArg, others: TArg) => TRet>; + /** + * Finalizes key generation in round3 using received round1 + round2 messages. + * @param secret - Private DKG state. This consumes the remaining local polynomial coefficients + * and transitions the package to its final post-round3 state. + * @param round1 - Public round1 broadcasts from all participants. + * @param round2 - Round2 messages received from others. + * @returns Final secret/public key information for the participant. + * Callers MUST pass the same verified remote `round1` package set that was already + * accepted in `round2()`, rather than re-fetching or rebuilding it from the network. + */ + round3: (secret: TArg, round1: TArg, round2: TArg) => TRet; + /** + * Best-effort erasure of internal secret state. Bigint/JIT copies may still survive outside the + * local object even after cleanup. + * @param secret - Private DKG state from round1. + */ + clean(secret: TArg): void; + }; + /** + * Trusted dealer mode: generates key shares from a central trusted authority. + * Mirrors RFC 9591 Appendix C and returns one shared VSS commitment package + * plus per-participant shares. + * @param signers - Threshold parameters (min/max). + * @param identifiers - Optional explicit participant list. + * @param secret - Optional secret scalar. + * @param rng - Optional RNG. + * @returns One shared public package plus the participant secret-share packages. + */ + trustedDealer(signers: Signers, identifiers?: Identifier[], secret?: TArg, rng?: RNG): TRet; + /** + * Validates the consistency of a secret share against the shared public commitments. + * This is the RFC 9591 Appendix C.2 `vss_verify` check against the shared dealer/DKG commitment. + * It does not relax RFC 9591 Section 3.1: public identity elements are still invalid even when + * the scalar/share algebra would otherwise be self-consistent. + * Throws if invalid. + * @param secret - A FrostSecret containing identifier and signing share. + * @param pub - Shared public package containing commitments. + */ + validateSecret(secret: TArg, pub: TArg): void; + /** + * Produces nonces and public commitments used in signing. + * RFC 9591 Section 5.1 `commit()`. + * @param secret - Participant's secret share. + * @param rng - Optional RNG. + * @returns Nonce values and their public commitments. + * Returned nonces are one-time-use and MUST NOT be reused across signing sessions. + * This API does not mutate or zeroize caller-owned nonce objects. + */ + commit(secret: TArg, rng?: RNG): TRet; + /** + * Signs a message using the participant's secret and nonce. + * @param secret - Participant's secret share. + * @param pub - Shared public package containing commitments. + * @param nonces - Participant's nonce pair. + * @param commitmentList - Commitments from all signing participants. + * @param msg - Message to be signed. + * @returns Signature share as a byte array. + * RFC 9591 Sections 4.1/5.1 require round-one commitments to be one-time-use, and + * Section 5.2 signs with the nonce corresponding to that published commitment. + * The caller MUST pass fresh nonces from `commit()`. On successful signing, this helper + * consumes the caller-owned nonce object by zeroing both nonce byte arrays in place. + * Later calls reject an all-zero nonce package, so same-object reuse fails closed and an + * accidentally generated zero nonce package is not silently used for signing. + */ + signShare(secret: TArg, pub: TArg, nonces: TArg, commitmentList: TArg, msg: TArg): TRet; + /** + * Verifies a signature share against public commitments. + * Matches the coordinator-side individual-share verification from RFC 9591 Section 5.4. + * @param pub - Group public key information. + * @param commitmentList - Commitments from all signing participants. + * @param msg - Message being signed. + * @param identifier - Identifier of the signer whose share is being verified. + * @param sigShare - Signature share to verify. + * @returns True if valid, false otherwise. + */ + verifyShare(pub: TArg, commitmentList: TArg, msg: TArg, identifier: Identifier, sigShare: TArg): boolean; + /** + * Aggregates signature shares into a full signature. + * RFC 9591 Section 5.3 `aggregate()`. + * @param pub - Group public key. + * @param commitmentList - Nonce commitments from all signers. + * @param msg - Message to sign. + * @param sigShares - Map from identifier to their signature share. + * @returns Final aggregated signature. + */ + aggregate(pub: TArg, commitmentList: TArg, msg: TArg, sigShares: TArg>): TRet; + /** + * Signs a message using a raw secret key (e.g. from combineSecret). + * @param msg - Message to sign. + * @param secretKey - Group secret key as bytes. + * @returns Signature bytes. + */ + sign(msg: TArg, secretKey: TArg): TRet; + /** + * Verifies a full signature against the group public key. + * @param sig - Signature bytes. + * @param msg - Message that was signed. + * @param publicKey - Group public key. + * @returns True if valid, false otherwise. + */ + verify(sig: TArg, msg: TArg, publicKey: TArg): boolean; + /** + * Combines multiple secret shares into a single secret key (e.g. for recovery). + * @param shares - Set of FrostSecret shares. + * @param signers - Threshold parameters. + * @returns Group secret key as bytes. + */ + combineSecret(shares: TArg, signers: Signers): TRet; + /** + * Low-level helper utilities (field arithmetic and polynomial tools). + */ + utils: { + /** + * Finite field used for scalars. + */ + Fn: IField; + /** + * Generates a random scalar (private key). + * @param rng - Optional RNG source. + * @returns Scalar as 32-byte Uint8Array. + */ + randomScalar: (rng?: RNG) => TRet; + /** + * Generates a secret-sharing polynomial and its public commitments. + * @param signers - Threshold parameters. + * @param secret - Optional initial secret scalar. + * @param coeffs - Optional manual coefficients. + * @param rng - Optional RNG. + * @returns Polynomial coefficients, commitments, and secret value. + */ + generateSecretPolynomial: (signers: Signers, secret?: TArg, coeffs?: bigint[], rng?: RNG) => { + coefficients: bigint[]; + commitment: TRet; + secret: bigint; + }; + }; +}; +export declare function createFROST

>(opts: FrostOpts

): TRet; +export {}; +//# sourceMappingURL=frost.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/frost.d.ts.map b/node_modules/@noble/curves/abstract/frost.d.ts.map new file mode 100644 index 0000000..5d15170 --- /dev/null +++ b/node_modules/@noble/curves/abstract/frost.d.ts.map @@ -0,0 +1 @@ +{"version":3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line at end of file diff --git a/node_modules/@noble/curves/abstract/frost.js b/node_modules/@noble/curves/abstract/frost.js new file mode 100644 index 0000000..3653ffa --- /dev/null +++ b/node_modules/@noble/curves/abstract/frost.js @@ -0,0 +1,704 @@ +/** + * FROST: Flexible Round-Optimized Schnorr Threshold Protocol for Two-Round Schnorr Signatures. + * + * See [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/) and [frost.zfnd.org](https://frost.zfnd.org). + * @module + */ +import { utf8ToBytes } from '@noble/hashes/utils.js'; +import { bytesToHex, bytesToNumberBE, bytesToNumberLE, concatBytes, hexToBytes, randomBytes, validateObject, } from "../utils.js"; +import { pippenger, validatePointCons } from "./curve.js"; +import { poly } from "./fft.js"; +import {} from "./hash-to-curve.js"; +import { getMinHashLength, mapHashToField } from "./modular.js"; +// PubKey = commitments, verifyingShares +// PrivKey = id, signingShare, commitment +const validateSigners = (signers) => { + if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max)) + throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max); + // Compatibility with frost-rs intentionally narrows RFC 9591's positive-nonzero threshold rule + // to `min >= 2`, even though the RFC text itself allows `MIN_PARTICIPANTS = 1`. + // This API is for actual threshold signing across participants; 1-of-n degenerates to ordinary + // single-signer mode, which does not need FROST's network/coordination machinery at all. + if (signers.min < 2 || signers.max < 2 || signers.min > signers.max) + throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max); +}; +const validateCommitmentsNum = (signers, len) => { + // RFC 9591 Sections 5.2/5.3 require MIN_PARTICIPANTS <= NUM_PARTICIPANTS <= MAX_PARTICIPANTS. + if (len < signers.min || len > signers.max) + throw new Error('Wrong number of commitments=' + len); +}; +class AggErr extends Error { + // Empty means aggregation failed before per-share verification could attribute a signer. + cheaters; + constructor(msg, cheaters) { + super(msg); + this.cheaters = cheaters; + } +} +export function createFROST(opts) { + validateObject(opts, { + name: 'string', + hash: 'function', + }, { + hashToScalar: 'function', + validatePoint: 'function', + parsePublicKey: 'function', + adjustScalar: 'function', + adjustPoint: 'function', + challenge: 'function', + adjustNonces: 'function', + adjustSecret: 'function', + adjustPublic: 'function', + adjustGroupCommitmentShare: 'function', + adjustDKG: 'function', + }); + // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that + // FROST consumes, but it does not certify point semantics like BASE/ZERO correctness. + validatePointCons(opts.Point); + const { Point } = opts; + const Fn = opts.Fn === undefined ? Point.Fn : opts.Fn; + // Hashes + const hashBytes = opts.hash; + const hashToScalar = opts.hashToScalar === undefined + ? (msg, opts = { DST: new Uint8Array() }) => { + const t = hashBytes(concatBytes(opts.DST, msg)); + return Fn.create(Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t)); + } + : opts.hashToScalar; + const H1Prefix = utf8ToBytes(opts.H1 !== undefined ? opts.H1 : opts.name + 'rho'); + const H2Prefix = utf8ToBytes(opts.H2 !== undefined ? opts.H2 : opts.name + 'chal'); + const H3Prefix = utf8ToBytes(opts.H3 !== undefined ? opts.H3 : opts.name + 'nonce'); + const H4Prefix = utf8ToBytes(opts.H4 !== undefined ? opts.H4 : opts.name + 'msg'); + const H5Prefix = utf8ToBytes(opts.H5 !== undefined ? opts.H5 : opts.name + 'com'); + const HDKGPrefix = utf8ToBytes(opts.HDKG !== undefined ? opts.HDKG : opts.name + 'dkg'); + const HIDPrefix = utf8ToBytes(opts.HID !== undefined ? opts.HID : opts.name + 'id'); + const H1 = (msg) => hashToScalar(msg, { DST: H1Prefix }); + // Empty H2 still passes `{ DST: new Uint8Array() }` into custom hashToScalar hooks. + // The built-in fallback hashes that identically to omitted DST, which is how + // the Ed25519 suite models RFC 9591's undecorated H2 challenge hash. + const H2 = (msg) => hashToScalar(msg, { DST: H2Prefix }); + const H3 = (msg) => hashToScalar(msg, { DST: H3Prefix }); + const H4 = (msg) => hashBytes(concatBytes(H4Prefix, msg)); + const H5 = (msg) => hashBytes(concatBytes(H5Prefix, msg)); + const HDKG = (msg) => hashToScalar(msg, { DST: HDKGPrefix }); + const HID = (msg) => hashToScalar(msg, { DST: HIDPrefix }); + // /Hashes + const randomScalar = (rng = randomBytes) => { + // Intentional divergence from RFC 9591 §4.1 / §5.1: the RFC nonce_generate helper outputs a + // Scalar in [0, p-1], but round-one commit publishes ScalarBaseMult(nonce) values and §3.1 + // requires SerializeElement / DeserializeElement to reject the identity element. Keep noble's + // mapHashToField generation here so round-one public nonce commitments stay in 1..n-1. + const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE); + // We cannot use Fn.fromBytes here because the field can have a different + // byte width, like ed448. + return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t); + }; + const serializePoint = (p) => p.toBytes(); + const parsePoint = (bytes) => { + // RFC 9591 Section 3.1 requires DeserializeElement validation. Suite-specific validatePoint + // hooks tighten this further for ciphersuites in Section 6. Bare createFROST(...) only gets + // canonical point decoding unless the caller installs those extra subgroup / identity checks. + const p = Point.fromBytes(bytes); + if (opts.validatePoint) + opts.validatePoint(p); + return p; + }; + // RFC 9591 Sections 4.1/5.1 model each participant's round-one output as two public commitments. + const nonceCommitments = (identifier, nonces) => ({ + identifier, + hiding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.hiding))), + binding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.binding))), + }); + const adjustPoint = opts.adjustPoint === undefined ? (n) => n : opts.adjustPoint; + // We use hex to make it easier to use inside objects + const validateIdentifier = (n) => { + // Identifiers are canonical non-zero scalars. Custom / derived identifiers are allowed, so this + // is intentionally not bounded by the current signers.max slot count. + if (!Fn.isValid(n) || Fn.is0(n)) + throw new Error('Invalid identifier ' + n); + return n; + }; + const serializeIdentifier = (id) => bytesToHex(Fn.toBytes(validateIdentifier(id))); + const parseIdentifier = (id) => { + const n = validateIdentifier(Fn.fromBytes(hexToBytes(id))); + // Keep string-keyed maps stable by accepting only the canonical serialized form. + if (serializeIdentifier(n) !== id) + throw new Error('expected canonical identifier hex'); + return n; + }; + const Signature = { + // RFC 9591 Appendix A encodes signatures canonically as + // SerializeElement(R) || SerializeScalar(z). + encode: (R, z) => { + let res = concatBytes(serializePoint(R), Fn.toBytes(z)); + if (opts.adjustTx) + res = opts.adjustTx.encode(res); + return res; + }, + decode: (sig) => { + if (opts.adjustTx) + sig = opts.adjustTx.decode(sig); + // We don't know size of point, but we know size of scalar + const R = parsePoint(sig.subarray(0, -Fn.BYTES)); + const z = Fn.fromBytes(sig.subarray(-Fn.BYTES)); + return { R, z }; + }, + }; + // Generates pair of (scalar, point) + const genPointScalarPair = (rng = randomBytes) => { + let n = randomScalar(rng); + if (opts.adjustScalar) + n = opts.adjustScalar(n); + let p = Point.BASE.multiply(n); + return { scalar: n, point: p }; + }; + // No roots here: root-based methods will throw. + // `poly` expects a structured roots-of-unity domain, but FROST uses an + // arbitrary domain and only needs the non-root operations below. + const nrErr = 'roots are unavailable in FROST polynomial mode'; + const noRoots = { + info: { G: Fn.ZERO, oddFactor: Fn.ZERO, powerOfTwo: 0 }, + roots() { + throw new Error(nrErr); + }, + brp() { + throw new Error(nrErr); + }, + inverse() { + throw new Error(nrErr); + }, + omega() { + throw new Error(nrErr); + }, + clear() { }, + }; + const Poly = poly(Fn, noRoots); + const msm = (points, scalars) => pippenger(Point, points, scalars); + // Internal stuff uses bigints & Points, external Uint8Arrays + const polynomialEvaluate = (x, coeffs) => { + if (!coeffs.length) + throw new Error('empty coefficients'); + return Poly.monomial.eval(coeffs, x); + }; + const deriveInterpolatingValue = (L, xi) => { + const err = 'invalid parameters'; + // Generates lagrange coefficient + if (!L.some((x) => Fn.eql(x, xi))) + throw new Error(err); + // Throws error if any x-coordinate is represented more than once in L. + const Lset = new Set(L); + if (Lset.size !== L.length) + throw new Error(err); + // Or if xi is missing + if (!Lset.has(xi)) + throw new Error(err); + let num = Fn.ONE; + let den = Fn.ONE; + for (const x of L) { + if (Fn.eql(x, xi)) + continue; + num = Fn.mul(num, x); // num *= x + den = Fn.mul(den, Fn.sub(x, xi)); // RFC 9591 §4.2: denominator *= x_j - x_i + } + return Fn.div(num, den); + }; + const evalutateVSS = (identifier, commitment) => { + // RFC 9591 Appendix C.2: S_i' = Σ_j ScalarMult(vss_commitment[j], i^j). + const monomial = Poly.monomial.basis(identifier, commitment.length); + return msm(commitment, monomial); + }; + // High-level internal stuff + const generateSecretPolynomial = (signers, secret, coeffs, rng = randomBytes) => { + validateSigners(signers); + // Dealer/DKG polynomial sampling reuses the same hardened scalar derivation as round-one + // nonces: overriding `rng` only swaps the entropy source, not the non-zero `1..n-1` policy. + const secretScalar = secret === undefined ? randomScalar(rng) : Fn.fromBytes(secret); + if (!coeffs) { + coeffs = []; + for (let i = 0; i < signers.min - 1; i++) + coeffs.push(randomScalar(rng)); + } + if (coeffs.length !== signers.min - 1) + throw new Error('wrong coefficients length'); + const coefficients = [secretScalar, ...coeffs]; + // RFC 9591 Appendix C.2 commits to every polynomial coefficient with ScalarBaseMult. + const commitment = coefficients.map((i) => Point.BASE.multiply(i)); + return { coefficients, commitment, secret: secretScalar }; + }; + // Pretty much sign+verify, same as basic + const ProofOfKnowledge = { + challenge: (id, verKey, R) => HDKG(concatBytes(Fn.toBytes(id), serializePoint(verKey), serializePoint(R))), + compute(id, coefficents, commitments, rng = randomBytes) { + if (coefficents.length < 1) + throw new Error('coefficients should have at least one element'); + const { point: R, scalar: k } = genPointScalarPair(rng); + const verKey = commitments[0]; // verify key is first one + const c = this.challenge(id, verKey, R); + const mu = Fn.add(k, Fn.mul(coefficents[0], c)); // mu = k + coeff[0] * c + return Signature.encode(R, mu); + }, + validate(id, commitment, proof) { + if (commitment.length < 1) + throw new Error('commitment should have at least one element'); + const { R, z } = Signature.decode(proof); + const phi = parsePoint(commitment[0]); + const c = this.challenge(id, phi, R); + // R === z*G - phi*c + if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c)))) + throw new Error('invalid proof of knowledge'); + }, + }; + const Basic = { + challenge: (R, PK, msg) => { + if (opts.challenge) + return opts.challenge(R, PK, msg); + return H2(concatBytes(serializePoint(R), serializePoint(PK), msg)); + }, + sign(msg, sk, rng = randomBytes) { + const { point: R, scalar: r } = genPointScalarPair(rng); + const PK = Point.BASE.multiply(sk); // sk*G + const c = this.challenge(R, PK, msg); + const z = Fn.add(r, Fn.mul(c, sk)); // r + c * sk + return [R, z]; + }, + verify(msg, R, z, PK) { + if (opts.adjustPoint) + PK = opts.adjustPoint(PK); + if (opts.adjustPoint) + R = opts.adjustPoint(R); + const c = this.challenge(R, PK, msg); + const zB = Point.BASE.multiply(z); // z*G + const cA = PK.multiply(c); // c*PK + let check = zB.subtract(cA).subtract(R); // zB - cA - R + // No clearCoffactor on ristretto + if (check.clearCofactor) + check = check.clearCofactor(); + return Point.ZERO.equals(check); + }, + }; + // === vssVerify + const validateSecretShare = (identifier, commitment, signingShare) => { + // RFC 9591 Appendix C.2 `vss_verify(share_i, vss_commitment)` is purely algebraic. + // Public FROST packages still go through Section 3.1 element encoding, + // which rejects identity points, so a zero share or commitment does not + // become valid wire data just because VSS matches. + if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment))) + throw new Error('invalid secret share'); + }; + const Identifier = { + fromNumber(n) { + if (!Number.isSafeInteger(n)) + throw new Error('expected safe interger'); + return serializeIdentifier(BigInt(n)); + }, + // Not in spec, but in FROST implementation, + // seems useful and nice, no need to sync identifiers (would require more interactions) + derive(s) { + if (typeof s !== 'string') + throw new Error('wrong identifier string: ' + s); + // Derived identifiers may land anywhere in the scalar field; they are not restricted to + // sequential `1..max_signers` values. + return serializeIdentifier(HID(utf8ToBytes(s))); + }, + }; + // RFC 9591 §4.1: nonce_generate() hashes 32 fresh RNG bytes with SerializeScalar(secret). + const generateNonce = (secret, rng = randomBytes) => H3(concatBytes(rng(32), Fn.toBytes(secret))); + const getGroupCommitment = (GPK, commitmentList, msg) => { + const CL = commitmentList.map((i) => [ + i.identifier, + parseIdentifier(i.identifier), + parsePoint(i.hiding), + parsePoint(i.binding), + ]); + // RFC 9591 Sections 4.3/4.4/4.5 and 5.2/5.3 treat commitment_list as sorted by identifier. + CL.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)); + // Encode commitment list + const Cbytes = []; + for (const [_, id, hC, bC] of CL) + Cbytes.push(Fn.toBytes(id), serializePoint(hC), serializePoint(bC)); + const encodedCommitmentHash = H5(concatBytes(...Cbytes)); + const rhoPrefix = concatBytes(serializePoint(GPK), H4(msg), encodedCommitmentHash); + // Compute binding factors + const bindingFactors = {}; + for (const [i, id] of CL) { + bindingFactors[i] = H1(concatBytes(rhoPrefix, Fn.toBytes(id))); + } + const points = []; + const scalars = []; + for (const [i, _, hC, bC] of CL) { + if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC)) + throw new Error('infinity commitment'); + points.push(hC, bC); + scalars.push(Fn.ONE, bindingFactors[i]); + } + const groupCommitment = msm(points, scalars); // GC += hC + bC*bindingFactor + const identifiers = CL.map((i) => i[1]); + return { identifiers, groupCommitment, bindingFactors }; + }; + const prepareShare = (PK, commitmentList, msg, identifier) => { + // RFC 9591 Sections 4.4/4.5/4.6 feed directly into the Section 5.2 signer computation. + const GPK = adjustPoint(parsePoint(PK)); + const id = parseIdentifier(identifier); + const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment(GPK, commitmentList, msg); + const bindingFactor = bindingFactors[identifier]; + const lambda = deriveInterpolatingValue(identifiers, id); + const challenge = Basic.challenge(groupCommitment, GPK, msg); + return { lambda, challenge, bindingFactor, groupCommitment }; + }; + Object.freeze(Identifier); + const frost = { + Identifier, + // DKG is Distributed Key Generation, not Trusted Dealer Key Generation. + DKG: Object.freeze({ + // NOTE: we allow to pass secret scalar from user side, + // this way it can be derived, instead of random generation + round1: (id, signers, secret, rng = randomBytes) => { + validateSigners(signers); + const idNum = parseIdentifier(id); + const { coefficients, commitment } = generateSecretPolynomial(signers, secret, undefined, rng); + const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng); + const commitmentBytes = commitment.map(serializePoint); + const round1Public = { + identifier: serializeIdentifier(idNum), + commitment: commitmentBytes, + proofOfKnowledge, + }; + // store secret information for signing + const round1Secret = { + identifier: idNum, + coefficients, + commitment: commitment.map(serializePoint), + // Copy threshold metadata instead of retaining the caller-owned object by reference. + signers: { min: signers.min, max: signers.max }, + step: 1, + }; + return { public: round1Public, secret: round1Secret }; + }, + round2: (secret, others) => { + if (others.length !== secret.signers.max - 1) + throw new Error('wrong number of round1 packages'); + if (!secret.coefficients || secret.step === 3) + throw new Error('round3 package used in round2'); + const res = {}; + for (const p of others) { + if (p.commitment.length !== secret.signers.min) + throw new Error('wrong number of commitments'); + const id = parseIdentifier(p.identifier); + if (id === secret.identifier) + throw new Error('duplicate id=' + serializeIdentifier(id)); + ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge); + for (const c of p.commitment) + parsePoint(c); + if (res[p.identifier]) + throw new Error('Duplicate id=' + id); + const signingShare = Fn.toBytes(polynomialEvaluate(id, secret.coefficients)); + res[p.identifier] = { + identifier: serializeIdentifier(secret.identifier), + signingShare: signingShare, + }; + } + secret.step = 2; + return res; + }, + round3: (secret, round1, round2) => { + // DKG is outside RFC 9591's signing flow; callers are expected to reuse the same + // remote round1 packages already accepted in round2, like frost-rs documents. + if (round1.length !== secret.signers.max - 1) + throw new Error('wrong length of round1 packages'); + if (!secret.coefficients || secret.step !== 2) + throw new Error('round2 package used in round3'); + if (round2.length !== round1.length) + throw new Error('wrong length of round2 packages'); + const merged = {}; + for (const r1 of round1) { + if (!r1.identifier || !r1.commitment) + throw new Error('wrong round1 share'); + merged[r1.identifier] = { ...r1 }; + } + for (const r2 of round2) { + if (!r2.identifier || !r2.signingShare) + throw new Error('wrong round2 share'); + if (!merged[r2.identifier]) + throw new Error('round1 share for ' + r2.identifier + ' is missing'); + merged[r2.identifier].signingShare = r2.signingShare; + } + if (Object.keys(merged).length !== round1.length) + throw new Error('mismatch identifiers between rounds'); + let signingShare = Fn.ZERO; + if (secret.commitment.length !== secret.signers.min) + throw new Error('wrong commitments length'); + const localCommitment = secret.commitment.map(parsePoint); + const localShare = polynomialEvaluate(secret.identifier, secret.coefficients); + validateSecretShare(secret.identifier, localCommitment, localShare); + const localCommitmentBytes = localCommitment.map(serializePoint); + const commitments = { + [serializeIdentifier(secret.identifier)]: localCommitmentBytes, + }; + for (const k in merged) { + const v = merged[k]; + if (!v.signingShare || !v.commitment) + throw new Error('mismatch identifiers'); + const id = parseIdentifier(k); // from + const signingSharePart = Fn.fromBytes(v.signingShare); + const commitment = v.commitment.map(parsePoint); + validateSecretShare(secret.identifier, commitment, signingSharePart); + signingShare = Fn.add(signingShare, signingSharePart); + const idSer = serializeIdentifier(id); + if (commitments[idSer]) + throw new Error('duplicated id=' + idSer); + commitments[idSer] = v.commitment; + } + signingShare = Fn.add(signingShare, localShare); + const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO); + for (const k in commitments) { + const v = commitments[k]; + if (v.length !== secret.signers.min) + throw new Error('wrong commitments length'); + for (let i = 0; i < v.length; i++) + mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i])); + } + const mergedCommitmentBytes = mergedCommitment.map(serializePoint); + const verifyingShares = {}; + for (const k in commitments) + verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment)); + // This is enough to sign stuff + let res = { + public: { + signers: { min: secret.signers.min, max: secret.signers.max }, + commitments: mergedCommitmentBytes, + verifyingShares: Object.fromEntries(Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()])), + }, + secret: { + identifier: serializeIdentifier(secret.identifier), + signingShare: Fn.toBytes(signingShare), + }, + }; + if (opts.adjustDKG) + res = opts.adjustDKG(res); + for (let i = 0; i < secret.coefficients.length; i++) + secret.coefficients[i] -= secret.coefficients[i]; + delete secret.coefficients; + secret.step = 3; + return res; + }, + clean(secret) { + // Instead of replacing secret bigint with another (zero?), we subtract it from itself + // in the hope that JIT will modify it inplace, instead of creating new value. + // This is unverified and may not work, but it is best we can do in regard of bigints. + secret.identifier -= secret.identifier; + if (secret.coefficients) { + for (let i = 0; i < secret.coefficients.length; i++) + secret.coefficients[i] -= secret.coefficients[i]; + } + // for (const c of secret.commitment) c.fill(0); + secret.step = 3; + }, + }), + // Trusted dealer setup + // Generates keys for all participants + trustedDealer(signers, identifiers, secret, rng = randomBytes) { + // if no identifiers provided, we generated default identifiers + validateSigners(signers); + if (identifiers === undefined) { + identifiers = []; + for (let i = 1; i <= signers.max; i++) + identifiers.push(Identifier.fromNumber(i)); + } + else { + if (!Array.isArray(identifiers) || identifiers.length !== signers.max) + throw new Error('identifiers should be array of ' + signers.max); + } + const identifierNums = {}; + for (const id of identifiers) { + const idNum = parseIdentifier(id); + if (id in identifierNums) + throw new Error('duplicated id=' + id); + identifierNums[id] = idNum; + } + const sp = generateSecretPolynomial(signers, secret, undefined, rng); + const commitmentBytes = sp.commitment.map(serializePoint); + const secretShares = {}; + const verifyingShares = {}; + for (const id of identifiers) { + const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients); + verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare)); + secretShares[id] = { + identifier: id, + signingShare: Fn.toBytes(signingShare), + }; + } + return { + public: { + signers: { min: signers.min, max: signers.max }, + commitments: commitmentBytes, + verifyingShares, + }, + secretShares, + }; + }, + // Validate secret (from trusted dealer or DKG) + validateSecret(secret, pub) { + const id = parseIdentifier(secret.identifier); + const commitment = pub.commitments.map(parsePoint); + const signingShare = Fn.fromBytes(secret.signingShare); + validateSecretShare(id, commitment, signingShare); + }, + // Actual signing + // Round 1: each participant commit to nonces + // Nonces kept private, commitments sent to coordinator (or every other participant) + // NOTE: we don't need the message at this point, which lets a coordinator + // keep multiple nonce commitments per participant in advance and skip + // round1 for signing. + // But then each participant needs to remember generated shares + commit(secret, rng = randomBytes) { + const secretScalar = Fn.fromBytes(secret.signingShare); + const hiding = generateNonce(secretScalar, rng); + const binding = generateNonce(secretScalar, rng); + const nonces = { hiding: Fn.toBytes(hiding), binding: Fn.toBytes(binding) }; + return { nonces, commitments: nonceCommitments(secret.identifier, nonces) }; + }, + // Round2: sign. Each participant creates a signature share from the secret + // and the selected nonce commitments. + signShare(secret, pub, nonces, commitmentList, msg) { + validateCommitmentsNum(pub.signers, commitmentList.length); + const hidingNonce0 = Fn.fromBytes(nonces.hiding); + const bindingNonce0 = Fn.fromBytes(nonces.binding); + if (Fn.is0(hidingNonce0) || Fn.is0(bindingNonce0)) + throw new Error('signing nonces already used'); + // Reject a coordinator-assigned commitment pair that does not match the signer's own nonce + // pair. This must happen before suite-specific nonce adjustment; secp256k1-tr may negate the + // actual signing nonces later, but the coordinator still assigns the original commitments. + const expectedCommitment = { + identifier: secret.identifier, + hiding: serializePoint(Point.BASE.multiply(hidingNonce0)), + binding: serializePoint(Point.BASE.multiply(bindingNonce0)), + }; + const commitment = commitmentList.find((i) => i.identifier === secret.identifier); + if (!commitment) + throw new Error('missing signer commitment'); + if (bytesToHex(commitment.hiding) !== bytesToHex(expectedCommitment.hiding) || + bytesToHex(commitment.binding) !== bytesToHex(expectedCommitment.binding)) + throw new Error('incorrect signer commitment'); + if (opts.adjustSecret) + secret = opts.adjustSecret(secret, pub); + if (opts.adjustPublic) + pub = opts.adjustPublic(pub); + const SK = Fn.fromBytes(secret.signingShare); + const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, secret.identifier); + const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces; + const hidingNonce = opts.adjustNonces ? Fn.fromBytes(N.hiding) : hidingNonce0; + const bindingNonce = opts.adjustNonces ? Fn.fromBytes(N.binding) : bindingNonce0; + const t = Fn.mul(Fn.mul(lambda, SK), challenge); // challenge * lambda * SK + const t2 = Fn.mul(bindingNonce, bindingFactor); // bindingNonce * bindingFactor + const r = Fn.toBytes(Fn.add(Fn.add(hidingNonce, t2), t)); // t + t2 + hidingNonce + // RFC 9591 round-one commitments are one-time-use, and round two must use the nonce + // corresponding to the published commitment. This API returns mutable local nonce bytes, + // so consume them after a successful signShare() call: later all-zero reuse fails closed. + nonces.hiding.fill(0); + nonces.binding.fill(0); + return r; + }, + // Each participant (or coordinator) can verify signatures from other participants + verifyShare(pub, commitmentList, msg, identifier, sigShare) { + if (opts.adjustPublic) + pub = opts.adjustPublic(pub); + const comm = commitmentList.find((i) => i.identifier === identifier); + if (!comm) + throw new Error('cannot find identifier commitment'); + const PK = parsePoint(pub.verifyingShares[identifier]); + const hidingNonceCommitment = parsePoint(comm.hiding); + const bindingNonceCommitment = parsePoint(comm.binding); + const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare(pub.commitments[0], commitmentList, msg, identifier); + // hC + bC * bF + let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor)); + if (opts.adjustGroupCommitmentShare) + commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare); + const l = Point.BASE.multiply(Fn.fromBytes(sigShare)); // sigShare*G + // commShare + PK * (challenge * lambda) + const r = commShare.add(PK.multiply(Fn.mul(challenge, lambda))); + return l.equals(r); + }, + // Aggregate multiple signature shares into groupSignature + aggregate(pub, commitmentList, msg, sigShares) { + if (opts.adjustPublic) + pub = opts.adjustPublic(pub); + try { + validateCommitmentsNum(pub.signers, commitmentList.length); + } + catch { + throw new AggErr('aggregation failed', []); + } + const ids = commitmentList.map((i) => i.identifier); + if (ids.length !== Object.keys(sigShares).length) + throw new AggErr('aggregation failed', []); + for (const id of ids) { + if (!(id in sigShares) || !(id in pub.verifyingShares)) + throw new AggErr('aggregation failed', []); + } + const GPK = parsePoint(pub.commitments[0]); + const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg); + let z = Fn.ZERO; + // RFC 9591 Section 5.3 aggregates by summing the validated signature shares. + for (const id of ids) + z = Fn.add(z, Fn.fromBytes(sigShares[id])); // z += zi + if (!Basic.verify(msg, groupCommitment, z, GPK)) { + const cheaters = []; + for (const id of ids) { + if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id])) + cheaters.push(id); + } + throw new AggErr('aggregation failed', cheaters); + } + return Signature.encode(groupCommitment, z); + }, + // Basic sign/verify using single key + sign(msg, secretKey) { + let sk = Fn.fromBytes(secretKey); + // Taproot single-key signing needs the same scalar normalization as threshold keys. + if (opts.adjustScalar) + sk = opts.adjustScalar(sk); + const [R, z] = Basic.sign(msg, sk); + return Signature.encode(R, z); + }, + verify(sig, msg, publicKey) { + const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey); + const { R, z } = Signature.decode(sig); + return Basic.verify(msg, R, z, PK); + }, + // Combine multiple secret shares to restore secret + combineSecret(shares, signers) { + validateSigners(signers); + if (!Array.isArray(shares) || shares.length < signers.min) + throw new Error('wrong secret shares array'); + const points = []; + const seen = {}; + // Interpolate over the full provided share set and reject duplicate identifiers. + for (const s of shares) { + const idNum = parseIdentifier(s.identifier); + const id = serializeIdentifier(idNum); + if (seen[id]) + throw new Error('duplicated id=' + id); + seen[id] = true; + points.push([idNum, Fn.fromBytes(s.signingShare)]); + } + const xCoords = points.map(([x]) => x); + let res = Fn.ZERO; + for (const [x, y] of points) + res = Fn.add(res, Fn.mul(y, deriveInterpolatingValue(xCoords, x))); + return Fn.toBytes(res); + }, + // Utils + utils: Object.freeze({ + Fn, // NOTE: we re-export it here because it may be different from Point.Fn (ed448 is fun!) + // Test RNG overrides still go through noble's non-zero scalar derivation; this is not a raw + // "bytes become scalar" escape hatch. + randomScalar: (rng = randomBytes) => Fn.toBytes(genPointScalarPair(rng).scalar), + generateSecretPolynomial: (signers, secret, coeffs, rng) => { + const res = generateSecretPolynomial(signers, secret, coeffs, rng); + return { ...res, commitment: res.commitment.map(serializePoint) }; + }, + }), + }; + return Object.freeze(frost); +} +//# sourceMappingURL=frost.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/frost.js.map b/node_modules/@noble/curves/abstract/frost.js.map new file mode 100644 index 0000000..153db08 --- /dev/null +++ b/node_modules/@noble/curves/abstract/frost.js.map @@ -0,0 +1 @@ +{"version":3,"file":"frost.js","source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wBAAwB,EAAE,CACxB,OAAgB,EAChB,MAAyB,EACzB,MAAiB,EACjB,GAAS,EACT,EAAE;gBACF,MAAM,GAAG,GAAG,wBAAwB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;gBACnE,OAAO,EAAE,GAAG,GAAG,EAAE,UAAU,EAAE,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,cAAc,CAAkB,EAAE,CAAC;YACrF,CAAC;SACF,CAAC;KACH,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAAC,KAAK,CAAgB,CAAC;AAC7C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.d.ts b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts new file mode 100644 index 0000000..64e5d61 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts @@ -0,0 +1,239 @@ +/** + * hash-to-curve from RFC 9380. + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + * https://www.rfc-editor.org/rfc/rfc9380 + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { CHash, TArg, TRet } from '../utils.ts'; +import type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts'; +import { type IField } from './modular.ts'; +/** ASCII domain-separation tag or raw bytes. */ +export type AsciiOrBytes = string | Uint8Array; +type H2CDefaults = { + DST: AsciiOrBytes; + expand: 'xmd' | 'xof'; + hash: CHash; + p: bigint; + m: number; + k: number; + encodeDST?: AsciiOrBytes; +}; +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +export type H2COpts = { + /** Domain separation tag. */ + DST: AsciiOrBytes; + /** Expander family used by RFC 9380. */ + expand: 'xmd' | 'xof'; + /** Hash or XOF implementation used by the expander. */ + hash: CHash; + /** Base-field characteristic. */ + p: bigint; + /** Extension degree (`1` for prime fields). */ + m: number; + /** Target security level in bits. */ + k: number; +}; +/** Hash-only subset of RFC 9380 options used by per-call overrides. */ +export type H2CHashOpts = { + /** Expander family used by RFC 9380. */ + expand: 'xmd' | 'xof'; + /** Hash or XOF implementation used by the expander. */ + hash: CHash; +}; +/** + * Map one hash-to-field output tuple onto affine curve coordinates. + * Implementations receive the validated scalar tuple by reference for performance and MUST treat it + * as read-only. Callers that need scratch space should copy before mutating. + * @param scalar - Field-element tuple produced by `hash_to_field`. + * @returns Affine point before subgroup clearing. + */ +export type MapToCurve = (scalar: bigint[]) => AffinePoint; +/** Per-call override for the domain-separation tag. */ +export type H2CDSTOpts = { + /** Domain-separation tag override. */ + DST: AsciiOrBytes; +}; +/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */ +export type H2CHasherBase = { + /** + * Hash arbitrary bytes to one curve point. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Curve point after hash-to-curve. + */ + hashToCurve(msg: TArg, options?: TArg): PC_P; + /** + * Hash arbitrary bytes to one scalar. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Scalar reduced into the target field. + */ + hashToScalar(msg: TArg, options?: TArg): bigint; + /** + * Derive one curve point from non-uniform bytes without the random-oracle + * guarantees of `hashToCurve`. + * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve + * path instead of the random-oracle construction. + */ + deriveToCurve?(msg: TArg, options?: TArg): PC_P; + /** Point constructor for the target curve. */ + Point: PC; +}; +/** + * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}. + * + * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing) + * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing) + * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing) + */ +export type H2CHasher = H2CHasherBase & { + /** + * Encode non-uniform bytes to one curve point. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Curve point after encode-to-curve. + */ + encodeToCurve(msg: TArg, options?: TArg): PC_P; + /** Deterministic map from `hash_to_field` tuples into affine coordinates. */ + mapToCurve: MapToCurve>; + /** Default RFC 9380 options captured by this hasher bundle. */ + defaults: H2CDefaults; +}; +/** + * Produces a uniformly random byte string using a cryptographic hash + * function H that outputs b bits. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param H - Hash function. + * @returns Uniform byte string. + * @throws If the message, DST, hash, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XMD construction. + * + * ```ts + * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256); + * ``` + */ +export declare function expand_message_xmd(msg: TArg, DST: TArg, lenInBytes: number, H: TArg): TRet; +/** + * Produces a uniformly random byte string using an extendable-output function (XOF) H. + * 1. The collision resistance of H MUST be at least k bits. + * 2. H MUST be an XOF that has been proved indifferentiable from + * a random oracle under a reasonable cryptographic assumption. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param k - Target security level. + * @param H - XOF hash function. + * @returns Uniform byte string. + * @throws If the message, DST, XOF, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XOF construction. + * + * ```ts + * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * const uniform = expand_message_xof( + * new TextEncoder().encode('hello noble'), + * 'DST', + * 32, + * 128, + * shake256 + * ); + * ``` + */ +export declare function expand_message_xof(msg: TArg, DST: TArg, lenInBytes: number, k: number, H: TArg): TRet; +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}. + * @param msg - Input message bytes. + * @param count - Number of field elements to derive. Must be `>= 1`. + * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`. + * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements. + * @throws If the expander choice or RFC 9380 options are invalid. {@link Error} + * @example + * Hash one message into field elements before mapping it onto a curve. + * + * ```ts + * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, { + * DST: 'DST', + * p: 17n, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * ``` + */ +export declare function hash_to_field(msg: TArg, count: number, options: TArg): bigint[][]; +type XY = (x: T, y: T) => { + x: T; + y: T; +}; +type XYRatio = [T[], T[], T[], T[]]; +/** + * @param field - Field implementation. + * @param map - Isogeny coefficients. + * @returns Isogeny mapping helper. + * @example + * Build one rational isogeny map, then apply it to affine x/y coordinates. + * + * ```ts + * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]); + * const point = iso(3n, 5n); + * ``` + */ +export declare function isogenyMap>(field: F, map: XYRatio): XY; +export declare const _DST_scalar: "HashToScalar-"; +/** + * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. + * @param Point - Point constructor. + * @param mapToCurve - Map-to-curve function. + * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as + * the shared defaults bundle for the returned helpers. + * @returns Hash-to-curve helper namespace. + * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error} + * @example + * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve. + * + * ```ts + * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), { + * DST: 'P256_XMD:SHA-256_SSWU_RO_', + * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + * p: p256.Point.Fp.ORDER, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare function createHasher(Point: PC, mapToCurve: MapToCurve>, defaults: TArg): H2CHasher; +export {}; +//# sourceMappingURL=hash-to-curve.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map new file mode 100644 index 0000000..b6cd38f --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.d.ts","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAWrD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAClE,OAAO,EAAsB,KAAK,MAAM,EAAE,MAAM,cAAc,CAAC;AAE/D,gDAAg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AAC,EAAE,IAAI,CAAC,KAAK,CAAC,GACb,IAAI,CAAC,UAAU,CAAC,CAqBlB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,aAAa,CAC3B,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GACrB,MAAM,EAAE,EAAE,CAwCZ;AAED,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,KAAK;IAAE,CAAC,EAAE,CAAC,CAAC;IAAC,CAAC,EAAE,CAAC,CAAA;CAAE,CAAC;AAC5C,KAAK,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;AACvC;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAiBnF;AAOD,eAAO,MAAM,WAAW,EAAG,eAAwB,CAAC;AAEpD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,wBAAgB,YAAY,CAAC,EAAE,SAAS,MAAM,EAC5C,KAAK,EAAE,EAAE,EACT,UAAU,EAAE,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,EAChC,QAAQ,EAAE,IAAI,CAAC,OAAO,GAAG;IAAE,SAAS,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC,GACrD,SAAS,CAAC,EAAE,CAAC,CAyEf"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.js b/node_modules/@noble/curves/abstract/hash-to-curve.js new file mode 100644 index 0000000..0b45827 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.js @@ -0,0 +1,346 @@ +import { abytes, asafenumber, asciiToBytes, bytesToNumberBE, copyBytes, concatBytes, isBytes, validateObject, } from "../utils.js"; +import { FpInvertBatch, mod } from "./modular.js"; +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; +// Integer to Octet Stream (numberToBytesBE). +function i2osp(value, length) { + asafenumber(value); + asafenumber(length); + // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should + // use bigint + numberToBytesBE instead of routing large widths through this small helper. + if (length < 0 || length > 4) + throw new Error('invalid I2OSP length: ' + length); + if (value < 0 || value > 2 ** (8 * length) - 1) + throw new Error('invalid I2OSP input: ' + value); + const res = Array.from({ length }).fill(0); + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res); +} +// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant. +function strxor(a, b) { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +// User can always use utf8 if they want, by passing Uint8Array. +// If string is passed, we treat it as ASCII: other formats are likely a mistake. +function normDST(DST) { + if (!isBytes(DST) && typeof DST !== 'string') + throw new Error('DST must be Uint8Array or ascii string'); + const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST; + // RFC 9380 §3.1 requirement 2: tags "MUST have nonzero length". + if (dst.length === 0) + throw new Error('DST must be non-empty'); + return dst; +} +/** + * Produces a uniformly random byte string using a cryptographic hash + * function H that outputs b bits. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param H - Hash function. + * @returns Uniform byte string. + * @throws If the message, DST, hash, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XMD construction. + * + * ```ts + * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256); + * ``` + */ +export function expand_message_xmd(msg, DST, lenInBytes, H) { + abytes(msg); + asafenumber(lenInBytes); + DST = normDST(DST); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) + DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) + throw new Error('expand_message_xmd: invalid lenInBytes'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes) + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell` + // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255` + // by reaching `I2OSP(256, 1)`. + for (let i = 1; i < ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} +/** + * Produces a uniformly random byte string using an extendable-output function (XOF) H. + * 1. The collision resistance of H MUST be at least k bits. + * 2. H MUST be an XOF that has been proved indifferentiable from + * a random oracle under a reasonable cryptographic assumption. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param k - Target security level. + * @param H - XOF hash function. + * @returns Uniform byte string. + * @throws If the message, DST, XOF, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XOF construction. + * + * ```ts + * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * const uniform = expand_message_xof( + * new TextEncoder().encode('hello noble'), + * 'DST', + * 32, + * 128, + * shake256 + * ); + * ``` + */ +export function expand_message_xof(msg, DST, lenInBytes, k, H) { + abytes(msg); + asafenumber(lenInBytes); + DST = normDST(DST); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // RFC 9380 §5.3.3: DST = H("H2C-OVERSIZE-DST-" || a_very_long_DST, ceil(2 * k / 8)). + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return (H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest()); +} +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}. + * @param msg - Input message bytes. + * @param count - Number of field elements to derive. Must be `>= 1`. + * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`. + * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements. + * @throws If the expander choice or RFC 9380 options are invalid. {@link Error} + * @example + * Hash one message into field elements before mapping it onto a curve. + * + * ```ts + * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, { + * DST: 'DST', + * p: 17n, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * ``` + */ +export function hash_to_field(msg, count, options) { + validateObject(options, { + p: 'bigint', + m: 'number', + k: 'number', + hash: 'function', + }); + const { p, k, m, hash, expand, DST } = options; + asafenumber(hash.outputLen, 'valid hash'); + abytes(msg); + asafenumber(count); + // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires + // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs. + if (count < 1) + throw new Error('hash_to_field: expected count >= 1'); + if (m < 1) + throw new Error('hash_to_field: expected m >= 1'); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } + else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } + else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } + else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} +/** + * @param field - Field implementation. + * @param map - Isogeny coefficients. + * @returns Isogeny mapping helper. + * @example + * Build one rational isogeny map, then apply it to affine x/y coordinates. + * + * ```ts + * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]); + * const point = iso(3n, 5n); + * ``` + */ +export function isogenyMap(field, map) { + // Make same order as in spec + const coeff = map.map((i) => Array.from(i).reverse()); + return (x, y) => { + const [xn, xd, yn, yd] = coeff.map((val) => val.reduce((acc, i) => field.add(field.mul(acc, x), i))); + // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must + // return the identity on E. + // Shipped Weierstrass consumers encode that affine identity as all-zero + // coordinates, so `passZero=true` intentionally collapses zero + // denominators to `{ x: 0, y: 0 }`. + const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true); + x = field.mul(xn, xd_inv); // xNum / xDen + y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev) + return { x, y }; + }; +} +// Keep the shared DST removable when the selected bundle never hashes to scalar. +// Callers that need protocol-specific scalar domain separation must override this generic default. +// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string. +// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior +// by mutating a shared Uint8Array in place. +export const _DST_scalar = 'HashToScalar-'; +/** + * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. + * @param Point - Point constructor. + * @param mapToCurve - Map-to-curve function. + * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as + * the shared defaults bundle for the returned helpers. + * @returns Hash-to-curve helper namespace. + * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error} + * @example + * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve. + * + * ```ts + * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), { + * DST: 'P256_XMD:SHA-256_SSWU_RO_', + * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + * p: p256.Point.Fp.ORDER, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export function createHasher(Point, mapToCurve, defaults) { + if (typeof mapToCurve !== 'function') + throw new Error('mapToCurve() must be defined'); + // `Point` is intentionally not shape-validated eagerly here: point constructors vary across + // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured + // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor(). + const snapshot = (src) => Object.freeze({ + ...src, + DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST, + ...(src.encodeDST === undefined + ? {} + : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }), + }); + // Keep one private defaults snapshot for actual hashing and expose fresh + // detached snapshots via the public getter. + // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison + // the singleton hasher for every other consumer in the same process. + const safeDefaults = snapshot(defaults); + function map(num) { + return Point.fromAffine(mapToCurve(num)); + } + function clear(initial) { + const P = initial.clearCofactor(); + // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity + // surfaces may still reject it later, but createHasher.clear() itself is not that boundary. + if (P.equals(Point.ZERO)) + return Point.ZERO; + P.assertValidity(); + return P; + } + return Object.freeze({ + get defaults() { + return snapshot(safeDefaults); + }, + Point, + hashToCurve(msg, options) { + const opts = Object.assign({}, safeDefaults, options); + const u = hash_to_field(msg, 2, opts); + const u0 = map(u[0]); + const u1 = map(u[1]); + return clear(u0.add(u1)); + }, + encodeToCurve(msg, options) { + const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {}; + const opts = Object.assign({}, safeDefaults, optsDst, options); + const u = hash_to_field(msg, 1, opts); + const u0 = map(u[0]); + return clear(u0); + }, + /** See {@link H2CHasher} */ + mapToCurve(scalars) { + // Curves with m=1 accept only single scalar + if (safeDefaults.m === 1) { + if (typeof scalars !== 'bigint') + throw new Error('expected bigint (m=1)'); + return clear(map([scalars])); + } + if (!Array.isArray(scalars)) + throw new Error('expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') + throw new Error('expected array of bigints'); + return clear(map(scalars)); + }, + // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393 + // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic + // `HashToScalar-` prefix above unless the caller overrides it per invocation. + hashToScalar(msg, options) { + // @ts-ignore + const N = Point.Fn.ORDER; + const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options); + return hash_to_field(msg, 1, opts)[0][0]; + }, + }); +} +//# sourceMappingURL=hash-to-curve.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/hash-to-curve.js.map b/node_modules/@noble/curves/abstract/hash-to-curve.js.map new file mode 100644 index 0000000..b1b9b28 --- /dev/null +++ b/node_modules/@noble/curves/abstract/hash-to-curve.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hash-to-curve.js","sourceRoot":"","sources":["../src/abstract/hash-to-curve.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,MAAM,EACN,WAAW,EACX,YAAY,EACZ,eAAe,EACf,SAAS,EACT,WAAW,EACX,OAAO,EACP,cAAc,GACf,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,aAAa,EAAE,GAAG,EAAe,MAAM,cAAc,CAAC;AA0G/D,6FAA6F;AAC7F,MAAM,KAAK,GAAG,eAAe,CAAC;AAE9B,6CAA6C;AAC7C,SAAS,KAAK,CAAC,KAAa,EAAE,MAAc;IAC1C,WAAW,CAAC,KAAK,CAAC,CAAC;IACnB,WAAW,CAAC,MAAM,CAAC,CAAC;IACpB,8FAA8F;IAC9F,0FAA0F;IAC1F,IAAI,MAAM,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,GAAG,MAAM,CAAC,CAAC;IACjF,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,uBAAuB,GAAG,KAAK,CAAC,CAAC;IACjG,MAAM,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAa,CAAC;IACvD,KAAK,IAAI,CAA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AC,CAAC,CAAC,CAAC;YAC/B,CAAC;YACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;gBAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;YAC1E,KAAK,MAAM,CAAC,IAAI,OAAO;gBACrB,IAAI,OAAO,CAAC,KAAK,QAAQ;oBAAE,MAAM,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC;YAC1E,OAAO,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;QAC7B,CAAC;QAED,0EAA0E;QAC1E,wFAAwF;QACxF,8EAA8E;QAC9E,YAAY,CAAC,GAAqB,EAAE,OAA0B;YAC5D,aAAa;YACb,MAAM,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,KAAK,CAAC;YACzB,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,YAAY,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,EAAE,OAAO,CAAC,CAAC;YACxF,OAAO,aAAa,CAAC,GAAG,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3C,CAAC;KACF,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.d.ts b/node_modules/@noble/curves/abstract/modular.d.ts new file mode 100644 index 0000000..af8d1b5 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.d.ts @@ -0,0 +1,551 @@ +/** + * Utils for modular division and fields. + * Field over 11 is a finite (Galois) field is integer number operations `mod 11`. + * There is no division: it is replaced by modular multiplicative inverse. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type TArg, type TRet } from '../utils.ts'; +/** + * @param a - Dividend value. + * @param b - Positive modulus. + * @returns Reduced value in `[0, b)` only when `b` is positive. + * @throws If the modulus is not positive. {@link Error} + * @example + * Normalize a bigint into one field residue. + * + * ```ts + * mod(-1n, 5n); + * ``` + */ +export declare function mod(a: bigint, b: bigint): bigint; +/** + * Efficiently raise num to a power with modular reduction. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen + * modulus instead of relying on the `power===0/1` fast paths to normalize it. + * @param num - Base value. + * @param power - Exponent value. + * @param modulo - Reduction modulus. + * @returns Modular exponentiation result. + * @throws If the modulus or exponent is invalid. {@link Error} + * @example + * Raise one bigint to a modular power. + * + * ```ts + * pow(2n, 6n, 11n) // 64n % 11n == 9n + * ``` + */ +export declare function pow(num: bigint, power: bigint, modulo: bigint): bigint; +/** + * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`. + * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen + * modulus; the `power===0` fast path intentionally returns the input unchanged. + * @param x - Base value. + * @param power - Number of squarings. + * @param modulo - Reduction modulus. + * @returns Repeated-squaring result. + * @throws If the exponent is negative. {@link Error} + * @example + * Apply repeated squaring inside one field. + * + * ```ts + * pow2(3n, 2n, 11n); + * ``` + */ +export declare function pow2(x: bigint, power: bigint, modulo: bigint): bigint; +/** + * Inverses number over modulo. + * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}. + * @param number - Value to invert. + * @param modulo - Positive modulus. + * @returns Multiplicative inverse. + * @throws If the modulus is invalid or the inverse does not exist. {@link Error} + * @example + * Compute one modular inverse with the extended Euclidean algorithm. + * + * ```ts + * invert(3n, 11n); + * ``` + */ +export declare function invert(number: bigint, modulo: bigint): bigint; +/** + * Tonelli-Shanks square root search algorithm. + * This implementation is variable-time: it searches data-dependently for the first non-residue `Z` + * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape. + * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12 + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * @param P - field order + * @returns function that takes field Fp (created from P) and number n + * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error} + * @example + * Construct a square-root helper for primes that need Tonelli-Shanks. + * + * ```ts + * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = tonelliShanks(17n)(Fp, 4n); + * ``` + */ +export declare function tonelliShanks(P: bigint): TRet<((Fp: IField, n: T) => T)>; +/** + * Square root for a finite field. Will try optimized versions first: + * + * 1. P ≡ 3 (mod 4) + * 2. P ≡ 5 (mod 8) + * 3. P ≡ 9 (mod 16) + * 4. Tonelli-Shanks algorithm + * + * Different algorithms can give different roots, it is up to user to decide which one they want. + * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness + * (used for hash-to-curve). + * @param P - Field order. + * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time + * behavior and this selector assumes prime-field-style integer moduli. + * @throws If the field is unsupported or the square root does not exist. {@link Error} + * @example + * Choose the square-root helper appropriate for one field modulus. + * + * ```ts + * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = FpSqrt(17n)(Fp, 4n); + * ``` + */ +export declare function FpSqrt(P: bigint): TRet<((Fp: IField, n: T) => T)>; +/** + * @param num - Value to inspect. + * @param modulo - Field modulus. + * @returns `true` when the least-significant little-endian bit is set. + * @throws If the modulus is invalid for `mod(...)`. {@link Error} + * @example + * Inspect the low bit used by little-endian sign conventions. + * + * ```ts + * isNegativeLE(3n, 11n); + * ``` + */ +export declare const isNegativeLE: (num: bigint, modulo: bigint) => boolean; +/** Generic field interface used by prime and extension fields alike. + * Generic helpers treat field operations as pure functions: implementations MUST treat provided + * values/byte buffers as read-only and return detached results instead of mutating arguments. + */ +export interface IField { + /** Field order `q`, which may be prime or a prime power. */ + ORDER: bigint; + /** Canonical encoded byte length. */ + BYTES: number; + /** Canonical encoded bit length. */ + BITS: number; + /** Whether encoded field elements use little-endian bytes. */ + isLE: boolean; + /** Additive identity. */ + ZERO: T; + /** Multiplicative identity. */ + ONE: T; + /** + * Normalize one value into the field. + * @param num - Input value. + * @returns Normalized field value. + */ + create: (num: T) => T; + /** + * Check whether one value already belongs to the field. + * @param num - Input value. + * Implementations may throw `TypeError` on malformed input types instead of returning `false`. + * @returns Whether the value already belongs to the field. + */ + isValid: (num: T) => boolean; + /** + * Check whether one value is zero. + * @param num - Input value. + * @returns Whether the value is zero. + */ + is0: (num: T) => boolean; + /** + * Check whether one value is non-zero and belongs to the field. + * @param num - Input value. + * Implementations may throw `TypeError` on malformed input types instead of returning `false`. + * @returns Whether the value is non-zero and valid. + */ + isValidNot0: (num: T) => boolean; + /** + * Negate one value. + * @param num - Input value. + * @returns Negated value. + */ + neg(num: T): T; + /** + * Invert one value multiplicatively. + * @param num - Input value. + * @returns Multiplicative inverse. + */ + inv(num: T): T; + /** + * Compute one square root when it exists. + * @param num - Input value. + * @returns Square root. + */ + sqrt(num: T): T; + /** + * Square one value. + * @param num - Input value. + * @returns Squared value. + */ + sqr(num: T): T; + /** + * Compare two field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Whether both values are equal. + */ + eql(lhs: T, rhs: T): boolean; + /** + * Add two normalized field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Sum value. + */ + add(lhs: T, rhs: T): T; + /** + * Subtract two normalized field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Difference value. + */ + sub(lhs: T, rhs: T): T; + /** + * Multiply two field values. + * @param lhs - Left value. + * @param rhs - Right value or scalar. + * @returns Product value. + */ + mul(lhs: T, rhs: T | bigint): T; + /** + * Raise one field value to a power. + * @param lhs - Base value. + * @param power - Exponent. + * @returns Power value. + */ + pow(lhs: T, power: bigint): T; + /** + * Divide one field value by another. + * @param lhs - Dividend. + * @param rhs - Divisor or scalar. + * @returns Quotient value. + */ + div(lhs: T, rhs: T | bigint): T; + /** + * Add two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Non-normalized sum. + */ + addN(lhs: T, rhs: T): T; + /** + * Subtract two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Non-normalized difference. + */ + subN(lhs: T, rhs: T): T; + /** + * Multiply two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value or scalar. + * @returns Non-normalized product. + */ + mulN(lhs: T, rhs: T | bigint): T; + /** + * Square one value without re-normalizing the result. + * @param num - Input value. + * @returns Non-normalized square. + */ + sqrN(num: T): T; + /** + * Return the RFC 9380 `sgn0`-style oddness bit when supported. + * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook. + * Returns whether the value is odd under the field encoding. + */ + isOdd?(num: T): boolean; + /** + * Invert many field elements in one batch. + * @param lst - Values to invert. + * @returns Batch of inverses. + */ + invertBatch: (lst: T[]) => T[]; + /** + * Encode one field value into fixed-width bytes. + * Callers that need canonical encodings MUST supply a valid field element. + * Low-level protocols may also use this to serialize raw / non-canonical residues. + * @param num - Input value. + * @returns Fixed-width byte encoding. + */ + toBytes(num: T): Uint8Array; + /** + * Decode one field value from fixed-width bytes. + * @param bytes - Fixed-width byte encoding. + * @param skipValidation - Whether to skip range validation. + * Implementations MUST treat `bytes` as read-only. + * @returns Decoded field value. + */ + fromBytes(bytes: Uint8Array, skipValidation?: boolean): T; + /** + * Constant-time conditional move. + * @param a - Value used when the condition is false. + * @param b - Value used when the condition is true. + * @param c - Selection bit. + * @returns Selected value. + */ + cmov(a: T, b: T, c: boolean): T; +} +/** + * @param field - Field implementation. + * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it + * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or + * field-specific extras beyond positive `BYTES` / `BITS`. + * @throws If the field shape or numeric metadata are invalid. {@link Error} + * @example + * Check that a field implementation exposes the operations curve code expects. + * + * ```ts + * import { Field, validateField } from '@noble/curves/abstract/modular.js'; + * const Fp = validateField(Field(17n)); + * ``` + */ +export declare function validateField(field: TArg>): TRet>; +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @param Fp - Field implementation. + * @param num - Base value. + * @param power - Exponent value. + * @returns Powered field element. + * @throws If the exponent is negative. {@link Error} + * @example + * Raise one field element to a public exponent. + * + * ```ts + * import { Field, FpPow } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpPow(Fp, 3n, 5n); + * ``` + */ +export declare function FpPow(Fp: TArg>, num: T, power: bigint): T; +/** + * Efficiently invert an array of Field elements. + * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled. + * @param Fp - Field implementation. + * @param nums - Values to invert. + * @param passZero - map 0 to 0 (instead of undefined) + * @returns Inverted values. + * @example + * Invert several field elements with one shared inversion. + * + * ```ts + * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]); + * ``` + */ +export declare function FpInvertBatch(Fp: TArg>, nums: T[], passZero?: boolean): T[]; +/** + * @param Fp - Field implementation. + * @param lhs - Dividend value. + * @param rhs - Divisor value. + * @returns Division result. + * @throws If the divisor is non-invertible. {@link Error} + * @example + * Divide one field element by another. + * + * ```ts + * import { Field, FpDiv } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpDiv(Fp, 6n, 3n); + * ``` + */ +export declare function FpDiv(Fp: TArg>, lhs: T, rhs: T | bigint): T; +/** + * Legendre symbol. + * Legendre constant is used to calculate Legendre symbol (a | p) + * which denotes the value of a^((p-1)/2) (mod p). + * + * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue + * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue + * * (a | p) ≡ 0 if a ≡ 0 (mod p) + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns Legendre symbol. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Compute the Legendre symbol of one field element. + * + * ```ts + * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const symbol = FpLegendre(Fp, 4n); + * ``` + */ +export declare function FpLegendre(Fp: TArg>, n: T): -1 | 0 | 1; +/** + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic + * residue" terminology often reserves that name for the non-zero square class. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Check whether one field element has a square root in the field. + * + * ```ts + * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const isSquare = FpIsSquare(Fp, 4n); + * ``` + */ +export declare function FpIsSquare(Fp: TArg>, n: T): boolean; +/** Byte and bit lengths derived from one scalar order. */ +export type NLength = { + /** Canonical byte length. */ + nByteLength: number; + /** Canonical bit length. */ + nBitLength: number; +}; +/** + * @param n - Curve order. Callers are expected to pass a positive order. + * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached + * value when overriding the derived bit length. + * @returns Byte and bit lengths. + * @throws If the order or cached bit length is invalid. {@link Error} + * @example + * Measure the encoding sizes needed for one modulus. + * + * ```ts + * nLength(255n); + * ``` + */ +export declare function nLength(n: bigint, nBitLength?: number): NLength; +type FpField = IField & Required, 'isOdd'>>; +type SqrtFn = (n: bigint) => bigint; +type FieldOpts = Partial<{ + isLE: boolean; + BITS: number; + sqrt: SqrtFn; + allowedLengths?: readonly number[]; + modFromBytes: boolean; +}>; +/** + * Creates a finite field. Major performance optimizations: + * * 1. Denormalized operations like mulN instead of mul. + * * 2. Identical object shape: never add or remove keys. + * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`. + * Fragile: always run a benchmark on a change. + * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for + * all elements for performance and protocol-flexibility reasons; callers are responsible for + * supplying valid elements when they need canonical field behavior. + * This is low-level code, please make sure you know what you're doing. + * + * Note about field properties: + * * CHARACTERISTIC p = prime number, number of elements in main subgroup. + * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`. + * + * @param ORDER - field order, probably prime, or could be composite + * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}. + * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight + * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`. + * @example + * Construct one prime field with optional overrides. + * + * ```ts + * Field(11n); + * ``` + */ +export declare function Field(ORDER: bigint, opts?: FieldOpts): TRet>; +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`, + * which is the only square root but is not odd. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the odd square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtOdd(Fp, 4n); + * ``` + */ +export declare function FpSqrtOdd(Fp: TArg>, elm: T): T; +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Even square root. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the even square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtEven(Fp, 4n); + * ``` + */ +export declare function FpSqrtEven(Fp: TArg>, elm: T): T; +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an + * order greater than 1. + * @returns byte length of field + * @throws If the field order is not a bigint. {@link Error} + * @example + * Read the fixed-width byte length of one field. + * + * ```ts + * getFieldBytesLength(255n); + * ``` + */ +export declare function getFieldBytesLength(fieldOrder: bigint): number; +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger + * absolute floor for policy reasons. + * @param fieldOrder - number of field elements greater than 1, usually CURVE.n. + * @returns byte length of target hash + * @throws If the field order is invalid. {@link Error} + * @example + * Compute the minimum hash length needed for field reduction. + * + * ```ts + * getMinHashLength(255n); + * ``` + */ +export declare function getMinHashLength(fieldOrder: bigint): number; +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard + * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look + * accidentally acceptable for real scalar derivation. + * 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}, + * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and + * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380 + * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`. + * @param key - Uniform input bytes. + * @param fieldOrder - Size of subgroup. + * @param isLE - interpret hash bytes as LE num + * @returns valid private scalar + * @throws If the hash length or field order is invalid for scalar reduction. {@link Error} + * @example + * Map hash output into a private scalar range. + * + * ```ts + * mapHashToField(new Uint8Array(48).fill(1), 255n); + * ``` + */ +export declare function mapHashToField(key: TArg, fieldOrder: bigint, isLE?: boolean): TRet; +export {}; +//# sourceMappingURL=modular.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.d.ts.map b/node_modules/@noble/curves/abstract/modular.d.ts.map new file mode 100644 index 0000000..0225247 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.d.ts","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EAWL,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AAWrB;;;;;;;;;;;GAWG;AACH,wBAAgB,GAAG,CAAC,C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,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,YAAY,EAAE,OAAO,CAAC;CACvB,CAAC,CAAC;AA4JH;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,GAAE,SAAc,GAAG,IAAI,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAElF;AAgBD;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAK3D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,UAAU,CAAC,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAK5D;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,mBAAmB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAO9D;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,gBAAgB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAG3D;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,cAAc,CAC5B,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,UAAU,EAAE,MAAM,EAClB,IAAI,UAAQ,GACX,IAAI,CAAC,UAAU,CAAC,CAalB"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.js b/node_modules/@noble/curves/abstract/modular.js new file mode 100644 index 0000000..157f239 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.js @@ -0,0 +1,850 @@ +/** + * Utils for modular division and fields. + * Field over 11 is a finite (Galois) field is integer number operations `mod 11`. + * There is no division: it is replaced by modular multiplicative inverse. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abool, abytes, anumber, asafenumber, bitLen, bytesToNumberBE, bytesToNumberLE, numberToBytesBE, numberToBytesLE, validateObject, } from "../utils.js"; +// Numbers aren't used in x25519 / x448 builds +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2); +// prettier-ignore +const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5); +// prettier-ignore +const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9); +const _16n = /* @__PURE__ */ BigInt(16); +/** + * @param a - Dividend value. + * @param b - Positive modulus. + * @returns Reduced value in `[0, b)` only when `b` is positive. + * @throws If the modulus is not positive. {@link Error} + * @example + * Normalize a bigint into one field residue. + * + * ```ts + * mod(-1n, 5n); + * ``` + */ +export function mod(a, b) { + if (b <= _0n) + throw new Error('mod: expected positive modulus, got ' + b); + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to a power with modular reduction. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen + * modulus instead of relying on the `power===0/1` fast paths to normalize it. + * @param num - Base value. + * @param power - Exponent value. + * @param modulo - Reduction modulus. + * @returns Modular exponentiation result. + * @throws If the modulus or exponent is invalid. {@link Error} + * @example + * Raise one bigint to a modular power. + * + * ```ts + * pow(2n, 6n, 11n) // 64n % 11n == 9n + * ``` + */ +export function pow(num, power, modulo) { + return FpPow(Field(modulo), num, power); +} +/** + * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`. + * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen + * modulus; the `power===0` fast path intentionally returns the input unchanged. + * @param x - Base value. + * @param power - Number of squarings. + * @param modulo - Reduction modulus. + * @returns Repeated-squaring result. + * @throws If the exponent is negative. {@link Error} + * @example + * Apply repeated squaring inside one field. + * + * ```ts + * pow2(3n, 2n, 11n); + * ``` + */ +export function pow2(x, power, modulo) { + if (power < _0n) + throw new Error('pow2: expected non-negative exponent, got ' + power); + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} +/** + * Inverses number over modulo. + * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}. + * @param number - Value to invert. + * @param modulo - Positive modulus. + * @returns Multiplicative inverse. + * @throws If the modulus is invalid or the inverse does not exist. {@link Error} + * @example + * Compute one modular inverse with the extended Euclidean algorithm. + * + * ```ts + * invert(3n, 11n); + * ``` + */ +export function invert(number, modulo) { + if (number === _0n) + throw new Error('invert: expected non-zero number'); + if (modulo <= _0n) + throw new Error('invert: expected positive modulus, got ' + modulo); + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + const q = b / a; + const r = b - a * q; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) + throw new Error('invert: does not exist'); + return mod(x, modulo); +} +function assertIsSquare(Fp, root, n) { + const F = Fp; + if (!F.eql(F.sqr(root), n)) + throw new Error('Cannot find square root'); +} +// Not all roots are possible! Example which will throw: +// const NUM = +// n = 72057594037927816n; +// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab')); +function sqrt3mod4(Fp, n) { + const F = Fp; + const p1div4 = (F.ORDER + _1n) / _4n; + const root = F.pow(n, p1div4); + assertIsSquare(F, root, n); + return root; +} +// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV +// pseudocode verbatim. +function sqrt5mod8(Fp, n) { + const F = Fp; + const p5div8 = (F.ORDER - _5n) / _8n; + const n2 = F.mul(n, _2n); + const v = F.pow(n2, p5div8); + const nv = F.mul(n, v); + const i = F.mul(F.mul(nv, _2n), v); + const root = F.mul(nv, F.sub(i, F.ONE)); + assertIsSquare(F, root, n); + return root; +} +// Based on RFC9380, Kong algorithm +// prettier-ignore +function sqrt9mod16(P) { + const Fp_ = Field(P); + const tn = tonelliShanks(P); + const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + return ((Fp, n) => { + const F = Fp; + let tv1 = F.pow(n, c4); // 1. tv1 = x^c4 + let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1 + const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1 + const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1 + const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x + const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x + tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x + const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2 + assertIsSquare(F, root, n); + return root; + }); +} +/** + * Tonelli-Shanks square root search algorithm. + * This implementation is variable-time: it searches data-dependently for the first non-residue `Z` + * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape. + * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12 + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * @param P - field order + * @returns function that takes field Fp (created from P) and number n + * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error} + * @example + * Construct a square-root helper for primes that need Tonelli-Shanks. + * + * ```ts + * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = tonelliShanks(17n)(Fp, 4n); + * ``` + */ +export function tonelliShanks(P) { + // Initialization (precomputation). + // Caching initialization could boost perf by 7%. + if (P < _3n) + throw new Error('sqrt is not defined for small field'); + // Factor P - 1 = Q * 2^S, where Q is odd + let Q = P - _1n; + let S = 0; + while (Q % _2n === _0n) { + Q /= _2n; + S++; + } + // Find the first quadratic non-residue Z >= 2 + let Z = _2n; + const _Fp = Field(P); + while (FpLegendre(_Fp, Z) === 1) { + // Basic primality test for P. After x iterations, chance of + // not finding quadratic non-residue is 2^x, so 2^1000. + if (Z++ > 1000) + throw new Error('Cannot find square root: probably non-prime P'); + } + // Fast-path; usually done before Z, but we do "primality test". + if (S === 1) + return sqrt3mod4; + // Slow-path + // TODO: test on Fp2 and others + let cc = _Fp.pow(Z, Q); // c = z^Q + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp, n) { + const F = Fp; + if (F.is0(n)) + return n; + // Check if n is a quadratic residue using Legendre symbol + if (FpLegendre(F, n) !== 1) + throw new Error('Cannot find square root'); + // Initialize variables for the main loop + let M = S; + let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp + let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor + let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root + // Main loop + // while t != 1 + while (!F.eql(t, F.ONE)) { + if (F.is0(t)) + return F.ZERO; // if t=0 return R=0 + let i = 1; + // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P) + let t_tmp = F.sqr(t); // t^(2^1) + while (!F.eql(t_tmp, F.ONE)) { + i++; + t_tmp = F.sqr(t_tmp); // t^(2^2)... + if (i === M) + throw new Error('Cannot find square root'); + } + // Calculate the exponent for b: 2^(M - i - 1) + const exponent = _1n << BigInt(M - i - 1); // bigint is important + const b = F.pow(c, exponent); // b = 2^(M - i - 1) + // Update variables + M = i; + c = F.sqr(b); // c = b^2 + t = F.mul(t, c); // t = (t * b^2) + R = F.mul(R, b); // R = R*b + } + return R; + }; +} +/** + * Square root for a finite field. Will try optimized versions first: + * + * 1. P ≡ 3 (mod 4) + * 2. P ≡ 5 (mod 8) + * 3. P ≡ 9 (mod 16) + * 4. Tonelli-Shanks algorithm + * + * Different algorithms can give different roots, it is up to user to decide which one they want. + * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness + * (used for hash-to-curve). + * @param P - Field order. + * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time + * behavior and this selector assumes prime-field-style integer moduli. + * @throws If the field is unsupported or the square root does not exist. {@link Error} + * @example + * Choose the square-root helper appropriate for one field modulus. + * + * ```ts + * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = FpSqrt(17n)(Fp, 4n); + * ``` + */ +export function FpSqrt(P) { + // P ≡ 3 (mod 4) => √n = n^((P+1)/4) + if (P % _4n === _3n) + return sqrt3mod4; + // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf + if (P % _8n === _5n) + return sqrt5mod8; + // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4) + if (P % _16n === _9n) + return sqrt9mod16(P); + // Tonelli-Shanks algorithm + return tonelliShanks(P); +} +/** + * @param num - Value to inspect. + * @param modulo - Field modulus. + * @returns `true` when the least-significant little-endian bit is set. + * @throws If the modulus is invalid for `mod(...)`. {@link Error} + * @example + * Inspect the low bit used by little-endian sign conventions. + * + * ```ts + * isNegativeLE(3n, 11n); + * ``` + */ +export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n; +// prettier-ignore +// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime +// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and +// field-specific extras like `isOdd` are left to the callers that actually need them. +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +]; +/** + * @param field - Field implementation. + * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it + * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or + * field-specific extras beyond positive `BYTES` / `BITS`. + * @throws If the field shape or numeric metadata are invalid. {@link Error} + * @example + * Check that a field implementation exposes the operations curve code expects. + * + * ```ts + * import { Field, validateField } from '@noble/curves/abstract/modular.js'; + * const Fp = validateField(Field(17n)); + * ``` + */ +export function validateField(field) { + const initial = { + ORDER: 'bigint', + BYTES: 'number', + BITS: 'number', + }; + const opts = FIELD_FIELDS.reduce((map, val) => { + map[val] = 'function'; + return map; + }, initial); + validateObject(field, opts); + // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN / + // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches. + asafenumber(field.BYTES, 'BYTES'); + asafenumber(field.BITS, 'BITS'); + // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the + // numeric shape checks above but still breaks encoding helpers and cached-length assumptions. + if (field.BYTES < 1 || field.BITS < 1) + throw new Error('invalid field: expected BYTES/BITS > 0'); + if (field.ORDER <= _1n) + throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER); + return field; +} +// Generic field functions +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @param Fp - Field implementation. + * @param num - Base value. + * @param power - Exponent value. + * @returns Powered field element. + * @throws If the exponent is negative. {@link Error} + * @example + * Raise one field element to a public exponent. + * + * ```ts + * import { Field, FpPow } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpPow(Fp, 3n, 5n); + * ``` + */ +export function FpPow(Fp, num, power) { + const F = Fp; + if (power < _0n) + throw new Error('invalid exponent, negatives unsupported'); + if (power === _0n) + return F.ONE; + if (power === _1n) + return num; + let p = F.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) + p = F.mul(p, d); + d = F.sqr(d); + power >>= _1n; + } + return p; +} +/** + * Efficiently invert an array of Field elements. + * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled. + * @param Fp - Field implementation. + * @param nums - Values to invert. + * @param passZero - map 0 to 0 (instead of undefined) + * @returns Inverted values. + * @example + * Invert several field elements with one shared inversion. + * + * ```ts + * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]); + * ``` + */ +export function FpInvertBatch(Fp, nums, passZero = false) { + const F = Fp; + const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined); + // Walk from first to last, multiply them by each other MOD p + const multipliedAcc = nums.reduce((acc, num, i) => { + if (F.is0(num)) + return acc; + inverted[i] = acc; + return F.mul(acc, num); + }, F.ONE); + // Invert last element + const invertedAcc = F.inv(multipliedAcc); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (F.is0(num)) + return acc; + inverted[i] = F.mul(acc, inverted[i]); + return F.mul(acc, num); + }, invertedAcc); + return inverted; +} +/** + * @param Fp - Field implementation. + * @param lhs - Dividend value. + * @param rhs - Divisor value. + * @returns Division result. + * @throws If the divisor is non-invertible. {@link Error} + * @example + * Divide one field element by another. + * + * ```ts + * import { Field, FpDiv } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpDiv(Fp, 6n, 3n); + * ``` + */ +export function FpDiv(Fp, lhs, rhs) { + const F = Fp; + return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs)); +} +/** + * Legendre symbol. + * Legendre constant is used to calculate Legendre symbol (a | p) + * which denotes the value of a^((p-1)/2) (mod p). + * + * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue + * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue + * * (a | p) ≡ 0 if a ≡ 0 (mod p) + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns Legendre symbol. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Compute the Legendre symbol of one field element. + * + * ```ts + * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const symbol = FpLegendre(Fp, 4n); + * ``` + */ +export function FpLegendre(Fp, n) { + const F = Fp; + // We can use 3rd argument as optional cache of this value + // but seems unneeded for now. The operation is very fast. + const p1mod2 = (F.ORDER - _1n) / _2n; + const powered = F.pow(n, p1mod2); + const yes = F.eql(powered, F.ONE); + const zero = F.eql(powered, F.ZERO); + const no = F.eql(powered, F.neg(F.ONE)); + if (!yes && !zero && !no) + throw new Error('invalid Legendre symbol result'); + return yes ? 1 : zero ? 0 : -1; +} +/** + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic + * residue" terminology often reserves that name for the non-zero square class. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Check whether one field element has a square root in the field. + * + * ```ts + * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const isSquare = FpIsSquare(Fp, 4n); + * ``` + */ +export function FpIsSquare(Fp, n) { + const l = FpLegendre(Fp, n); + // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0. + return l !== -1; +} +/** + * @param n - Curve order. Callers are expected to pass a positive order. + * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached + * value when overriding the derived bit length. + * @returns Byte and bit lengths. + * @throws If the order or cached bit length is invalid. {@link Error} + * @example + * Measure the encoding sizes needed for one modulus. + * + * ```ts + * nLength(255n); + * ``` + */ +export function nLength(n, nBitLength) { + // Bit size, byte size of CURVE.n + if (nBitLength !== undefined) + anumber(nBitLength); + if (n <= _0n) + throw new Error('invalid n length: expected positive n, got ' + n); + if (nBitLength !== undefined && nBitLength < 1) + throw new Error('invalid n length: expected positive bit length, got ' + nBitLength); + const bits = bitLen(n); + // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison + // any math that relies on the derived field metadata. + if (nBitLength !== undefined && nBitLength < bits) + throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`); + const _nBitLength = nBitLength !== undefined ? nBitLength : bits; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the +// cached helper write would keep the field surface externally mutable. +const FIELD_SQRT = new WeakMap(); +class _Field { + ORDER; + BITS; + BYTES; + isLE; + ZERO = _0n; + ONE = _1n; + _lengths; + _mod; + constructor(ORDER, opts = {}) { + // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv + // would stop modeling field arithmetic. + if (ORDER <= _1n) + throw new Error('invalid field: expected ORDER > 1, got ' + ORDER); + let _nbitLength = undefined; + this.isLE = false; + if (opts != null && typeof opts === 'object') { + // Cached bit lengths are trusted here and should already be positive / consistent with ORDER. + if (typeof opts.BITS === 'number') + _nbitLength = opts.BITS; + if (typeof opts.sqrt === 'function') + // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties + // explicitly instead of relying on writable prototype shadowing via assignment. + Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true }); + if (typeof opts.isLE === 'boolean') + this.isLE = opts.isLE; + if (opts.allowedLengths) + this._lengths = Object.freeze(opts.allowedLengths.slice()); + if (typeof opts.modFromBytes === 'boolean') + this._mod = opts.modFromBytes; + } + const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength); + if (nByteLength > 2048) + throw new Error('invalid field: expected ORDER of <= 2048 bytes'); + this.ORDER = ORDER; + this.BITS = nBitLength; + this.BYTES = nByteLength; + Object.freeze(this); + } + create(num) { + return mod(num, this.ORDER); + } + isValid(num) { + if (typeof num !== 'bigint') + throw new TypeError('invalid field element: expected bigint, got ' + typeof num); + return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible + } + is0(num) { + return num === _0n; + } + // is valid and invertible + isValidNot0(num) { + return !this.is0(num) && this.isValid(num); + } + isOdd(num) { + return (num & _1n) === _1n; + } + neg(num) { + return mod(-num, this.ORDER); + } + eql(lhs, rhs) { + return lhs === rhs; + } + sqr(num) { + return mod(num * num, this.ORDER); + } + add(lhs, rhs) { + return mod(lhs + rhs, this.ORDER); + } + sub(lhs, rhs) { + return mod(lhs - rhs, this.ORDER); + } + mul(lhs, rhs) { + return mod(lhs * rhs, this.ORDER); + } + pow(num, power) { + return FpPow(this, num, power); + } + div(lhs, rhs) { + return mod(lhs * invert(rhs, this.ORDER), this.ORDER); + } + // Same as above, but doesn't normalize + sqrN(num) { + return num * num; + } + addN(lhs, rhs) { + return lhs + rhs; + } + subN(lhs, rhs) { + return lhs - rhs; + } + mulN(lhs, rhs) { + return lhs * rhs; + } + inv(num) { + return invert(num, this.ORDER); + } + sqrt(num) { + // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping + // the field instance itself mutable. + let sqrt = FIELD_SQRT.get(this); + if (!sqrt) + FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER))); + return sqrt(this, num); + } + toBytes(num) { + // Serialize fixed-width limbs without re-validating the field range. Callers that need a + // canonical encoding must pass a valid element; some protocols intentionally serialize raw + // residues here and reduce or validate them elsewhere. + return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES); + } + fromBytes(bytes, skipValidation = false) { + abytes(bytes); + const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this; + if (allowedLengths) { + // `allowedLengths` must list real positive byte lengths; otherwise empty input would get + // padded into zero and silently decode as a field element. + if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) { + throw new Error('Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length); + } + const padded = new Uint8Array(BYTES); + // isLE add 0 to right, !isLE to the left. + padded.set(bytes, isLE ? 0 : padded.length - bytes.length); + bytes = padded; + } + if (bytes.length !== BYTES) + throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length); + let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + if (modFromBytes) + scalar = mod(scalar, ORDER); + if (!skipValidation) + if (!this.isValid(scalar)) + throw new Error('invalid field element: outside of range 0..ORDER'); + // Range validation is optional here because some protocols intentionally decode raw residues + // and reduce or validate them elsewhere. + return scalar; + } + // TODO: we don't need it here, move out to separate fn + invertBatch(lst) { + return FpInvertBatch(this, lst); + } + // We can't move this out because Fp6, Fp12 implement it + // and it's unclear what to return in there. + cmov(a, b, condition) { + // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject + // non-boolean selectors here instead of letting JS truthiness silently change arithmetic. + abool(condition, 'condition'); + return condition ? b : a; + } +} +// Freeze the shared method surface too; otherwise callers can still poison every Field instance by +// monkey-patching `_Field.prototype` even if each instance is frozen. +Object.freeze(_Field.prototype); +/** + * Creates a finite field. Major performance optimizations: + * * 1. Denormalized operations like mulN instead of mul. + * * 2. Identical object shape: never add or remove keys. + * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`. + * Fragile: always run a benchmark on a change. + * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for + * all elements for performance and protocol-flexibility reasons; callers are responsible for + * supplying valid elements when they need canonical field behavior. + * This is low-level code, please make sure you know what you're doing. + * + * Note about field properties: + * * CHARACTERISTIC p = prime number, number of elements in main subgroup. + * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`. + * + * @param ORDER - field order, probably prime, or could be composite + * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}. + * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight + * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`. + * @example + * Construct one prime field with optional overrides. + * + * ```ts + * Field(11n); + * ``` + */ +export function Field(ORDER, opts = {}) { + return new _Field(ORDER, opts); +} +// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)? +// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG). +// which mean we cannot force this via opts. +// Not sure what to do with randomBytes, we can accept it inside opts if wanted. +// Probably need to export getMinHashLength somewhere? +// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) { +// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES; +// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes? +// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); +// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 +// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n; +// return reduced; +// }, +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`, + * which is the only square root but is not odd. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the odd square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtOdd(Fp, 4n); + * ``` + */ +export function FpSqrtOdd(Fp, elm) { + const F = Fp; + if (!F.isOdd) + throw new Error("Field doesn't have isOdd"); + const root = F.sqrt(elm); + return F.isOdd(root) ? root : F.neg(root); +} +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Even square root. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the even square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtEven(Fp, 4n); + * ``` + */ +export function FpSqrtEven(Fp, elm) { + const F = Fp; + if (!F.isOdd) + throw new Error("Field doesn't have isOdd"); + const root = F.sqrt(elm); + return F.isOdd(root) ? F.neg(root) : root; +} +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an + * order greater than 1. + * @returns byte length of field + * @throws If the field order is not a bigint. {@link Error} + * @example + * Read the fixed-width byte length of one field. + * + * ```ts + * getFieldBytesLength(255n); + * ``` + */ +export function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== 'bigint') + throw new Error('field order must be bigint'); + // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate. + if (fieldOrder <= _1n) + throw new Error('field order must be greater than 1'); + // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1. + const bitLength = bitLen(fieldOrder - _1n); + return Math.ceil(bitLength / 8); +} +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger + * absolute floor for policy reasons. + * @param fieldOrder - number of field elements greater than 1, usually CURVE.n. + * @returns byte length of target hash + * @throws If the field order is invalid. {@link Error} + * @example + * Compute the minimum hash length needed for field reduction. + * + * ```ts + * getMinHashLength(255n); + * ``` + */ +export function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard + * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look + * accidentally acceptable for real scalar derivation. + * 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}, + * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and + * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380 + * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`. + * @param key - Uniform input bytes. + * @param fieldOrder - Size of subgroup. + * @param isLE - interpret hash bytes as LE num + * @returns valid private scalar + * @throws If the hash length or field order is invalid for scalar reduction. {@link Error} + * @example + * Map hash output into a private scalar range. + * + * ```ts + * mapHashToField(new Uint8Array(48).fill(1), 255n); + * ``` + */ +export function mapHashToField(key, fieldOrder, isLE = false) { + abytes(key); + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = Math.max(getMinHashLength(fieldOrder), 16); + // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge + // inputs: easier to reason about JS timing / allocation behavior. + if (len < minLen || len > 1024) + throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len); + const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} +//# sourceMappingURL=modular.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/modular.js.map b/node_modules/@noble/curves/abstract/modular.js.map new file mode 100644 index 0000000..21f9457 --- /dev/null +++ b/node_modules/@noble/curves/abstract/modular.js.map @@ -0,0 +1 @@ +{"version":3,"file":"modular.js","sourceRoot":"","sources":["../src/abstract/modular.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EACL,KAAK,EACL,MAAM,EACN,OAAO,EACP,WAAW,EACX,MAAM,EACN,eAAe,EACf,eAAe,EACf,eAAe,EACf,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C,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,gBAAgB,CAAC,UAAkB;IACjD,MAAM,MAAM,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IAC/C,OAAO,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;AACxC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,cAAc,CAC5B,GAAqB,EACrB,UAAkB,EAClB,IAAI,GAAG,KAAK;IAEZ,MAAM,CAAC,GAAG,CAAC,CAAC;IACZ,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC;IACvB,MAAM,QAAQ,GAAG,mBAAmB,CAAC,UAAU,CAAC,CAAC;IACjD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC;IAC1D,+FAA+F;IAC/F,kEAAkE;IAClE,IAAI,GAAG,GAAG,MAAM,IAAI,GAAG,GAAG,IAAI;QAC5B,MAAM,IAAI,KAAK,CAAC,WAAW,GAAG,MAAM,GAAG,4BAA4B,GAAG,GAAG,CAAC,CAAC;IAC7E,MAAM,GAAG,GAAG,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAC/D,+EAA+E;IAC/E,MAAM,OAAO,GAAG,GAAG,CAAC,GAAG,EAAE,UAAU,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;IACjD,OAAO,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACxF,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.d.ts b/node_modules/@noble/curves/abstract/montgomery.d.ts new file mode 100644 index 0000000..836cd93 --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.d.ts @@ -0,0 +1,96 @@ +/** + * Montgomery curve methods. It's not really whole montgomery curve, + * just bunch of very specific methods for X25519 / X448 from + * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748) + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type TArg, type TRet } from '../utils.ts'; +import { type CurveLengths } from './curve.ts'; +/** Curve-specific hooks required to build one X25519/X448 helper. */ +export type MontgomeryOpts = { + /** Prime field modulus. */ + P: bigint; + /** RFC 7748 variant name. */ + type: 'x25519' | 'x448'; + /** + * Clamp or otherwise normalize one scalar byte string before use. + * @param bytes - Raw secret scalar bytes. + * @returns Adjusted scalar bytes ready for Montgomery multiplication. + */ + adjustScalarBytes: (bytes: TArg) => TRet; + /** + * Invert one field element with exponentiation by `p - 2`. + * @param x - Field element to invert. + * @returns Multiplicative inverse of `x`. + */ + powPminus2: (x: bigint) => bigint; + /** + * Optional randomness source for `keygen()` and `utils.randomSecretKey()`. + * Receives the requested byte length and returns fresh random bytes. + */ + randomBytes?: (bytesLength?: number) => TRet; +}; +/** Public X25519/X448 ECDH API built on a Montgomery ladder. */ +export type MontgomeryECDH = { + /** + * Multiply one scalar by one Montgomery `u` coordinate. + * @param scalar - Secret scalar bytes. + * @param u - Public Montgomery `u` coordinate. + * @returns Shared point encoded as bytes. + */ + scalarMult: (scalar: TArg, u: TArg) => TRet; + /** + * Multiply one scalar by the curve base point. + * @param scalar - Secret scalar bytes. + * @returns Public key bytes. + */ + scalarMultBase: (scalar: TArg) => TRet; + /** + * Derive a shared secret from a local secret key and peer public key. + * @param secretKeyA - Local secret key bytes. + * @param publicKeyB - Peer public key bytes. + * Rejects low-order public inputs instead of returning the all-zero shared secret. + * @returns Shared secret bytes. + */ + getSharedSecret: (secretKeyA: TArg, publicKeyB: TArg) => TRet; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: TArg) => TRet; + /** Utility helpers for secret-key generation. */ + utils: { + /** Generate one random secret key with the curve's expected byte length. */ + randomSecretKey: () => TRet; + }; + /** Encoded Montgomery base point `u`. */ + GuBytes: TRet; + /** Public lengths for keys and seeds. */ + lengths: CurveLengths; + /** + * Generate one random secret/public keypair. + * @param seed - Optional seed bytes to use instead of random generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; +}; +/** + * @param curveDef - Montgomery curve definition. + * @returns ECDH helper namespace. + * @throws If the curve definition or derived shared point is invalid. {@link Error} + * @example + * Perform one X25519 key exchange through the generic Montgomery helper. + * + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export declare function montgomery(curveDef: TArg): TRet; +//# sourceMappingURL=montgomery.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.d.ts.map b/node_modules/@noble/curves/abstract/montgomery.d.ts.map new file mode 100644 index 0000000..a8df1c8 --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.d.ts","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EASL,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAAgB,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAO7D,qEAAqE;AACrE,MAAM,MAAM,cAAc,GAAG;IAC3B,2BAA2B;IAC3B,CAAC,EAAE,MAAM,CAAC;IACV,6BAA6B;IAC7B,IAAI,EAAE,QAAQ,GAAG,MAAM,CAAC;IACxB;;;;OAIG;IACH,iBAAiB,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,UAAU,CAAC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ACH,wBAAgB,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC,cAAc,CAAC,GAAG,IAAI,CAAC,cAAc,CAAC,CA0I/E"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.js b/node_modules/@noble/curves/abstract/montgomery.js new file mode 100644 index 0000000..2a5dcea --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.js @@ -0,0 +1,178 @@ +/** + * Montgomery curve methods. It's not really whole montgomery curve, + * just bunch of very specific methods for X25519 / X448 from + * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748) + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abytes, aInRange, bytesToNumberLE, copyBytes, numberToBytesLE, randomBytes, validateObject, } from "../utils.js"; +import { createKeygen } from "./curve.js"; +import { mod } from "./modular.js"; +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +function validateOpts(curve) { + // Validate constructor config eagerly, but do not call user-provided hooks here: + // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are + // enough to fail fast on malformed configs without consuming user state. + validateObject(curve, { + P: 'bigint', + type: 'string', + adjustScalarBytes: 'function', + powPminus2: 'function', + }, { + randomBytes: 'function', + }); + return Object.freeze({ ...curve }); +} +/** + * @param curveDef - Montgomery curve definition. + * @returns ECDH helper namespace. + * @throws If the curve definition or derived shared point is invalid. {@link Error} + * @example + * Perform one X25519 key exchange through the generic Montgomery helper. + * + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export function montgomery(curveDef) { + const CURVE = validateOpts(curveDef); + const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE; + const is25519 = type === 'x25519'; + if (!is25519 && type !== 'x448') + throw new Error('invalid type'); + const randomBytes_ = rand === undefined ? randomBytes : rand; + const montgomeryBits = is25519 ? 255 : 448; + const fieldLen = is25519 ? 32 : 56; + const Gu = is25519 ? BigInt(9) : BigInt(5); + // RFC 7748 #5: + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and + // (156326 - 2) / 4 = 39081 for curve448/X448 + // const a = is25519 ? 486662n : 156326n; + const a24 = is25519 ? BigInt(121665) : BigInt(39081); + // RFC: x25519 "the resulting integer is of the form 2^254 plus + // eight times a value between 0 and 2^251 - 1 (inclusive)" + // x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)" + const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447); + const maxAdded = is25519 + ? BigInt(8) * _2n ** BigInt(251) - _1n + : BigInt(4) * _2n ** BigInt(445) - _1n; + const maxScalar = minScalar + maxAdded + _1n; // (inclusive) + const modP = (n) => mod(n, P); + const GuBytes = encodeU(Gu); + function encodeU(u) { + return numberToBytesLE(modP(u), fieldLen); + } + function decodeU(u) { + const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate')); + // RFC: When receiving such an array, implementations of X25519 + // (but not X448) MUST mask the most significant bit in the final byte. + if (is25519) + _u[31] &= 127; // 0b0111_1111 + // RFC: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. The non-canonical + // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224 + // - 1 through 2^448 - 1 for X448. + return modP(bytesToNumberLE(_u)); + } + function decodeScalar(scalar) { + return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar')))); + } + function scalarMult(scalar, u) { + const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar)); + // Some public keys are useless, of low-order. Curve author doesn't think + // it needs to be validated, but we do it nonetheless. + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) + throw new Error('invalid private or public key received'); + return encodeU(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + function scalarMultBase(scalar) { + return scalarMult(scalar, GuBytes); + } + const getPublicKey = scalarMultBase; + const getSharedSecret = scalarMult; + // cswap from RFC7748 "example code" + function cswap(swap, x_2, x_3) { + // dummy = mask(swap) AND (x_2 XOR x_3) + // Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + // and x_3, computed, e.g., as mask(swap) = 0 - swap. + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy + x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy + return { x_2, x_3 }; + } + /** + * Montgomery x-only multiplication ladder for the selected X25519/X448 curve. + * @param pointU - decoded Montgomery u coordinate for the selected curve + * @param scalar - decoded clamped scalar by which the point is multiplied + * @returns resulting Montgomery u coordinate for the selected curve + */ + function montgomeryLadder(u, scalar) { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, minScalar, maxScalar); + const k = scalar; + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + ({ x_2, x_3 } = cswap(swap, x_2, x_3)); + ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3)); + swap = k_t; + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + ({ x_2, x_3 } = cswap(swap, x_2, x_3)); + ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3)); + const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent + return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2)) + } + const lengths = { + secretKey: fieldLen, + publicKey: fieldLen, + seed: fieldLen, + }; + const randomSecretKey = (seed) => { + seed = seed === undefined ? randomBytes_(fieldLen) : seed; + abytes(seed, lengths.seed, 'seed'); + // Reuse caller-supplied seed bytes verbatim; clamping is deferred until + // decodeScalar(...) when the secret key is actually used. + return seed; + }; + const utils = { randomSecretKey }; + Object.freeze(lengths); + Object.freeze(utils); + return Object.freeze({ + keygen: createKeygen(randomSecretKey, getPublicKey), + getSharedSecret, + getPublicKey, + scalarMult, + scalarMultBase, + utils, + GuBytes: GuBytes.slice(), + lengths, + }); +} +//# sourceMappingURL=montgomery.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/montgomery.js.map b/node_modules/@noble/curves/abstract/montgomery.js.map new file mode 100644 index 0000000..a848bba --- /dev/null +++ b/node_modules/@noble/curves/abstract/montgomery.js.map @@ -0,0 +1 @@ +{"version":3,"file":"montgomery.js","sourceRoot":"","sources":["../src/abstract/montgomery.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,sEAAsE;AACtE,OAAO,EACL,MAAM,EACN,QAAQ,EACR,eAAe,EACf,SAAS,EACT,eAAe,EACf,WAAW,EACX,cAAc,GAIf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,YAAY,EAAqB,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAEnC,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AACtB,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;AA4EtB,SAAS,YAAY,CAAC,KAA2B;IAC/C,iFAAiF;IACjF,0FAA0F;IAC1F,yEAAyE;IACzE,cAAc,CACZ,KAAK,EACL;QACE,CAAC,EAAE,QAAQ;QACX,IAAI,EAAE,QAAQ;QACd,iBAAiB,EAAE,UAAU;QAC7B,UAAU,EAAE,UAAU;KACvB,EACD;QACE,WAAW,EAAE,UAAU;KACxB,CACF,CAAC;IACF,OAAO,MAAM,CAAC,MAAM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;QACf,YAAY;QACZ,UAAU;QACV,cAAc;QACd,KAAK;QACL,OAAO,EAAE,OAAO,CAAC,KAAK,EAAsB;QAC5C,OAAO;KACR,CAAsB,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/oprf.d.ts b/node_modules/@noble/curves/abstract/oprf.d.ts new file mode 100644 index 0000000..0ebf1e0 --- /dev/null +++ b/node_modules/@noble/curves/abstract/oprf.d.ts @@ -0,0 +1,355 @@ +/** + * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups. + * https://www.rfc-editor.org/rfc/rfc9497 + * + +OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`: + +- Server cannot calculate Output by itself: it doesn't know Input +- Client cannot calculate Output by itself: it doesn't know server secretKey +- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't + link Input to some value. + +## Issues + +- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server + (solveable by domain separation in POPRF) +- High-level protocol needs to be constructed on top, because OPRF is low-level + +## Use cases + +1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE) + without revealing the password to the server. +2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their + private sets without revealing non-intersecting elements. +3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials + (e.g., Privacy Pass) using blind OPRF evaluation. +4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which + item they accessed. +5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping + queries private. +6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse + (e.g., CAPTCHA bypass) without compromising user privacy. + +## Modes + +- OPRF: simple mode, client doesn't need to know server public key +- VOPRF: verifiable mode. It lets the client verify that the server used the + secret key corresponding to a known public key +- POPRF: partially oblivious mode, VOPRF + domain separation + +There is also non-interactive mode (Evaluate), which creates Output +non-interactively with knowledge of the secret key. + +Flow: +- (once) Server generates secret and public keys, distributes public keys to clients + - deterministically: `deriveKeyPair` or just random: `generateKeyPair` +- Client blinds input: `blind(secretInput)` +- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client +- Client creates output using result of evaluation via 'finalize' + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { randomBytes, type TArg, type TRet } from '../utils.ts'; +import { type CurvePoint, type CurvePointCons } from './curve.ts'; +import { type H2CDSTOpts } from './hash-to-curve.ts'; +/** Serialized group element passed between OPRF participants. */ +export type PointBytes = Uint8Array; +/** Serialized scalar used for blinds and server secret keys. */ +export type ScalarBytes = Uint8Array; +/** Arbitrary byte input or output used by the OPRF protocol. */ +export type Bytes = Uint8Array; +/** Cryptographically secure byte generator used for blinds and proofs. */ +export type RNG = typeof randomBytes; +/** Curve and hash hooks required to instantiate one OPRF ciphersuite. */ +export type OPRFOpts

> = { + /** Human-readable suite identifier used for domain separation. */ + name: string; + /** + * Prime-order group used by the OPRF construction. + * Kept generic because the suite returns serialized points. + */ + Point: CurvePointCons

; + /** + * Hash function used for transcripts, proofs, and outputs. + * @param msg - Message bytes to hash. + * @returns Digest bytes. + */ + hash(msg: TArg): TRet; + /** + * Hash arbitrary bytes into one scalar in the suite order. + * @param msg - Message bytes to map. + * @param options - Hash-to-field domain-separation options. See {@link H2CDSTOpts}. + * Implementations MUST treat `msg` and `options` as read-only. + * @returns Scalar in the suite order. + */ + hashToScalar(msg: TArg, options: TArg): bigint; + /** + * Hash arbitrary bytes directly onto one curve point. + * @param msg - Message bytes to map. + * @param options - Hash-to-curve domain-separation options. See {@link H2CDSTOpts}. + * Implementations MUST treat `msg` and `options` as read-only. + * @returns Point on the suite curve. + */ + hashToGroup(msg: TArg, options: TArg): P; +}; +/** Server keypair for one OPRF suite. */ +export type OPRFKeys = { + /** Secret scalar kept by the server. */ + secretKey: TRet; + /** Public point distributed to clients in verifiable modes. */ + publicKey: TRet; +}; +/** Result of the client-side blind step. */ +export type OPRFBlind = { + /** Secret blind scalar that the client keeps locally. */ + blind: TRet; + /** Blinded group element sent to the server. */ + blinded: TRet; +}; +/** Server response for one verifiable OPRF evaluation. */ +export type OPRFBlindEval = { + /** Evaluated group element returned by the server. */ + evaluated: TRet; + /** DLEQ proof binding the evaluation to the server public key. */ + proof: TRet; +}; +/** Server response for a batch of verifiable OPRF evaluations. */ +export type OPRFBlindEvalBatch = { + /** Evaluated group elements returned for each blinded input. */ + evaluated: TRet; + /** Batch proof covering all evaluated elements. */ + proof: TRet; +}; +/** One finalized transcript item used by batch verification helpers. */ +export type OPRFFinalizeItem = { + /** Original client input. */ + input: Bytes; + /** Secret blind scalar used for the input. */ + blind: ScalarBytes; + /** Evaluated point returned by the server. */ + evaluated: PointBytes; + /** Blinded point originally sent to the server. */ + blinded: PointBytes; +}; +/** Result of the POPRF client-side blind step with the tweaked server public key. */ +export type OPRFBlindTweaked = OPRFBlind & { + tweakedKey: TRet; +}; +/** + * Represents a full OPRF ciphersuite implementation according to RFC 9497. + * This object bundles the three protocol variants (OPRF, VOPRF, POPRF) for a specific + * prime-order group and hash function combination. + * + * @see https://www.rfc-editor.org/rfc/rfc9497.html + */ +export type OPRF = { + /** + * The unique identifier for the ciphersuite, e.g., "ristretto255-SHA512". + * This name is used for domain separation to prevent cross-protocol attacks. + */ + readonly name: string; + /** + * The base Oblivious Pseudorandom Function (OPRF) mode (mode 0x00). + * This is a two-party protocol between a client and a server to compute F(k, x) + * where 'k' is the server's key and 'x' is the client's input. + * + * The client learns the output F(k, x) but nothing about 'k'. + * The server learns nothing about 'x' or F(k, x). + * This mode is NOT verifiable; the client cannot prove the server used a specific key. + */ + readonly oprf: { + /** + * (Server-side) Generates a new random private/public key pair for the server. + * @returns A new key pair. + */ + generateKeyPair(): TRet; + /** + * (Server-side) Deterministically derives a private/public key pair from a seed. + * @param seed - A 32-byte cryptographically secure random seed. + * @param keyInfo - An optional byte string for domain separation. + * @returns The derived key pair. + */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + /** + * (Client-side) The first step of the protocol. The client blinds its private input. + * @param input - The client's private input bytes. + * @param rng - An optional cryptographically secure random number generator. + * @returns An object containing the `blind` scalar (which the client MUST keep secret) + * and the `blinded` element (which the client sends to the server). + */ + blind(input: TArg, rng?: RNG): TRet; + /** + * (Server-side) The second step. The server evaluates the client's blinded element + * using its secret key. + * @param secretKey - The server's private key. + * @param blinded - The blinded group element received from the client. + * @returns The evaluated group element, to be sent back to the client. + */ + blindEvaluate(secretKey: TArg, blinded: TArg): TRet; + /** + * (Client-side) The final step. The client unblinds the server's response to + * compute the final OPRF output. + * @param input - The original private input from the `blind` step. + * @param blind - The secret scalar from the `blind` step. + * @param evaluated - The evaluated group element received from the server. + * @returns The final OPRF output, `Hash(len(input)||input||len(unblinded)||unblinded||"Finalize")`. + */ + finalize(input: TArg, blind: TArg, evaluated: TArg): TRet; + }; + /** + * The Verifiable Oblivious Pseudorandom Function (VOPRF) mode (mode 0x01). + * This mode extends the base OPRF by providing a proof that the server used the + * secret key corresponding to its known public key. + */ + readonly voprf: { + /** (Server-side) Generates a key pair for the VOPRF mode. */ + generateKeyPair(): TRet; + /** (Server-side) Deterministically derives a key pair for the VOPRF mode. */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + /** (Client-side) Blinds the client's private input for the VOPRF protocol. */ + blind(input: TArg, rng?: RNG): TRet; + /** + * (Server-side) Evaluates the client's blinded element and generates a DLEQ proof + * of correctness. + * @param secretKey - The server's private key. + * @param publicKey - The server's public key, used in proof generation. + * @param blinded - The blinded group element received from the client. + * @param rng - An optional cryptographically secure random number generator for the proof. + * @returns The evaluated element and a proof of correct computation. + */ + blindEvaluate(secretKey: TArg, publicKey: TArg, blinded: TArg, rng?: RNG): TRet; + /** + * (Server-side) An optimized batch version of `blindEvaluate`. It evaluates multiple + * blinded elements and produces a single, constant-size proof for the entire batch, + * amortizing the cost of proof generation. + * @param secretKey - The server's private key. + * @param publicKey - The server's public key. + * @param blinded - An array of blinded group elements from one or more clients. + * @param rng - An optional cryptographically secure random number generator for the proof. + * @returns An array of evaluated elements and a single proof for the batch. + */ + blindEvaluateBatch(secretKey: TArg, publicKey: TArg, blinded: TArg, rng?: RNG): TRet; + /** + * (Client-side) The final step. The client verifies the server's proof, and if valid, + * unblinds the result to compute the final VOPRF output. + * @param input - The original private input. + * @param blind - The secret scalar from the `blind` step. + * @param evaluated - The evaluated element from the server. + * @param blinded - The blinded element sent to the server (needed for proof verification). + * @param publicKey - The server's public key against which the proof is verified. + * @param proof - The DLEQ proof from the server. + * @returns The final VOPRF output. + * @throws If the proof verification fails. {@link Error} + */ + finalize(input: TArg, blind: TArg, evaluated: TArg, blinded: TArg, publicKey: TArg, proof: TArg): TRet; + /** + * (Client-side) The batch-aware version of `finalize`. It verifies a single batch proof + * against a list of corresponding inputs and outputs. + * @param items - An array of objects, each containing the parameters for a single finalization. + * @param publicKey - The server's public key. + * @param proof - The single DLEQ proof for the entire batch. + * @returns An array of final VOPRF outputs, one for each item in the input. + * @throws If the proof verification fails. {@link Error} + */ + finalizeBatch(items: TArg, publicKey: TArg, proof: TArg): TRet; + }; + /** + * A factory for the Partially Oblivious Pseudorandom Function (POPRF) mode (mode 0x02). + * This mode extends VOPRF to include a public `info` parameter, known to both client and + * server, which is cryptographically bound to the final output. + * This is useful for domain separation at the application level. + * @param info - A public byte string to be mixed into the computation. + * @returns An object with the POPRF protocol functions. + */ + readonly poprf: (info: TArg) => { + /** (Server-side) Generates a key pair for the POPRF mode. */ + generateKeyPair(): TRet; + /** (Server-side) Deterministically derives a key pair for the POPRF mode. */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + /** + * (Client-side) Blinds the client's private input and computes the "tweaked key". + * The tweaked key is a public value derived from the server's public key and the public `info`. + * @param input - The client's private input. + * @param publicKey - The server's public key. + * @param rng - An optional cryptographically secure random number generator. + * @returns The `blind`, `blinded` element, and the `tweakedKey` + * the client uses for verification. + */ + blind(input: TArg, publicKey: TArg, rng?: RNG): TRet; + /** + * (Server-side) Evaluates the blinded element using a key derived from + * its secret key and the public `info`. + * It generates a DLEQ proof against the tweaked key. + * @param secretKey - The server's private key. + * @param blinded - The blinded element from the client. + * @param rng - An optional RNG for the proof. + * @returns The evaluated element and a proof of correct computation. + */ + blindEvaluate(secretKey: TArg, blinded: TArg, rng?: RNG): TRet; + /** + * (Server-side) A batch-aware version of `blindEvaluate` for the POPRF mode. + * @param secretKey - The server's private key. + * @param blinded - An array of blinded elements. + * @param rng - An optional RNG for the proof. + * @returns An array of evaluated elements and a single proof for the batch. + */ + blindEvaluateBatch(secretKey: TArg, blinded: TArg, rng: RNG): TRet; + /** + * (Client-side) A batch-aware version of `finalize` for the POPRF mode. + * It verifies the proof against the tweaked key. + * @param items - An array containing the parameters for each finalization. + * @param proof - The single DLEQ proof for the batch. + * @param tweakedKey - The tweaked key corresponding to the proof. + * All items must share the same `info` and `publicKey`. + * @returns An array of final POPRF outputs. + * @throws If proof verification fails. {@link Error} + */ + finalizeBatch(items: TArg, proof: TArg, tweakedKey: TArg): TRet; + /** + * (Client-side) Finalizes the POPRF protocol. It verifies the server's proof against the + * `tweakedKey` computed in the `blind` step. The final output is bound to the public `info`. + * @param input - The original private input. + * @param blind - The secret scalar. + * @param evaluated - The evaluated element from the server. + * @param blinded - The blinded element sent to the server. + * @param proof - The DLEQ proof from the server. + * @param tweakedKey - The public tweaked key computed by the client during the `blind` step. + * @returns The final POPRF output. + * @throws If proof verification fails. {@link Error} + */ + finalize(input: TArg, blind: TArg, evaluated: TArg, blinded: TArg, proof: TArg, tweakedKey: TArg): TRet; + /** + * A non-interactive evaluation function for an entity that knows all inputs. + * Computes the final POPRF output directly. Useful for testing or specific applications + * where the server needs to compute the output for a known input. + * @param secretKey - The server's private key. + * @param input - The client's private input. + * @returns The final POPRF output. + */ + evaluate(secretKey: TArg, input: TArg): TRet; + }; +}; +/** + * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}. + * @returns OPRF helper namespace. + * @example + * Instantiate an OPRF suite from curve-specific hashing hooks. + * + * ```ts + * import { createOPRF } from '@noble/curves/abstract/oprf.js'; + * import { p256, p256_hasher } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const oprf = createOPRF({ + * name: 'P256-SHA256', + * Point: p256.Point, + * hash: sha256, + * hashToGroup: p256_hasher.hashToCurve, + * hashToScalar: p256_hasher.hashToScalar, + * }); + * const keys = oprf.oprf.generateKeyPair(); + * ``` + */ +export declare function createOPRF

>(opts: OPRFOpts

): TRet; +//# sourceMappingURL=oprf.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/oprf.d.ts.map b/node_modules/@noble/curves/abstract/oprf.d.ts.map new file mode 100644 index 0000000..91c8ec9 --- /dev/null +++ b/node_modules/@noble/curves/abstract/oprf.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"oprf.d.ts","sourceRoot":"","sources":["../src/abstract/oprf.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,sEAAsE;AACtE,OAAO,EAOL,WAAW,EAEX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAAgC,KAAK,UAAU,EAAE,KAAK,cAAc,EAAE,MAAM,YAAY,CAAC;AAChG,OAAO,EAAe,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAIlE,iEAAiE;AACjE,MAAM,MAAM,UAAU,GAAG,UAAU,CAAC;AACpC,gEAAgE;AAChE,MAAM,MAAM,WAAW,GAAG,UAAU,CAAC;AACrC,gEAAgE;AAChE,MAAM,MAAM,KAAK,GAAG,UAAU,CAAC;AAE/B,0EAA0E;AAC1E,MAAM,MAAM,GAAG,GAAG,OAAO,WAAW,CAAC;AAErC,yEAAyE;AACzE,MAAM,MAAM,QAAQ,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI;IACnD,kEAAkE;IAClE,IAAI,EAAE,M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QAAQ,CACN,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,EAClB,KAAK,EAAE,IAAI,CAAC,WAAW,CAAC,EACxB,SAAS,EAAE,IAAI,CAAC,UAAU,CAAC,EAC3B,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,EACzB,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,EAClB,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC,GAC3B,IAAI,CAAC,KAAK,CAAC,CAAC;QAEf;;;;;;;WAOG;QACH,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC;KACzE,CAAC;CACH,CAAC;AAGF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,UAAU,CAAC,CAAC,SAAS,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,CAmWtF"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/oprf.js b/node_modules/@noble/curves/abstract/oprf.js new file mode 100644 index 0000000..32dc1f0 --- /dev/null +++ b/node_modules/@noble/curves/abstract/oprf.js @@ -0,0 +1,356 @@ +/** + * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups. + * https://www.rfc-editor.org/rfc/rfc9497 + * + +OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`: + +- Server cannot calculate Output by itself: it doesn't know Input +- Client cannot calculate Output by itself: it doesn't know server secretKey +- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't + link Input to some value. + +## Issues + +- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server + (solveable by domain separation in POPRF) +- High-level protocol needs to be constructed on top, because OPRF is low-level + +## Use cases + +1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE) + without revealing the password to the server. +2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their + private sets without revealing non-intersecting elements. +3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials + (e.g., Privacy Pass) using blind OPRF evaluation. +4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which + item they accessed. +5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping + queries private. +6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse + (e.g., CAPTCHA bypass) without compromising user privacy. + +## Modes + +- OPRF: simple mode, client doesn't need to know server public key +- VOPRF: verifiable mode. It lets the client verify that the server used the + secret key corresponding to a known public key +- POPRF: partially oblivious mode, VOPRF + domain separation + +There is also non-interactive mode (Evaluate), which creates Output +non-interactively with knowledge of the secret key. + +Flow: +- (once) Server generates secret and public keys, distributes public keys to clients + - deterministically: `deriveKeyPair` or just random: `generateKeyPair` +- Client blinds input: `blind(secretInput)` +- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client +- Client creates output using result of evaluation via 'finalize' + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abytes, asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, randomBytes, validateObject, } from "../utils.js"; +import { pippenger, validatePointCons } from "./curve.js"; +import { _DST_scalar } from "./hash-to-curve.js"; +import { getMinHashLength, mapHashToField } from "./modular.js"; +const _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar); +// welcome to generic hell +/** + * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}. + * @returns OPRF helper namespace. + * @example + * Instantiate an OPRF suite from curve-specific hashing hooks. + * + * ```ts + * import { createOPRF } from '@noble/curves/abstract/oprf.js'; + * import { p256, p256_hasher } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const oprf = createOPRF({ + * name: 'P256-SHA256', + * Point: p256.Point, + * hash: sha256, + * hashToGroup: p256_hasher.hashToCurve, + * hashToScalar: p256_hasher.hashToScalar, + * }); + * const keys = oprf.oprf.generateKeyPair(); + * ``` + */ +export function createOPRF(opts) { + validateObject(opts, { + name: 'string', + hash: 'function', + hashToScalar: 'function', + hashToGroup: 'function', + }); + // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that + // OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness. + validatePointCons(opts.Point); + const { name, Point, hash } = opts; + const { Fn } = Point; + const hashToGroup = (msg, ctx) => opts.hashToGroup(msg, { + DST: concatBytes(asciiToBytes('HashToGroup-'), ctx), + }); + const hashToScalarPrefixed = (msg, ctx) => opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) }); + const randomScalar = (rng = randomBytes) => { + // RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys + // both rely on keeping this helper in the `1..n-1` range. + const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE); + // We cannot use Fn.fromBytes here, because field + // can have different number of bytes (like ed448) + return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t); + }; + const msm = (points, scalars) => pippenger(Point, points, scalars); + const getCtx = (mode) => concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name)); + const ctxOPRF = getCtx(0x00); + const ctxVOPRF = getCtx(0x01); + const ctxPOPRF = getCtx(0x02); + function encode(...args) { + const res = []; + for (const a of args) { + if (typeof a === 'number') + res.push(numberToBytesBE(a, 2)); + else if (typeof a === 'string') + res.push(asciiToBytes(a)); + else { + abytes(a); + res.push(numberToBytesBE(a.length, 2), a); + } + } + // No wipe here, since will modify actual bytes + return concatBytes(...res); + } + const inputBytes = (title, bytes) => { + abytes(bytes, undefined, title); + // RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are + // length-prefixed with two bytes before use throughout the protocol. + if (bytes.length > 0xffff) + throw new Error(`"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}`); + return bytes; + }; + const hashInput = (...bytes) => hash(encode(...bytes, 'Finalize')); + function getTranscripts(B, C, D, ctx) { + const Bm = B.toBytes(); + const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx))); + const res = []; + for (let i = 0; i < C.length; i++) { + const Ci = C[i].toBytes(); + const Di = D[i].toBytes(); + const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx); + res.push(di); + } + return res; + } + function computeComposites(B, C, D, ctx) { + const T = getTranscripts(B, C, D, ctx); + const M = msm(C, T); + const Z = msm(D, T); + return { M, Z }; + } + function computeCompositesFast(k, B, C, D, ctx) { + const T = getTranscripts(B, C, D, ctx); + const M = msm(C, T); + // RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(), + // then uses the server shortcut Z = k * M instead of a second MSM over D. + const Z = M.multiply(k); + return { M, Z }; + } + function challengeTranscript(B, M, Z, t2, t3, ctx) { + const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes()); + return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx); + } + function generateProof(ctx, k, B, C, D, rng) { + const { M, Z } = computeCompositesFast(k, B, C, D, ctx); + const r = randomScalar(rng); + const t2 = Point.BASE.multiply(r); + const t3 = M.multiply(r); + const c = challengeTranscript(B, M, Z, t2, t3, ctx); + const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k + return concatBytes(...[c, s].map((i) => Fn.toBytes(i))); + } + function verifyProof(ctx, B, C, D, proof) { + abytes(proof, 2 * Fn.BYTES); + const { M, Z } = computeComposites(B, C, D, ctx); + const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => Fn.fromBytes(f)); + const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B + const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z + const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx); + if (!Fn.eql(c, expectedC)) + throw new Error('proof verification failed'); + } + function generateKeyPair() { + const skS = randomScalar(); + const pkS = Point.BASE.multiply(skS); + return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() }; + } + function deriveKeyPair(ctx, seed, info) { + // RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already + // documents a 32-byte seed instead of generic input keying material. + abytes(seed, 32, 'seed'); + info = inputBytes('keyInfo', info); + const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx); + const msg = concatBytes(seed, encode(info), Uint8Array.of(0)); + for (let counter = 0; counter <= 255; counter++) { + msg[msg.length - 1] = counter; + const skS = opts.hashToScalar(msg, { DST: dst }); + if (Fn.is0(skS)) + continue; // should not happen + return { + secretKey: Fn.toBytes(skS), + publicKey: Point.BASE.multiply(skS).toBytes(), + }; + } + throw new Error('Cannot derive key'); + } + const wirePoint = (label, bytes) => { + const point = Point.fromBytes(bytes); + // RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire + // after deserialization, even if the suite decoder itself accepts the identity encoding. + if (point.equals(Point.ZERO)) + throw new Error(label + ' point at infinity'); + return point; + }; + function blind(ctx, input, rng = randomBytes) { + input = inputBytes('input', input); + const blind = randomScalar(rng); + const inputPoint = hashToGroup(input, ctx); + if (inputPoint.equals(Point.ZERO)) + throw new Error('Input point at infinity'); + const blinded = inputPoint.multiply(blind); + return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() }; + } + function evaluate(ctx, secretKey, input) { + input = inputBytes('input', input); + const skS = Fn.fromBytes(secretKey); + const inputPoint = hashToGroup(input, ctx); + if (inputPoint.equals(Point.ZERO)) + throw new Error('Input point at infinity'); + const unblinded = inputPoint.multiply(skS).toBytes(); + return hashInput(input, unblinded); + } + const oprf = Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxOPRF, seed, keyInfo), + blind: (input, rng = randomBytes) => blind(ctxOPRF, input, rng), + blindEvaluate(secretKey, blindedPoint) { + const skS = Fn.fromBytes(secretKey); + const elm = wirePoint('blinded', blindedPoint); + return elm.multiply(skS).toBytes(); + }, + finalize(input, blindBytes, evaluatedBytes) { + input = inputBytes('input', input); + const blind = Fn.fromBytes(blindBytes); + const evalPoint = wirePoint('evaluated', evaluatedBytes); + const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes(); + return hashInput(input, unblinded); + }, + evaluate: (secretKey, input) => evaluate(ctxOPRF, secretKey, input), + }); + const voprf = Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxVOPRF, seed, keyInfo), + blind: (input, rng = randomBytes) => blind(ctxVOPRF, input, rng), + blindEvaluateBatch(secretKey, publicKey, blinded, rng = randomBytes) { + if (!Array.isArray(blinded)) + throw new Error('expected array'); + const skS = Fn.fromBytes(secretKey); + const pkS = wirePoint('public key', publicKey); + const blindedPoints = blinded.map((i) => wirePoint('blinded', i)); + const evaluated = blindedPoints.map((i) => i.multiply(skS)); + const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng); + return { evaluated: evaluated.map((i) => i.toBytes()), proof }; + }, + blindEvaluate(secretKey, publicKey, blinded, rng = randomBytes) { + const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng); + return { evaluated: res.evaluated[0], proof: res.proof }; + }, + finalizeBatch(items, publicKey, proof) { + if (!Array.isArray(items)) + throw new Error('expected array'); + const pkS = wirePoint('public key', publicKey); + const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded)); + const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated)); + verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof); + return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated)); + }, + finalize(input, blind, evaluated, blinded, publicKey, proof) { + return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0]; + }, + evaluate: (secretKey, input) => evaluate(ctxVOPRF, secretKey, input), + }); + // NOTE: info is domain separation + const poprf = (info) => { + info = inputBytes('info', info); + const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF); + const T = Point.BASE.multiply(m); + return Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed, keyInfo) => deriveKeyPair(ctxPOPRF, seed, keyInfo), + blind(input, publicKey, rng = randomBytes) { + input = inputBytes('input', input); + const pkS = wirePoint('public key', publicKey); + const tweakedKey = T.add(pkS); + if (tweakedKey.equals(Point.ZERO)) + throw new Error('tweakedKey point at infinity'); + const blind = randomScalar(rng); + const inputPoint = hashToGroup(input, ctxPOPRF); + if (inputPoint.equals(Point.ZERO)) + throw new Error('Input point at infinity'); + const blindedPoint = inputPoint.multiply(blind); + return { + blind: Fn.toBytes(blind), + blinded: blindedPoint.toBytes(), + tweakedKey: tweakedKey.toBytes(), + }; + }, + blindEvaluateBatch(secretKey, blinded, rng = randomBytes) { + if (!Array.isArray(blinded)) + throw new Error('expected array'); + const skS = Fn.fromBytes(secretKey); + const t = Fn.add(skS, m); + // "Hence, this error can be a signal for the server to replace its + // private key". We throw inside; this should be impossible. + const invT = Fn.inv(t); + const blindedPoints = blinded.map((i) => wirePoint('blinded', i)); + const evalPoints = blindedPoints.map((i) => i.multiply(invT)); + const tweakedKey = Point.BASE.multiply(t); + const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng); + return { evaluated: evalPoints.map((i) => i.toBytes()), proof }; + }, + blindEvaluate(secretKey, blinded, rng = randomBytes) { + const res = this.blindEvaluateBatch(secretKey, [blinded], rng); + return { evaluated: res.evaluated[0], proof: res.proof }; + }, + finalizeBatch(items, proof, tweakedKey) { + if (!Array.isArray(items)) + throw new Error('expected array'); + const inputs = items.map((i) => inputBytes('input', i.input)); + const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated)); + verifyProof(ctxPOPRF, wirePoint('tweakedKey', tweakedKey), evalPoints, items.map((i) => wirePoint('blinded', i.blinded)), proof); + return items.map((i, j) => { + const blind = Fn.fromBytes(i.blind); + const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes(); + return hashInput(inputs[j], info, point); + }); + }, + finalize(input, blind, evaluated, blinded, proof, tweakedKey) { + return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0]; + }, + evaluate(secretKey, input) { + input = inputBytes('input', input); + const skS = Fn.fromBytes(secretKey); + const inputPoint = hashToGroup(input, ctxPOPRF); + if (inputPoint.equals(Point.ZERO)) + throw new Error('Input point at infinity'); + const t = Fn.add(skS, m); + const invT = Fn.inv(t); + const unblinded = inputPoint.multiply(invT).toBytes(); + return hashInput(input, info, unblinded); + }, + }); + }; + const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) }; + return Object.freeze(res); +} +//# sourceMappingURL=oprf.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/oprf.js.map b/node_modules/@noble/curves/abstract/oprf.js.map new file mode 100644 index 0000000..6d6380f --- /dev/null +++ b/node_modules/@noble/curves/abstract/oprf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"oprf.js","sourceRoot":"","sources":["../src/abstract/oprf.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmDG;AACH,sEAAsE;AACtE,OAAO,EACL,MAAM,EACN,YAAY,EACZ,eAAe,EACf,eAAe,EACf,WAAW,EACX,eAAe,EACf,WAAW,EACX,cAAc,GAGf,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,iBAAiB,EAAwC,MAAM,YAAY,CAAC;AAChG,OAAO,EAAE,WAAW,EAAmB,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAShE,MAAM,gBAAgB,GAAG,eAAe,CAAC,YAAY,CAAC,WAAW,CAAC,CAAC;AAgVnE,0BAA0B;AAC1B;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,UAAU,CAA+B,IAAiB;IACxE,cAAc,CAAC,IAAI,EAAE;QACnB,IA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CAAC,CAAC;gBAC9E,MAAM,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;gBACzB,MAAM,IAAI,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;gBACvB,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,CAAC;gBACtD,OAAO,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;YAC3C,CAAC;SACF,CAAC,CAAC;IACL,CAAC,CAAC;IACF,MAAM,GAAG,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC;IACzE,OAAO,MAAM,CAAC,MAAM,CAAC,GAAG,CAAe,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.d.ts b/node_modules/@noble/curves/abstract/poseidon.d.ts new file mode 100644 index 0000000..441f435 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.d.ts @@ -0,0 +1,199 @@ +/** + * Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + * + * There are many poseidon variants with different constants. + * We don't provide them: you should construct them manually. + * Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type TArg, type TRet } from '../utils.ts'; +import { type IField } from './modular.ts'; +/** Core Poseidon permutation parameters shared by all variants. */ +export type PoseidonBasicOpts = { + /** Prime field used by the permutation. */ + Fp: IField; + /** Poseidon width `t = rate + capacity`. */ + t: number; + /** Number of full S-box rounds. */ + roundsFull: number; + /** Number of partial S-box rounds. */ + roundsPartial: number; + /** Whether to use the inverse S-box variant. */ + isSboxInverse?: boolean; +}; +/** Poseidon settings used by the Grain-LFSR constant generator. */ +export type PoseidonGrainOpts = PoseidonBasicOpts & { + /** S-box power used while generating constants. */ + sboxPower?: number; +}; +type PoseidonConstants = { + mds: bigint[][]; + roundConstants: bigint[][]; +}; +/** + * @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}. + * @param skipMDS - Number of MDS samples to skip. + * @returns Generated constants. + * @throws If the generated MDS matrix contains a zero denominator. {@link Error} + * @example + * Generate Poseidon round constants and an MDS matrix from the Grain LFSR. + * + * ```ts + * import { grainGenConstants } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * ``` + */ +export declare function grainGenConstants(opts: TArg, skipMDS?: number): PoseidonConstants; +/** Fully specified Poseidon permutation options with explicit constants. */ +export type PoseidonOpts = PoseidonBasicOpts & PoseidonConstants & { + /** S-box power used by the permutation. */ + sboxPower?: number; + /** Whether to reverse the partial-round S-box index. */ + reversePartialPowIdx?: boolean; +}; +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Normalized poseidon options. + * @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error} + * @example + * Validate generated constants before constructing a permutation. + * + * ```ts + * import { grainGenConstants, validateOpts } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * ``` + */ +export declare function validateOpts(opts: TArg): TRet bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; +}>>; +/** + * @param rc - Flattened round constants. + * @param t - Poseidon width. + * @returns Constants grouped by round. + * @throws If the width or flattened constant array is invalid. {@link Error} + * @example + * Regroup a flat constant list into per-round chunks. + * + * ```ts + * const rounds = splitConstants([1n, 2n, 3n, 4n], 2); + * ``` + */ +export declare function splitConstants(rc: bigint[], t: number): bigint[][]; +/** + * Poseidon permutation callable. + * @param values - Poseidon state vector. Non-canonical bigints are normalized with `Fp.create(...)`. + * @returns Permuted state vector. + */ +export type PoseidonFn = { + (values: bigint[]): bigint[]; + /** Round constants captured by the permutation instance. */ + roundConstants: bigint[][]; +}; +/** Poseidon NTT-friendly hash. */ +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Poseidon permutation. + * @throws If the Poseidon options or state vector are invalid. {@link Error} + * @example + * Build a Poseidon permutation from validated parameters and constants. + * + * ```ts + * import { grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const state = hash([1n, 2n]); + * ``` + */ +export declare function poseidon(opts: TArg): PoseidonFn; +/** + * @param Fp - Field implementation. + * @param rate - Sponge rate. + * @param capacity - Sponge capacity. + * @param hash - Poseidon permutation. + * @example + * Wrap one Poseidon permutation in a sponge interface. + * + * ```ts + * import { PoseidonSponge, grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const sponge = new PoseidonSponge(Fp, 1, 1, hash); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export declare class PoseidonSponge { + private Fp; + readonly rate: number; + readonly capacity: number; + readonly hash: PoseidonFn; + private state; + private pos; + private isAbsorbing; + constructor(Fp: IField, rate: number, capacity: number, hash: PoseidonFn); + private process; + absorb(input: bigint[]): void; + squeeze(count: number): bigint[]; + clean(): void; + clone(): PoseidonSponge; +} +/** Options for the non-standard but commonly used Poseidon sponge wrapper. */ +export type PoseidonSpongeOpts = Omit & { + /** Sponge rate. */ + rate: number; + /** Sponge capacity. */ + capacity: number; +}; +/** + * The method is not defined in spec, but nevertheless used often. + * Check carefully for compatibility: there are many edge cases, like absorbing an empty array. + * We cross-test against: + * - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms} + * - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives} + * @param opts - Sponge options. See {@link PoseidonSpongeOpts}. + * @returns Factory for sponge instances. + * @throws If the sponge dimensions or backing permutation options are invalid. {@link Error} + * @example + * Use the sponge helper to absorb several field elements and squeeze one digest. + * + * ```ts + * import { grainGenConstants, poseidonSponge } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const makeSponge = poseidonSponge({ + * ...constants, + * Fp, + * rate: 1, + * capacity: 1, + * roundsFull: 8, + * roundsPartial: 8, + * sboxPower: 3, + * }); + * const sponge = makeSponge(); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export declare function poseidonSponge(opts: TArg): TRet<() => PoseidonSponge>; +export {}; +//# sourceMappingURL=poseidon.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.d.ts.map b/node_modules/@noble/curves/abstract/poseidon.d.ts.map new file mode 100644 index 0000000..7741b16 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.d.ts","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sEAAsE;AACtE,OAAO,EAAuC,KAAK,IA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IAgB7B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IAiBhC,KAAK,IAAI,IAAI;IAKb,KAAK,IAAI,cAAc;CAOxB;AAED,8EAA8E;AAC9E,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,YAAY,EAAE,GAAG,CAAC,GAAG;IACzD,mBAAmB;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAaF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,kBAAkB,CAAC,GAAG,IAAI,CAAC,MAAM,cAAc,CAAC,CAQzF"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.js b/node_modules/@noble/curves/abstract/poseidon.js new file mode 100644 index 0000000..45fdceb --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.js @@ -0,0 +1,463 @@ +/** + * Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + * + * There are many poseidon variants with different constants. + * We don't provide them: you should construct them manually. + * Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { asafenumber, bitGet, validateObject } from "../utils.js"; +import { FpInvertBatch, FpPow, validateField } from "./modular.js"; +// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf +function grainLFSR(state) { + // Advances the caller-provided 80-entry state array in place; only the length + // is checked here, so entries are assumed to already be bits. + let pos = 0; + if (state.length !== 80) + throw new Error('grainLFRS: wrong state length, should be 80 bits'); + const getBit = () => { + const r = (offset) => state[(pos + offset) % 80]; + const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0); + state[pos] = bit; + pos = ++pos % 80; + return !!bit; + }; + for (let i = 0; i < 160; i++) + getBit(); + return () => { + // https://en.wikipedia.org/wiki/Shrinking_generator + while (true) { + const b1 = getBit(); + const b2 = getBit(); + if (!b1) + continue; + return b2; + } + }; +} +function assertValidPosOpts(opts) { + const { Fp, roundsFull } = opts; + validateField(Fp); + validateObject(opts, { + t: 'number', + roundsFull: 'number', + roundsPartial: 'number', + }, { + isSboxInverse: 'boolean', + }); + for (const k of ['t', 'roundsFull', 'roundsPartial']) { + asafenumber(opts[k], k); + if (opts[k] < 1) + throw new Error('invalid number ' + k); + } + // Poseidon splits full rounds as `R_F / 2`, then partial rounds, then `R_F / 2` again. + if (roundsFull & 1) + throw new Error('roundsFull is not even' + roundsFull); +} +function poseidonGrain(opts) { + assertValidPosOpts(opts); + const { Fp } = opts; + const state = Array(80).fill(1); + let pos = 0; + const writeBits = (value, bitCount) => { + for (let i = bitCount - 1; i >= 0; i--) + state[pos++] = Number(bitGet(value, i)); + }; + const _0n = BigInt(0); + const _1n = BigInt(1); + // The Grain seed layout is fixed-width: `Fp.BITS` and `t` use 12 bits, + // `roundsFull` and `roundsPartial` use 10, so larger values are truncated here. + // This is intentional for compatibility with snarkVM / arkworks PoseidonGrainLFSR: + // they write the same fixed-width seed fields without range checks, then still consume + // the LFSR using the caller-provided round count for ARK/MDS generation. + // Normalizing or rejecting here would diverge from those implementations. + writeBits(_1n, 2); // prime field + writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5 + writeBits(BigInt(Fp.BITS), 12); // b6..b17 + writeBits(BigInt(opts.t), 12); // b18..b29 + writeBits(BigInt(opts.roundsFull), 10); // b30..b39 + writeBits(BigInt(opts.roundsPartial), 10); // b40..b49 + const getBit = grainLFSR(state); + return (count, reject) => { + const res = []; + for (let i = 0; i < count; i++) { + while (true) { + let num = _0n; + for (let i = 0; i < Fp.BITS; i++) { + num <<= _1n; + if (getBit()) + num |= _1n; + } + if (reject && num >= Fp.ORDER) + continue; // rejection sampling + res.push(Fp.create(num)); + break; + } + } + return res; + }; +} +// NOTE: this is not standard but used often for constant generation for poseidon +// (grain LFRS-like structure) +/** + * @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}. + * @param skipMDS - Number of MDS samples to skip. + * @returns Generated constants. + * @throws If the generated MDS matrix contains a zero denominator. {@link Error} + * @example + * Generate Poseidon round constants and an MDS matrix from the Grain LFSR. + * + * ```ts + * import { grainGenConstants } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * ``` + */ +export function grainGenConstants(opts, skipMDS = 0) { + const { Fp, t, roundsFull, roundsPartial } = opts; + // `skipMDS` counts how many candidate matrices to discard before taking one. + asafenumber(skipMDS, 'skipMDS'); + if (skipMDS < 0) + throw new Error('invalid number skipMDS'); + const rounds = roundsFull + roundsPartial; + // `sboxPower` is carried in the opts shape for Poseidon compatibility, but + // Grain constant generation here only depends on field/size/round counts/inverse flag. + const sample = poseidonGrain(opts); + const roundConstants = []; + for (let r = 0; r < rounds; r++) + roundConstants.push(sample(t, true)); + if (skipMDS > 0) + for (let i = 0; i < skipMDS; i++) + sample(2 * t, false); + const xs = sample(t, false); + const ys = sample(t, false); + // Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j]) + const mds = []; + for (let i = 0; i < t; i++) { + const row = []; + for (let j = 0; j < t; j++) { + const xy = Fp.add(xs[i], ys[j]); + if (Fp.is0(xy)) + throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`); + row.push(xy); + } + mds.push(FpInvertBatch(Fp, row)); + } + return { roundConstants, mds }; +} +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Normalized poseidon options. + * @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error} + * @example + * Validate generated constants before constructing a permutation. + * + * ```ts + * import { grainGenConstants, validateOpts } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * ``` + */ +export function validateOpts(opts) { + // This only normalizes shapes and field membership for the provided constants; + // it does not prove the stronger MDS/security criteria discussed in the specs. + assertValidPosOpts(opts); + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) + throw new Error('Poseidon: invalid MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error('invalid MDS matrix row: ' + mdsRow); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') + throw new Error('invalid MDS matrix bigint: ' + i); + // Hardcoded Poseidon MDS matrices often use signed entries like `-1`; + // accept bigint representatives here and reduce them into the field. + return Fp.create(i); + }); + }); + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error('invalid param reversePartialPowIdx=' + rev); + if (roundsFull & 1) + throw new Error('roundsFull is not even' + roundsFull); + const rounds = roundsFull + roundsPartial; + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: invalid round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) + throw new Error('invalid round constants'); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) + throw new Error('invalid round constant'); + return Fp.create(i); + }); + }); + // Freeze nested constants so exported handles cannot retune a live permutation instance. + const freezeRows = (rows) => Object.freeze(rows.map((row) => Object.freeze(row))); + if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower)) + throw new Error('invalid sboxPower'); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) + sboxFn = (n) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) + sboxFn = (n) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + return Object.freeze({ + ...opts, + rounds, + sboxFn, + roundConstants: freezeRows(roundConstants), + mds: freezeRows(_mds), + }); +} +/** + * @param rc - Flattened round constants. + * @param t - Poseidon width. + * @returns Constants grouped by round. + * @throws If the width or flattened constant array is invalid. {@link Error} + * @example + * Regroup a flat constant list into per-round chunks. + * + * ```ts + * const rounds = splitConstants([1n, 2n, 3n, 4n], 2); + * ``` + */ +export function splitConstants(rc, t) { + asafenumber(t, 't'); + if (t < 1) + throw new Error('poseidonSplitConstants: invalid t'); + if (!Array.isArray(rc) || rc.length % t) + throw new Error('poseidonSplitConstants: invalid rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + const c = rc[i]; + if (typeof c !== 'bigint') + throw new Error('invalid bigint=' + c); + tmp.push(c); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} +/** Poseidon NTT-friendly hash. */ +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Poseidon permutation. + * @throws If the Poseidon options or state vector are invalid. {@link Error} + * @example + * Build a Poseidon permutation from validated parameters and constants. + * + * ```ts + * import { grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const state = hash([1n, 2n]); + * ``` + */ +export function poseidon(opts) { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values, isFull, idx) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + if (isFull) + values = values.map((i) => sboxFn(i)); + else + values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values) { + if (!Array.isArray(values) || values.length !== t) + throw new Error('invalid values, expected array of bigints with length ' + t); + // `.map()` skips sparse holes, which would leak `undefined` into round math below. + values = values.slice(); + for (let j = 0; j < values.length; j++) { + const i = values[j]; + if (typeof i !== 'bigint') + throw new Error('invalid bigint=' + i); + values[j] = Fp.create(i); + } + let lastRound = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, lastRound++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) + values = poseidonRound(values, false, lastRound++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) + values = poseidonRound(values, true, lastRound++); + if (lastRound !== totalRounds) + throw new Error('invalid number of rounds'); + return values; + }; + // For verification in tests + Object.defineProperty(poseidonHash, 'roundConstants', { + value: roundConstants, + enumerable: true, + }); + return poseidonHash; +} +/** + * @param Fp - Field implementation. + * @param rate - Sponge rate. + * @param capacity - Sponge capacity. + * @param hash - Poseidon permutation. + * @example + * Wrap one Poseidon permutation in a sponge interface. + * + * ```ts + * import { PoseidonSponge, grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const sponge = new PoseidonSponge(Fp, 1, 1, hash); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export class PoseidonSponge { + Fp; + rate; + capacity; + hash; + state; // [...capacity, ...rate] + pos = 0; + isAbsorbing = true; + constructor(Fp, rate, capacity, hash) { + const width = spongeShape(rate, capacity); + // The direct constructor accepts an arbitrary permutation hook, but callers still + // need to preserve the `PoseidonFn.roundConstants` width metadata. Reject width + // mismatches here instead of deferring them until the first `process()` call. + if (width !== hash.roundConstants[0]?.length) + throw new Error(`invalid sponge width: expected ${hash.roundConstants[0]?.length}, got ${width}`); + this.Fp = Fp; + this.hash = hash; + this.rate = rate; + this.capacity = capacity; + this.state = new Array(width); + this.clean(); + } + process() { + // The permutation is expected to return an owned state array. If callers inject a custom + // hook that reuses external storage, `clean()` will zero that shared buffer too. + this.state = this.hash(this.state); + } + absorb(input) { + for (const i of input) + if (typeof i !== 'bigint' || !this.Fp.isValid(i)) + throw new Error('invalid input: ' + i); + for (let i = 0; i < input.length;) { + if (!this.isAbsorbing || this.pos === this.rate) { + this.process(); + this.pos = 0; + this.isAbsorbing = true; + } + const chunk = Math.min(this.rate - this.pos, input.length - i); + for (let j = 0; j < chunk; j++) { + const idx = this.capacity + this.pos++; + this.state[idx] = this.Fp.add(this.state[idx], input[i++]); + } + } + } + squeeze(count) { + // Rust oracles use unsigned counts. In JS we keep `squeeze(0) => []` for + // compatibility, but still reject negative/fractional counts explicitly. + asafenumber(count, 'count'); + if (count < 0) + throw new Error('invalid number count'); + const res = []; + while (res.length < count) { + if (this.isAbsorbing || this.pos === this.rate) { + this.process(); + this.pos = 0; + this.isAbsorbing = false; + } + const chunk = Math.min(this.rate - this.pos, count - res.length); + for (let i = 0; i < chunk; i++) + res.push(this.state[this.capacity + this.pos++]); + } + return res; + } + clean() { + this.state.fill(this.Fp.ZERO); + this.isAbsorbing = true; + this.pos = 0; + } + clone() { + const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash); + c.pos = this.pos; + c.isAbsorbing = this.isAbsorbing; + c.state = [...this.state]; + return c; + } +} +const spongeShape = (rate, capacity) => { + asafenumber(rate, 'rate'); + asafenumber(capacity, 'capacity'); + // A sponge with zero rate cannot absorb or squeeze any field elements. + if (rate < 1) + throw new Error('invalid number rate'); + // Negative capacity can accidentally keep `rate + capacity` coherent while still + // producing a nonsensical sponge shape. + if (capacity < 0) + throw new Error('invalid number capacity'); + return rate + capacity; +}; +/** + * The method is not defined in spec, but nevertheless used often. + * Check carefully for compatibility: there are many edge cases, like absorbing an empty array. + * We cross-test against: + * - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms} + * - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives} + * @param opts - Sponge options. See {@link PoseidonSpongeOpts}. + * @returns Factory for sponge instances. + * @throws If the sponge dimensions or backing permutation options are invalid. {@link Error} + * @example + * Use the sponge helper to absorb several field elements and squeeze one digest. + * + * ```ts + * import { grainGenConstants, poseidonSponge } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const makeSponge = poseidonSponge({ + * ...constants, + * Fp, + * rate: 1, + * capacity: 1, + * roundsFull: 8, + * roundsPartial: 8, + * sboxPower: 3, + * }); + * const sponge = makeSponge(); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export function poseidonSponge(opts) { + const { rate, capacity } = opts; + const t = spongeShape(rate, capacity); + // Re-use one hash instance between sponge instances; isolation depends on + // poseidon(...) itself staying immutable and not carrying mutable call state. + const hash = poseidon({ ...opts, t }); + const { Fp } = opts; + return (() => new PoseidonSponge(Fp, rate, capacity, hash)); +} +//# sourceMappingURL=poseidon.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/poseidon.js.map b/node_modules/@noble/curves/abstract/poseidon.js.map new file mode 100644 index 0000000..97036f0 --- /dev/null +++ b/node_modules/@noble/curves/abstract/poseidon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"poseidon.js","sourceRoot":"","sources":["../src/abstract/poseidon.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sEAAsE;AACtE,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,cAAc,EAAw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AG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7D,OAAO,IAAI,GAAG,QAAQ,CAAC;AACzB,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,UAAU,cAAc,CAAC,IAA8B;IAC3D,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,IAAI,CAAC;IAChC,MAAM,CAAC,GAAG,WAAW,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACtC,0EAA0E;IAC1E,8EAA8E;IAC9E,MAAM,IAAI,GAAG,QAAQ,CAAC,EAAE,GAAG,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IACtC,MAAM,EAAE,EAAE,EAAE,GAAG,IAAI,CAAC;IACpB,OAAO,CAAC,GAAG,EAAE,CAAC,IAAI,cAAc,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,CAA+B,CAAC;AAC5F,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/tower.d.ts b/node_modules/@noble/curves/abstract/tower.d.ts new file mode 100644 index 0000000..02559d8 --- /dev/null +++ b/node_modules/@noble/curves/abstract/tower.d.ts @@ -0,0 +1,214 @@ +/** + * Towered extension fields. + * Rather than implementing a massive 12th-degree extension directly, it is more efficient + * to build it up from smaller extensions: a tower of extensions. + * + * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, + * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + * + * For more info: "Pairings for beginners" by Costello, section 7.3. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type TArg, type TRet } from '../utils.ts'; +import * as mod from './modular.ts'; +import type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass.ts'; +/** Pair of bigints used for quadratic-extension tuples. */ +export type BigintTuple = [bigint, bigint]; +/** Prime-field element. */ +export type Fp = bigint; +/** Quadratic-extension field element `c0 + c1 * u`. */ +export type Fp2 = { + /** Real component. */ + c0: bigint; + /** Imaginary component. */ + c1: bigint; +}; +/** Six bigints used for sextic-extension tuples. */ +export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +/** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */ +export type Fp6 = { + /** Constant coefficient. */ + c0: Fp2; + /** Linear coefficient. */ + c1: Fp2; + /** Quadratic coefficient. */ + c2: Fp2; +}; +/** + * Degree-12 extension field element `c0 + c1 * w`. + * Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v. + */ +export type Fp12 = { + /** Constant coefficient. */ + c0: Fp6; + /** Linear coefficient. */ + c1: Fp6; +}; +/** Twelve bigints used for degree-12 extension tuples. */ +export type BigintTwelve = [ + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint, + bigint +]; +/** BLS-friendly helpers on top of the quadratic extension field. */ +export type Fp2Bls = mod.IField & { + /** Underlying prime field. */ + Fp: mod.IField; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp2, power: number): Fp2; + /** Build one field element from a raw bigint tuple. */ + fromBigTuple(num: BigintTuple): Fp2; + /** Multiply by the curve `b` constant. */ + mulByB: (num: Fp2) => Fp2; + /** Multiply by the quadratic non-residue. */ + mulByNonresidue: (num: Fp2) => Fp2; + /** Split one quadratic element into real and imaginary components. */ + reim: (num: Fp2) => { + re: Fp; + im: Fp; + }; + /** Specialized helper used by sextic squaring formulas. */ + Fp4Square: (a: Fp2, b: Fp2) => { + first: Fp2; + second: Fp2; + }; + /** Quadratic non-residue used by the extension. */ + NONRESIDUE: Fp2; +}; +/** BLS-friendly helpers on top of the sextic extension field. */ +export type Fp6Bls = mod.IField & { + /** Underlying quadratic extension field. */ + Fp2: Fp2Bls; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp6, power: number): Fp6; + /** Build one field element from a raw six-bigint tuple. */ + fromBigSix: (tuple: BigintSix) => Fp6; + /** Multiply by a sparse `(0, b1, 0)` sextic element. */ + mul1(num: Fp6, b1: Fp2): Fp6; + /** Multiply by a sparse `(b0, b1, 0)` sextic element. */ + mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + /** Multiply by one quadratic-extension element. */ + mulByFp2(lhs: Fp6, rhs: Fp2): Fp6; + /** Multiply by the sextic non-residue. */ + mulByNonresidue: (num: Fp6) => Fp6; +}; +/** BLS-friendly helpers on top of the degree-12 extension field. */ +export type Fp12Bls = mod.IField & { + /** Underlying sextic extension field. */ + Fp6: Fp6Bls; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp12, power: number): Fp12; + /** Build one field element from a raw twelve-bigint tuple. */ + fromBigTwelve: (t: BigintTwelve) => Fp12; + /** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */ + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + /** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */ + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + /** Multiply by one quadratic-extension element. */ + mulByFp2(lhs: Fp12, rhs: Fp2): Fp12; + /** Conjugate one degree-12 element. */ + conjugate(num: Fp12): Fp12; + /** Apply the final exponentiation from pairing arithmetic. */ + finalExponentiate(num: Fp12): Fp12; + /** Apply one cyclotomic square. */ + _cyclotomicSquare(num: Fp12): Fp12; + /** Apply one cyclotomic exponentiation. */ + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; +declare function calcFrobeniusCoefficients(Fp: TArg>, nonResidue: T, modulus: bigint, degree: number, num?: number, divisor?: number): T[][]; +export declare const __TEST: { + calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients; +}; +/** + * @param Fp - Base field implementation. + * @param Fp2 - Quadratic extension field. + * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants. + * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`. + * @returns Frobenius endomorphism helpers. + * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error} + * @example + * Build Frobenius endomorphism helpers for a BLS extension tower. + * + * ```ts + * import { psiFrobenius } from '@noble/curves/abstract/tower.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const Fp = bls12_381.fields.Fp; + * const Fp2 = bls12_381.fields.Fp2; + * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); + * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE); + * ``` + */ +export declare function psiFrobenius(Fp: TArg>, Fp2: TArg, base: TArg): { + psi: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + G2psi: (c: WeierstrassPointCons, P: WeierstrassPoint) => WeierstrassPoint; + G2psi2: (c: WeierstrassPointCons, P: WeierstrassPoint) => WeierstrassPoint; + PSI_X: Fp2; + PSI_Y: Fp2; + PSI2_X: Fp2; + PSI2_Y: Fp2; +}; +/** Construction options for the BLS-style degree-12 tower. */ +export type Tower12Opts = { + /** Prime-field order. */ + ORDER: bigint; + /** Bit length of the BLS parameter `x`. */ + X_LEN: number; + /** Prime-field non-residue used by the quadratic extension. */ + NONRESIDUE?: Fp; + /** Quadratic-extension non-residue used by the sextic tower. */ + FP2_NONRESIDUE: BigintTuple; + /** + * Optional custom quadratic square-root helper. + * Receives one quadratic-extension element and returns one square root. + */ + Fp2sqrt?: (num: Fp2) => Fp2; + /** + * Multiply one quadratic element by the curve `b` constant. + * @param num - Quadratic-extension element to scale. + * @returns Product by the curve `b` constant. + */ + Fp2mulByB: (num: Fp2) => Fp2; + /** + * Final exponentiation used by pairing arithmetic. + * @param num - Degree-12 field element to exponentiate. + * @returns Pairing result after final exponentiation. + */ + Fp12finalExponentiate: (num: Fp12) => Fp12; +}; +/** + * @param opts - Tower construction options. See {@link Tower12Opts}. + * @returns BLS tower fields. + * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error} + * @example + * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve. + * + * ```ts + * const fields = tower12({ + * ORDER: 17n, + * X_LEN: 4, + * FP2_NONRESIDUE: [1n, 1n], + * Fp2mulByB: (num) => num, + * Fp12finalExponentiate: (num) => num, + * }); + * const fp12 = fields.Fp12.ONE; + * ``` + */ +export declare function tower12(opts: TArg): TRet<{ + Fp: Readonly & Required, 'isOdd'>>>; + Fp2: Fp2Bls; + Fp6: Fp6Bls; + Fp12: Fp12Bls; +}>; +export {}; +//# sourceMappingURL=tower.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/tower.d.ts.map b/node_modules/@noble/curves/abstract/tower.d.ts.map new file mode 100644 index 0000000..7991bc0 --- /dev/null +++ b/node_modules/@noble/curves/abstract/tower.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.d.ts","sourceRoot":"","sources":["../src/abstract/tower.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,sEAAsE;AACtE,OAAO,EASL,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AACpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAO/E,2DAA2D;AAC3D,MAAM,MAAM,WAAW,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAC3C,2BAA2B;AAC3B,MAAM,MAAM,EAAE,GAAG,MAAM,CAAC;AAGxB,uDAAuD;AACvD,MAAM,MAAM,GAAG,GAAG;IAChB,sBAAsB;IACtB,EAAE,EAAE,MAAM,CAAC;IACX,2BAA2B;IAC3B,EAAE,EAAE,MAAM,CAAC;CACZ,CAAC;AACF,oDAAoD;AACpD,MAAM,MAAM,SAAS,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AACzE,+DAA+D;AAC/D,MA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G,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;IAC/E,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,OAAO,CAAC;CACf,CAAC,CA6BD"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/tower.js b/node_modules/@noble/curves/abstract/tower.js new file mode 100644 index 0000000..c1f8420 --- /dev/null +++ b/node_modules/@noble/curves/abstract/tower.js @@ -0,0 +1,926 @@ +/** + * Towered extension fields. + * Rather than implementing a massive 12th-degree extension directly, it is more efficient + * to build it up from smaller extensions: a tower of extensions. + * + * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, + * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + * + * For more info: "Pairings for beginners" by Costello, section 7.3. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abytes, aInRange, asafenumber, bitGet, bitLen, concatBytes, notImplemented, validateObject, } from "../utils.js"; +import * as mod from "./modular.js"; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _6n = /* @__PURE__ */ BigInt(6), _12n = /* @__PURE__ */ BigInt(12); +const isObj = (value) => !!value && typeof value === 'object'; +function calcFrobeniusCoefficients(Fp, nonResidue, modulus, degree, num = 1, divisor) { + asafenumber(num, 'num'); + const F = Fp; + // Generic callers can hit empty / fractional row counts through `__TEST`; fail closed instead of + // silently returning `[]` or deriving extra Frobenius rows from a truncated loop bound. + if (num <= 0) + throw new Error('calcFrobeniusCoefficients: expected positive row count, got ' + num); + const _divisor = BigInt(divisor === undefined ? degree : divisor); + const towerModulus = modulus ** BigInt(degree); + const res = []; + // Derive tower-basis multipliers for the `p^k` Frobenius action. The + // divisions below are expected to be exact for the chosen tower parameters. + for (let i = 0; i < num; i++) { + const a = BigInt(i + 1); + const powers = []; + for (let j = 0, qPower = _1n; j < degree; j++) { + const numer = a * qPower - a; + // Shipped towers divide cleanly here, but generic callers can pick bad + // params. Bigint division would floor and derive the wrong Frobenius table. + if (numer % _divisor) + throw new Error('calcFrobeniusCoefficients: inexact tower exponent'); + const power = (numer / _divisor) % towerModulus; + powers.push(F.pow(nonResidue, power)); + qPower *= modulus; + } + res.push(powers); + } + return res; +} +export const __TEST = +/* @__PURE__ */ Object.freeze({ + calcFrobeniusCoefficients, +}); +// This works same at least for bls12-381, bn254 and bls12-377 +/** + * @param Fp - Base field implementation. + * @param Fp2 - Quadratic extension field. + * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants. + * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`. + * @returns Frobenius endomorphism helpers. + * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error} + * @example + * Build Frobenius endomorphism helpers for a BLS extension tower. + * + * ```ts + * import { psiFrobenius } from '@noble/curves/abstract/tower.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const Fp = bls12_381.fields.Fp; + * const Fp2 = bls12_381.fields.Fp2; + * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); + * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE); + * ``` + */ +export function psiFrobenius(Fp, Fp2, base) { + // GLV endomorphism Ψ(P) + const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3) + const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2) + function psi(x, y) { + // This x10 faster than previous version in bls12-381 + const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X); + const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y); + return [x2, y2]; + } + // Ψ²(P) endomorphism (psi2(x) = psi(psi(x))) + const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3) + // Current towers rely on this landing on `-1`, which lets psi2 map `y` with + // one negation instead of carrying a separate Frobenius multiplier. + const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/2) + if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) + throw new Error('psiFrobenius: PSI2_Y!==-1'); + function psi2(x, y) { + return [Fp2.mul(x, PSI2_X), Fp2.neg(y)]; + } + // Map points + const mapAffine = (fn) => (c, P) => { + const affine = P.toAffine(); + const p = fn(affine.x, affine.y); + return c.fromAffine({ x: p[0], y: p[1] }); + }; + const G2psi = mapAffine(psi); + const G2psi2 = mapAffine(psi2); + return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y }; +} +class _Field2 { + ORDER; + BITS; + BYTES; + isLE; + ZERO; + ONE; + Fp; + NONRESIDUE; + mulByB; + Fp_NONRESIDUE; + Fp_div2; + FROBENIUS_COEFFICIENTS; + constructor(Fp, opts = {}) { + const { NONRESIDUE = BigInt(-1), FP2_NONRESIDUE, Fp2mulByB } = opts; + const ORDER = Fp.ORDER; + const FP2_ORDER = ORDER * ORDER; + this.Fp = Fp; + this.ORDER = FP2_ORDER; + this.BITS = bitLen(FP2_ORDER); + this.BYTES = Math.ceil(bitLen(FP2_ORDER) / 8); + this.isLE = Fp.isLE; + this.ZERO = this.create({ c0: Fp.ZERO, c1: Fp.ZERO }); + this.ONE = this.create({ c0: Fp.ONE, c1: Fp.ZERO }); + // These knobs only swap constants for the shipped quadratic tower shape: + // arithmetic below assumes `u^2 = -1`, and bytes are handled as two adjacent + // `Fp` limbs (`fromBytes` / `toBytes` expect the shipped `2 * Fp.BYTES` layout). + this.Fp_NONRESIDUE = Fp.create(NONRESIDUE); + this.Fp_div2 = Fp.div(Fp.ONE, _2n); // 1/2 + this.NONRESIDUE = this.create({ c0: FP2_NONRESIDUE[0], c1: FP2_NONRESIDUE[1] }); + // const Fp2Nonresidue = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] }); + this.FROBENIUS_COEFFICIENTS = Object.freeze(calcFrobeniusCoefficients(Fp, this.Fp_NONRESIDUE, Fp.ORDER, 2)[0]); + this.mulByB = (num) => { + // This config hook is trusted to return a canonical Fp2 value already. + // Copy+freeze it to keep the tower immutability invariant without mutating caller objects. + const { c0, c1 } = Fp2mulByB(num); + return Object.freeze({ c0, c1 }); + }; + Object.freeze(this); + } + fromBigTuple(tuple) { + if (!Array.isArray(tuple) || tuple.length !== 2) + throw new Error('invalid Fp2.fromBigTuple'); + const [c0, c1] = tuple; + if (typeof c0 !== 'bigint' || typeof c1 !== 'bigint') + throw new Error('invalid Fp2.fromBigTuple'); + return this.create({ c0, c1 }); + } + create(num) { + const { Fp } = this; + const c0 = Fp.create(num.c0); + const c1 = Fp.create(num.c1); + // Bigint field elements are immutable values, and higher-level code relies on + // that invariant. Copy+freeze tower values too without mutating caller-owned objects. + return Object.freeze({ c0, c1 }); + } + isValid(num) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1 } = num; + const { Fp } = this; + // Match base-field `isValid(...)`: malformed coordinate types are errors, not a `false` + // predicate result. + return Fp.isValid(c0) && Fp.isValid(c1); + } + is0(num) { + if (!isObj(num)) + return false; + const { c0, c1 } = num; + const { Fp } = this; + return Fp.is0(c0) && Fp.is0(c1); + } + isValidNot0(num) { + return !this.is0(num) && this.isValid(num); + } + eql({ c0, c1 }, { c0: r0, c1: r1 }) { + const { Fp } = this; + return Fp.eql(c0, r0) && Fp.eql(c1, r1); + } + neg({ c0, c1 }) { + const { Fp } = this; + return Object.freeze({ c0: Fp.neg(c0), c1: Fp.neg(c1) }); + } + pow(num, power) { + return mod.FpPow(this, num, power); + } + invertBatch(nums) { + return mod.FpInvertBatch(this, nums); + } + // Normalized + add(f1, f2) { + const { Fp } = this; + const { c0, c1 } = f1; + const { c0: r0, c1: r1 } = f2; + return Object.freeze({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), + }); + } + sub({ c0, c1 }, { c0: r0, c1: r1 }) { + const { Fp } = this; + return Object.freeze({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), + }); + } + mul({ c0, c1 }, rhs) { + const { Fp } = this; + if (typeof rhs === 'bigint') + return Object.freeze({ c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }); + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return Object.freeze({ c0: o0, c1: o1 }); + } + sqr({ c0, c1 }) { + const { Fp } = this; + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return Object.freeze({ c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }); + } + // NonNormalized stuff + addN(a, b) { + return this.add(a, b); + } + subN(a, b) { + return this.sub(a, b); + } + mulN(a, b) { + return this.mul(a, b); + } + sqrN(a) { + return this.sqr(a); + } + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div(lhs, rhs) { + const { Fp } = this; + // @ts-ignore + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + inv({ c0: a, c1: b }) { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const { Fp } = this; + const factor = Fp.inv(Fp.create(a * a + b * b)); + return Object.freeze({ c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }); + } + sqrt(num) { + // This is generic for all quadratic extensions (Fp2) + const { Fp } = this; + const Fp2 = this; + const { c0, c1 } = num; + if (Fp.is0(c1)) { + // if c0 is quadratic residue + if (mod.FpLegendre(Fp, c0) === 1) + return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO }); + else + return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, this.Fp_NONRESIDUE)) }); + } + const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), this.Fp_NONRESIDUE))); + let d = Fp.mul(Fp.add(a, c0), this.Fp_div2); + const legendre = mod.FpLegendre(Fp, d); + // -1, Quadratic non residue + if (legendre === -1) + d = Fp.sub(d, a); + const a0 = Fp.sqrt(d); + const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, this.Fp_div2), a0) }); + if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) + throw new Error('Cannot find square root'); + // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num + const x1 = candidateSqrt; + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) + return x1; + return x2; + } + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd(x) { + const { re: x0, im: x1 } = this.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + } + // Bytes util + fromBytes(b) { + const { Fp } = this; + abytes(b); + if (b.length !== this.BYTES) + throw new Error('fromBytes invalid length=' + b.length); + return this.create({ + c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), + c1: Fp.fromBytes(b.subarray(Fp.BYTES)), + }); + } + toBytes({ c0, c1 }) { + return concatBytes(this.Fp.toBytes(c0), this.Fp.toBytes(c1)); + } + cmov({ c0, c1 }, { c0: r0, c1: r1 }, c) { + const { Fp } = this; + return this.create({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }); + } + reim({ c0, c1 }) { + return { re: c0, im: c1 }; + } + Fp4Square(a, b) { + const Fp2 = this; + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; + } + // multiply by u + 1 + mulByNonresidue({ c0, c1 }) { + return this.mul({ c0, c1 }, this.NONRESIDUE); + } + frobeniusMap({ c0, c1 }, power) { + return Object.freeze({ + c0, + c1: this.Fp.mul(c1, this.FROBENIUS_COEFFICIENTS[power % 2]), + }); + } +} +class _Field6 { + ORDER; + BITS; + BYTES; + isLE; + ZERO; + ONE; + Fp2; + constructor(Fp2) { + this.Fp2 = Fp2; + // `IField.ORDER` is the field cardinality `q`; for sextic extensions that is `p^6`. + // Generic helpers like Frobenius-style `x^q = x` checks rely on the literal field size here. + this.ORDER = Fp2.Fp.ORDER ** _6n; + this.BITS = 3 * Fp2.BITS; + this.BYTES = 3 * Fp2.BYTES; + this.isLE = Fp2.isLE; + this.ZERO = this.create({ c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }); + this.ONE = this.create({ c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }); + Object.freeze(this); + } + // Most callers never touch Frobenius maps, so keep the sextic tables lazy: + // eagerly deriving them dominates `bls12-381.js` / `bn254.js` import time. + get FROBENIUS_COEFFICIENTS_1() { + const frob = _FROBENIUS_COEFFICIENTS_6.get(this); + if (frob) + return frob[0]; + const { Fp2 } = this; + const { Fp } = Fp2; + const rows = calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 6, 2, 3); + const cache = [Object.freeze(rows[0]), Object.freeze(rows[1])]; + _FROBENIUS_COEFFICIENTS_6.set(this, cache); + return cache[0]; + } + get FROBENIUS_COEFFICIENTS_2() { + const frob = _FROBENIUS_COEFFICIENTS_6.get(this); + if (frob) + return frob[1]; + void this.FROBENIUS_COEFFICIENTS_1; + return _FROBENIUS_COEFFICIENTS_6.get(this)[1]; + } + add({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), + }); + } + sub({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), + }); + } + mul({ c0, c1, c2 }, rhs) { + const { Fp2 } = this; + if (typeof rhs === 'bigint') { + return Object.freeze({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }); + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return Object.freeze({ + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add(t0, Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2)))), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), Fp2.mulByNonresidue(t2)), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }); + } + sqr({ c0, c1, c2 }) { + const { Fp2 } = this; + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return Object.freeze({ + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }); + } + addN(a, b) { + return this.add(a, b); + } + subN(a, b) { + return this.sub(a, b); + } + mulN(a, b) { + return this.mul(a, b); + } + sqrN(a) { + return this.sqr(a); + } + create(num) { + const { Fp2 } = this; + const c0 = Fp2.create(num.c0); + const c1 = Fp2.create(num.c1); + const c2 = Fp2.create(num.c2); + return Object.freeze({ c0, c1, c2 }); + } + isValid(num) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1, c2 } = num; + const { Fp2 } = this; + return Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2); + } + is0(num) { + if (!isObj(num)) + return false; + const { c0, c1, c2 } = num; + const { Fp2 } = this; + return Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2); + } + isValidNot0(num) { + return !this.is0(num) && this.isValid(num); + } + neg({ c0, c1, c2 }) { + const { Fp2 } = this; + return Object.freeze({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }); + } + eql({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }) { + const { Fp2 } = this; + return Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2); + } + sqrt(_) { + // Sextic extensions can use generic odd-field Tonelli-Shanks, but the helper must work + // over `IField` with a quadratic non-residue from Fp6 itself. The current + // `mod.tonelliShanks(P)` precomputation only searches integer residues in the base field. + return notImplemented(); + } + // Do we need division by bigint at all? Should be done via order: + div(lhs, rhs) { + const { Fp2 } = this; + const { Fp } = Fp2; + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + pow(num, power) { + return mod.FpPow(this, num, power); + } + invertBatch(nums) { + return mod.FpInvertBatch(this, nums); + } + inv({ c0, c1, c2 }) { + const { Fp2 } = this; + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv(Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0))); + return Object.freeze({ c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }); + } + // Bytes utils + fromBytes(b) { + const { Fp2 } = this; + abytes(b); + if (b.length !== this.BYTES) + throw new Error('fromBytes invalid length=' + b.length); + const B2 = Fp2.BYTES; + return this.create({ + c0: Fp2.fromBytes(b.subarray(0, B2)), + c1: Fp2.fromBytes(b.subarray(B2, B2 * 2)), + c2: Fp2.fromBytes(b.subarray(2 * B2)), + }); + } + toBytes({ c0, c1, c2 }) { + const { Fp2 } = this; + return concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)); + } + cmov({ c0, c1, c2 }, { c0: r0, c1: r1, c2: r2 }, c) { + const { Fp2 } = this; + return this.create({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }); + } + fromBigSix(tuple) { + const { Fp2 } = this; + if (!Array.isArray(tuple) || tuple.length !== 6) + throw new Error('invalid Fp6.fromBigSix'); + for (let i = 0; i < 6; i++) + if (typeof tuple[i] !== 'bigint') + throw new Error('invalid Fp6.fromBigSix'); + const t = tuple; + return this.create({ + c0: Fp2.fromBigTuple(t.slice(0, 2)), + c1: Fp2.fromBigTuple(t.slice(2, 4)), + c2: Fp2.fromBigTuple(t.slice(4, 6)), + }); + } + frobeniusMap({ c0, c1, c2 }, power) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), this.FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), this.FROBENIUS_COEFFICIENTS_2[power % 6]), + }); + } + mulByFp2({ c0, c1, c2 }, rhs) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }); + } + mulByNonresidue({ c0, c1, c2 }) { + const { Fp2 } = this; + return Object.freeze({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }); + } + // Sparse multiplication + mul1({ c0, c1, c2 }, b1) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }); + } + // Sparse multiplication + mul01({ c0, c1, c2 }, b0, b1) { + const { Fp2 } = this; + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return Object.freeze({ + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }); + } +} +// Keep lazy tower caches off-object: field instances stay frozen, and debugger output +// stays readable without JS private slots while second/subsequent lookups still hit cache. +const _FROBENIUS_COEFFICIENTS_6 = new WeakMap(); +class _Field12 { + ORDER; + BITS; + BYTES; + isLE; + ZERO; + ONE; + Fp6; + X_LEN; + finalExponentiate; + constructor(Fp6, opts) { + const { X_LEN, Fp12finalExponentiate } = opts; + const { Fp2 } = Fp6; + const { Fp } = Fp2; + this.Fp6 = Fp6; + // `IField.ORDER` is the field cardinality `q`; for degree-12 extensions that is `p^12`. + // Keeping `p^2` here breaks generic field identities like `x^q = x` on Fp12. + this.ORDER = Fp.ORDER ** _12n; + this.BITS = 2 * Fp6.BITS; + this.BYTES = 2 * Fp6.BYTES; + this.isLE = Fp6.isLE; + // Returned tower values are frozen, so larger constants can safely reuse + // already-frozen child coefficients instead of cloning them. + this.ZERO = this.create({ c0: Fp6.ZERO, c1: Fp6.ZERO }); + this.ONE = this.create({ c0: Fp6.ONE, c1: Fp6.ZERO }); + this.X_LEN = X_LEN; + this.finalExponentiate = (num) => { + const copy2 = ({ c0, c1 }) => Object.freeze({ c0, c1 }); + const copy6 = ({ c0, c1, c2 }) => Object.freeze({ c0: copy2(c0), c1: copy2(c1), c2: copy2(c2) }); + // This config hook is trusted to return a canonical Fp12 value already. + // Copy+freeze it to keep the tower immutability invariant without mutating caller objects. + const res = Fp12finalExponentiate(num); + return Object.freeze({ c0: copy6(res.c0), c1: copy6(res.c1) }); + }; + Object.freeze(this); + } + // Keep the degree-12 Frobenius row lazy too; after the first lookup the cached + // array is reused exactly like the old eager table. + get FROBENIUS_COEFFICIENTS() { + const frob = _FROBENIUS_COEFFICIENTS_12.get(this); + if (frob) + return frob; + const { Fp2 } = this.Fp6; + const { Fp } = Fp2; + const cache = Object.freeze(calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 12, 1, 6)[0]); + _FROBENIUS_COEFFICIENTS_12.set(this, cache); + return cache; + } + create(num) { + const { Fp6 } = this; + const c0 = Fp6.create(num.c0); + const c1 = Fp6.create(num.c1); + return Object.freeze({ c0, c1 }); + } + isValid(num) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1 } = num; + const { Fp6 } = this; + return Fp6.isValid(c0) && Fp6.isValid(c1); + } + is0(num) { + if (!isObj(num)) + return false; + const { c0, c1 } = num; + const { Fp6 } = this; + return Fp6.is0(c0) && Fp6.is0(c1); + } + isValidNot0(num) { + return !this.is0(num) && this.isValid(num); + } + neg({ c0, c1 }) { + const { Fp6 } = this; + return Object.freeze({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }); + } + eql({ c0, c1 }, { c0: r0, c1: r1 }) { + const { Fp6 } = this; + return Fp6.eql(c0, r0) && Fp6.eql(c1, r1); + } + sqrt(_) { + // Fp12 is quadratic over Fp6, so a dedicated quadratic-extension sqrt is possible here + // once Fp6.sqrt() exists. Without that lower-level sqrt, only a field-generic + // Tonelli-Shanks path over Fp12 itself would work. + return notImplemented(); + } + inv({ c0, c1 }) { + const { Fp6 } = this; + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + // ((C0 * T) * T) + (-C1 * T) * w + return Object.freeze({ c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }); + } + div(lhs, rhs) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { Fp } = Fp2; + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + pow(num, power) { + return mod.FpPow(this, num, power); + } + invertBatch(nums) { + return mod.FpInvertBatch(this, nums); + } + // Normalized + add({ c0, c1 }, { c0: r0, c1: r1 }) { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), + }); + } + sub({ c0, c1 }, { c0: r0, c1: r1 }) { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), + }); + } + mul({ c0, c1 }, rhs) { + const { Fp6 } = this; + if (typeof rhs === 'bigint') + return Object.freeze({ c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }); + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return Object.freeze({ + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }); + } + sqr({ c0, c1 }) { + const { Fp6 } = this; + let ab = Fp6.mul(c0, c1); // c0 * c1 + return Object.freeze({ + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub(Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), Fp6.mulByNonresidue(ab)), + c1: Fp6.add(ab, ab), + }); // AB + AB + } + // NonNormalized stuff + addN(a, b) { + return this.add(a, b); + } + subN(a, b) { + return this.sub(a, b); + } + mulN(a, b) { + return this.mul(a, b); + } + sqrN(a) { + return this.sqr(a); + } + // Bytes utils + fromBytes(b) { + const { Fp6 } = this; + abytes(b); + if (b.length !== this.BYTES) + throw new Error('fromBytes invalid length=' + b.length); + return this.create({ + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }); + } + toBytes({ c0, c1 }) { + const { Fp6 } = this; + return concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1)); + } + cmov({ c0, c1 }, { c0: r0, c1: r1 }, c) { + const { Fp6 } = this; + return this.create({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }); + } + // Utils + // toString() { + // return '' + 'Fp12(' + this.c0 + this.c1 + '* w'); + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve(tuple) { + const { Fp6 } = this; + if (!Array.isArray(tuple) || tuple.length !== 12) + throw new Error('invalid Fp12.fromBigTwelve'); + for (let i = 0; i < 12; i++) + if (typeof tuple[i] !== 'bigint') + throw new Error('invalid Fp12.fromBigTwelve'); + const t = tuple; + return this.create({ + c0: Fp6.fromBigSix(t.slice(0, 6)), + c1: Fp6.fromBigSix(t.slice(6, 12)), + }); + } + // Raises to q**i -th power + frobeniusMap(lhs, power) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = this.FROBENIUS_COEFFICIENTS[power % 12]; + return Object.freeze({ + c0: Fp6.frobeniusMap(lhs.c0, power), + c1: Object.freeze({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }); + } + mulByFp2({ c0, c1 }, rhs) { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.mulByFp2(c0, rhs), + c1: Fp6.mulByFp2(c1, rhs), + }); + } + conjugate({ c0, c1 }) { + // Reuse `c0` by reference and only negate the `w` coefficient. + return Object.freeze({ c0, c1: this.Fp6.neg(c1) }); + } + // Sparse multiplication + mul014({ c0, c1 }, o0, o1, o4) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + let t0 = Fp6.mul01(c0, o0, o1); + let t1 = Fp6.mul1(c1, o4); + return Object.freeze({ + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }); + } + mul034({ c0, c1 }, o0, o3, o4) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const a = Object.freeze({ + c0: Fp2.mul(c0.c0, o0), + c1: Fp2.mul(c0.c1, o0), + c2: Fp2.mul(c0.c2, o0), + }); + const b = Fp6.mul01(c1, o3, o4); + const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4); + return Object.freeze({ + c0: Fp6.add(Fp6.mulByNonresidue(b), a), + c1: Fp6.sub(e, Fp6.add(a, b)), + }); + } + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + // https://eprint.iacr.org/2010/354.pdf + _cyclotomicSquare({ c0, c1 }) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp2.Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp2.Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp2.Fp4Square(c0c1, c1c2); + const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return Object.freeze({ + c0: Object.freeze({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Object.freeze({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }); // 2 * (T6 + c1c2) + T6 + } + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicExp(num, n) { + // The loop only consumes `X_LEN` bits, so out-of-range exponents would otherwise get silently + // truncated (or sign-extended for negatives) instead of matching the caller's requested power. + aInRange('cyclotomic exponent', n, _0n, _1n << BigInt(this.X_LEN)); + let z = this.ONE; + for (let i = this.X_LEN - 1; i >= 0; i--) { + z = this._cyclotomicSquare(z); + if (bitGet(n, i)) + z = this.mul(z, num); + } + return z; + } +} +const _FROBENIUS_COEFFICIENTS_12 = new WeakMap(); +/** + * @param opts - Tower construction options. See {@link Tower12Opts}. + * @returns BLS tower fields. + * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error} + * @example + * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve. + * + * ```ts + * const fields = tower12({ + * ORDER: 17n, + * X_LEN: 4, + * FP2_NONRESIDUE: [1n, 1n], + * Fp2mulByB: (num) => num, + * Fp12finalExponentiate: (num) => num, + * }); + * const fp12 = fields.Fp12.ONE; + * ``` + */ +export function tower12(opts) { + validateObject(opts, { + ORDER: 'bigint', + X_LEN: 'number', + FP2_NONRESIDUE: 'object', + Fp2mulByB: 'function', + Fp12finalExponentiate: 'function', + }, { NONRESIDUE: 'bigint' }); + asafenumber(opts.X_LEN, 'X_LEN'); + if (opts.X_LEN < 1) + throw new Error('invalid X_LEN'); + const nonresidue = opts.FP2_NONRESIDUE; + if (!Array.isArray(nonresidue) || nonresidue.length !== 2) + throw new Error('invalid FP2_NONRESIDUE'); + if (typeof nonresidue[0] !== 'bigint' || typeof nonresidue[1] !== 'bigint') + throw new Error('invalid FP2_NONRESIDUE'); + const Fp = mod.Field(opts.ORDER); + const Fp2 = new _Field2(Fp, opts); + const Fp6 = new _Field6(Fp2); + const Fp12 = new _Field12(Fp6, opts); + return { Fp, Fp2, Fp6, Fp12 }; +} +//# sourceMappingURL=tower.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/tower.js.map b/node_modules/@noble/curves/abstract/tower.js.map new file mode 100644 index 0000000..2876887 --- /dev/null +++ b/node_modules/@noble/curves/abstract/tower.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tower.js","sourceRoot":"","sources":["../src/abstract/tower.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,sEAAsE;AACtE,OAAO,EACL,MAAM,EACN,QAAQ,EACR,WAAW,EACX,MAAM,EACN,MAAM,EACN,WAAW,EACX,cAAc,EACd,cAAc,GAGf,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,GAAG,MAAM,cAAc,CAAC;AAGpC,qEAAqE;AACrE,kBAAkB;AAClB,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AA4C7M,MAAM,KAAK,GAAG,CAAC,KAAc,EAAoC,EAAE,CACjE,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC;AAgEvC,SAAS,yBAAyB,CAChC,EAAuB,EACvB,UAAa,EACb,OAAe,EACf,MAAc,EACd,MAAc,CAAC,EACf,OAAgB;IAEhB,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACxB,MAAM,CAAC,GAAG,EAAmB,CAAC;IAC9B,iGAAiG;IACjG,wFAAwF;IACxF,IAAI,GAAG,IAAI,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,8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AC,wBAAwB,CAAC,CAAC;IAC5C,IAAI,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,QAAQ,IAAI,OAAO,UAAU,CAAC,CAAC,CAAC,KAAK,QAAQ;QACxE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;IAC5C,MAAM,EAAE,GAAG,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,EAAE,EAAE,IAAI,CAAC,CAAC;IAClC,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC,CAAC;IAC7B,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;IACrC,OAAO,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAKzB,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.d.ts b/node_modules/@noble/curves/abstract/weierstrass.d.ts new file mode 100644 index 0000000..9c43b76 --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.d.ts @@ -0,0 +1,588 @@ +import { type CHash, type HmacFn, type TArg, type TRet } from '../utils.ts'; +import { type AffinePoint, type CurveLengths, type CurvePoint, type CurvePointCons } from './curve.ts'; +import { type IField } from './modular.ts'; +/** Shared affine point shape used by Weierstrass helpers. */ +export type { AffinePoint }; +type EndoBasis = [[bigint, bigint], [bigint, bigint]]; +/** + * When Weierstrass curve has `a=0`, it becomes Koblitz curve. + * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * + * Endomorphism consists of beta, lambda and splitScalar: + * + * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)` + * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)` + * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)` + * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than + * one 256-bit multiplication. + * + * where + * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1 + * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1 + * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors. + * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)` + * + * Check out `test/misc/endomorphism.js` and + * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}. + */ +export type EndomorphismOpts = { + /** Cube root of unity used by the GLV endomorphism. */ + beta: bigint; + /** Reduced lattice basis used for scalar splitting. */ + basises?: EndoBasis; + /** + * Optional custom scalar-splitting helper. + * Receives one scalar and returns two half-sized scalar components. + */ + splitScalar?: (k: bigint) => { + k1neg: boolean; + k1: bigint; + k2neg: boolean; + k2: bigint; + }; +}; +/** Two half-sized scalar components returned by endomorphism splitting. */ +export type ScalarEndoParts = { + /** Whether the first split scalar should be negated. */ + k1neg: boolean; + /** Absolute value of the first split scalar. */ + k1: bigint; + /** Whether the second split scalar should be negated. */ + k2neg: boolean; + /** Absolute value of the second split scalar. */ + k2: bigint; +}; +/** Splits scalar for GLV endomorphism. */ +export declare function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts; +/** + * Option to enable hedged signatures with improved security. + * + * * Randomly generated k is bad, because broken CSPRNG would leak private keys. + * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks. + * + * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness + * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure + * as ordinary sig without ExtraEntropy. + * + * * `true` means "fetch data, from CSPRNG, incorporate it into k generation" + * * `false` means "disable extra entropy, use purely deterministic k" + * * `Uint8Array` passed means "incorporate following data into k generation" + * + * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}. + */ +export type ECDSAExtraEntropy = boolean | Uint8Array; +/** + * - `compact` is the default format + * - `recovered` is the same as compact, but with an extra byte indicating recovery byte + * - `der` is ASN.1 DER encoding + */ +export type ECDSASignatureFormat = 'compact' | 'recovered' | 'der'; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + */ +export type ECDSARecoverOpts = { + /** Whether to hash the message before signature recovery. */ + prehash?: boolean; +}; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`. + * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures, + * which is default openssl behavior. + * Non-malleable signatures can still be successfully verified in openssl. + * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte + */ +export type ECDSAVerifyOpts = { + /** Whether to hash the message before verification. */ + prehash?: boolean; + /** Whether to reject high-S signatures. */ + lowS?: boolean; + /** Signature encoding to accept. */ + format?: ECDSASignatureFormat; +}; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`. + * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures, + * which is default openssl behavior. + * Non-malleable signatures can still be successfully verified in openssl. + * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte + * - `extraEntropy`: (default: false) creates signatures with increased + * security, see {@link ECDSAExtraEntropy} + */ +export type ECDSASignOpts = { + /** Whether to hash the message before signing. */ + prehash?: boolean; + /** Whether to normalize signatures into the low-S half-order. */ + lowS?: boolean; + /** Signature encoding to produce. */ + format?: ECDSASignatureFormat; + /** Optional hedging input for deterministic k generation. */ + extraEntropy?: ECDSAExtraEntropy; +}; +/** Projective XYZ point used by short Weierstrass curves. */ +export interface WeierstrassPoint extends CurvePoint> { + /** projective X coordinate. Different from affine x. */ + readonly X: T; + /** projective Y coordinate. Different from affine y. */ + readonly Y: T; + /** projective z coordinate */ + readonly Z: T; + /** affine x coordinate. Different from projective X. */ + get x(): T; + /** affine y coordinate. Different from projective Y. */ + get y(): T; + /** + * Encode the point into compressed or uncompressed SEC1 bytes. + * @param isCompressed - Whether to use the compressed form. + * @returns Encoded point bytes. + */ + toBytes(isCompressed?: boolean): TRet; + /** + * Encode the point into compressed or uncompressed SEC1 hex. + * @param isCompressed - Whether to use the compressed form. + * @returns Encoded point hex. + */ + toHex(isCompressed?: boolean): string; +} +/** Constructor and metadata helpers for Weierstrass points. */ +export interface WeierstrassPointCons extends CurvePointCons> { + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + new (X: T, Y: T, Z: T): WeierstrassPoint; + /** + * Return the curve parameters captured by this point constructor. + * @returns Curve parameters. + */ + CURVE(): WeierstrassOpts; +} +/** + * Weierstrass curve options. + * + * * p: prime characteristic (order) of finite field, in which arithmetics is done + * * n: order of prime subgroup a.k.a total amount of valid curve points + * * h: cofactor, usually 1. h*n is group order; n is subgroup order + * * a: formula param, must be in field of p + * * b: formula param, must be in field of p + * * Gx: x coordinate of generator point a.k.a. base point + * * Gy: y coordinate of generator point + */ +export type WeierstrassOpts = Readonly<{ + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Curve cofactor. */ + h: bigint; + /** Weierstrass curve parameter `a`. */ + a: T; + /** Weierstrass curve parameter `b`. */ + b: T; + /** Generator x coordinate. */ + Gx: T; + /** Generator y coordinate. */ + Gy: T; +}>; +/** + * Optional helpers and overrides for a Weierstrass point constructor. + * + * When a cofactor != 1, there can be effective methods to: + * 1. Determine whether a point is torsion-free + * 2. Clear torsion component + */ +export type WeierstrassExtraOpts = Partial<{ + /** Optional base-field override. */ + Fp: IField; + /** Optional scalar-field override. */ + Fn: IField; + /** Whether the point constructor accepts infinity points. */ + allowInfinityPoint: boolean; + /** Optional GLV endomorphism data. */ + endo: EndomorphismOpts; + /** Optional torsion-check override. */ + isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean; + /** Optional cofactor-clearing override. */ + clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint; + /** Optional custom point decoder. */ + fromBytes: (bytes: TArg) => AffinePoint; + /** Optional custom point encoder. */ + toBytes: (c: WeierstrassPointCons, point: WeierstrassPoint, isCompressed: boolean) => TRet; +}>; +/** + * Options for ECDSA signatures over a Weierstrass curve. + * + * * lowS: (default: true) whether produced or verified signatures occupy the + * low half of `ecdsaOpts.n`. Prevents malleability. + * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation. + * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness. + * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are + * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or + * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in + * `[0..Point.Fn.ORDER-1]`. + */ +export type ECDSAOpts = Partial<{ + /** Default low-S policy for this ECDSA instance. */ + lowS: boolean; + /** HMAC implementation used by RFC6979 DRBG. */ + hmac: HmacFn; + /** RNG override used by helper constructors. */ + randomBytes: (bytesLength?: number) => TRet; + /** Hash-to-integer conversion override. */ + bits2int: (bytes: TArg) => bigint; + /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */ + bits2int_modN: (bytes: TArg) => bigint; +}>; +/** Elliptic Curve Diffie-Hellman helper namespace. */ +export interface ECDH { + /** + * Generate a secret/public key pair. + * @param seed - Optional seed material. + * @returns Secret/public key pair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @param isCompressed - Whether to emit compressed SEC1 bytes. + * @returns Encoded public key. + */ + getPublicKey: (secretKey: TArg, isCompressed?: boolean) => TRet; + /** + * Compute the shared secret point from a secret key and peer public key. + * @param secretKeyA - Local secret key bytes. + * @param publicKeyB - Peer public key bytes. + * @param isCompressed - Whether to emit compressed SEC1 bytes. + * @returns Encoded shared point. + */ + getSharedSecret: (secretKeyA: TArg, publicKeyB: TArg, isCompressed?: boolean) => TRet; + /** Point constructor used by this ECDH instance. */ + Point: WeierstrassPointCons; + /** Validation and random-key helpers. */ + utils: { + /** Check whether a secret key has the expected encoding. */ + isValidSecretKey: (secretKey: TArg) => boolean; + /** Check whether a public key decodes to a valid point. */ + isValidPublicKey: (publicKey: TArg, isCompressed?: boolean) => boolean; + /** Generate a valid random secret key. */ + randomSecretKey: (seed?: TArg) => TRet; + }; + /** Byte lengths for keys and signatures exposed by this curve. */ + lengths: CurveLengths; +} +/** + * ECDSA interface. + * Only supported for prime fields, not Fp2 (extension fields). + */ +export interface ECDSA extends ECDH { + /** + * Sign a message with the given secret key. + * @param message - Message bytes. + * @param secretKey - Secret key bytes. + * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}. + * @returns Encoded signature bytes. + */ + sign: (message: TArg, secretKey: TArg, opts?: TArg) => TRet; + /** + * Verify a signature against a message and public key. + * @param signature - Encoded signature bytes. + * @param message - Message bytes. + * @param publicKey - Encoded public key. + * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}. + * @returns Whether the signature is valid. + */ + verify: (signature: TArg, message: TArg, publicKey: TArg, opts?: TArg) => boolean; + /** + * Recover the public key encoded into a recoverable signature. + * @param signature - Recoverable signature bytes. + * @param message - Message bytes. + * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}. + * @returns Encoded recovered public key. + */ + recoverPublicKey(signature: TArg, message: TArg, opts?: TArg): TRet; + /** Signature constructor and parser helpers. */ + Signature: ECDSASignatureCons; +} +/** + * @param m - Error message. + * @example + * Throw a DER-specific error when signature parsing encounters invalid bytes. + * + * ```ts + * new DERErr('bad der'); + * ``` + */ +export declare class DERErr extends Error { + constructor(m?: string); +} +/** DER helper namespace used by ECDSA signature parsing and encoding. */ +export type IDER = { + /** + * DER-specific error constructor. + * @param m - Error message. + * @returns DER-specific error instance. + */ + Err: typeof DERErr; + /** Low-level tag-length-value helpers used by DER encoders. */ + _tlv: { + /** + * Encode one TLV record. + * @param tag - ASN.1 tag byte. + * @param data - Hex-encoded value payload. + * @returns Encoded TLV string. + */ + encode: (tag: number, data: string) => string; + /** + * Decode one TLV record and return the value plus leftover bytes. + * @param tag - Expected ASN.1 tag byte. + * @param data - Remaining DER bytes. + * @returns Parsed value plus leftover bytes. + */ + decode(tag: number, data: TArg): TRet<{ + v: Uint8Array; + l: Uint8Array; + }>; + }; + /** Positive-integer DER helpers used by ECDSA signature encoding. */ + _int: { + /** + * Encode one positive bigint as a DER INTEGER. + * @param num - Positive integer to encode. + * @returns Encoded DER INTEGER. + */ + encode(num: bigint): string; + /** + * Decode one DER INTEGER into a bigint. + * @param data - DER INTEGER bytes. + * @returns Decoded bigint. + */ + decode(data: TArg): bigint; + }; + /** + * Parse a DER signature into `{ r, s }`. + * @param bytes - DER signature bytes. + * @returns Parsed signature components. + */ + toSig(bytes: TArg): { + r: bigint; + s: bigint; + }; + /** + * Encode `{ r, s }` as a DER signature. + * @param sig - Signature components. + * @returns DER-encoded signature hex. + */ + hexFromSig(sig: { + r: bigint; + s: bigint; + }): string; +}; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and + * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}. + * @example + * ASN.1 DER encoding utilities. + * + * ```ts + * const der = DER.hexFromSig({ r: 1n, s: 2n }); + * ``` + */ +export declare const DER: IDER; +/** + * Creates weierstrass Point constructor, based on specified curve options. + * + * See {@link WeierstrassOpts}. + * @param params - Curve parameters. See {@link WeierstrassOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}. + * @returns Weierstrass point constructor. + * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error} + * + * @example + * Construct a point type from explicit Weierstrass curve parameters. + * + * ```js + * const opts = { + * p: 0xfffffffffffffffffffffffffffffffeffffac73n, + * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n, + * h: 1n, + * a: 0n, + * b: 7n, + * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn, + * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen, + * }; + * const secp160k1_Point = weierstrass(opts); + * ``` + */ +export declare function weierstrass(params: WeierstrassOpts, extraOpts?: WeierstrassExtraOpts): WeierstrassPointCons; +/** Parsed ECDSA signature with helpers for recovery and re-encoding. */ +export interface ECDSASignature { + /** Signature component `r`. */ + readonly r: bigint; + /** Signature component `s`. */ + readonly s: bigint; + /** Optional recovery bit for recoverable signatures. */ + readonly recovery?: number; + /** + * Return a copy of the signature with a recovery bit attached. + * @param recovery - Recovery bit to attach. + * @returns Signature with an attached recovery bit. + */ + addRecoveryBit(recovery: number): ECDSASignature & { + readonly recovery: number; + }; + /** + * Check whether the signature uses the high-S half-order. + * @returns Whether the signature uses the high-S half-order. + */ + hasHighS(): boolean; + /** + * Recover the public key from the hashed message and recovery bit. + * @param messageHash - Hashed message bytes. + * @returns Recovered public-key point. + */ + recoverPublicKey(messageHash: TArg): WeierstrassPoint; + /** + * Encode the signature into bytes. + * @param format - Signature encoding to produce. + * @returns Encoded signature bytes. + */ + toBytes(format?: string): TRet; + /** + * Encode the signature into hex. + * @param format - Signature encoding to produce. + * @returns Encoded signature hex. + */ + toHex(format?: string): string; +} +/** Constructor and decoding helpers for ECDSA signatures. */ +export type ECDSASignatureCons = { + /** Create a signature from `r`, `s`, and an optional recovery bit. */ + new (r: bigint, s: bigint, recovery?: number): ECDSASignature; + /** + * Decode a signature from bytes. + * @param bytes - Encoded signature bytes. + * @param format - Signature encoding to parse. + * @returns Parsed signature. + */ + fromBytes(bytes: TArg, format?: ECDSASignatureFormat): ECDSASignature; + /** + * Decode a signature from hex. + * @param hex - Encoded signature hex. + * @param format - Signature encoding to parse. + * @returns Parsed signature. + */ + fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature; +}; +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it. + * @param Fp - Field implementation. + * @param Z - Simplified SWU map parameter. + * @returns Square-root ratio helper. + * @example + * Build the square-root ratio helper used by SWU map implementations. + * + * ```ts + * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n); + * const out = sqrtRatio(4n, 1n); + * ``` + */ +export declare function SWUFpSqrtRatio(Fp: TArg>, Z: T): (u: T, v: T) => { + isValid: boolean; + value: T; +}; +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}. + * @param Fp - Field implementation. + * @param opts - SWU parameters: + * - `A`: Curve parameter `A`. + * - `B`: Curve parameter `B`. + * - `Z`: Simplified SWU map parameter. + * @returns Deterministic map-to-curve function. + * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error} + * @example + * Map one field element to a Weierstrass curve point with the SWU recipe. + * + * ```ts + * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n }); + * const point = map(5n); + * ``` + */ +export declare function mapToCurveSimpleSWU(Fp: TArg>, opts: { + A: T; + B: T; + Z: T; +}): (u: T) => { + x: T; + y: T; +}; +/** + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * This helper ensures no signature functionality is present. Less code, smaller bundle size. + * @param Point - Weierstrass point constructor. + * @param ecdhOpts - Optional randomness helpers: + * - `randomBytes` (optional): Optional RNG override. + * @returns ECDH helper namespace. + * @example + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * + * ```ts + * import { ecdh } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const dh = ecdh(p256.Point); + * const alice = dh.keygen(); + * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export declare function ecdh(Point: WeierstrassPointCons, ecdhOpts?: TArg<{ + randomBytes?: (bytesLength?: number) => TRet; +}>): ECDH; +/** + * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function. + * + * @param Point - created using {@link weierstrass} function + * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash) + * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}: + * - `lowS`: Default low-S policy. + * - `hmac`: HMAC implementation used by RFC6979 DRBG. + * - `randomBytes`: Optional RNG override. + * - `bits2int`: Optional hash-to-int conversion override. + * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override. + * + * @returns ECDSA helper namespace. + * @example + * Create an ECDSA signer/verifier bundle for one curve implementation. + * + * ```ts + * import { ecdsa } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const p256ecdsa = ecdsa(p256.Point, sha256); + * const { secretKey, publicKey } = p256ecdsa.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256ecdsa.sign(msg, secretKey); + * const isValid = p256ecdsa.verify(sig, msg, publicKey); + * ``` + */ +export declare function ecdsa(Point: WeierstrassPointCons, hash: TArg, ecdsaOpts?: TArg): ECDSA; +//# sourceMappingURL=weierstrass.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.d.ts.map b/node_modules/@noble/curves/abstract/weierstrass.d.ts.map new file mode 100644 index 0000000..edaf101 --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.d.ts","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AA6BA,OAAO,EAiBL,KAAK,KAAK,EACV,KAAK,MAAM,EAEX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,aAAa,CAAC;AACrB,OAAO,EAOL,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,UAAU,EACf,KAAK,cAAc,EACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAML,KAAK,MAAM,EACZ,MAAM,cAAc,CAAC;AAEtB,6DAA6D;AAC7D,YAAY,EAAE,WAAW,EAAE,CAAC;AAE5B,KAAK,SAAS,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AACtD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,CAAC,CAAC,EAAE,MAAM,KAAK;QAAE,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,OAAO,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;CACzF,CAAC;AAOF,2EAA2E;AAC3E,MAAM,MAAM,eAAe,GAAG;IAC5B,wDAAwD;IACxD,KAAK,EAAE,OAAO,CAAC;IACf,gDAAgD;IAChD,EAAE,EAAE,MAAM,CAAC;IACX,yDAAyD;IACzD,KAAK,EAAE,OAAO,CAAC;IACf,iDAAiD;IACjD,EAAE,EAAE,MAAM,CAAC;CACZ,C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AACH,wBAAgB,KAAK,CACnB,KAAK,EAAE,oBAAoB,CAAC,MAAM,CAAC,EACnC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,SAAS,GAAE,IAAI,CAAC,SAAS,CAAM,GAC9B,KAAK,CAoWP"} \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.js b/node_modules/@noble/curves/abstract/weierstrass.js new file mode 100644 index 0000000..21b5ad7 --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.js @@ -0,0 +1,1412 @@ +/** + * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b. + * + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance + * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create + * unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac as nobleHmac } from '@noble/hashes/hmac.js'; +import { ahash } from '@noble/hashes/utils.js'; +import { abignumber, abool, abytes, aInRange, asafenumber, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, createHmacDrbg, hexToBytes, isBytes, numberToHexUnpadded, validateObject, randomBytes as wcRandomBytes, } from "../utils.js"; +import { createCurveFields, createKeygen, mulEndoUnsafe, negateCt, normalizeZ, wNAF, } from "./curve.js"; +import { FpInvertBatch, FpIsSquare, getMinHashLength, mapHashToField, validateField, } from "./modular.js"; +// We construct the basis so `den` is always positive and equals `n`, +// but the `num` sign depends on the basis, not on the secret value. +// Exact half-way cases round away from zero, which keeps the split symmetric +// around the reduced-basis boundaries used by endomorphism decomposition. +const divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n) / den; +/** Splits scalar for GLV endomorphism. */ +export function _splitEndoScalar(k, basis, n) { + // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)` + // Since part can be negative, we need to do this on point. + // Callers must provide a reduced GLV basis whose vectors satisfy + // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`. + // Reject unreduced scalars instead of silently treating them mod n. + aInRange('scalar', k, _0n, n); + // TODO: verifyScalar function which consumes lambda + const [[a1, b1], [a2, b2]] = basis; + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + // |k1|/|k2| is < sqrt(N), but can be negative. + // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead. + let k1 = k - c1 * a1 - c2 * a2; + let k2 = -c1 * b1 - c2 * b2; + const k1neg = k1 < _0n; + const k2neg = k2 < _0n; + if (k1neg) + k1 = -k1; + if (k2neg) + k2 = -k2; + // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail. + // This should only happen on wrong bases. + // Also, the math inside is complex enough that this guard is worth keeping. + const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N + if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) { + throw new Error('splitScalar (endomorphism): failed for k'); + } + return { k1neg, k1, k2neg, k2 }; +} +function validateSigFormat(format) { + if (!['compact', 'recovered', 'der'].includes(format)) + throw new Error('Signature format must be "compact", "recovered", or "der"'); + return format; +} +function validateSigOpts(opts, def) { + validateObject(opts); + const optsn = {}; + // Normalize only the declared option subset from `def`; unknown keys are + // intentionally ignored so shared / superset option bags stay valid here too. + // `extraEntropy` stays an opaque payload until the signing path consumes it. + for (let optName of Object.keys(def)) { + // @ts-ignore + optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName]; + } + abool(optsn.lowS, 'lowS'); + abool(optsn.prehash, 'prehash'); + if (optsn.format !== undefined) + validateSigFormat(optsn.format); + return optsn; +} +/** + * @param m - Error message. + * @example + * Throw a DER-specific error when signature parsing encounters invalid bytes. + * + * ```ts + * new DERErr('bad der'); + * ``` + */ +export class DERErr extends Error { + constructor(m = '') { + super(m); + } +} +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and + * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}. + * @example + * ASN.1 DER encoding utilities. + * + * ```ts + * const der = DER.hexFromSig({ r: 1n, s: 2n }); + * ``` + */ +export const DER = { + // asn.1 DER encoding utils + Err: DERErr, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + asafenumber(tag, 'tag'); + if (tag < 0 || tag > 255) + throw new E('tlv.encode: wrong tag'); + if (typeof data !== 'string') + throw new TypeError('"data" expected string, got type=' + typeof data); + // Internal helper: callers hand this already-validated hex payload, so we only enforce + // byte alignment here instead of re-validating every nibble. + if (data.length & 1) + throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 0b1000_0000) + throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : ''; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + data = abytes(data, undefined, 'DER data'); + let pos = 0; + if (tag < 0 || tag > 255) + throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) + throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + // First bit of first length byte is the short/long form flag. + const isLong = !!(first & 0b1000_0000); + let length = 0; + if (!isLong) + length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 0b0111_1111; + if (!lenLen) + throw new E('tlv.decode(long): indefinite length not supported'); + // This would overflow u32 in JS. + if (lenLen > 4) + throw new E('tlv.decode(long): byte length is too big'); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) + throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) + length = (length << 8) | b; + pos += lenLen; + if (length < 128) + throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) }; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + abignumber(num); + if (num < _0n) + throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) + hex = '00' + hex; + if (hex.length & 1) + throw new E('unexpected DER parsing assertion: unpadded hex'); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data.length < 1) + throw new E('invalid signature integer: empty'); + if (data[0] & 0b1000_0000) + throw new E('invalid signature integer: negative'); + // Single-byte zero `00` is the canonical DER INTEGER encoding for zero. + if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000)) + throw new E('invalid signature integer: unnecessary leading zero'); + return bytesToNumberBE(data); + }, + }, + toSig(bytes) { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = abytes(bytes, undefined, 'signature'); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) + throw new E('invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) + throw new E('invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs = tlv.encode(0x02, int.encode(sig.r)); + const ss = tlv.encode(0x02, int.encode(sig.s)); + const seq = rs + ss; + return tlv.encode(0x30, seq); + }, +}; +Object.freeze(DER._tlv); +Object.freeze(DER._int); +Object.freeze(DER); +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4); +/** + * Creates weierstrass Point constructor, based on specified curve options. + * + * See {@link WeierstrassOpts}. + * @param params - Curve parameters. See {@link WeierstrassOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}. + * @returns Weierstrass point constructor. + * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error} + * + * @example + * Construct a point type from explicit Weierstrass curve parameters. + * + * ```js + * const opts = { + * p: 0xfffffffffffffffffffffffffffffffeffffac73n, + * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n, + * h: 1n, + * a: 0n, + * b: 7n, + * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn, + * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen, + * }; + * const secp160k1_Point = weierstrass(opts); + * ``` + */ +export function weierstrass(params, extraOpts = {}) { + const validated = createCurveFields('weierstrass', params, extraOpts); + const Fp = validated.Fp; + const Fn = validated.Fn; + let CURVE = validated.CURVE; + const { h: cofactor, n: CURVE_ORDER } = CURVE; + validateObject(extraOpts, {}, { + allowInfinityPoint: 'boolean', + clearCofactor: 'function', + isTorsionFree: 'function', + fromBytes: 'function', + toBytes: 'function', + endo: 'object', + }); + // Snapshot constructor-time flags whose later mutation would otherwise change + // validity semantics of an already-built point type. + const { endo, allowInfinityPoint } = extraOpts; + if (endo) { + // validateObject(endo, { beta: 'bigint', splitScalar: 'function' }); + if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) { + throw new Error('invalid endo: expected "beta": bigint and "basises": array'); + } + } + const lengths = getWLengths(Fp, Fn); + function assertCompressionIsSupported() { + if (!Fp.isOdd) + throw new Error('compression is not supported: Field does not have .isOdd()'); + } + // Implements IEEE P1363 point encoding + function pointToBytes(_c, point, isCompressed) { + // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves + // that opt into infinity as a public point value should expose that byte form. + if (allowInfinityPoint && point.is0()) + return Uint8Array.of(0); + const { x, y } = point.toAffine(); + const bx = Fp.toBytes(x); + abool(isCompressed, 'isCompressed'); + if (isCompressed) { + assertCompressionIsSupported(); + const hasEvenY = !Fp.isOdd(y); + return concatBytes(pprefix(hasEvenY), bx); + } + else { + return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)); + } + } + function pointFromBytes(bytes) { + abytes(bytes, undefined, 'Point'); + const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65 + const length = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (allowInfinityPoint && length === 1 && head === 0x00) + return { x: Fp.ZERO, y: Fp.ZERO }; + // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation + // rejects infinity. We therefore keep 0x00 rejected by default because callers + // reuse this parser as the strict public-key boundary, and only admit it when + // the curve explicitly opts into infinity as a public point value. secp256k1 + // crosstests show OpenSSL raw point codecs accept 0x00 too. + // No actual validation is done here: use .assertValidity() + if (length === comp && (head === 0x02 || head === 0x03)) { + const x = Fp.fromBytes(tail); + if (!Fp.isValid(x)) + throw new Error('bad point: is not on curve, wrong x'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } + catch (sqrtError) { + const err = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('bad point: is not on curve, sqrt error' + err); + } + assertCompressionIsSupported(); + const evenY = Fp.isOdd(y); + const evenH = (head & 1) === 1; // ECDSA-specific + if (evenH !== evenY) + y = Fp.neg(y); + return { x, y }; + } + else if (length === uncomp && head === 0x04) { + // TODO: more checks + const L = Fp.BYTES; + const x = Fp.fromBytes(tail.subarray(0, L)); + const y = Fp.fromBytes(tail.subarray(L, L * 2)); + if (!isValidXY(x, y)) + throw new Error('bad point: is not on curve'); + return { x, y }; + } + else { + throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`); + } + } + const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes; + const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes; + function weierstrassEquation(x) { + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x² * x + return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b + } + // TODO: move top-level + /** Checks whether equation holds for given x, y: y² == x³ + ax + b */ + function isValidXY(x, y) { + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + return Fp.eql(left, right); + } + // Keep constructor-time generator validation cheap: callers are responsible for supplying the + // correct prime-order base point, while eager subgroup checks here would slow heavy module imports. + // Test 1: equation y² = x³ + ax + b should work for generator point. + if (!isValidXY(CURVE.Gx, CURVE.Gy)) + throw new Error('bad curve params: generator point'); + // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0. + // Guarantees curve is genus-1, smooth (non-singular). + const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n); + const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); + if (Fp.is0(Fp.add(_4a3, _27b2))) + throw new Error('bad curve params: a or b'); + /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */ + function acoord(title, n, banZero = false) { + if (!Fp.isValid(n) || (banZero && Fp.is0(n))) + throw new Error(`bad point coordinate ${title}`); + return n; + } + function aprjpoint(other) { + if (!(other instanceof Point)) + throw new Error('Weierstrass Point expected'); + } + function splitEndoScalarN(k) { + if (!endo || !endo.basises) + throw new Error('no endo'); + return _splitEndoScalar(k, endo.basises, Fn.ORDER); + } + function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { + k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); + k1p = negateCt(k1neg, k1p); + k2p = negateCt(k2neg, k2p); + return k1p.add(k2p); + } + /** + * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z). + * Default Point works in 2d / affine coordinates: (x, y). + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point { + // base / generator point + static BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + // zero / infinity / identity point + static ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0 + // math field + static Fp = Fp; + // scalar field + static Fn = Fn; + X; + Y; + Z; + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + constructor(X, Y, Z) { + this.X = acoord('x', X); + // This is not just about ZERO / infinity: ambient curves can have real + // finite points with y=0. Those points are 2-torsion, so they cannot lie + // in the odd prime-order subgroups this point type is meant to represent. + this.Y = acoord('y', Y, true); + this.Z = acoord('z', Z); + Object.freeze(this); + } + static CURVE() { + return CURVE; + } + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('invalid affine point'); + if (p instanceof Point) + throw new Error('projective point not allowed'); + // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0) + if (Fp.is0(x) && Fp.is0(y)) + return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + static fromBytes(bytes) { + const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point'))); + P.assertValidity(); + return P; + } + static fromHex(hex) { + return Point.fromBytes(hexToBytes(hex)); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * + * @param windowSize + * @param isLazy - true will defer table computation until the first multiplication + * @returns + */ + precompute(windowSize = 8, isLazy = true) { + wnaf.createCache(this, windowSize); + if (!isLazy) + this.multiply(_3n); // random number + return this; + } + // TODO: return `this` + /** A point on curve is valid if it conforms to equation. */ + assertValidity() { + const p = this; + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points + // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard. + if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error('bad point: x or y not field elements'); + if (!isValidXY(x, y)) + throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) + throw new Error('bad point: not in prime-order subgroup'); + } + hasEvenY() { + const { y } = this.toAffine(); + if (!Fp.isOdd) + throw new Error("Field doesn't support isOdd"); + return !Fp.isOdd(y); + } + /** Compare one point to another. */ + equals(other) { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ + negate() { + return new Point(this.X, Fp.neg(this.Y), this.Z); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { X: X1, Y: Y1, Z: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + subtract(other) { + // Validate before calling `negate()` so wrong inputs fail with the point guard + // instead of leaking a foreign `negate()` error. + aprjpoint(other); + return this.add(other.negate()); + } + is0() { + return this.equals(Point.ZERO); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar - by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo } = extraOpts; + // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO. + // In key/signature-style callers, those values usually mean broken hash/scalar plumbing, + // and failing closed is safer than silently producing the identity point. + if (!Fn.isValidNot0(scalar)) + throw new RangeError('invalid scalar: out of range'); // 0 is invalid + let point, fake; // Fake point is used to const-time mult + const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)); + /** See docs for {@link EndomorphismOpts} */ + if (endo) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); + const { p: k1p, f: k1f } = mul(k1); + const { p: k2p, f: k2f } = mul(k2); + fake = k1f.add(k2f); + point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg); + } + else { + const { p, f } = mul(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return normalizeZ(Point, [point, fake])[0]; + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed secret key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(scalar) { + const { endo } = extraOpts; + const p = this; + const sc = scalar; + // Public-scalar callers may need 0, but n and larger values stay rejected here too. + // Reducing them mod n would turn bad caller input into an accidental identity point. + if (!Fn.isValid(sc)) + throw new RangeError('invalid scalar: out of range'); // 0 is valid + if (sc === _0n || p.is0()) + return Point.ZERO; // 0 + if (sc === _1n) + return p; // 1 + if (wnaf.hasCache(this)) + return this.multiply(sc); // precomputes + // We don't have method for double scalar multiplication (aP + bQ): + // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add. + if (endo) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); + const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe + return finishEndo(endo.beta, p1, p2, k1neg, k2neg); + } + else { + return wnaf.unsafe(p, sc); + } + } + /** + * Converts Projective point to affine (x, y) coordinates. + * (X, Y, Z) ∋ (x=X/Z, y=Y/Z). + * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch + */ + toAffine(invertedZ) { + const p = this; + let iz = invertedZ; + const { X, Y, Z } = p; + // Fast-path for normalized points + if (Fp.eql(Z, Fp.ONE)) + return { x: X, y: Y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(Z); + const x = Fp.mul(X, iz); + const y = Fp.mul(Y, iz); + const zz = Fp.mul(Z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error('invZ was invalid'); + return { x, y }; + } + /** + * Checks whether Point is free of torsion elements (is in prime subgroup). + * Always torsion-free for cofactor=1 curves. + */ + isTorsionFree() { + const { isTorsionFree } = extraOpts; + if (cofactor === _1n) + return true; + if (isTorsionFree) + return isTorsionFree(Point, this); + return wnaf.unsafe(this, CURVE_ORDER).is0(); + } + clearCofactor() { + const { clearCofactor } = extraOpts; + if (cofactor === _1n) + return this; // Fast-path + if (clearCofactor) + return clearCofactor(Point, this); + // Default fallback assumes the cofactor fits the usual subgroup-scalar + // multiplyUnsafe() contract. Curves with larger / structured cofactors + // should define a clearCofactor override anyway (e.g. psi/Frobenius maps). + return this.multiplyUnsafe(cofactor); + } + isSmallOrder() { + if (cofactor === _1n) + return this.is0(); // Fast-path + return this.clearCofactor().is0(); + } + toBytes(isCompressed = true) { + abool(isCompressed, 'isCompressed'); + // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because + // callers use these encodings as public keys, where SEC 1 validation rejects infinity. + this.assertValidity(); + return encodePoint(Point, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex(this.toBytes(isCompressed)); + } + toString() { + return ``; + } + } + const bits = Fn.BITS; + const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits); + // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the + // eager W=8 cache there instead of rejecting an otherwise valid constructor. + if (bits >= 8) + Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + Object.freeze(Point.prototype); + Object.freeze(Point); + return Point; +} +// Points start with byte 0x02 when y is even; otherwise 0x03 +function pprefix(hasEvenY) { + return Uint8Array.of(hasEvenY ? 0x02 : 0x03); +} +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it. + * @param Fp - Field implementation. + * @param Z - Simplified SWU map parameter. + * @returns Square-root ratio helper. + * @example + * Build the square-root ratio helper used by SWU map implementations. + * + * ```ts + * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n); + * const out = sqrtRatio(4n, 1n); + * ``` + */ +export function SWUFpSqrtRatio(Fp, Z) { + // Fail with the usual field-shape error before touching pow/cmov on malformed field shims. + const F = validateField(Fp); + // Generic implementation + const q = F.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) + l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = F.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0. + // We keep v=0 on the regular result path with isValid=false instead of + // throwing so the helper stays closer to the RFC's fixed control flow. + let sqrtRatio = (u, v) => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = F.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1 + tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1 + tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0. + // When u = 0 and v != 0, u / v = 0 is square and the computed root is + // still 0, so widen only the final flag and keep the full control flow. + return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 }; + }; + if (F.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u, v) => { + let tv1 = F.sqr(v); // 1. tv1 = v^2 + const tv2 = F.mul(u, v); // 2. tv2 = u * v + tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u + let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}. + * @param Fp - Field implementation. + * @param opts - SWU parameters: + * - `A`: Curve parameter `A`. + * - `B`: Curve parameter `B`. + * - `Z`: Simplified SWU map parameter. + * @returns Deterministic map-to-curve function. + * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error} + * @example + * Map one field element to a Weierstrass curve point with the SWU recipe. + * + * ```ts + * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n }); + * const point = map(5n); + * ``` + */ +export function mapToCurveSimpleSWU(Fp, opts) { + const F = validateField(Fp); + const { A, B, Z } = opts; + if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + // RFC 9380 §6.6.2 and Appendix H.2 require: + // 1. Z is non-square in F + // 2. Z != -1 in F + // 3. g(x) - Z is irreducible over F + // 4. g(B / (Z * A)) is square in F + // We can enforce 1, 2, and 4 with the current field API. + // Criterion 3 is not checked here because generic `IField` does not expose + // polynomial-ring / irreducibility operations, and this helper is used for + // both prime and extension fields. + if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F. + // x = B / (Z * A) + const x = F.mul(B, F.inv(F.mul(Z, A))); + // g(x) = x^3 + A*x + B + const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B); + if (!FpIsSquare(F, gx)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(F, Z); + if (!F.isOdd) + throw new Error('Field does not have .isOdd()'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u) => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = F.sqr(u); // 1. tv1 = u^2 + tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1 + tv2 = F.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1 + tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3 + tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4 + tv2 = F.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = F.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6 + tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6 + tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = F.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = F.mul(y, value); // 20. y = y * y1 + x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = F.isOdd(u) === F.isOdd(y); // 23. e1 = sgn0(u) == sgn0(y) + y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + const tv4_inv = FpInvertBatch(F, [tv4], true)[0]; + x = F.mul(x, tv4_inv); // 25. x = x / tv4 + return { x, y }; + }; +} +function getWLengths(Fp, Fn) { + return { + secretKey: Fn.BYTES, + publicKey: 1 + Fp.BYTES, + publicKeyUncompressed: 1 + 2 * Fp.BYTES, + publicKeyHasPrefix: true, + // Raw compact `(r || s)` signature width; DER and recovered signatures use + // different lengths outside this helper. + signature: 2 * Fn.BYTES, + }; +} +/** + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * This helper ensures no signature functionality is present. Less code, smaller bundle size. + * @param Point - Weierstrass point constructor. + * @param ecdhOpts - Optional randomness helpers: + * - `randomBytes` (optional): Optional RNG override. + * @returns ECDH helper namespace. + * @example + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * + * ```ts + * import { ecdh } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const dh = ecdh(p256.Point); + * const alice = dh.keygen(); + * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export function ecdh(Point, ecdhOpts = {}) { + const { Fn } = Point; + const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes; + // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte + // minimum even on toy curves. + const lengths = Object.assign(getWLengths(Point.Fp, Fn), { + seed: Math.max(getMinHashLength(Fn.ORDER), 16), + }); + function isValidSecretKey(secretKey) { + try { + const num = Fn.fromBytes(secretKey); + return Fn.isValidNot0(num); + } + catch (error) { + return false; + } + } + function isValidPublicKey(publicKey, isCompressed) { + const { publicKey: comp, publicKeyUncompressed } = lengths; + try { + const l = publicKey.length; + if (isCompressed === true && l !== comp) + return false; + if (isCompressed === false && l !== publicKeyUncompressed) + return false; + return !!Point.fromBytes(publicKey); + } + catch (error) { + return false; + } + } + /** + * Produces cryptographically secure secret key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + function randomSecretKey(seed) { + seed = seed === undefined ? randomBytes_(lengths.seed) : seed; + return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER); + } + /** + * Computes public key for a secret key. Checks for validity of the secret key. + * @param isCompressed - whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(secretKey, isCompressed = true) { + return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed); + } + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item) { + const { secretKey, publicKey, publicKeyUncompressed } = lengths; + const allowedLengths = Fn._lengths; + if (!isBytes(item)) + return undefined; + const l = abytes(item, undefined, 'key').length; + const isPub = l === publicKey || l === publicKeyUncompressed; + const isSec = l === secretKey || !!allowedLengths?.includes(l); + // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous. + if (isPub && isSec) + return undefined; + return isPub; + } + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes encoded shared point from secret key A and public key B. + * Checks: 1) secret key validity 2) shared key is on-curve. + * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`. + * Returns the encoded shared point on purpose: callers that need `x_P` + * can derive it from the encoded point, but `x_P` alone cannot recover the + * point/parity back. + * This helper only exposes the fully validated public-key path, not cofactor DH. + * @param isCompressed - whether to return compact (default), or full key + * @returns shared point encoding + */ + function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) { + if (isProbPub(secretKeyA) === true) + throw new Error('first arg must be private key'); + if (isProbPub(publicKeyB) === false) + throw new Error('second arg must be public key'); + const s = Fn.fromBytes(secretKeyA); + const b = Point.fromBytes(publicKeyB); // checks for being on-curve + return b.multiply(s).toBytes(isCompressed); + } + const utils = { + isValidSecretKey, + isValidPublicKey, + randomSecretKey, + }; + const keygen = createKeygen(randomSecretKey, getPublicKey); + Object.freeze(utils); + Object.freeze(lengths); + return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths }); +} +/** + * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function. + * + * @param Point - created using {@link weierstrass} function + * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash) + * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}: + * - `lowS`: Default low-S policy. + * - `hmac`: HMAC implementation used by RFC6979 DRBG. + * - `randomBytes`: Optional RNG override. + * - `bits2int`: Optional hash-to-int conversion override. + * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override. + * + * @returns ECDSA helper namespace. + * @example + * Create an ECDSA signer/verifier bundle for one curve implementation. + * + * ```ts + * import { ecdsa } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const p256ecdsa = ecdsa(p256.Point, sha256); + * const { secretKey, publicKey } = p256ecdsa.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256ecdsa.sign(msg, secretKey); + * const isValid = p256ecdsa.verify(sig, msg, publicKey); + * ``` + */ +export function ecdsa(Point, hash, ecdsaOpts = {}) { + // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes. + const hash_ = hash; + ahash(hash_); + validateObject(ecdsaOpts, {}, { + hmac: 'function', + lowS: 'boolean', + randomBytes: 'function', + bits2int: 'function', + bits2int_modN: 'function', + }); + ecdsaOpts = Object.assign({}, ecdsaOpts); + const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes; + const hmac = ecdsaOpts.hmac === undefined + ? (key, msg) => nobleHmac(hash_, key, msg) + : ecdsaOpts.hmac; + const { Fp, Fn } = Point; + const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn; + const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts); + const defaultSigOpts = { + prehash: true, + lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true, + format: 'compact', + extraEntropy: false, + }; + // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature + // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n. + // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the + // smallest such lift is 1 + 2n, not 2n. + const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER; + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function validateRS(title, num) { + if (!Fn.isValidNot0(num)) + throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); + return num; + } + function assertRecoverableCurve() { + // ECDSA recovery only supports curves where the current recovery id can distinguish + // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches. + // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1. + // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n. + // To easily get i, we either need to: + // a. increase amount of valid recid values (4, 5...); OR + // b. prohibit recovered signatures for those curves. + if (hasLargeRecoveryLifts) + throw new Error('"recovered" sig type is not supported for cofactor >2 curves'); + } + function validateSigLength(bytes, format) { + validateSigFormat(format); + const size = lengths.signature; + const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined; + return abytes(bytes, sizer); + } + /** + * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations. + */ + class Signature { + r; + s; + recovery; + constructor(r, s, recovery) { + this.r = validateRS('r', r); // r in [1..N-1]; + this.s = validateRS('s', s); // s in [1..N-1]; + if (recovery != null) { + assertRecoverableCurve(); + if (![0, 1, 2, 3].includes(recovery)) + throw new Error('invalid recovery id'); + this.recovery = recovery; + } + Object.freeze(this); + } + static fromBytes(bytes, format = defaultSigOpts.format) { + validateSigLength(bytes, format); + let recid; + if (format === 'der') { + const { r, s } = DER.toSig(abytes(bytes)); + return new Signature(r, s); + } + if (format === 'recovered') { + recid = bytes[0]; + format = 'compact'; + bytes = bytes.subarray(1); + } + const L = lengths.signature / 2; + const r = bytes.subarray(0, L); + const s = bytes.subarray(L, L * 2); + return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid); + } + static fromHex(hex, format) { + return this.fromBytes(hexToBytes(hex), format); + } + assertRecovery() { + const { recovery } = this; + if (recovery == null) + throw new Error('invalid recovery id: must be present'); + return recovery; + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + // Unlike the top-level helper below, this method expects a digest that has + // already been hashed to the curve's message representative. + recoverPublicKey(messageHash) { + const { r, s } = this; + const recovery = this.assertRecovery(); + const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r; + if (!Fp.isValid(radj)) + throw new Error('invalid recovery id: sig.r+curve.n != R.x'); + const x = Fp.toBytes(radj); + const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x)); + const ir = Fn.inv(radj); // r^-1 + const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash + const u1 = Fn.create(-h * ir); // -hr^-1 + const u2 = Fn.create(s * ir); // sr^-1 + // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data. + const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); + if (Q.is0()) + throw new Error('invalid recovery: point at infinify'); + Q.assertValidity(); + return Q; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + toBytes(format = defaultSigOpts.format) { + validateSigFormat(format); + if (format === 'der') + return hexToBytes(DER.hexFromSig(this)); + const { r, s } = this; + const rb = Fn.toBytes(r); + const sb = Fn.toBytes(s); + if (format === 'recovered') { + assertRecoverableCurve(); + return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb); + } + return concatBytes(rb, sb); + } + toHex(format) { + return bytesToHex(this.toBytes(format)); + } + } + Object.freeze(Signature.prototype); + Object.freeze(Signature); + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int = ecdsaOpts.bits2int === undefined + ? function bits2int_def(bytes) { + // Our custom check "just in case", for protection against DoS + if (bytes.length > 8192) + throw new Error('input is too large'); + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + } + : ecdsaOpts.bits2int; + const bits2int_modN = ecdsaOpts.bits2int_modN === undefined + ? function bits2int_modN_def(bytes) { + return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here + } + : ecdsaOpts.bits2int_modN; + const ORDER_MASK = bitMask(fnBits); + // Pads output with zero as per spec. + /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */ + function int2octets(num) { + aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK); + return Fn.toBytes(num); + } + function validateMsgAndHash(message, prehash) { + abytes(message, undefined, 'message'); + return (prehash ? abytes(hash_(message), undefined, 'prehashed message') : message); + } + /** + * Steps A, D of RFC6979 3.2. + * Creates RFC6979 seed; converts msg/privKey to numbers. + * Used only in sign, not in verify. + * + * Warning: we cannot assume here that message has same amount of bytes as curve order, + * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256. + */ + function prepSig(message, secretKey, opts) { + const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m) + // We can't later call bits2octets, since nested bits2int is broken for curves + // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(message); + const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint + if (!Fn.isValidNot0(d)) + throw new Error('invalid private key'); + const seedArgs = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (extraEntropy != null && extraEntropy !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + // gen random bytes OR pass as-is + const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy; + seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes + } + const seed = concatBytes(...seedArgs); // Step D of RFC6979 3.2 + const m = h1int; // no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + // To transform k => Signature: + // q = k⋅G + // r = q.x mod n + // s = k^-1(m + rd) mod n + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + function k2sig(kBytes) { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + // Important: all mod() calls here must be done over N + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!Fn.isValidNot0(k)) + return; // Valid scalars (including k) must be in 1..N-1 + const ik = Fn.inv(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G + const r = Fn.create(q.x); // r = q.x mod n + if (r === _0n) + return; + const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n + if (s === _0n) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N + recovery ^= 1; + } + return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery); + } + return { seed, k2sig }; + } + /** + * Signs a message or message hash with a secret key. + * With the default `prehash: true`, raw message bytes are hashed internally; + * only `{ prehash: false }` expects a caller-supplied digest. + * + * ``` + * sign(m, d) where + * k = rfc6979_hmac_drbg(m, d) + * (x, y) = G × k + * r = x mod n + * s = (m + dr) / k mod n + * ``` + */ + function sign(message, secretKey, opts = {}) { + const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2. + const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac); + const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G + return sig.toBytes(opts.format); + } + /** + * Verifies a signature against message and public key. + * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}. + * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * u1 = hs^-1 mod n + * u2 = rs^-1 mod n + * R = u1⋅G + u2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify(signature, message, publicKey, opts = {}) { + const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts); + publicKey = abytes(publicKey, undefined, 'publicKey'); + message = validateMsgAndHash(message, prehash); + if (!isBytes(signature)) { + const end = signature instanceof Signature ? ', use sig.toBytes()' : ''; + throw new Error('verify expects Uint8Array signature' + end); + } + validateSigLength(signature, format); // execute this twice because we want loud error + try { + const sig = Signature.fromBytes(signature, format); + const P = Point.fromBytes(publicKey); + if (lowS && sig.hasHighS()) + return false; + const { r, s } = sig; + const h = bits2int_modN(message); // mod n, not mod p + const is = Fn.inv(s); // s^-1 mod n + const u1 = Fn.create(h * is); // u1 = hs^-1 mod n + const u2 = Fn.create(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P + if (R.is0()) + return false; + const v = Fn.create(R.x); // v = r.x mod n + return v === r; + } + catch (e) { + return false; + } + } + function recoverPublicKey(signature, message, opts = {}) { + // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message + // bytes first unless the caller passes `{ prehash: false }`. + const { prehash } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes(); + } + return Object.freeze({ + keygen, + getPublicKey, + getSharedSecret, + utils, + lengths, + Point, + sign, + verify, + recoverPublicKey, + Signature, + hash: hash_, + }); +} +//# sourceMappingURL=weierstrass.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/abstract/weierstrass.js.map b/node_modules/@noble/curves/abstract/weierstrass.js.map new file mode 100644 index 0000000..466df4b --- /dev/null +++ b/node_modules/@noble/curves/abstract/weierstrass.js.map @@ -0,0 +1 @@ +{"version":3,"file":"weierstrass.js","sourceRoot":"","sources":["../src/abstract/weierstrass.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,sEAAsE;AACtE,OAAO,EAAE,IAAI,IAAI,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAC;AAC/C,OAAO,EACL,UAAU,EACV,KAAK,EACL,MAAM,EACN,QAAQ,EACR,WAAW,EACX,MAAM,EACN,OAAO,EACP,UAAU,EACV,eAAe,EACf,WAAW,EACX,cAAc,EACd,UAAU,EACV,OAAO,EACP,mBAAmB,EACnB,cAAc,EACd,WAAW,IAAI,aAAa,GAM7B,MAAM,aAAa,CAAC;AACrB,OAAO,EACL,iBAAiB,EACjB,YAAY,EACZ,aAAa,EACb,QAAQ,EACR,UAAU,EACV,IAAI,GAKL,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,aAAa,EACb,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,aAAa,GAEd,MAAM,cAAc,CAAC;AAwCtB,qEAAqE;AACrE,oEAAoE;AACpE,6EAA6E;AAC7E,0EAA0E;AAC1E,MAAM,UAAU,GAAG,CAAC,GAAW,EAAE,GAAW,EAAE,EAAE,CAAC,CAAC,GAAG,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,GAAG,CAAC,GAAG,GAAG,CAAC;AAc7F,0CAA0C;AAC1C,MAAM,UAAU,gBAAgB,CAAC,CAAS,EAAE,KAAgB,EAAE,CAAS;IACrE,4EAA4E;IAC5E,2DAA2D;IAC3D,iEAAiE;IACjE,y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E,OAAO,EAAE,GAAG,eAAe,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;QAC1D,OAAO,GAAG,kBAAkB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC/C,OAAO,SAAS,CAAC,SAAS,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,CAAC;IACzF,CAAC;IAED,OAAO,MAAM,CAAC,MAAM,CAAC;QACnB,MAAM;QACN,YAAY;QACZ,eAAe;QACf,KAAK;QACL,OAAO;QACP,KAAK;QACL,IAAI;QACJ,MAAM;QACN,gBAAgB;QAChB,SAAS;QACT,IAAI,EAAE,KAAK;KACZ,CAAkB,CAAC;AACtB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.d.ts b/node_modules/@noble/curves/bls12-381.d.ts new file mode 100644 index 0000000..1265480 --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.d.ts @@ -0,0 +1,24 @@ +import { type BlsCurvePairWithSignatures } from './abstract/bls.ts'; +import { type IField } from './abstract/modular.ts'; +import { type TRet } from './utils.ts'; +/** + * bls12-381 Fr (Fn) field. + * `fromBytes()` reduces modulo `q` instead of rejecting non-canonical encodings. + */ +export declare const bls12_381_Fr: TRet>; +/** + * bls12-381 pairing-friendly curve construction. + * Provides both longSignatures and shortSignatures. + * @example + * bls12-381 pairing-friendly curve construction. + * + * ```ts + * const bls = bls12_381.longSignatures; + * const { secretKey, publicKey } = bls.keygen(); + * const msg = bls.hash(new TextEncoder().encode('hello noble')); + * const sig = bls.sign(msg, secretKey); + * const isValid = bls.verify(sig, msg, publicKey); + * ``` + */ +export declare const bls12_381: BlsCurvePairWithSignatures; +//# sourceMappingURL=bls12-381.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.d.ts.map b/node_modules/@noble/curves/bls12-381.d.ts.map new file mode 100644 index 0000000..4b4560a --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.d.ts","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":"AAgFA,OAAO,EAAO,KAAK,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAS,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAYL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AA2DpB;;;GAGG;AACH,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAEpB,CAAC;AA+Y3B;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,SAAS,EAAE,0BAOvB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.js b/node_modules/@noble/curves/bls12-381.js new file mode 100644 index 0000000..60f68f7 --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.js @@ -0,0 +1,678 @@ +/** + * bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to: + +* Construct zk-SNARKs at the ~120-bit security, as per [Barbulescu-Duquesne 2017](https://hal.science/hal-01534101/file/main.pdf) +* Efficiently verify N aggregate signatures with 1 pairing and N ec additions: +the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr + +BLS can mean 2 different things: + +* Barreto-Lynn-Scott: BLS12, a Pairing Friendly Elliptic Curve +* Boneh-Lynn-Shacham: A Signature Scheme. + +### Summary + +1. BLS Relies on expensive bilinear pairing +2. Secret Keys: 32 bytes +3. Public Keys: 48 OR 96 bytes - big-endian x coordinate of point on G1 OR G2 curve +4. Signatures: 96 OR 48 bytes - big-endian x coordinate of point on G2 OR G1 curve +5. The 12 stands for the Embedding degree. + +Modes of operation: + +* Long signatures: 48-byte keys + 96-byte sigs (G1 keys + G2 sigs). +* Short signatures: 96-byte keys + 48-byte sigs (G2 keys + G1 sigs). + +### Formulas + +- `P = pk x G` - public keys +- `S = pk x H(m)` - signing, uses hash-to-curve on m +- `e(P, H(m)) == e(G, S)` - verification using pairings +- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation + +### Curves + +G1 is ordinary elliptic curve. G2 is extension field curve, think "over complex numbers". + +- G1: y² = x³ + 4 +- G2: y² = x³ + 4(u + 1) where u = √−1; r-order subgroup of E'(Fp²), M-type twist + +### Towers + +Pairing G1 + G2 produces element in Fp₁₂, 12-degree polynomial. +Fp₁₂ is usually implemented using tower of lower-degree polynomials for speed. + +- Fp₁₂ = Fp₆² => Fp₂³ +- Fp(u) / (u² - β) where β = -1 +- Fp₂(v) / (v³ - ξ) where ξ = u + 1 +- Fp₆(w) / (w² - γ) where γ = v +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-1-u +- Fp¹²[w] = Fp⁶/w²-v + +### Params + +* Embedding degree (k): 12 +* Seed is sometimes named x or t +* t = -15132376222941642752 +* p = (t-1)² * (t⁴-t²+1)/3 + t +* r = t⁴-t²+1 +* Ate loop size: X + +To verify curve parameters, see +[pairing-friendly-curves spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11). +Basic math is done over finite fields over p. +More complicated math is done over polynominal extension fields. + +### Compatibility and notes +1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC. +Filecoin uses little endian byte arrays for secret keys - make sure to reverse byte order. +2. Make sure to correctly select mode: "long signature" or "short signature". +3. Compatible with specs: + RFC 9380, + [cfrg-pairing-friendly-curves-11](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11), + [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). + + * + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha2.js'; +import { bls } from "./abstract/bls.js"; +import { Field } from "./abstract/modular.js"; +import { abytes, bitLen, bitMask, bytesToHex, bytesToNumberBE, concatBytes, copyBytes, hexToBytes, numberToBytesBE, randomBytes, } from "./utils.js"; +// Types +import { isogenyMap } from "./abstract/hash-to-curve.js"; +import { psiFrobenius, tower12 } from "./abstract/tower.js"; +import { mapToCurveSimpleSWU, weierstrass, } from "./abstract/weierstrass.js"; +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); +// To verify math: +// https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11 +// The BLS parameter x (seed) for BLS12-381. The stored constant is `|x|`; call +// sites that need the signed parameter apply the minus sign themselves. +// x = -2^63 - 2^62 - 2^60 - 2^57 - 2^48 - 2^16 +const BLS_X = BigInt('0xd201000000010000'); +// t = x (called differently in different places) +// const t = -BLS_X; +const BLS_X_LEN = bitLen(BLS_X); +// a=0, b=4 +// P is characteristic of field Fp, in which curve calculations are done. +// p = (t-1)² * (t⁴-t²+1)/3 + t +// bls12_381_Fp = (t-1n)**2n * (t**4n - t**2n + 1n) / 3n + t +// r*h is curve order, amount of points on curve, +// where r is order of prime subgroup and h is cofactor. +// r = t⁴-t²+1 +// r = (t**4n - t**2n + 1n) +// cofactor h of G1: (t - 1)²/3, with the signed convention `t = -x` +// cofactorG1 = (t-1n)**2n/3n +// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 +// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 +const bls12_381_CURVE_G1 = { + p: BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab'), + n: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'), + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + a: _0n, + b: _4n, + Gx: BigInt('0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb'), + Gy: BigInt('0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1'), +}; +// CURVE FIELDS +// r = z⁴ − z² + 1; CURVE.n from other curves +/** + * bls12-381 Fr (Fn) field. + * `fromBytes()` reduces modulo `q` instead of rejecting non-canonical encodings. + */ +export const bls12_381_Fr = Field(bls12_381_CURVE_G1.n, { + modFromBytes: true, +}); +const { Fp, Fp2, Fp6, Fp12 } = tower12({ + ORDER: bls12_381_CURVE_G1.p, + X_LEN: BLS_X_LEN, + // Finite extension field over irreducible polynominal. + // Fp(u) / (u² - β) where β = -1 + // Public `Fp2.NONRESIDUE` below is the sextic-tower value `(1, 1) = u + 1`; + // the quadratic non-residue for the base Fp2 construction is still `-1`. + FP2_NONRESIDUE: [_1n, _1n], + Fp2mulByB: ({ c0, c1 }) => { + const t0 = Fp.mul(c0, _4n); // 4 * c0 + const t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + Fp12finalExponentiate: (num) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}); +// GLV endomorphism Ψ(P), for fast cofactor clearing. `Fp2.NONRESIDUE` here is +// the tower value `u + 1`, so the Frobenius base passed to psiFrobenius is +// `1 / (u + 1)`, and psi2 derives the published `1 / 2^((p - 1) / 3)` constant internally. +let frob; +const getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE))); +// Eager psiFrobenius setup now dominates `bls12-381.js` import, so defer it to +// first use. After that these locals are rewritten to the direct helper refs. +let G2psi = (c, P) => { + const fn = getFrob().G2psi; + G2psi = fn; + return fn(c, P); +}; +let G2psi2 = (c, P) => { + const fn = getFrob().G2psi2; + G2psi2 = fn; + return fn(c, P); +}; +/** + * Default hash_to_field / hash-to-curve for BLS. + * m: 1 for G1, 2 for G2 + * k: target security level in bits + * hash: any function, e.g. BBS+ uses BLAKE2: see [github](https://github.com/hyperledger/aries-framework-go/issues/2247). + * Field/hash parameters come from [section 8.8.2 of RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2), + * but the `DST` / `encodeDST` strings below are the BLS-signature-suite override. + */ +const hasher_opts = Object.freeze({ + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + p: Fp.ORDER, + m: 2, + k: 128, + expand: 'xmd', + hash: sha256, +}); +// a=0, b=4 +// cofactor h of G2, derived with the signed convention `t = -x` +// (t^8 - 4t^7 + 5t^6 - 4t^4 + 6t^3 - 4t^2 - 4t + 13)/9 +// cofactorG2 = (t**8n - 4n*t**7n + 5n*t**6n - 4n*t**4n + 6n*t**3n - 4n*t**2n - 4n*t+13n)/9n +// x = 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160 +// y = 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 +const bls12_381_CURVE_G2 = { + p: Fp2.ORDER, + n: bls12_381_CURVE_G1.n, + h: BigInt('0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5'), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + Gx: Fp2.fromBigTuple([ + BigInt('0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8'), + BigInt('0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801'), + BigInt('0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be'), + ]), +}; +// Encoding utils +const sortBit = (parts, p) => { + for (const part of parts) { + if (part !== _0n) + return Boolean((part * _2n) / p); + } + return false; +}; +const fp2 = { + // Generic tower bytes use `c0 || c1`, but the BLS12-381 G2 point/signature wire encoding uses + // `c1 || c0`, so keep this local wrapper instead of changing generic field serialization. + encode({ c0, c1 }) { + const { BYTES: L } = Fp; + return concatBytes(numberToBytesBE(c1, L), numberToBytesBE(c0, L)); + }, + decode(bytes) { + const { BYTES: L } = Fp; + return Fp2.create({ + c0: Fp.create(bytesToNumberBE(bytes.subarray(L))), + c1: Fp.create(bytesToNumberBE(bytes.subarray(0, L))), + }); + }, +}; +const BaseFp = Fp; +// Keep BLS12-381 point/signature codecs on one control-flow skeleton: the G1/G2 +// and point/signature variants differ only in field packing, subgroup bytes, and +// whether uncompressed form is allowed. Copy-paste decoders were diverging. +const coder = (name, Fp, b, encode, decode, yparts) => { + const F = Fp; + const enc = encode; + const dec = decode; + const W = F.BYTES; + return (allowUncompressed) => ({ + encode(point, compressed = true) { + if (!compressed && !allowUncompressed) + throw new Error('invalid signature: expected compressed encoding'); + const infinity = point.is0(); + const { x, y } = point.toAffine(); + const bytes = compressed ? enc(x) : concatBytes(enc(x), enc(y)); + let sort; + if (compressed && !infinity) + sort = sortBit(yparts(y), BaseFp.ORDER); + return setMask(bytes, { compressed, infinity, sort }); + }, + decode(bytes) { + const raw = allowUncompressed + ? abytes(bytes, undefined, 'point') + : abytes(bytes, W, 'signature'); + const { compressed, infinity, sort, value } = parseMask(raw); + if (!allowUncompressed && !compressed) + throw new Error('invalid signature: expected compressed encoding'); + const len = compressed ? W : 2 * W; + if (value.length !== len) + throw new Error(`invalid ${name} point: expected ${len} bytes`); + if (infinity) { + // Infinity canonicality has to be checked on raw bytes before decode() + // reduces coordinates modulo p and turns non-empty payloads into zero. + for (const b of value) { + if (b) + throw new Error(`invalid ${name} point: non-canonical zero`); + } + return { x: F.ZERO, y: F.ZERO }; + } + const x = dec(compressed ? value : value.subarray(0, W)); + let y; + if (compressed) { + y = F.sqrt(F.add(F.pow(x, _3n), b)); + if (!y) + throw new Error(`invalid ${name} point: compressed`); + if (sortBit(yparts(y), BaseFp.ORDER) !== sort) + y = F.neg(y); + } + else { + y = dec(value.subarray(W)); + } + // Noble keeps the permissive coordinate reduction path here, but an + // omitted infinity flag must not still decode to ZERO afterwards. + if (!compressed && F.is0(x) && F.is0(y)) + throw new Error(`invalid ${name} point: uncompressed`); + return { x, y }; + }, + }); +}; +// Internal helper only: it copies before clearing the top flag bits. The +// pairing-friendly-curves draft C.2 step 1 rejects 0x20 / 0x60 / 0xe0 because +// S_bit must be zero for infinity and for all uncompressed encodings. +function validateMask({ compressed, infinity, sort }) { + if ((!compressed && !infinity && sort) || // 0010_0000 = 0x20 + (!compressed && infinity && sort) || // 0110_0000 = 0x60 + (compressed && infinity && sort) // 1110_0000 = 0xe0 + ) + throw new Error('invalid encoding flag'); +} +function parseMask(bytes) { + // Copy, so we can remove mask data. + // It will be removed also later, when Fp.create will call modulo. + bytes = copyBytes(bytes); + const mask = bytes[0] & 0b1110_0000; + const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000) + const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000) + const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000) + validateMask({ compressed, infinity, sort }); + bytes[0] &= 0b0001_1111; // clear mask (zero first 3 bits) + return { compressed, infinity, sort, value: bytes }; +} +// Internal helper only: mutates a non-empty fresh buffer in place and just +// sets bits. Keep the same invalid-flag guard as parseMask() so encoders cannot +// manufacture states that decoders already reject. +function setMask(bytes, mask) { + if (bytes[0] & 0b1110_0000) + throw new Error('setMask: non-empty mask'); + validateMask({ compressed: !!mask.compressed, infinity: !!mask.infinity, sort: !!mask.sort }); + if (mask.compressed) + bytes[0] |= 0b1000_0000; + if (mask.infinity) + bytes[0] |= 0b0100_0000; + if (mask.sort) + bytes[0] |= 0b0010_0000; + return bytes; +} +const g1coder = coder('G1', Fp, Fp.create(bls12_381_CURVE_G1.b), (x) => numberToBytesBE(x, Fp.BYTES), (bytes) => Fp.create(bytesToNumberBE(bytes) & bitMask(Fp.BITS)), (y) => [y]); +const g1 = { point: g1coder(true), sig: g1coder(false) }; +const signatureG1ToBytes = (point) => { + point.assertValidity(); + return g1.sig.encode(point); +}; +function signatureG1FromBytes(bytes) { + const Point = bls12_381.G1.Point; + const point = Point.fromAffine(g1.sig.decode(bytes)); + point.assertValidity(); + return point; +} +const g2coder = coder('G2', Fp2, bls12_381_CURVE_G2.b, fp2.encode, fp2.decode, (y) => [ + y.c1, + y.c0, +]); +const g2 = { point: g2coder(true), sig: g2coder(false) }; +const signatureG2ToBytes = (point) => { + point.assertValidity(); + return g2.sig.encode(point); +}; +function signatureG2FromBytes(bytes) { + const Point = bls12_381.G2.Point; + const point = Point.fromAffine(g2.sig.decode(bytes)); + point.assertValidity(); + return point; +} +const signatureCoders = { + ShortSignature: { + fromBytes(bytes) { + return signatureG1FromBytes(abytes(bytes)); + }, + fromHex(hex) { + return signatureG1FromBytes(hexToBytes(hex)); + }, + toBytes(point) { + return signatureG1ToBytes(point); + }, + // Historical alias: BLS signatures have a single compressed byte format here. + toRawBytes(point) { + return signatureG1ToBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG1ToBytes(point)); + }, + }, + LongSignature: { + fromBytes(bytes) { + return signatureG2FromBytes(abytes(bytes)); + }, + fromHex(hex) { + return signatureG2FromBytes(hexToBytes(hex)); + }, + toBytes(point) { + return signatureG2ToBytes(point); + }, + // Historical alias: BLS signatures have a single compressed byte format here. + toRawBytes(point) { + return signatureG2ToBytes(point); + }, + toHex(point) { + return bytesToHex(signatureG2ToBytes(point)); + }, + }, +}; +const fields = { + Fp, + Fp2, + Fp6, + Fp12, + Fr: bls12_381_Fr, +}; +const G1_Point = weierstrass(bls12_381_CURVE_G1, { + // Public point APIs still accept infinity, even though the Zcash proof + // encoding rules cited above only define nonzero point encodings. + allowInfinityPoint: true, + Fn: bls12_381_Fr, + fromBytes: g1.point.decode, + toBytes: (_c, point, isComp) => g1.point.encode(point, isComp), + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point) => { + // GLV endomorphism ψ(P) + const beta = BigInt('0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe'); + const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z); + // TODO: unroll + const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P + const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P + return u2P.equals(phi); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(BLS_X).add(point); // x*P + P + }, +}); +const G2_Point = weierstrass(bls12_381_CURVE_G2, { + Fp: Fp2, + // Public point APIs still accept infinity, even though the Zcash proof + // encoding rules cited above only define nonzero point encodings. + allowInfinityPoint: true, + Fn: bls12_381_Fr, + fromBytes: g2.point.decode, + toBytes: (_c, point, isComp) => g2.point.encode(point, isComp), + // https://eprint.iacr.org/2021/1130.pdf + // Older version: https://eprint.iacr.org/2019/814.pdf + isTorsionFree: (c, P) => { + return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + }, + // clear_cofactor_bls12381_g2 from RFC 9380. + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = BLS_X; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, +}); +const bls12_hasher_opts = { + mapToG1: mapToG1, + mapToG2: mapToG2, + hasherOpts: hasher_opts, + // RFC 9380 Appendix J defines distinct G1/G2 RO and NU suite IDs, and + // draft-irtf-cfrg-bls-signature-06 §4.2.1 gives separate G1/G2 `_NUL_` DSTs. + // Keep G1 encode-to-curve on the G1 domain instead of inheriting G2's `encodeDST`. + hasherOptsG1: { + ...hasher_opts, + m: 1, + DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_', + }, + hasherOptsG2: { ...hasher_opts }, +}; +const bls12_params = { + ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381 + xNegative: true, + twistType: 'multiplicative', + randomBytes: randomBytes, +}; +/** + * bls12-381 pairing-friendly curve construction. + * Provides both longSignatures and shortSignatures. + * @example + * bls12-381 pairing-friendly curve construction. + * + * ```ts + * const bls = bls12_381.longSignatures; + * const { secretKey, publicKey } = bls.keygen(); + * const msg = bls.hash(new TextEncoder().encode('hello noble')); + * const sig = bls.sign(msg, secretKey); + * const isValid = bls.verify(sig, msg, publicKey); + * ``` + */ +export const bls12_381 = bls(fields, G1_Point, G2_Point, bls12_params, bls12_hasher_opts, signatureCoders); +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +// Coefficients stay in ascending `k_(?,0)`..`k_(?,d)` order; isogenyMap() +// reverses them internally for Horner evaluation. +const isogenyMapG2 = isogenyMap(Fp2, [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], +].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt))))); +// 11-isogeny map from E' to E. Coefficients stay in ascending +// `k_(?,0)`..`k_(?,d)` order; isogenyMap() reverses them for Horner evaluation. +const isogenyMapG1 = isogenyMap(Fp, [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))); +let G1_SWU; +let G2_SWU; +// SWU setup validates the pre-isogeny curve parameters and builds sqrt-ratio helpers. +// Doing that eagerly adds about 10ms to `bls12-381.js` import here, so keep it lazy; after the +// first map call the cached mapper is reused directly. +const getG1_SWU = () => G1_SWU || + (G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create(BigInt('0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d')), + B: Fp.create(BigInt('0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0')), + Z: Fp.create(BigInt(11)), + })); +const getG2_SWU = () => G2_SWU || + (G2_SWU = mapToCurveSimpleSWU(Fp2, { + // SWU map for the RFC 9380 §8.8.2 pre-isogeny G2 curve E': + // y² = x³ + 240i * x + 1012 + 1012i + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) + })); +// Internal hash-to-curve step: G1 uses `m = 1`, so only `scalars[0]` is read, +// and the result is the isogeny image on E before the subgroup clear. +function mapToG1(scalars) { + const { x, y } = getG1_SWU()(Fp.create(scalars[0])); + return isogenyMapG1(x, y); +} +// Internal hash-to-curve step: G2 expects the RFC `m = 2` pair, and the result +// is the isogeny image on E before the subgroup clear. +function mapToG2(scalars) { + const { x, y } = getG2_SWU()(Fp2.fromBigTuple(scalars)); + return isogenyMapG2(x, y); +} +//# sourceMappingURL=bls12-381.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bls12-381.js.map b/node_modules/@noble/curves/bls12-381.js.map new file mode 100644 index 0000000..59e8fe9 --- /dev/null +++ b/node_modules/@noble/curves/bls12-381.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bls12-381.js","sourceRoot":"","sources":["src/bls12-381.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AC,EAAE,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,cAAc;KACxF,CAAC,CAAC,CAAC;AAEN,8EAA8E;AAC9E,sEAAsE;AACtE,SAAS,OAAO,CAAC,OAAiB;IAChC,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,SAAS,EAAE,CAAC,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACpD,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC;AACD,+EAA+E;AAC/E,uDAAuD;AACvD,SAAS,OAAO,CAAC,OAAiB;IAChC,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,SAAS,EAAE,CAAC,GAAG,CAAC,YAAY,CAAC,OAAsB,CAAC,CAAC,CAAC;IACvE,OAAO,YAAY,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;AAC5B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.d.ts b/node_modules/@noble/curves/bn254.d.ts new file mode 100644 index 0000000..6472432 --- /dev/null +++ b/node_modules/@noble/curves/bn254.d.ts @@ -0,0 +1,75 @@ +/** + * bn254, previously known as alt_bn_128, when it had 128-bit security. + +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf. +Compatible with EIP-196 and EIP-197. + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +We don't implement Point methods toHex / toBytes. +To work around this limitation, has to initialize points on their own from BigInts. +Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109). +Points of divergence: + +- Endianness: LE vs BE (byte-swapped) +- Flags as first hex bits (similar to BLS) vs no-flags +- Imaginary part last in G2 vs first (c0, c1 vs c1, c0) + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/py_ecc/tree/main/py_ecc/bn128 +- Points are encoded differently in different implementations + +### Params +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +### Towers +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { type BlsCurvePair, type BlsPostPrecomputeFn } from './abstract/bls.ts'; +import { type IField } from './abstract/modular.ts'; +import { type TRet } from './utils.ts'; +/** bn254 scalar field. */ +export declare const bn254_Fr: TRet>; +export declare const _postPrecompute: BlsPostPrecomputeFn; +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings only; the commented-out + * hash-to-curve and signature surface is intentionally not exposed here. + * @example + * Compute a pairing from the two generator points. + * + * ```ts + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +export declare const bn254: BlsCurvePair; +//# sourceMappingURL=bn254.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.d.ts.map b/node_modules/@noble/curves/bn254.d.ts.map new file mode 100644 index 0000000..5a5a128 --- /dev/null +++ b/node_modules/@noble/curves/bn254.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bn254.d.ts","sourceRoot":"","sources":["src/bn254.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsDG;AACH,sEAAsE;AACtE,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAEzB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAS,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAI3D,OAAO,EAAU,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AA8B/C,0BAA0B;AAC1B,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CACU,CAAC;AA+DrD,eAAO,MAAM,eAAe,EAAE,mBAY7B,CAAC;AAyFF;;;;;;;;;;GAUG;AAEH,eAAO,MAAM,KAAK,EAAE,YAKnB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.js b/node_modules/@noble/curves/bn254.js new file mode 100644 index 0000000..835721d --- /dev/null +++ b/node_modules/@noble/curves/bn254.js @@ -0,0 +1,245 @@ +/** + * bn254, previously known as alt_bn_128, when it had 128-bit security. + +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf. +Compatible with EIP-196 and EIP-197. + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +We don't implement Point methods toHex / toBytes. +To work around this limitation, has to initialize points on their own from BigInts. +Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109). +Points of divergence: + +- Endianness: LE vs BE (byte-swapped) +- Flags as first hex bits (similar to BLS) vs no-flags +- Imaginary part last in G2 vs first (c0, c1 vs c1, c0) + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/py_ecc/tree/main/py_ecc/bn128 +- Points are encoded differently in different implementations + +### Params +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +### Towers +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { blsBasic, } from "./abstract/bls.js"; +import { Field } from "./abstract/modular.js"; +import { psiFrobenius, tower12 } from "./abstract/tower.js"; +import { weierstrass } from "./abstract/weierstrass.js"; +import { bitLen } from "./utils.js"; +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3); +const _6n = /* @__PURE__ */ BigInt(6); +// Locally documented BN pairing seed. EIP-197 does not name this scalar +// directly; noble stores the positive value and derives any `-x` uses later. +const BN_X = /* @__PURE__ */ BigInt('4965661367192848881'); +// Bit width of the stored seed itself, not the derived Miller-loop scalar `6x+2`. +const BN_X_LEN = /* @__PURE__ */ (() => bitLen(BN_X))(); +// Derived scalar used by the optimized G2 subgroup test required by EIP-197. +const SIX_X_SQUARED = /* @__PURE__ */ (() => _6n * BN_X ** _2n)(); +const bn254_G1_CURVE = { + p: BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47'), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + // The Ethereum specs define G1 as prime-order but do not spell out the + // cofactor separately; `h = 1` is the implementation-derived value. + h: _1n, + a: _0n, + b: _3n, + Gx: _1n, + Gy: BigInt(2), +}; +// r == n +// Finite field over r. It's for convenience and is not used in the code below, +// and its canonical `fromBytes()` decoder is stricter than the EIP-196 MUL +// scalar rule that accepts any 256-bit integer. +// These factories are side-effect free; mark them pure so single-export bundles can drop the rest. +/** bn254 scalar field. */ +export const bn254_Fr = /* @__PURE__ */ (() => Field(bn254_G1_CURVE.n))(); +// `3 / (i + 9)` from EIP-197, stored in noble's internal `(c0, c1) = (b, a)` +// order rather than the spec's `a * i + b` notation. +const Fp2B = /* @__PURE__ */ (() => ({ + c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'), + c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'), +}))(); +// Bootstrap binding: `Fp12finalExponentiate` needs to reference the finished +// field object while `tower12(...)` is still constructing it. +let Fp12; +const tower = /* @__PURE__ */ (() => { + const res = tower12({ + ORDER: bn254_G1_CURVE.p, + X_LEN: BN_X_LEN, + // Public `Fp2.NONRESIDUE` below is the sextic-tower seed `(9, 1)`, not the + // quadratic relation `i^2 + 1 = 0` from the EIP text. + FP2_NONRESIDUE: [BigInt(9), _1n], + Fp2mulByB: (num) => Fp2.mul(num, Fp2B), + Fp12finalExponentiate: (num) => { + const powMinusX = (num) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X)); + const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num)); + const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0); + const y1 = Fp12._cyclotomicSquare(powMinusX(r)); + const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1); + const y4 = powMinusX(y2); + const y6 = powMinusX(Fp12._cyclotomicSquare(y4)); + const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2)); + const y9 = Fp12.mul(y8, y1); + return Fp12.mul(Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), Fp12.mul(Fp12.frobeniusMap(y8, 2), Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r)))); + }, + }); + Fp12 = res.Fp12; + return res; +})(); +const Fp = /* @__PURE__ */ (() => tower.Fp)(); +const Fp2 = /* @__PURE__ */ (() => tower.Fp2)(); +// END OF CURVE FIELDS +// BN254 uses the same tower seed `(9, 1)` for the Frobenius helper that powers +// the divisive-twist G2 endomorphism. +let frob; +const getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.NONRESIDUE)); +// Eager psiFrobenius setup now dominates `bn254.js` import, so defer it to +// first use. After that these locals are rewritten to the direct helper refs. +let psi = (x, y) => { + const fn = getFrob().psi; + psi = fn; + return fn(x, y); +}; +let G2psi = (c, P) => { + const fn = getFrob().G2psi; + G2psi = fn; + return fn(c, P); +}; +export const _postPrecompute = (Rx, Ry, Rz, Qx, Qy, pointAdd) => { + const q = psi(Qx, Qy); + ({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1])); + const q2 = psi(q[0], q[1]); + pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1])); +}; +// cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1 +const bn254_G2_CURVE = /* @__PURE__ */ (() => ({ + p: Fp2.ORDER, + n: bn254_G1_CURVE.n, + // As with G1, the Ethereum specs do not spell out the G2 cofactor + // separately; this literal is the implementation-derived value. + h: BigInt('0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d'), + a: Fp2.ZERO, + b: Fp2B, + Gx: Fp2.fromBigTuple([ + BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'), + BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'), + BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'), + ]), +}))(); +const fields = /* @__PURE__ */ (() => ({ Fp, Fp2, Fp6: tower.Fp6, Fp12, Fr: bn254_Fr }))(); +const bn254_G1 = /* @__PURE__ */ weierstrass(bn254_G1_CURVE, { + Fp, + Fn: bn254_Fr, + // Ethereum encodes infinity as `(0, 0)`, so the public point API accepts it + // even though it is not an affine curve point, and `fromAffine()` stays lazy: + // adversarial inputs still need `assertValidity()`. + allowInfinityPoint: true, +}); +const bn254_G2 = /* @__PURE__ */ weierstrass(bn254_G2_CURVE, { + Fp: Fp2, + Fn: bn254_Fr, + // Ethereum encodes infinity as `((0, 0), (0, 0))`, so the public point API + // accepts it even though it is not an affine curve point. + allowInfinityPoint: true, + // Optimized BN254 G2 subgroup test used to satisfy the EIP-197 order check. + isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P +}); +/* +No hashToCurve for now (and signatures): + +- RFC 9380 doesn't mention bn254 and doesn't provide test vectors +- Overall seems like nobody is using BLS signatures on top of bn254 +- Seems like it can utilize SVDW, which is not implemented yet +*/ +// const htfDefaults = Object.freeze({ +// // DST: a domain separation tag defined in section 2.2.5 +// DST: 'BN254G2_XMD:SHA-256_SVDW_RO_', +// encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_', +// p: Fp.ORDER, +// m: 2, +// k: 128, +// expand: 'xmd', +// hash: sha256, +// }); +// const hasherOpts = { +// { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' } +// }; +const bn254_params = /* @__PURE__ */ (() => ({ + // Optimal-ate Miller loop parameter derived from the positive BN seed. + ateLoopSize: BN_X * _6n + _2n, + r: bn254_Fr.ORDER, + xNegative: false, + // EIP-197 writes G2 as `y^2 = x^3 + 3 / (i + 9)`, so the pairing + // configuration uses the divisive twist convention. + twistType: 'divisive', + postPrecompute: _postPrecompute, +}))(); +// const bn254_hasher = { +// hasherOpts: htfDefaults, +// hasherOptsG1: { m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' }, +// hasherOptsG2: htfDefaults +// }; +// G2_heff hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), +// fromBytes: notImplemented, +// toBytes: notImplemented, +// mapToCurve: notImplemented, +// fromBytes: notImplemented, +// toBytes: notImplemented, +// ShortSignature: { +// fromBytes: notImplemented, +// fromHex: notImplemented, +// toBytes: notImplemented, +// toRawBytes: notImplemented, +// toHex: notImplemented, +// }, +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings only; the commented-out + * hash-to-curve and signature surface is intentionally not exposed here. + * @example + * Compute a pairing from the two generator points. + * + * ```ts + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +// bn254_hasher +export const bn254 = /* @__PURE__ */ blsBasic(fields, bn254_G1, bn254_G2, bn254_params); +//# sourceMappingURL=bn254.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/bn254.js.map b/node_modules/@noble/curves/bn254.js.map new file mode 100644 index 0000000..afea859 --- /dev/null +++ b/node_modules/@noble/curves/bn254.js.map @@ -0,0 +1 @@ +{"version":3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AACH,eAAe;AACf,MAAM,CAAC,MAAM,KAAK,GAAiB,eAAe,CAAC,QAAQ,CACzD,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,YAAY,CACb,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.d.ts b/node_modules/@noble/curves/ed25519.d.ts new file mode 100644 index 0000000..ac231ed --- /dev/null +++ b/node_modules/@noble/curves/ed25519.d.ts @@ -0,0 +1,212 @@ +import { type AffinePoint } from './abstract/curve.ts'; +import { PrimeEdwardsPoint, type EdDSA, type EdwardsPoint, type EdwardsPointCons } from './abstract/edwards.ts'; +import { type FROST } from './abstract/frost.ts'; +import { type H2CHasher, type H2CHasherBase } from './abstract/hash-to-curve.ts'; +import { type IField } from './abstract/modular.ts'; +import { type MontgomeryECDH } from './abstract/montgomery.ts'; +import { type OPRF } from './abstract/oprf.ts'; +import { type TArg, type TRet } from './utils.ts'; +/** + * ed25519 curve with EdDSA signatures. + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Generate one Ed25519 keypair, sign a message, and verify it. + * + * ```js + * import { ed25519 } from '@noble/curves/ed25519.js'; + * const { secretKey, publicKey } = ed25519.keygen(); + * // const publicKey = ed25519.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519.sign(msg, secretKey); + * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215 + * // RFC8032 / FIPS 186-5 + * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false }); + * ``` + */ +export declare const ed25519: EdDSA; +/** + * Context version of ed25519 (ctx for domain separation). See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Sign and verify with Ed25519ctx under one explicit context. + * + * ```ts + * const context = new TextEncoder().encode('docs'); + * const { secretKey, publicKey } = ed25519ctx.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ctx.sign(msg, secretKey, { context }); + * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context }); + * ``` + */ +export declare const ed25519ctx: EdDSA; +/** + * Prehashed version of ed25519. See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Use the prehashed Ed25519 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed25519ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ph.sign(msg, secretKey); + * const isValid = ed25519ph.verify(sig, msg, publicKey); + * ``` + */ +export declare const ed25519ph: EdDSA; +/** + * FROST threshold signatures over ed25519. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed25519 signing. + * + * ```ts + * const alice = ed25519_FROST.Identifier.derive('alice@example.com'); + * const bob = ed25519_FROST.Identifier.derive('bob@example.com'); + * const carol = ed25519_FROST.Identifier.derive('carol@example.com'); + * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const ed25519_FROST: TRet; +/** + * ECDH using curve25519 aka x25519. + * `getSharedSecret()` rejects low-order peer inputs by default, and seeded + * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it. + * @example + * Derive one shared secret between two X25519 peers. + * + * ```js + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const bob = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export declare const x25519: TRet; +/** + * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later. + * @private + */ +export declare function _map_to_curve_elligator2_curve25519(u: bigint): { + xMn: bigint; + xMd: bigint; + yMn: bigint; + yMd: bigint; +}; +/** + * Hashing to ed25519 points / field. RFC 9380 methods. + * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the + * internal map callback below consumes one field element bigint, not `[bigint]`. + * @example + * Hash one message onto the ed25519 curve. + * + * ```ts + * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const ed25519_hasher: H2CHasher; +/** + * Wrapper over Edwards Point for ristretto255. + * + * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +declare class _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> { + static BASE: _RistrettoPoint; + static ZERO: _RistrettoPoint; + static Fp: IField; + static Fn: IField; + constructor(ep: EdwardsPoint); + /** + * Create one Ristretto255 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical ristretto255 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter. + */ + static fromAffine(ap: AffinePoint): _RistrettoPoint; + protected assertSame(other: _RistrettoPoint): void; + protected init(ep: EdwardsPoint): _RistrettoPoint; + static fromBytes(bytes: TArg): _RistrettoPoint; + /** + * Converts ristretto-encoded string to ristretto point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode). + * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: string): _RistrettoPoint; + /** + * Encodes ristretto point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode). + */ + toBytes(): TRet; + /** + * Compares two Ristretto points. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals). + */ + equals(other: _RistrettoPoint): boolean; + is0(): boolean; +} +/** Prime-order Ristretto255 group bundle. */ +export declare const ristretto255: { + Point: typeof _RistrettoPoint; +}; +/** + * Hashing to ristretto255 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496 + * §4.3.4 element-derivation building block, and `hashToScalar()` is a + * library-specific helper for OPRF-style use. + * @example + * Hash one message onto ristretto255. + * + * ```ts + * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const ristretto255_hasher: H2CHasherBase; +/** + * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over ristretto255. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = ristretto255_oprf.oprf.generateKeyPair(); + * const blind = ristretto255_oprf.oprf.blind(input); + * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export declare const ristretto255_oprf: TRet; +/** + * FROST threshold signatures over ristretto255. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ristretto255 signing. + * + * ```ts + * const alice = ristretto255_FROST.Identifier.derive('alice@example.com'); + * const bob = ristretto255_FROST.Identifier.derive('bob@example.com'); + * const carol = ristretto255_FROST.Identifier.derive('carol@example.com'); + * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const ristretto255_FROST: TRet; +/** + * Weird / bogus points, useful for debugging. + * All 8 ed25519 points of 8-torsion subgroup can be generated from the point + * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`. + * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the + * array below is that set, not the powers in that exact index order. + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js'; + * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]); + * ``` + */ +export declare const ED25519_TORSION_SUBGROUP: readonly string[]; +export {}; +//# sourceMappingURL=ed25519.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.d.ts.map b/node_modules/@noble/curves/ed25519.d.ts.map new file mode 100644 index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;AACR;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,kBAAkB,EAAE,IAAI,CAAC,KAAK,CASpC,CAAC;AAER;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,wBAAwB,EAAE,SAAS,MAAM,EASpD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.js b/node_modules/@noble/curves/ed25519.js new file mode 100644 index 0000000..bff1851 --- /dev/null +++ b/node_modules/@noble/curves/ed25519.js @@ -0,0 +1,624 @@ +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js'; +import {} from "./abstract/curve.js"; +import { eddsa, edwards, PrimeEdwardsPoint, } from "./abstract/edwards.js"; +import { createFROST } from "./abstract/frost.js"; +import { _DST_scalar, createHasher, expand_message_xmd, } from "./abstract/hash-to-curve.js"; +import { FpInvertBatch, FpSqrtEven, isNegativeLE, mod, pow2, } from "./abstract/modular.js"; +import { montgomery } from "./abstract/montgomery.js"; +import { createOPRF } from "./abstract/oprf.js"; +import { asciiToBytes, bytesToNumberLE, equalBytes } from "./utils.js"; +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3); +// prettier-ignore +const _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8); +// P = 2n**255n - 19n +const ed25519_CURVE_p = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed'); +// N = 2n**252n + 27742317777372353535851937790883648493n +// a = Fp.create(BigInt(-1)) +// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666)) +const ed25519_CURVE = /* @__PURE__ */ (() => ({ + p: ed25519_CURVE_p, + n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'), + h: _8n, + a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'), + d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'), + Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'), + Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'), +}))(); +function ed25519_pow_2_252_3(x) { + // prettier-ignore + const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + const P = ed25519_CURVE_p; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8). + return { pow_p_5_8, b2 }; +} +// Mutates and returns the provided 32-byte buffer in place. +function adjustScalarBytes(bytes) { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes; +} +// √(-1) aka √(a) aka 2^((p-1)/4) +// Fp.sqrt(Fp.neg(1)) +const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt('19681161376707505956807079304988542015446066515923890162744021073123829784752'); +// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a +// dummy root-shaped field element so callers can stay constant-time. +function uvRatio(u, v) { + const P = ed25519_CURVE_p; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) + x = root1; + if (useRoot2 || noRoot) + x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) + x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} +const ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio }); +// Public field alias stays stricter than the RFC 8032 Appendix A sample code: +// `Fp.inv(0)` throws instead of returning `0`. +const Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)(); +const Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)(); +// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the +// empty-domain path in `ed()` and would be wrong if routed through this helper. +function ed25519_domain(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('Context is too big'); + return concatBytes(asciiToBytes('SigEd25519 no Ed25519 collisions'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +function ed(opts) { + // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility. + return eddsa(ed25519_Point, sha512, Object.assign({ adjustScalarBytes, zip215: true }, opts)); +} +/** + * ed25519 curve with EdDSA signatures. + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Generate one Ed25519 keypair, sign a message, and verify it. + * + * ```js + * import { ed25519 } from '@noble/curves/ed25519.js'; + * const { secretKey, publicKey } = ed25519.keygen(); + * // const publicKey = ed25519.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519.sign(msg, secretKey); + * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215 + * // RFC8032 / FIPS 186-5 + * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false }); + * ``` + */ +export const ed25519 = /* @__PURE__ */ ed({}); +/** + * Context version of ed25519 (ctx for domain separation). See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Sign and verify with Ed25519ctx under one explicit context. + * + * ```ts + * const context = new TextEncoder().encode('docs'); + * const { secretKey, publicKey } = ed25519ctx.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ctx.sign(msg, secretKey, { context }); + * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context }); + * ``` + */ +export const ed25519ctx = /* @__PURE__ */ ed({ domain: ed25519_domain }); +/** + * Prehashed version of ed25519. See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Use the prehashed Ed25519 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed25519ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ph.sign(msg, secretKey); + * const isValid = ed25519ph.verify(sig, msg, publicKey); + * ``` + */ +export const ed25519ph = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 }); +/** + * FROST threshold signatures over ed25519. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed25519 signing. + * + * ```ts + * const alice = ed25519_FROST.Identifier.derive('alice@example.com'); + * const bob = ed25519_FROST.Identifier.derive('bob@example.com'); + * const carol = ed25519_FROST.Identifier.derive('carol@example.com'); + * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ed25519_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-ED25519-SHA512-v1', + Point: ed25519_Point, + validatePoint: (p) => { + p.assertValidity(); + if (!p.isTorsionFree()) + throw new Error('bad point: not torsion-free'); + }, + hash: sha512, + // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(), + // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats + // that the same as omitted DST, even though custom hooks can still observe the empty bag. + H2: '', +}))(); +/** + * ECDH using curve25519 aka x25519. + * `getSharedSecret()` rejects low-order peer inputs by default, and seeded + * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it. + * @example + * Derive one shared secret between two X25519 peers. + * + * ```js + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const bob = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export const x25519 = /* @__PURE__ */ (() => { + const P = ed25519_CURVE_p; + return montgomery({ + P, + type: 'x25519', + powPminus2: (x) => { + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, _3n, P) * b2, P); + }, + adjustScalarBytes, + }); +})(); +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards +// map constant below, so use the even root explicitly. +// 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); +const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1 +const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1) +/** + * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later. + * @private + */ +// prettier-ignore +export function _map_to_curve_elligator2_curve25519(u) { + const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic + const ELL2_J = BigInt(486662); + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let xd = Fp.add(tv1, Fp.ONE); + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let y1 = Fp.cmov(y12, y11, e1); + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + let y2 = Fp.cmov(y22, y21, e2); + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} +// sgn0(c1) MUST equal 0 +const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); +function map_to_curve_elligator2_edwards25519(u) { + // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u) + const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let yd = Fp.add(xMn, xMd); + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division + // Noble normalizes the RFC rational representation to affine `{ x, y }` + // before returning from the internal helper. + return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd) +} +/** + * Hashing to ed25519 points / field. RFC 9380 methods. + * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the + * internal map callback below consumes one field element bigint, not `[bigint]`. + * @example + * Hash one message onto the ed25519 curve. + * + * ```ts + * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ed25519_hasher = /* @__PURE__ */ (() => createHasher(ed25519_Point, (scalars) => map_to_curve_elligator2_edwards25519(scalars[0]), { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: ed25519_CURVE_p, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, +}))(); +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt('25063068953384623474111414158702152701244531502492656460079210482610430750235'); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt('54469307008909316920995813868745141605393597292927456921205312896311721017578'); +// 1-d² +const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt('1159843021668779879193775521855586647937357759715417654439879720876111806838'); +// (d-1)² +const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt('40440834346308536858101042469323190826248399146238708352240133220865137265952'); +// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`, +// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch. +const invertSqrt = (number) => uvRatio(_1n, number); +const MAX_255B = /* @__PURE__ */ BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element +// derivation. The decode path has the opposite contract and rejects that bit. +const bytes255ToNumberLE = (bytes) => Fp.create(bytesToNumberLE(bytes) & MAX_255B); +/** + * Computes Elligator map for Ristretto255. + * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds + * `hash_to_ristretto255` on top of this helper. + * Returns an internal Edwards representative, not a public `_RistrettoPoint`. + */ +function calcElligatorRistrettoMap(r0) { + const { d } = ed25519_CURVE; + const P = ed25519_CURVE_p; + const mod = (n) => Fp.create(n); + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) + s_ = mod(-s_); + if (!Ns_D_is_sq) + s = s_; // 7 + if (!Ns_D_is_sq) + c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +/** + * Wrapper over Edwards Point for ristretto255. + * + * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +class _RistrettoPoint extends PrimeEdwardsPoint { + // Do NOT change syntax: the following gymnastics is done, + // because typescript strips comments, which makes bundlers disable tree-shaking. + // prettier-ignore + static BASE = + /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))(); + // prettier-ignore + static ZERO = + /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))(); + // prettier-ignore + static Fp = + /* @__PURE__ */ (() => Fp)(); + // prettier-ignore + static Fn = + /* @__PURE__ */ (() => Fn)(); + constructor(ep) { + super(ep); + } + /** + * Create one Ristretto255 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical ristretto255 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter. + */ + static fromAffine(ap) { + return new _RistrettoPoint(ed25519_Point.fromAffine(ap)); + } + assertSame(other) { + if (!(other instanceof _RistrettoPoint)) + throw new Error('RistrettoPoint expected'); + } + init(ep) { + return new _RistrettoPoint(ep); + } + static fromBytes(bytes) { + abytes(bytes, 32); + const { a, d } = ed25519_CURVE; + const P = ed25519_CURVE_p; + const mod = (n) => Fp.create(n); + const s = bytes255ToNumberLE(bytes); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P)) + throw new Error('invalid ristretto255 encoding 1'); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) + x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error('invalid ristretto255 encoding 2'); + return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t)); + } + /** + * Converts ristretto-encoded string to ristretto point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode). + * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex) { + return _RistrettoPoint.fromBytes(hexToBytes(hex)); + } + /** + * Encodes ristretto point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode). + */ + toBytes() { + let { X, Y, Z, T } = this.ep; + const P = ed25519_CURVE_p; + const mod = (n) => Fp.create(n); + const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1 + const u2 = mod(X * Y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * T); // 6 + let D; // 7 + if (isNegativeLE(T * zInv, P)) { + let _x = mod(Y * SQRT_M1); + let _y = mod(X * SQRT_M1); + X = _x; + Y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } + else { + D = D2; // 8 + } + if (isNegativeLE(X * zInv, P)) + Y = mod(-Y); // 9 + let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) + s = mod(-s); + return Fp.toBytes(s); // 11 + } + /** + * Compares two Ristretto points. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals). + */ + equals(other) { + this.assertSame(other); + const { X: X1, Y: Y1 } = this.ep; + const { X: X2, Y: Y2 } = other.ep; + const mod = (n) => Fp.create(n); + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + is0() { + return this.equals(_RistrettoPoint.ZERO); + } +} +Object.freeze(_RistrettoPoint.BASE); +Object.freeze(_RistrettoPoint.ZERO); +Object.freeze(_RistrettoPoint.prototype); +Object.freeze(_RistrettoPoint); +/** Prime-order Ristretto255 group bundle. */ +export const ristretto255 = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint }); +/** + * Hashing to ristretto255 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496 + * §4.3.4 element-derivation building block, and `hashToScalar()` is a + * library-specific helper for OPRF-style use. + * @example + * Hash one message onto ristretto255. + * + * ```ts + * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ristretto255_hasher = Object.freeze({ + Point: _RistrettoPoint, + /** + * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats: + * * There are no test vectors + * * encodeToCurve / mapToCurve is undefined + * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map! + * * hashToScalar is undefined too, so we just use OPRF implementation + * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC + (os2ip -> bytes255ToNumberLE) + * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map + * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF + version here. Using `bytes255ToNumblerLE` will create a different result + if we use `bytes255ToNumberLE` as os2ip + * * current version is closest to spec. + */ + hashToCurve(msg, options) { + // == 'hash_to_ristretto255' + // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them. + const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST; + const xmd = expand_message_xmd(msg, DST, 64, sha512); + // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`. + // In RFC 9496, `map` was the per-point function inside the construction. + // That also led to confusion that `ristretto255_map` is `mapToCurve`. + // It is not: it is the older hash-to-curve construction. + return ristretto255_hasher.deriveToCurve(xmd); + }, + hashToScalar(msg, options = { DST: _DST_scalar }) { + const xmd = expand_message_xmd(msg, options.DST, 64, sha512); + return Fn.create(bytesToNumberLE(xmd)); + }, + /** + * HashToCurve-like construction based on RFC 9496 (Element Derivation). + * Converts 64 uniform random bytes into a curve point. + * + * WARNING: This represents an older hash-to-curve construction from before + * RFC 9380 was finalized. + * It was later reused as a component in the newer + * `hash_to_ristretto255` function defined in RFC 9380. + */ + deriveToCurve(bytes) { + // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation + abytes(bytes, 64); + const r1 = bytes255ToNumberLE(bytes.subarray(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(bytes.subarray(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new _RistrettoPoint(R1.add(R2)); + }, +}); +/** + * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over ristretto255. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = ristretto255_oprf.oprf.generateKeyPair(); + * const blind = ristretto255_oprf.oprf.blind(input); + * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const ristretto255_oprf = /* @__PURE__ */ (() => createOPRF({ + name: 'ristretto255-SHA512', + Point: _RistrettoPoint, + hash: sha512, + hashToGroup: ristretto255_hasher.hashToCurve, + hashToScalar: ristretto255_hasher.hashToScalar, +}))(); +/** + * FROST threshold signatures over ristretto255. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ristretto255 signing. + * + * ```ts + * const alice = ristretto255_FROST.Identifier.derive('alice@example.com'); + * const bob = ristretto255_FROST.Identifier.derive('bob@example.com'); + * const carol = ristretto255_FROST.Identifier.derive('carol@example.com'); + * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ristretto255_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-RISTRETTO255-SHA512-v1', + Point: _RistrettoPoint, + validatePoint: (p) => { + // Prime-order wrappers are torsion-free at the abstract-group level. + p.assertValidity(); + }, + hash: sha512, +}))(); +/** + * Weird / bogus points, useful for debugging. + * All 8 ed25519 points of 8-torsion subgroup can be generated from the point + * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`. + * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the + * array below is that set, not the powers in that exact index order. + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js'; + * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]); + * ``` + */ +export const ED25519_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]); +//# sourceMappingURL=ed25519.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed25519.js.map b/node_modules/@noble/curves/ed25519.js.map new file mode 100644 index 0000000..b629803 --- /dev/null +++ b/node_modules/@noble/curves/ed25519.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed25519.js","sourceRoot":"","sources":["src/ed25519.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAoB,MAAM,qBAAqB,CAAC;AACvD,OAAO,EACL,KAAK,EACL,OAAO,EACP,iBAAiB,GAMlB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAc,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EACL,WAAW,EACX,YAAY,EACZ,kBAAkB,GAInB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EACL,aAAa,EACb,UAAU,EACV,YAAY,EACZ,GAAG,EACH,IAAI,GAEL,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,UAAU,EAAuB,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAa,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,eAAe,EAAE,UAAU,EAAwB,MAAM,YAAY,CAAC;AAE7F,kBAAkB;AAClB,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,G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;QACnB,qEAAqE;QACrE,CAAC,CAAC,cAAc,EAAE,CAAC;IACrB,CAAC;IACD,IAAI,EAAE,MAAM;CACb,CAAC,CAAC,EAAE,CAAC;AAER;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAsB,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IACvF,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;IAClE,kEAAkE;CACnE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.d.ts b/node_modules/@noble/curves/ed448.d.ts new file mode 100644 index 0000000..90ba82d --- /dev/null +++ b/node_modules/@noble/curves/ed448.d.ts @@ -0,0 +1,185 @@ +import type { AffinePoint } from './abstract/curve.ts'; +import { PrimeEdwardsPoint, type EdDSA, type EdwardsPoint, type EdwardsPointCons } from './abstract/edwards.ts'; +import { type FROST } from './abstract/frost.ts'; +import { type H2CHasher, type H2CHasherBase } from './abstract/hash-to-curve.ts'; +import { type IField } from './abstract/modular.ts'; +import { type MontgomeryECDH } from './abstract/montgomery.ts'; +import { type OPRF } from './abstract/oprf.ts'; +import { type TArg, type TRet } from './utils.ts'; +/** + * ed448 EdDSA curve and methods. + * @example + * Generate one Ed448 keypair, sign a message, and verify it. + * + * ```js + * import { ed448 } from '@noble/curves/ed448.js'; + * const { secretKey, publicKey } = ed448.keygen(); + * // const publicKey = ed448.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448.sign(msg, secretKey); + * const isValid = ed448.verify(sig, msg, publicKey); + * ``` + */ +export declare const ed448: EdDSA; +/** + * Prehashed version of ed448. See {@link ed448} + * @example + * Use the prehashed Ed448 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed448ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448ph.sign(msg, secretKey); + * const isValid = ed448ph.verify(sig, msg, publicKey); + * ``` + */ +export declare const ed448ph: EdDSA; +/** + * E448 here is NIST SP 800-186 §3.2.3.3 E448, the Edwards representation of + * Curve448, not RFC 8032 edwards448 / Goldilocks. + * Goldilocks is the separate 4-isogenous curve exposed as `ed448`. + * We keep the corrected prime-order base here; RFC 7748's literal Edwards + * point / map are wrong for this curve model, and the literal point is the + * wrong-sign order-2*n variant. + * @param X - Projective X coordinate. + * @param Y - Projective Y coordinate. + * @param Z - Projective Z coordinate. + * @param T - Projective T coordinate. + * @example + * Multiply the E448 base point. + * + * ```ts + * const point = E448.BASE.multiply(2n); + * ``` + */ +export declare const E448: EdwardsPointCons; +/** + * ECDH using curve448 aka x448. + * The wrapper aborts on all-zero shared secrets by default, and seeded + * `keygen(seed)` reuses the provided 56-byte seed buffer instead of copying it. + * + * @example + * Derive one shared secret between two X448 peers. + * + * ```js + * import { x448 } from '@noble/curves/ed448.js'; + * const alice = x448.keygen(); + * const bob = x448.keygen(); + * const shared = x448.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export declare const x448: TRet; +/** + * Hashing / encoding to ed448 points / field. RFC 9380 methods. + * Public `mapToCurve()` consumes one field element bigint for `m = 1`, and RFC + * Appendix J vectors use the special `QUUX-V01-*` test DST overrides rather + * than the default suite IDs below. + * @example + * Hash one message onto the ed448 curve. + * + * ```ts + * const point = ed448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const ed448_hasher: H2CHasher; +/** + * FROST threshold signatures over ed448. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed448 signing. + * + * ```ts + * const alice = ed448_FROST.Identifier.derive('alice@example.com'); + * const bob = ed448_FROST.Identifier.derive('bob@example.com'); + * const carol = ed448_FROST.Identifier.derive('carol@example.com'); + * const deal = ed448_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const ed448_FROST: TRet; +/** + * Each ed448/EdwardsPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +declare class _DecafPoint extends PrimeEdwardsPoint<_DecafPoint> { + static BASE: _DecafPoint; + static ZERO: _DecafPoint; + static Fp: IField; + static Fn: IField; + constructor(ep: EdwardsPoint); + /** + * Create one Decaf448 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical decaf448 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical decaf448 bytes matter. + */ + static fromAffine(ap: AffinePoint): _DecafPoint; + protected assertSame(other: _DecafPoint): void; + protected init(ep: EdwardsPoint): _DecafPoint; + static fromBytes(bytes: TArg): _DecafPoint; + /** + * Converts decaf-encoded string to decaf point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2). + * @param hex - Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: string): _DecafPoint; + /** + * Encodes decaf point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2). + */ + toBytes(): TRet; + /** + * Compare one point to another. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2). + */ + equals(other: _DecafPoint): boolean; + is0(): boolean; +} +/** Prime-order Decaf448 group bundle. */ +export declare const decaf448: { + Point: typeof _DecafPoint; +}; +/** + * Hashing to decaf448 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 `hash_to_decaf448`, `deriveToCurve()` is RFC + * 9496 element derivation, and `hashToScalar()` is a library helper layered on + * top of RFC 9496 scalar reduction. + * @example + * Hash one message onto decaf448. + * + * ```ts + * const point = decaf448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const decaf448_hasher: H2CHasherBase; +/** + * decaf448 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over decaf448. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = decaf448_oprf.oprf.generateKeyPair(); + * const blind = decaf448_oprf.oprf.blind(input); + * const evaluated = decaf448_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = decaf448_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export declare const decaf448_oprf: TRet; +/** + * Weird / bogus points, useful for debugging. + * Unlike ed25519, there is no ed448 generator point which can produce full T subgroup. + * Instead, the torsion subgroup here is cyclic of order 4, generated by + * `(1, 0)`, and the array below lists that subgroup set (Klein four-group). + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED448_TORSION_SUBGROUP, ed448 } from '@noble/curves/ed448.js'; + * const point = ed448.Point.fromHex(ED448_TORSION_SUBGROUP[1]); + * ``` + */ +export declare const ED448_TORSION_SUBGROUP: readonly string[]; +export {}; +//# sourceMappingURL=ed448.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.d.ts.map b/node_modules/@noble/curves/ed448.d.ts.map new file mode 100644 index 0000000..5edebc1 --- /dev/null +++ b/node_modules/@noble/curves/ed448.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.d.ts","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAGL,iBAAiB,EACjB,KAAK,KAAK,EAGV,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACtB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAe,KAAK,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,aAAa,EACnB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAiD,KAAK,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAc,KAAK,IAAI,EAAE,MAAM,oBA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IAIxC;;;OAGG;IACH,OAAO,IAAI,IAAI,CAAC,UAAU,CAAC;IAe3B;;;OAGG;IACH,MAAM,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO;IAQnC,GAAG,IAAI,OAAO;CAGf;AAMD,yCAAyC;AACzC,eAAO,MAAM,QAAQ,EAAE;IACrB,KAAK,EAAE,OAAO,WAAW,CAAC;CAC6B,CAAC;AAE1D;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,EAAE,aAAa,CAAC,OAAO,WAAW,CAsC5D,CAAC;AAEH;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,aAAa,EAAE,IAAI,CAAC,IAAI,CAO9B,CAAC;AAER;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,sBAAsB,EAAE,SAAS,MAAM,EAKlD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.js b/node_modules/@noble/curves/ed448.js new file mode 100644 index 0000000..0745043 --- /dev/null +++ b/node_modules/@noble/curves/ed448.js @@ -0,0 +1,594 @@ +/** + * Edwards448 (also called Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3.js'; +import { concatBytes, hexToBytes, createHasher as wrapConstructor } from '@noble/hashes/utils.js'; +import { eddsa, edwards, PrimeEdwardsPoint, } from "./abstract/edwards.js"; +import { createFROST } from "./abstract/frost.js"; +import { _DST_scalar, createHasher, expand_message_xof, } from "./abstract/hash-to-curve.js"; +import { Field, FpInvertBatch, isNegativeLE, mod, pow2 } from "./abstract/modular.js"; +import { montgomery } from "./abstract/montgomery.js"; +import { createOPRF } from "./abstract/oprf.js"; +import { abytes, asciiToBytes, bytesToNumberLE, equalBytes, } from "./utils.js"; +// edwards448 curve +// a = 1n +// d = Fp.neg(39081n) +// Finite field 2n**448n - 2n**224n - 1n +// Subgroup order +// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n +const ed448_CURVE_p = /* @__PURE__ */ BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff'); +const ed448_CURVE = /* @__PURE__ */ (() => ({ + p: ed448_CURVE_p, + n: BigInt('0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3'), + h: BigInt(4), + a: BigInt(1), + d: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756'), + Gx: BigInt('0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e'), + Gy: BigInt('0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14'), +}))(); +// This is not RFC 8032 edwards448 / Goldilocks (`ed448` below, d = -39081). +// It is NIST SP 800-186 §3.2.3.3 E448, the Curve448-isomorphic Edwards model +// also described in draft-ietf-lwig-curve-representations-23 Appendix M, with +// d = 39082/39081 and Gy = 3/2. +// RFC 7748's literal Edwards point / birational map are wrong here: the literal +// point is the wrong-sign (Gx, -Gy) order-2*n variant. Keep the corrected +// prime-order (Gx, Gy) base so Point.BASE stays a subgroup generator, which is +// what noble's generic Edwards API expects. +const E448_CURVE = /* @__PURE__ */ (() => Object.assign({}, ed448_CURVE, { + d: BigInt('0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9'), + Gx: BigInt('0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc'), + Gy: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001'), +}))(); +const shake256_114 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 64 })); +// prettier-ignore +const _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _11n = /* @__PURE__ */ BigInt(11); +// prettier-ignore +const _22n = /* @__PURE__ */ BigInt(22), _44n = /* @__PURE__ */ BigInt(44), _88n = /* @__PURE__ */ BigInt(88), _223n = /* @__PURE__ */ BigInt(223); +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x) { + const P = ed448_CURVE_p; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} +// Mutates and returns the provided buffer in place. The final `bytes[56] = 0` +// write is the Ed448 path; for 56-byte X448 inputs it is an out-of-bounds no-op. +function adjustScalarBytes(bytes) { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes; +} +// Constant-time Ed448 decode helper for RFC 8032 §5.2.3 steps 2-3. Unlike +// `SQRT_RATIO_M1`, the returned `value` only has the documented meaning when +// `isValid` is true. +function uvRatio(u, v) { + const P = ed448_CURVE_p; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} +// Finite field 2n**448n - 2n**224n - 1n +// RFC 8032 encodes Ed448 field/scalar elements in 57 bytes even though field +// values fit in 448 bits and scalars in 446 bits. Noble models that with a +// 456-bit storage width so the final-octet x-sign bit (bit 455) still fits in +// the shared little-endian container. +const Fp = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 456, isLE: true }))(); +// Same 57-byte container shape as `Fp`; canonical scalar encodings still have +// the top ten bits clear per RFC 8032. +const Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 456, isLE: true }))(); +// Generic 56-byte field shape used by decaf448 and raw X448 u-coordinates. +// Plain `Field` decoding stays canonical here, so callers that want RFC 7748's +// modulo-p acceptance must reduce externally. +const Fp448 = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 448, isLE: true }))(); +// Strict 56-byte scalar parser matching RFC 9496's recommended canonical form. +const Fn448 = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 448, isLE: true }))(); +// SHAKE256(dom4(phflag,context)||x, 114) +// RFC 8032 `dom4` prefix. Empty contexts are valid; the accepted length range +// is 0..255 octets inclusive. +function dom4(data, ctx, phflag) { + if (ctx.length > 255) + throw new Error('context must be smaller than 255, got: ' + ctx.length); + return concatBytes(asciiToBytes('SigEd448'), new Uint8Array([phflag ? 1 : 0, ctx.length]), ctx, data); +} +const ed448_Point = /* @__PURE__ */ edwards(ed448_CURVE, { Fp, Fn, uvRatio }); +// Shared internal factory for both `ed448` and `ed448ph`; callers are only +// expected to override narrow family options such as prehashing. +function ed4(opts) { + return eddsa(ed448_Point, shake256_114, Object.assign({ adjustScalarBytes, domain: dom4 }, opts)); +} +/** + * ed448 EdDSA curve and methods. + * @example + * Generate one Ed448 keypair, sign a message, and verify it. + * + * ```js + * import { ed448 } from '@noble/curves/ed448.js'; + * const { secretKey, publicKey } = ed448.keygen(); + * // const publicKey = ed448.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448.sign(msg, secretKey); + * const isValid = ed448.verify(sig, msg, publicKey); + * ``` + */ +export const ed448 = /* @__PURE__ */ ed4({}); +// There is no ed448ctx, since ed448 supports ctx by default +/** + * Prehashed version of ed448. See {@link ed448} + * @example + * Use the prehashed Ed448 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed448ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448ph.sign(msg, secretKey); + * const isValid = ed448ph.verify(sig, msg, publicKey); + * ``` + */ +export const ed448ph = /* @__PURE__ */ ed4({ prehash: shake256_64 }); +/** + * E448 here is NIST SP 800-186 §3.2.3.3 E448, the Edwards representation of + * Curve448, not RFC 8032 edwards448 / Goldilocks. + * Goldilocks is the separate 4-isogenous curve exposed as `ed448`. + * We keep the corrected prime-order base here; RFC 7748's literal Edwards + * point / map are wrong for this curve model, and the literal point is the + * wrong-sign order-2*n variant. + * @param X - Projective X coordinate. + * @param Y - Projective Y coordinate. + * @param Z - Projective Z coordinate. + * @param T - Projective T coordinate. + * @example + * Multiply the E448 base point. + * + * ```ts + * const point = E448.BASE.multiply(2n); + * ``` + */ +export const E448 = /* @__PURE__ */ edwards(E448_CURVE); +/** + * ECDH using curve448 aka x448. + * The wrapper aborts on all-zero shared secrets by default, and seeded + * `keygen(seed)` reuses the provided 56-byte seed buffer instead of copying it. + * + * @example + * Derive one shared secret between two X448 peers. + * + * ```js + * import { x448 } from '@noble/curves/ed448.js'; + * const alice = x448.keygen(); + * const bob = x448.keygen(); + * const shared = x448.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export const x448 = /* @__PURE__ */ (() => { + const P = ed448_CURVE_p; + return montgomery({ + P, + type: 'x448', + powPminus2: (x) => { + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, _2n, P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + }); +})(); +// Hash To Curve Elligator2 Map +// 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_C1 = /* @__PURE__ */ (() => (ed448_CURVE_p - BigInt(3)) / BigInt(4))(); +const ELL2_J = /* @__PURE__ */ BigInt(156326); +// Returns RFC 9380 Appendix G.2.3 rational Montgomery numerators/denominators +// `{ xn, xd, yn, yd }`, not an affine point. +function map_to_curve_elligator2_curve448(u) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let x2n = Fp.mul(x1n, Fp.neg(tv1)); + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} +// Returns affine `{ x, y }` after inverting the Appendix G.2.4 denominators. +function map_to_curve_elligator2_edwards448(u) { + // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + const inv = FpInvertBatch(Fp, [xEd, yEd], true); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} +/** + * Hashing / encoding to ed448 points / field. RFC 9380 methods. + * Public `mapToCurve()` consumes one field element bigint for `m = 1`, and RFC + * Appendix J vectors use the special `QUUX-V01-*` test DST overrides rather + * than the default suite IDs below. + * @example + * Hash one message onto the ed448 curve. + * + * ```ts + * const point = ed448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ed448_hasher = /* @__PURE__ */ (() => createHasher(ed448_Point, (scalars) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: ed448_CURVE_p, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, +}))(); +/** + * FROST threshold signatures over ed448. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed448 signing. + * + * ```ts + * const alice = ed448_FROST.Identifier.derive('alice@example.com'); + * const bob = ed448_FROST.Identifier.derive('bob@example.com'); + * const carol = ed448_FROST.Identifier.derive('carol@example.com'); + * const deal = ed448_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ed448_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-ED448-SHAKE256-v1', + Point: ed448_Point, + validatePoint: (p) => { + p.assertValidity(); + if (!p.isTorsionFree()) + throw new Error('bad point: not torsion-free'); + }, + // Group: edwards448 [RFC8032], where Ne = 57 and Ns = 57. + // Fn is 57 bytes, Fp is 57 bytes too + Fn, + hash: shake256_114, + H2: 'SigEd448\0\0', +}))(); +// 1-d +const ONE_MINUS_D = /* @__PURE__ */ BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = /* @__PURE__ */ BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = /* @__PURE__ */ BigInt('98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214'); +// 1 / √(-d) +const INVSQRT_MINUS_D = /* @__PURE__ */ BigInt('315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716'); +// RFC 9496 `SQRT_RATIO_M1` must return `CT_ABS(s)`, i.e. the nonnegative root. +// Keep this Decaf-local: RFC 9496 decode/encode/map formulas depend on that +// canonical representative, while ordinary Ed448 decoding still uses `uvRatio()` +// plus the public sign bit from RFC 8032. +const sqrtRatioM1 = (u, v) => { + const P = ed448_CURVE_p; + const { isValid, value } = uvRatio(u, v); + return { isValid, value: isNegativeLE(value, P) ? Fp448.create(-value) : value }; +}; +const invertSqrt = (number) => sqrtRatioM1(_1n, number); +/** + * Elligator map for hash-to-curve of decaf448. + * Primary formula source is RFC 9496 §5.3.4. Step 1 intentionally reduces the + * input modulo `p`, and the return value is the internal Edwards + * representation, not a public decaf encoding. + */ +function calcElligatorDecafMap(r0) { + const { d, p: P } = ed448_CURVE; + const mod = (n) => Fp448.create(n); + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + const { isValid: was_square, value: v } = sqrtRatioM1(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + let v_prime = v; // 5 + if (!was_square) + v_prime = mod(r0 * v); + let sgn = _1n; // 6 + if (!was_square) + sgn = mod(-_1n); + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) + s_abs = mod(-s); + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} +// Keep the Decaf448 base representative literal here: deriving it with +// `new _DecafPoint(ed448_Point.BASE).multiplyUnsafe(2)` forces eager WNAF precomputes and +// adds about 100ms to `ed448.js` import time. +const DECAF_BASE_X = /* @__PURE__ */ BigInt('0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa955555555555555555555555555555555555555555555555555555555'); +const DECAF_BASE_Y = /* @__PURE__ */ BigInt('0xae05e9634ad7048db359d6205086c2b0036ed7a035884dd7b7e36d728ad8c4b80d6565833a2a3098bbbcb2bed1cda06bdaeafbcdea9386ed'); +const DECAF_BASE_T = /* @__PURE__ */ BigInt('0x696d84643374bace9d70983a12aa9d461da74d2d5c35e8d97ba72c3aba4450a5d29274229bd22c1d5e3a6474ee4ffb0e7a9e200a28eee402'); +/** + * Each ed448/EdwardsPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +class _DecafPoint extends PrimeEdwardsPoint { + // The following gymnastics is done because typescript strips comments otherwise + // prettier-ignore + static BASE = + /* @__PURE__ */ (() => new _DecafPoint(new ed448_Point(DECAF_BASE_X, DECAF_BASE_Y, _1n, DECAF_BASE_T)))(); + // prettier-ignore + static ZERO = + /* @__PURE__ */ (() => new _DecafPoint(ed448_Point.ZERO))(); + // prettier-ignore + static Fp = + /* @__PURE__ */ (() => Fp448)(); + // prettier-ignore + static Fn = + /* @__PURE__ */ (() => Fn448)(); + constructor(ep) { + super(ep); + } + /** + * Create one Decaf448 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical decaf448 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical decaf448 bytes matter. + */ + static fromAffine(ap) { + return new _DecafPoint(ed448_Point.fromAffine(ap)); + } + assertSame(other) { + if (!(other instanceof _DecafPoint)) + throw new Error('DecafPoint expected'); + } + init(ep) { + return new _DecafPoint(ep); + } + static fromBytes(bytes) { + abytes(bytes, 56); + const { d, p: P } = ed448_CURVE; + const mod = (n) => Fp448.create(n); + const s = Fp448.fromBytes(bytes); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(Fn448.toBytes(s), bytes) || isNegativeLE(s, P)) + throw new Error('invalid decaf448 encoding 1'); + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) + u3 = mod(-u3); + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + if (!isValid) + throw new Error('invalid decaf448 encoding 2'); + return new _DecafPoint(new ed448_Point(x, y, _1n, t)); + } + /** + * Converts decaf-encoded string to decaf point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2). + * @param hex - Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex) { + return _DecafPoint.fromBytes(hexToBytes(hex)); + } + /** + * Encodes decaf point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2). + */ + toBytes() { + const { X, Z, T } = this.ep; + const P = ed448_CURVE.p; + const mod = (n) => Fp448.create(n); + const u1 = mod(mod(X + T) * mod(X - T)); // 1 + const x2 = mod(X * X); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) + ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * Z - T); // 4 + let s = mod(ONE_MINUS_D * invsqrt * X * u2); // 5 + if (isNegativeLE(s, P)) + s = mod(-s); + return Fn448.toBytes(s); + } + /** + * Compare one point to another. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2). + */ + equals(other) { + this.assertSame(other); + const { X: X1, Y: Y1 } = this.ep; + const { X: X2, Y: Y2 } = other.ep; + // (x1 * y2 == y1 * x2) + return Fp448.create(X1 * Y2) === Fp448.create(Y1 * X2); + } + is0() { + return this.equals(_DecafPoint.ZERO); + } +} +Object.freeze(_DecafPoint.BASE); +Object.freeze(_DecafPoint.ZERO); +Object.freeze(_DecafPoint.prototype); +Object.freeze(_DecafPoint); +/** Prime-order Decaf448 group bundle. */ +export const decaf448 = /* @__PURE__ */ Object.freeze({ Point: _DecafPoint }); +/** + * Hashing to decaf448 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 `hash_to_decaf448`, `deriveToCurve()` is RFC + * 9496 element derivation, and `hashToScalar()` is a library helper layered on + * top of RFC 9496 scalar reduction. + * @example + * Hash one message onto decaf448. + * + * ```ts + * const point = decaf448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const decaf448_hasher = Object.freeze({ + Point: _DecafPoint, + hashToCurve(msg, options) { + // Preserve explicit empty/invalid DST overrides so expand_message_xof() can reject them. + const DST = options?.DST === undefined ? 'decaf448_XOF:SHAKE256_D448MAP_RO_' : options.DST; + return decaf448_hasher.deriveToCurve(expand_message_xof(msg, DST, 112, 224, shake256)); + }, + /** + * Warning: has big modulo bias of 2^-64. + * RFC is invalid. RFC says "use 64-byte xof", while for 2^-112 bias + * it must use 84-byte xof (56+56/2), not 64. + */ + hashToScalar(msg, options = { DST: _DST_scalar }) { + // Can't use `Fn448.fromBytes()`. 64-byte input => 56-byte field element + const xof = expand_message_xof(msg, options.DST, 64, 256, shake256); + return Fn448.create(bytesToNumberLE(xof)); + }, + /** + * HashToCurve-like construction based on RFC 9496 (Element Derivation). + * Converts 112 uniform random bytes into a curve point. + * + * WARNING: This represents an older hash-to-curve construction from before + * RFC 9380 was finalized. + * It was later reused as a component in the newer + * `hash_to_decaf448` function defined in RFC 9380. + */ + deriveToCurve(bytes) { + abytes(bytes, 112); + const skipValidation = true; + // Note: Similar to the field element decoding described in + // [RFC7748], and unlike the field element decoding described in + // Section 5.3.1, non-canonical values are accepted. + const r1 = Fp448.create(Fp448.fromBytes(bytes.subarray(0, 56), skipValidation)); + const R1 = calcElligatorDecafMap(r1); + const r2 = Fp448.create(Fp448.fromBytes(bytes.subarray(56, 112), skipValidation)); + const R2 = calcElligatorDecafMap(r2); + return new _DecafPoint(R1.add(R2)); + }, +}); +/** + * decaf448 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over decaf448. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = decaf448_oprf.oprf.generateKeyPair(); + * const blind = decaf448_oprf.oprf.blind(input); + * const evaluated = decaf448_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = decaf448_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const decaf448_oprf = /* @__PURE__ */ (() => createOPRF({ + name: 'decaf448-SHAKE256', + Point: _DecafPoint, + hash: (msg) => shake256(msg, { dkLen: 64 }), + hashToGroup: decaf448_hasher.hashToCurve, + hashToScalar: decaf448_hasher.hashToScalar, +}))(); +/** + * Weird / bogus points, useful for debugging. + * Unlike ed25519, there is no ed448 generator point which can produce full T subgroup. + * Instead, the torsion subgroup here is cyclic of order 4, generated by + * `(1, 0)`, and the array below lists that subgroup set (Klein four-group). + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED448_TORSION_SUBGROUP, ed448 } from '@noble/curves/ed448.js'; + * const point = ed448.Point.fromHex(ED448_TORSION_SUBGROUP[1]); + * ``` + */ +export const ED448_TORSION_SUBGROUP = /* @__PURE__ */ Object.freeze([ + '010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + 'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00', + '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080', +]); +//# sourceMappingURL=ed448.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/ed448.js.map b/node_modules/@noble/curves/ed448.js.map new file mode 100644 index 0000000..73572e0 --- /dev/null +++ b/node_modules/@noble/curves/ed448.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ed448.js","sourceRoot":"","sources":["src/ed448.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,IAAI,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAElG,OAAO,EACL,KAAK,EACL,OAAO,EACP,iBAAiB,GAMlB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,WAAW,EAAc,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EACL,WAAW,EACX,YAAY,EACZ,kBAAkB,GAInB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,KAAK,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AAsB,GAAsB,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IACrF,oHAAoH;IACpH,oHAAoH;IACpH,oHAAoH;IACpH,oHAAoH;CACrH,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/index.d.ts b/node_modules/@noble/curves/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/node_modules/@noble/curves/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/index.d.ts.map b/node_modules/@noble/curves/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/curves/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/curves/index.js b/node_modules/@noble/curves/index.js new file mode 100644 index 0000000..49820ba --- /dev/null +++ b/node_modules/@noble/curves/index.js @@ -0,0 +1,39 @@ +/** + * Audited & minimal JS implementation of elliptic curve cryptography. + * @module + * @example +```js +import { secp256k1, schnorr } from '@noble/curves/secp256k1.js'; +import { ed25519, ed25519ph, ed25519ctx, x25519, ristretto255 } from '@noble/curves/ed25519.js'; +import { ed448, ed448ph, x448, decaf448 } from '@noble/curves/ed448.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { bls12_381 } from '@noble/curves/bls12-381.js'; +import { bn254 } from '@noble/curves/bn254.js'; +import { + jubjub, + babyjubjub, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, +} from '@noble/curves/misc.js'; +import * as webcrypto from '@noble/curves/webcrypto.js'; + +// hash-to-curve +import { secp256k1_hasher } from '@noble/curves/secp256k1.js'; +import { p256_hasher, p384_hasher, p521_hasher } from '@noble/curves/nist.js'; +import { ristretto255_hasher } from '@noble/curves/ed25519.js'; +import { decaf448_hasher } from '@noble/curves/ed448.js'; + +// OPRFs +import { p256_oprf, p384_oprf, p521_oprf } from '@noble/curves/nist.js'; +import { ristretto255_oprf } from '@noble/curves/ed25519.js'; +import { decaf448_oprf } from '@noble/curves/ed448.js'; + +// utils +import { bytesToHex, hexToBytes, concatBytes } from '@noble/curves/abstract/utils.js'; +import { Field } from '@noble/curves/abstract/modular.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/index.js.map b/node_modules/@noble/curves/index.js.map new file mode 100644 index 0000000..671e14b --- /dev/null +++ b/node_modules/@noble/curves/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/misc.d.ts b/node_modules/@noble/curves/misc.d.ts new file mode 100644 index 0000000..ead84f7 --- /dev/null +++ b/node_modules/@noble/curves/misc.d.ts @@ -0,0 +1,114 @@ +import { type EdDSA, type EdwardsPoint } from './abstract/edwards.ts'; +import { type ECDSA } from './abstract/weierstrass.ts'; +import { type TArg } from './utils.ts'; +/** + * Generic EdDSA-over-Jubjub convenience wrapper with `sha512`. + * This is not the Zcash RedJubjub / Sapling signature scheme. + * @example + * Generate one Jubjub keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = jubjub.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = jubjub.sign(msg, secretKey); + * const isValid = jubjub.verify(sig, msg, publicKey); + * ``` + */ +export declare const jubjub: EdDSA; +/** + * Curve over scalar field of bn254. babyjubjub Fp = bn254 n + * This is a working generic EdDSA-over-BabyJubJub wrapper that uses `blake512` for the 64-byte + * secret expansion required by the shared EdDSA helper. + * It is not the BabyJubJub stack used by iden3/circomlib, `babyjubjub-rs`, or + * `@zk-kit/eddsa-poseidon`: those pair the subgroup base B/B8 with Blake-style secret expansion + * plus dedicated Poseidon / MiMC / Pedersen transcript hashing. This wrapper stays generic and is + * not meant as an interoperability target for those BabyJubJub signing stacks. + * @example + * Access the BabyJubJub base point and round-trip it through the point codec. + * + * ```ts + * import { babyjubjub } from '@noble/curves/misc.js'; + * const base = babyjubjub.Point.BASE; + * const encoded = base.toBytes(); + * const decoded = babyjubjub.Point.fromBytes(encoded); + * ``` + */ +export declare const babyjubjub: EdDSA; +/** + * @param tag - Hash input. + * @param personalization - BLAKE2 personalization bytes. + * @returns Prime-order Jubjub point. + * @throws If the digest does not decode to a Jubjub point, or if the + * cofactor-cleared point has small order. {@link Error} + * @example + * Hash a tag into a prime-order Jubjub point. + * + * ```ts + * import { jubjub_groupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const tag = Uint8Array.of(2); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_groupHash(tag, personalization); + * ``` + */ +export declare function jubjub_groupHash(tag: TArg, personalization: TArg): EdwardsPoint; +/** + * No secret data is leaked here at all. + * It operates over public data. + * @param m - Message prefix. + * @param personalization - 8-byte BLAKE2 personalization bytes. + * @returns First non-zero group hash. + * @throws If the personalization is invalid, or if no non-zero Jubjub group + * hash can be found. {@link Error} + * @example + * Derive the first non-zero Jubjub group hash for one personalization tag. + * + * ```ts + * import { jubjub_findGroupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const msg = Uint8Array.of(); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_findGroupHash(msg, personalization); + * ``` + */ +export declare function jubjub_findGroupHash(m: TArg, personalization: TArg): EdwardsPoint; +/** + * Brainpool P256r1 with sha256, from RFC 5639. + * @example + * Generate one Brainpool P256r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP256r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP256r1.sign(msg, secretKey); + * const isValid = brainpoolP256r1.verify(sig, msg, publicKey); + * ``` + */ +export declare const brainpoolP256r1: ECDSA; +/** + * Brainpool P384r1 with sha384, from RFC 5639. + * @example + * Generate one Brainpool P384r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP384r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP384r1.sign(msg, secretKey); + * const isValid = brainpoolP384r1.verify(sig, msg, publicKey); + * ``` + */ +export declare const brainpoolP384r1: ECDSA; +/** + * Brainpool P512r1 with sha512, from RFC 5639. + * @example + * Generate one Brainpool P512r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP512r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP512r1.sign(msg, secretKey); + * const isValid = brainpoolP512r1.verify(sig, msg, publicKey); + * ``` + */ +export declare const brainpoolP512r1: ECDSA; +//# sourceMappingURL=misc.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/misc.d.ts.map b/node_modules/@noble/curves/misc.d.ts.map new file mode 100644 index 0000000..abfb0d1 --- /dev/null +++ b/node_modules/@noble/curves/misc.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"misc.d.ts","sourceRoot":"","sources":["src/misc.ts"],"names":[],"mappings":"AAUA,OAAO,EAGL,KAAK,KAAK,EAEV,KAAK,YAAY,EAClB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAsB,KAAK,KAAK,EAAwB,MAAM,2BAA2B,CAAC;AACjG,OAAO,EAAgB,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAgBrD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,MAAM,EAAE,KAAsE,CAAC;AAoB5F;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,UAAU,EAAE,KACsB,CAAC;AAQhD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,GAChC,YAAY,CAUd;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAClC,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,EACnB,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,GAChC,YAAY,CAcd;AAWD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,EAAE,KACwB,CAAC;AAuBvD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,EAAE,KACwB,CAAC;AAuBvD;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,eAAe,EAAE,KACwB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/misc.js b/node_modules/@noble/curves/misc.js new file mode 100644 index 0000000..4c01302 --- /dev/null +++ b/node_modules/@noble/curves/misc.js @@ -0,0 +1,212 @@ +/** + * Miscellaneous, rarely used curves. + * jubjub, babyjubjub, pallas, vesta. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { blake512 } from '@noble/hashes/blake1.js'; +import { blake2s } from '@noble/hashes/blake2.js'; +import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes } from '@noble/hashes/utils.js'; +import { eddsa, edwards, } from "./abstract/edwards.js"; +import { ecdsa, weierstrass } from "./abstract/weierstrass.js"; +import { asciiToBytes } from "./utils.js"; +// Jubjub curves have 𝔽p over scalar fields of other curves. They are friendly to ZK proofs. +// Zcash Protocol Specification "Jubjub" parameters: +// q = BLS12-381 Fr, r, h = 8, a = -1, d = -10240/10241. +// Gx/Gy keep the canonical Jubjub base point used by Zcash implementations. +const jubjub_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'), + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + h: BigInt(8), + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), +}))(); +/** + * Generic EdDSA-over-Jubjub convenience wrapper with `sha512`. + * This is not the Zcash RedJubjub / Sapling signature scheme. + * @example + * Generate one Jubjub keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = jubjub.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = jubjub.sign(msg, secretKey); + * const isValid = jubjub.verify(sig, msg, publicKey); + * ``` + */ +export const jubjub = /* @__PURE__ */ (() => eddsa(edwards(jubjub_CURVE), sha512))(); +// BabyJubJub over bn254 Fr. EIP-2494 explicitly defines both the full-group generator G and the +// prime-order subgroup base point B = 8*G. +// noble's Edwards abstraction expects Point.BASE / curve.n to describe the prime-order subgroup, so +// use the EIP base point B here. +// Historical noble incorrectly used the EIP generator G as Point.BASE, which mismatched the +// abstraction and leaked the wrong order into consumers. +// Historical noble used G instead: +// Gx = 995203441582195749578291179787384436505546430278305826713579947235728471134 +// Gy = 5472060717959818805561601436314318772137091100104008585924551046643952123905 +const babyjubjub_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + n: BigInt('0x060c89ce5c263405370a08b6d0302b0bab3eedb83920ee0a677297dc392126f1'), + h: BigInt(8), + a: BigInt('168700'), + d: BigInt('168696'), + Gx: BigInt('0xbb77a6ad63e739b4eacb2e09d6277c12ab8d8010534e0b62893f3f6bb957051'), + Gy: BigInt('0x25797203f7a0b24925572e1cd16bf9edfce0051fb9e133774b3c257a872d7d8b'), +}))(); +/** + * Curve over scalar field of bn254. babyjubjub Fp = bn254 n + * This is a working generic EdDSA-over-BabyJubJub wrapper that uses `blake512` for the 64-byte + * secret expansion required by the shared EdDSA helper. + * It is not the BabyJubJub stack used by iden3/circomlib, `babyjubjub-rs`, or + * `@zk-kit/eddsa-poseidon`: those pair the subgroup base B/B8 with Blake-style secret expansion + * plus dedicated Poseidon / MiMC / Pedersen transcript hashing. This wrapper stays generic and is + * not meant as an interoperability target for those BabyJubJub signing stacks. + * @example + * Access the BabyJubJub base point and round-trip it through the point codec. + * + * ```ts + * import { babyjubjub } from '@noble/curves/misc.js'; + * const base = babyjubjub.Point.BASE; + * const encoded = base.toBytes(); + * const decoded = babyjubjub.Point.fromBytes(encoded); + * ``` + */ +export const babyjubjub = /* @__PURE__ */ (() => eddsa(edwards(babyjubjub_CURVE), blake512))(); +// Sapling URS randomness beacon from the Zcash protocol. This stays as the 64-byte ASCII +// lowercase-hex string used for the first Blake2s block, not 32 raw bytes. +const jubjub_gh_first_block = /* @__PURE__ */ asciiToBytes('096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0'); +/** + * @param tag - Hash input. + * @param personalization - BLAKE2 personalization bytes. + * @returns Prime-order Jubjub point. + * @throws If the digest does not decode to a Jubjub point, or if the + * cofactor-cleared point has small order. {@link Error} + * @example + * Hash a tag into a prime-order Jubjub point. + * + * ```ts + * import { jubjub_groupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const tag = Uint8Array.of(2); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_groupHash(tag, personalization); + * ``` + */ +export function jubjub_groupHash(tag, personalization) { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(jubjub_gh_first_block); + h.update(tag); + // NOTE: returns EdwardsPoint, in case it will be multiplied later + let p = jubjub.Point.fromBytes(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub_CURVE.h); + if (p.equals(jubjub.Point.ZERO)) + throw new Error('Point has small order'); + return p; +} +/** + * No secret data is leaked here at all. + * It operates over public data. + * @param m - Message prefix. + * @param personalization - 8-byte BLAKE2 personalization bytes. + * @returns First non-zero group hash. + * @throws If the personalization is invalid, or if no non-zero Jubjub group + * hash can be found. {@link Error} + * @example + * Derive the first non-zero Jubjub group hash for one personalization tag. + * + * ```ts + * import { jubjub_findGroupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const msg = Uint8Array.of(); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_findGroupHash(msg, personalization); + * ``` + */ +export function jubjub_findGroupHash(m, personalization) { + // Validate BLAKE2s personalization once up front; otherwise the retry loop swallows the real + // input error and turns it into a misleading "tag overflow". + abytes(personalization, 8, 'personalization'); + const tag = concatBytes(m, Uint8Array.of(0)); + const hashes = []; + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + hashes.push(jubjub_groupHash(tag, personalization)); + } + catch (e) { } + } + if (!hashes.length) + throw new Error('findGroupHash tag overflow'); + return hashes[0]; +} +const brainpoolP256r1_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'), + a: BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'), + b: BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'), + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), +}))(); +/** + * Brainpool P256r1 with sha256, from RFC 5639. + * @example + * Generate one Brainpool P256r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP256r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP256r1.sign(msg, secretKey); + * const isValid = brainpoolP256r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP256r1 = /* @__PURE__ */ (() => ecdsa(weierstrass(brainpoolP256r1_CURVE), sha256))(); +const brainpoolP384r1_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53'), + a: BigInt('0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826'), + b: BigInt('0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11'), + n: BigInt('0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565'), + Gx: BigInt('0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e'), + Gy: BigInt('0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315'), + h: BigInt(1), +}))(); +/** + * Brainpool P384r1 with sha384, from RFC 5639. + * @example + * Generate one Brainpool P384r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP384r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP384r1.sign(msg, secretKey); + * const isValid = brainpoolP384r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP384r1 = /* @__PURE__ */ (() => ecdsa(weierstrass(brainpoolP384r1_CURVE), sha384))(); +const brainpoolP512r1_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3'), + a: BigInt('0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca'), + b: BigInt('0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723'), + n: BigInt('0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069'), + Gx: BigInt('0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822'), + Gy: BigInt('0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892'), + h: BigInt(1), +}))(); +/** + * Brainpool P512r1 with sha512, from RFC 5639. + * @example + * Generate one Brainpool P512r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP512r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP512r1.sign(msg, secretKey); + * const isValid = brainpoolP512r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP512r1 = /* @__PURE__ */ (() => ecdsa(weierstrass(brainpoolP512r1_CURVE), sha512))(); +//# sourceMappingURL=misc.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/misc.js.map b/node_modules/@noble/curves/misc.js.map new file mode 100644 index 0000000..198561a --- /dev/null +++ b/node_modules/@noble/curves/misc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"misc.js","sourceRoot":"","sources":["src/misc.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,sEAAsE;AACtE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB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AqB,CAAC,EAAE,MAAM,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/nist.d.ts b/node_modules/@noble/curves/nist.d.ts new file mode 100644 index 0000000..03b3691 --- /dev/null +++ b/node_modules/@noble/curves/nist.d.ts @@ -0,0 +1,137 @@ +import { type FROST } from './abstract/frost.ts'; +import { type H2CHasher } from './abstract/hash-to-curve.ts'; +import { type OPRF } from './abstract/oprf.ts'; +import { type ECDSA, type WeierstrassPointCons } from './abstract/weierstrass.ts'; +import { type TRet } from './utils.ts'; +/** + * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. + * Hashes inputs with sha256 by default. + * + * @example + * Generate one P-256 keypair, sign a message, and verify it. + * + * ```js + * import { p256 } from '@noble/curves/nist.js'; + * const { secretKey, publicKey } = p256.keygen(); + * // const publicKey = p256.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256.sign(msg, secretKey); + * const isValid = p256.verify(sig, msg, publicKey); + * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export declare const p256: ECDSA; +/** + * Hashing / encoding to p256 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-256 curve. + * + * ```ts + * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const p256_hasher: H2CHasher>; +/** + * p256 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-256. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p256_oprf.oprf.generateKeyPair(); + * const blind = p256_oprf.oprf.blind(input); + * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export declare const p256_oprf: TRet; +/** + * FROST threshold signatures over p256. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 p256 signing. + * + * ```ts + * const alice = p256_FROST.Identifier.derive('alice@example.com'); + * const bob = p256_FROST.Identifier.derive('bob@example.com'); + * const carol = p256_FROST.Identifier.derive('carol@example.com'); + * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const p256_FROST: TRet; +/** + * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default. + * @example + * Generate one P-384 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p384.sign(msg, secretKey); + * const isValid = p384.verify(sig, msg, publicKey); + * ``` + */ +export declare const p384: ECDSA; +/** + * Hashing / encoding to p384 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-384 curve. + * + * ```ts + * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const p384_hasher: H2CHasher>; +/** + * p384 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-384. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p384_oprf.oprf.generateKeyPair(); + * const blind = p384_oprf.oprf.blind(input); + * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export declare const p384_oprf: TRet; +/** + * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default. + * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation + * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width. + * @example + * Generate one P-521 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p521.sign(msg, secretKey); + * const isValid = p521.verify(sig, msg, publicKey); + * ``` + */ +export declare const p521: ECDSA; +/** + * Hashing / encoding to p521 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-521 curve. + * + * ```ts + * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const p521_hasher: H2CHasher>; +/** + * p521 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-521. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p521_oprf.oprf.generateKeyPair(); + * const blind = p521_oprf.oprf.blind(input); + * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export declare const p521_oprf: TRet; +//# sourceMappingURL=nist.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/nist.d.ts.map b/node_modules/@noble/curves/nist.d.ts.map new file mode 100644 index 0000000..f7d6d54 --- /dev/null +++ b/node_modules/@noble/curves/nist.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"nist.d.ts","sourceRoot":"","sources":["src/nist.ts"],"names":[],"mappings":"AAOA,OAAO,EAAe,KAAK,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAgB,KAAK,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAC3E,OAAO,EAAc,KAAK,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAIL,KAAK,KAAK,EAEV,KAAK,oBAAoB,EAC1B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AA4EvC;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI,EAAE,KAAiD,CAAC;AACrE;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAkB5D,CAAC;AACL;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,IAAI,CAO1B,CAAC;AACR;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,KAAK,CAM5B,CAAC;AAIR;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,IAAI,EAAE,KAAiD,CAAC;AACrE;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAkB5D,CAAC;AACL;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,IAAI,CAO1B,CAAC;AAmBR;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,IAAI,EAAE,KAAiD,CAAC;AACrE;;;;;;;;GAQG;AACH,eAAO,MAAM,WAAW,EAAE,SAAS,CAAC,oBAAoB,CAAC,MAAM,CAAC,CAkB5D,CAAC;AACL;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,IAAI,CAO1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/nist.js b/node_modules/@noble/curves/nist.js new file mode 100644 index 0000000..9c1741e --- /dev/null +++ b/node_modules/@noble/curves/nist.js @@ -0,0 +1,268 @@ +/** + * Internal module for NIST P256, P384, P521 curves. + * Do not use for now. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js'; +import { createFROST } from "./abstract/frost.js"; +import { createHasher } from "./abstract/hash-to-curve.js"; +import { createOPRF } from "./abstract/oprf.js"; +import { ecdsa, mapToCurveSimpleSWU, weierstrass, } from "./abstract/weierstrass.js"; +import {} from "./utils.js"; +// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n +// a = Fp256.create(BigInt('-3')); +const p256_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'), + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + h: BigInt(1), + a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'), + b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'), + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), +}))(); +// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n +const p384_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff'), + n: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973'), + h: BigInt(1), + a: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc'), + b: BigInt('0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef'), + Gx: BigInt('0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7'), + Gy: BigInt('0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f'), +}))(); +// p = 2n**521n - 1n +const p521_CURVE = /* @__PURE__ */ (() => ({ + p: BigInt('0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'), + n: BigInt('0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409'), + h: BigInt(1), + a: BigInt('0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc'), + b: BigInt('0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00'), + Gx: BigInt('0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66'), + Gy: BigInt('0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650'), +}))(); +function createSWU(Point, opts) { + let map; + // RFC 9380's NIST suites here all use m = 1, so createHasher passes one field element per map. + // Building the SWU sqrt-ratio helper eagerly adds noticeable `nist.js` import cost, so defer it + // to first use; after that the cached mapper is reused directly. + return (scalars) => (map || (map = mapToCurveSimpleSWU(Point.Fp, opts)))(scalars[0]); +} +// NIST P256 +const p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE); +/** + * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. + * Hashes inputs with sha256 by default. + * + * @example + * Generate one P-256 keypair, sign a message, and verify it. + * + * ```js + * import { p256 } from '@noble/curves/nist.js'; + * const { secretKey, publicKey } = p256.keygen(); + * // const publicKey = p256.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256.sign(msg, secretKey); + * const isValid = p256.verify(sig, msg, publicKey); + * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export const p256 = /* @__PURE__ */ ecdsa(p256_Point, sha256); +/** + * Hashing / encoding to p256 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-256 curve. + * + * ```ts + * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p256_hasher = /* @__PURE__ */ (() => { + return createHasher(p256_Point, createSWU(p256_Point, { + A: p256_CURVE.a, + B: p256_CURVE.b, + Z: p256_Point.Fp.create(BigInt('-10')), + }), { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: p256_CURVE.p, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + }); +})(); +/** + * p256 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-256. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p256_oprf.oprf.generateKeyPair(); + * const blind = p256_oprf.oprf.blind(input); + * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p256_oprf = /* @__PURE__ */ (() => createOPRF({ + name: 'P256-SHA256', + Point: p256_Point, + hash: sha256, + hashToGroup: p256_hasher.hashToCurve, + hashToScalar: p256_hasher.hashToScalar, +}))(); +/** + * FROST threshold signatures over p256. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 p256 signing. + * + * ```ts + * const alice = p256_FROST.Identifier.derive('alice@example.com'); + * const bob = p256_FROST.Identifier.derive('bob@example.com'); + * const carol = p256_FROST.Identifier.derive('carol@example.com'); + * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const p256_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-P256-SHA256-v1', + Point: p256_Point, + hashToScalar: p256_hasher.hashToScalar, + hash: sha256, +}))(); +// NIST P384 +const p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE); +/** + * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default. + * @example + * Generate one P-384 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p384.sign(msg, secretKey); + * const isValid = p384.verify(sig, msg, publicKey); + * ``` + */ +export const p384 = /* @__PURE__ */ ecdsa(p384_Point, sha384); +/** + * Hashing / encoding to p384 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-384 curve. + * + * ```ts + * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p384_hasher = /* @__PURE__ */ (() => { + return createHasher(p384_Point, createSWU(p384_Point, { + A: p384_CURVE.a, + B: p384_CURVE.b, + Z: p384_Point.Fp.create(BigInt('-12')), + }), { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: p384_CURVE.p, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + }); +})(); +/** + * p384 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-384. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p384_oprf.oprf.generateKeyPair(); + * const blind = p384_oprf.oprf.blind(input); + * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p384_oprf = /* @__PURE__ */ (() => createOPRF({ + name: 'P384-SHA384', + Point: p384_Point, + hash: sha384, + hashToGroup: p384_hasher.hashToCurve, + hashToScalar: p384_hasher.hashToScalar, +}))(); +// NIST P521 +// RFC 7518 fixes the canonical JWK/JOSE width at 66 bytes: +// - Section 3.4 says ECDSA octet strings must not omit leading zero octets +// - Sections 6.2.1.2/6.2.1.3 say P-521 coordinates "x"/"y" must be 66 octets +// - Section 6.2.2.1 says private scalar "d" must be ceil(log2(n)/8) octets, i.e. 66 for P-521 +// NIST FIPS 186-5 Appendix A.3.3 also routes deterministic ECDSA private keys through Appendix +// B.2.3, whose Integer-to-Octet-String output has explicit fixed length L; for P-521 that is the +// same 66-byte order width. +// RFC 6979 matches that width too: private key x is an integer, while `int2octets(x)` uses +// rlen = 8 * ceil(qlen/8); for P-521, qlen = 521 so the canonical octet width is 66 bytes. +// Wycheproof ECDH stores private values as integers, not fixed-width scalar bytes, so it does not +// require a dedicated 65-byte parser path; the repo tests now normalize those integer fixtures to +// the canonical 66-byte width before use. There is no good standards or oracle reason to accept +// exactly 65 bytes here: the coherent choices are canonical 66 only, or a broader integer-style +// parser across many widths. Since this field parser is fixed-width, keep it canonical and use the +// default exact-66-byte scalar field path. +const p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE); +/** + * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default. + * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation + * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width. + * @example + * Generate one P-521 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p521.sign(msg, secretKey); + * const isValid = p521.verify(sig, msg, publicKey); + * ``` + */ +export const p521 = /* @__PURE__ */ ecdsa(p521_Point, sha512); +/** + * Hashing / encoding to p521 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-521 curve. + * + * ```ts + * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p521_hasher = /* @__PURE__ */ (() => { + return createHasher(p521_Point, createSWU(p521_Point, { + A: p521_CURVE.a, + B: p521_CURVE.b, + Z: p521_Point.Fp.create(BigInt('-4')), + }), { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: p521_CURVE.p, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + }); +})(); +/** + * p521 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-521. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p521_oprf.oprf.generateKeyPair(); + * const blind = p521_oprf.oprf.blind(input); + * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p521_oprf = /* @__PURE__ */ (() => createOPRF({ + name: 'P521-SHA512', + Point: p521_Point, + hash: sha512, + hashToGroup: p521_hasher.hashToCurve, + hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC +}))(); +//# sourceMappingURL=nist.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/nist.js.map b/node_modules/@noble/curves/nist.js.map new file mode 100644 index 0000000..7596d15 --- /dev/null +++ b/node_modules/@noble/curves/nist.js.map @@ -0,0 +1 @@ +{"version":3,"file":"nist.js","sourceRoot":"","sources":["src/nist.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAc,MAAM,qBAAqB,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAkB,MAAM,6BAA6B,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAa,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EACL,KAAK,EACL,mBAAmB,EACnB,WAAW,GAIZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAa,MAAM,YAAY,CAAC;AAEvC,wDAAwD;AACxD,kCAAkC;AAClC,MAAM,UAAU,GAA4B,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAClE,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;IACZ,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,CAAC,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAC/E,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;IAChF,EAAE,EAAE,MAAM,CAAC,oEAAoE,CAAC;CACjF,CAAC,CAAC,EAAE,CAAC;AAEN,mDAAmD;AACnD,MAAM,UAAU,GAA4B,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;IAClE,CAAC,EAAE,MAAM,CACP,oGAAoG,CACrG;IACD,CAAC,EAAE,MAAM,CACP,oGAAoG,CACrG;IACD,CAAC,EAAE,MAAM,CAAC,CAAC,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AAC,GAAG,EAAE;IACxF,OAAO,YAAY,CACjB,UAAU,EACV,SAAS,CAAC,UAAU,EAAE;QACpB,CAAC,EAAE,UAAU,CAAC,CAAC;QACf,CAAC,EAAE,UAAU,CAAC,CAAC;QACf,CAAC,EAAE,UAAU,CAAC,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;KACtC,CAAC,EACF;QACE,GAAG,EAAE,2BAA2B;QAChC,SAAS,EAAE,2BAA2B;QACtC,CAAC,EAAE,UAAU,CAAC,CAAC;QACf,CAAC,EAAE,CAAC;QACJ,CAAC,EAAE,GAAG;QACN,MAAM,EAAE,KAAK;QACb,IAAI,EAAE,MAAM;KACb,CACF,CAAC;AACJ,CAAC,CAAC,EAAE,CAAC;AACL;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,SAAS,GAAe,eAAe,CAAC,CAAC,GAAG,EAAE,CACzD,UAAU,CAAC;IACT,IAAI,EAAE,aAAa;IACnB,KAAK,EAAE,UAAU;IACjB,IAAI,EAAE,MAAM;IACZ,WAAW,EAAE,WAAW,CAAC,WAAW;IACpC,YAAY,EAAE,WAAW,CAAC,YAAY,EAAE,iCAAiC;CAC1E,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/package.json b/node_modules/@noble/curves/package.json new file mode 100644 index 0000000..fcc6b92 --- /dev/null +++ b/node_modules/@noble/curves/package.json @@ -0,0 +1,103 @@ +{ + "name": "@noble/curves", + "version": "2.2.0", + "description": "Audited & minimal JS implementation of elliptic curve cryptography", + "files": [ + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map", + "abstract", + "src" + ], + "dependencies": { + "@noble/hashes": "2.2.0" + }, + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "@types/node": "25.3.0", + "fast-check": "4.2.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "cd test/benchmark; node secp256k1.ts; node curves.ts; node utils.ts; node bls.ts", + "bench:install": "cd test/benchmark; npm install; npm install ../.. --install-links", + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "build:clean": "rm {.,abstract}/*.{js,d.ts,d.ts.map,js.map} 2> /dev/null", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/*.{js,ts}'", + "test": "node test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts", + "test:node20": "cd test; npx tsc; node compiled/test/index.js", + "test:coverage": "npm install --no-save c8@10.1.2 && npx c8 npm test" + }, + "exports": { + ".": "./index.js", + "./abstract/bls.js": "./abstract/bls.js", + "./abstract/curve.js": "./abstract/curve.js", + "./abstract/edwards.js": "./abstract/edwards.js", + "./abstract/fft.js": "./abstract/fft.js", + "./abstract/frost.js": "./abstract/frost.js", + "./abstract/hash-to-curve.js": "./abstract/hash-to-curve.js", + "./abstract/modular.js": "./abstract/modular.js", + "./abstract/montgomery.js": "./abstract/montgomery.js", + "./abstract/oprf.js": "./abstract/oprf.js", + "./abstract/poseidon.js": "./abstract/poseidon.js", + "./abstract/tower.js": "./abstract/tower.js", + "./abstract/weierstrass.js": "./abstract/weierstrass.js", + "./bls12-381.js": "./bls12-381.js", + "./bn254.js": "./bn254.js", + "./ed448.js": "./ed448.js", + "./ed25519.js": "./ed25519.js", + "./misc.js": "./misc.js", + "./nist.js": "./nist.js", + "./secp256k1.js": "./secp256k1.js", + "./utils.js": "./utils.js", + "./webcrypto.js": "./webcrypto.js" + }, + "engines": { + "node": ">= 20.19.0" + }, + "keywords": [ + "cryptography", + "secp256k1", + "ed25519", + "p256", + "p384", + "p521", + "secp256r1", + "ed448", + "x25519", + "ed25519", + "bls12-381", + "bn254", + "alt_bn128", + "bls", + "noble", + "ecc", + "ecdsa", + "eddsa", + "oprf", + "schnorr", + "fft" + ], + "homepage": "https://paulmillr.com/noble/", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-curves.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@noble/curves/secp256k1.d.ts b/node_modules/@noble/curves/secp256k1.d.ts new file mode 100644 index 0000000..baf5050 --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.d.ts @@ -0,0 +1,153 @@ +import { type CurveLengths } from './abstract/curve.ts'; +import { type FROST } from './abstract/frost.ts'; +import { type H2CHasher } from './abstract/hash-to-curve.ts'; +import { type ECDSA, type WeierstrassPoint as PointType, type WeierstrassPointCons } from './abstract/weierstrass.ts'; +import { type TArg, type TRet } from './utils.ts'; +/** + * secp256k1 curve: ECDSA and ECDH methods. + * + * Uses sha256 to hash messages. To use a different hash, + * pass `{ prehash: false }` to sign / verify. + * + * @example + * Generate one secp256k1 keypair, sign a message, and verify it. + * + * ```js + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = secp256k1.keygen(); + * // const publicKey = secp256k1.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = secp256k1.sign(msg, secretKey); + * const isValid = secp256k1.verify(sig, msg, publicKey); + * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export declare const secp256k1: ECDSA; +declare function taggedHash(tag: string, ...messages: TArg): TRet; +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +declare function lift_x(x: bigint): PointType; +/** Schnorr public key is just `x` coordinate of Point as per BIP340. */ +declare function schnorrGetPublicKey(secretKey: TArg): TRet; +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not + * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden + * deterministic signing against side-channel and fault-injection attacks. + */ +declare function schnorrSign(message: TArg, secretKey: TArg, auxRand?: TArg): TRet; +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +declare function schnorrVerify(signature: TArg, message: TArg, publicKey: TArg): boolean; +export declare const __TEST: { + lift_x: typeof lift_x; +}; +/** Schnorr-specific secp256k1 API from BIP340. */ +export type SecpSchnorr = { + /** + * Generate one Schnorr secret/public keypair. + * @param seed - Optional seed for deterministic testing or custom randomness. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; + /** + * Derive the x-only public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns X-only public key bytes. + */ + getPublicKey: typeof schnorrGetPublicKey; + /** + * Create one BIP340 Schnorr signature. + * @param message - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @param auxRand - Optional auxiliary randomness. + * @returns Compact Schnorr signature bytes. + */ + sign: typeof schnorrSign; + /** + * Verify one BIP340 Schnorr signature. + * @param signature - Compact signature bytes. + * @param message - Signed message bytes. + * @param publicKey - X-only public key bytes. + * @returns `true` when the signature is valid. + */ + verify: typeof schnorrVerify; + /** Underlying secp256k1 point constructor. */ + Point: WeierstrassPointCons; + /** Helper utilities for Schnorr-specific key handling and tagged hashing. */ + utils: { + /** Generate one Schnorr secret key. */ + randomSecretKey: (seed?: TArg) => TRet; + /** Convert one point into its x-only BIP340 byte encoding. */ + pointToBytes: (point: TArg>) => TRet; + /** Lift one x coordinate into the unique even-Y point. */ + lift_x: typeof lift_x; + /** Compute a BIP340 tagged hash. */ + taggedHash: typeof taggedHash; + }; + /** Public byte lengths for keys, signatures, and seeds. */ + lengths: CurveLengths; +}; +/** + * Schnorr signatures over secp256k1. + * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}. + * @example + * Generate one BIP340 Schnorr keypair, sign a message, and verify it. + * + * ```js + * import { schnorr } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = schnorr.keygen(); + * // const publicKey = schnorr.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello'); + * const sig = schnorr.sign(msg, secretKey); + * const isValid = schnorr.verify(sig, msg, publicKey); + * ``` + */ +export declare const schnorr: SecpSchnorr; +/** + * Hashing / encoding to secp256k1 points / field. RFC 9380 methods. + * @example + * Hash one message onto secp256k1. + * + * ```ts + * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export declare const secp256k1_hasher: H2CHasher>; +/** + * FROST threshold signatures over secp256k1. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 secp256k1 signing. + * + * ```ts + * const alice = secp256k1_FROST.Identifier.derive('alice@example.com'); + * const bob = secp256k1_FROST.Identifier.derive('bob@example.com'); + * const carol = secp256k1_FROST.Identifier.derive('carol@example.com'); + * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const secp256k1_FROST: TRet; +/** + * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591. + * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while + * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves. + * @example + * Create one trusted-dealer package for Taproot-compatible FROST signing. + * + * ```ts + * const alice = schnorr_FROST.Identifier.derive('alice@example.com'); + * const bob = schnorr_FROST.Identifier.derive('bob@example.com'); + * const carol = schnorr_FROST.Identifier.derive('carol@example.com'); + * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export declare const schnorr_FROST: TRet; +export {}; +//# sourceMappingURL=secp256k1.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.d.ts.map b/node_modules/@noble/curves/secp256k1.d.ts.map new file mode 100644 index 0000000..63dcca6 --- /dev/null +++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;;;GAWG;AACH,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,KAAK,CAMjC,CAAC;AAqFR;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,aAAa,EAAE,IAAI,CAAC,KAAK,CAuC/B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.js b/node_modules/@noble/curves/secp256k1.js new file mode 100644 index 0000000..fc6cf70 --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.js @@ -0,0 +1,466 @@ +/** + * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf). + * + * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ, + * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored). + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha2.js'; +import { randomBytes } from '@noble/hashes/utils.js'; +import { createKeygen } from "./abstract/curve.js"; +import { createFROST, } from "./abstract/frost.js"; +import { createHasher, isogenyMap } from "./abstract/hash-to-curve.js"; +import { Field, mapHashToField, pow2 } from "./abstract/modular.js"; +import { ecdsa, mapToCurveSimpleSWU, weierstrass, } from "./abstract/weierstrass.js"; +import { abytes, asciiToBytes, bytesToNumberBE, concatBytes, } from "./utils.js"; +// Seems like generator was produced from some seed: +// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x` +// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n +const secp256k1_CURVE = { + p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + h: BigInt(1), + a: BigInt(0), + b: BigInt(7), + Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'), +}; +const secp256k1_ENDO = { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + basises: [ + [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')], + [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')], + ], +}; +const _0n = /* @__PURE__ */ BigInt(0); +const _2n = /* @__PURE__ */ BigInt(2); +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y) { + const P = secp256k1_CURVE.p; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fpk1.eql(Fpk1.sqr(root), y)) + throw new Error('Cannot find square root'); + return root; +} +const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod }); +const Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, { + Fp: Fpk1, + endo: secp256k1_ENDO, +}); +/** + * secp256k1 curve: ECDSA and ECDH methods. + * + * Uses sha256 to hash messages. To use a different hash, + * pass `{ prehash: false }` to sign / verify. + * + * @example + * Generate one secp256k1 keypair, sign a message, and verify it. + * + * ```js + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = secp256k1.keygen(); + * // const publicKey = secp256k1.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = secp256k1.sign(msg, secretKey); + * const isValid = secp256k1.verify(sig, msg, publicKey); + * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export const secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256); +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES = {}; +// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII. +function taggedHash(tag, ...messages) { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(asciiToBytes(tag)); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)); +} +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point) => point.toBytes(true).slice(1); +const hasEven = (y) => y % _2n === _0n; +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv) { + const { Fn, BASE } = Pointk1; + const d_ = Fn.fromBytes(priv); + const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = hasEven(p.y) ? d_ : Fn.neg(d_); + return { scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x) { + const Fp = Fpk1; + if (!Fp.isValidNot0(x)) + throw new Error('invalid x: Fail if x ≥ p'); + const xx = Fp.create(x * x); + const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt(). + // Return the unique point P such that x(P) = x and + // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + if (!hasEven(y)) + y = Fp.neg(y); + const p = Pointk1.fromAffine({ x, y }); + p.assertValidity(); + return p; +} +// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only +// parses big-endian bytes and does not enforce the fixed-width contract itself. +const num = bytesToNumberBE; +/** Create tagged hash, convert it to bigint, reduce modulo-n. */ +function challenge(...args) { + return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args))); +} +/** Schnorr public key is just `x` coordinate of Point as per BIP340. */ +function schnorrGetPublicKey(secretKey) { + return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not + * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden + * deterministic signing against side-channel and fault-injection attacks. + */ +function schnorrSign(message, secretKey, auxRand = randomBytes(32)) { + const { Fn, BASE } = Pointk1; + const m = abytes(message, undefined, 'message'); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder + const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array + // Let t be the byte-wise xor of bytes(d) and hash/aux(a). + const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand) + // here: that helper parses canonical secret keys and rejects rand >= n instead + // of reducing the nonce hash modulo the group order. + const k_ = Fn.create(num(rand)); + // BIP-340: "Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G." + if (k_ === 0n) + throw new Error('sign failed: k is zero'); + const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction. + const k = hasEven(p.y) ? k_ : Fn.neg(k_); + const rx = pointToBytes(p); + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(Fn.toBytes(Fn.create(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) + throw new Error('sign: Invalid signature produced'); + return sig; +} +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify(signature, message, publicKey) { + const { Fp, Fn, BASE } = Pointk1; + const sig = abytes(signature, 64, 'signature'); + const m = abytes(message, undefined, 'message'); + const pub = abytes(publicKey, 32, 'publicKey'); + try { + const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails + const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!Fp.isValidNot0(r)) + return false; + const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches + // s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as + // crafted edge cases and fail closed instead of carrying that extra verification surface. + if (!Fn.isValidNot0(s)) + return false; + // int(challenge(bytes(r) || bytes(P) || m)) % n + const e = challenge(Fn.toBytes(r), pointToBytes(P), m); + // R = s⋅G - e⋅P, where -eP == (n-e)P + const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e))); + const { x, y } = R.toAffine(); + // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + if (R.is0() || !hasEven(y) || x !== r) + return false; + return true; + } + catch (error) { + return false; + } +} +export const __TEST = /* @__PURE__ */ Object.freeze({ lift_x }); +/** + * Schnorr signatures over secp256k1. + * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}. + * @example + * Generate one BIP340 Schnorr keypair, sign a message, and verify it. + * + * ```js + * import { schnorr } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = schnorr.keygen(); + * // const publicKey = schnorr.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello'); + * const sig = schnorr.sign(msg, secretKey); + * const isValid = schnorr.verify(sig, msg, publicKey); + * ``` + */ +export const schnorr = /* @__PURE__ */ (() => { + const size = 32; + const seedLength = 48; + const randomSecretKey = (seed) => { + seed = seed === undefined ? randomBytes(seedLength) : seed; + return mapHashToField(seed, secp256k1_CURVE.n); + }; + return Object.freeze({ + keygen: createKeygen(randomSecretKey, schnorrGetPublicKey), + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + Point: Pointk1, + utils: Object.freeze({ + randomSecretKey, + taggedHash, + lift_x, + pointToBytes, + }), + lengths: Object.freeze({ + secretKey: size, + publicKey: size, + publicKeyHasPrefix: false, + signature: size * 2, + seed: seedLength, + }), + }); +})(); +// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order. +// The final `1` in each denominator array is the explicit monic leading term. +const isoMap = /* @__PURE__ */ (() => isogenyMap(Fpk1, [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], +].map((i) => i.map((j) => BigInt(j)))))(); +// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below. +let mapSWU; +const getMapSWU = () => mapSWU || + (mapSWU = mapToCurveSimpleSWU(Fpk1, { + // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so + // defer it to first use; after that the cached mapper is reused directly. + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fpk1.create(BigInt('-11')), + })); +/** + * Hashing / encoding to secp256k1 points / field. RFC 9380 methods. + * @example + * Hash one message onto secp256k1. + * + * ```ts + * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const secp256k1_hasher = /* @__PURE__ */ (() => createHasher(Pointk1, (scalars) => { + const { x, y } = getMapSWU()(Fpk1.create(scalars[0])); + return isoMap(x, y); +}, { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, +}))(); +/** + * FROST threshold signatures over secp256k1. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 secp256k1 signing. + * + * ```ts + * const alice = secp256k1_FROST.Identifier.derive('alice@example.com'); + * const bob = secp256k1_FROST.Identifier.derive('bob@example.com'); + * const carol = secp256k1_FROST.Identifier.derive('carol@example.com'); + * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const secp256k1_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-secp256k1-SHA256-v1', + Point: Pointk1, + hashToScalar: secp256k1_hasher.hashToScalar, + hash: sha256, +}))(); +// Taproot utils +// `undefined` means "disable TapTweak entirely"; callers that want the BIP-341/BIP-386 empty +// merkle root must pass `new Uint8Array(0)` explicitly. +function tweak(point, merkleRoot) { + if (merkleRoot === undefined) + return _0n; + const x = pointToBytes(point); + const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot)); + // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: "if t >= SECP256K1_ORDER: + // raise ValueError". TapTweak must reject overflow instead of reducing modulo n. + if (!Pointk1.Fn.isValid(t)) + throw new Error('invalid TapTweak hash'); + return t; +} +function frostPubToEvenY(pub) { + const VK = Pointk1.fromBytes(pub.commitments[0]); + // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning. + if (hasEven(VK.y)) + return pub; + return { + signers: { min: pub.signers.min, max: pub.signers.max }, + commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()), + verifyingShares: Object.fromEntries(Object.entries(pub.verifyingShares).map(([k, v]) => [ + k, + Pointk1.fromBytes(v).negate().toBytes(), + ])), + }; +} +function frostSecretToEvenY(s, pub) { + const VK = Pointk1.fromBytes(pub.commitments[0]); + // Keep aliasing on the already-even path so wrapper callers can preserve package identity. + if (hasEven(VK.y)) + return s; + const Fn = Pointk1.Fn; + return { + ...s, + signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))), + }; +} +function frostNoncesToEvenY(PK, nonces) { + if (hasEven(PK.y)) + return nonces; + const Fn = Pointk1.Fn; + return { + binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))), + hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))), + }; +} +function frostTweakSecret(s, pub, merkleRoot) { + const Fn = Pointk1.Fn; + const keyPackage = frostSecretToEvenY(s, pub); + const evenPub = frostPubToEvenY(pub); + const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot); + const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t)); + return { + identifier: keyPackage.identifier, + signingShare, + }; +} +function frostTweakPublic(pub, merkleRoot) { + const PKPackage = frostPubToEvenY(pub); + const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot); + const tp = Pointk1.BASE.multiply(t); + const commitments = PKPackage.commitments.map((c, i) => (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes()); + const verifyingShares = {}; + for (const k in PKPackage.verifyingShares) { + verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes(); + } + return { + signers: { min: PKPackage.signers.min, max: PKPackage.signers.max }, + commitments, + verifyingShares, + }; +} +/** + * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591. + * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while + * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves. + * @example + * Create one trusted-dealer package for Taproot-compatible FROST signing. + * + * ```ts + * const alice = schnorr_FROST.Identifier.derive('alice@example.com'); + * const bob = schnorr_FROST.Identifier.derive('bob@example.com'); + * const carol = schnorr_FROST.Identifier.derive('carol@example.com'); + * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const schnorr_FROST = /* @__PURE__ */ (() => createFROST({ + name: 'FROST-secp256k1-SHA256-TR-v1', + Point: Pointk1, + hashToScalar: secp256k1_hasher.hashToScalar, + hash: sha256, + // Taproot related hacks + parsePublicKey(publicKey) { + // External Taproot keys are x-only, but local key packages still use compressed points. + if (publicKey.length === 32) + return lift_x(bytesToNumberBE(publicKey)); + if (publicKey.length === 33) + return Pointk1.fromBytes(publicKey); + throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`); + }, + adjustScalar(n) { + const PK = Pointk1.BASE.multiply(n); + return hasEven(PK.y) ? n : Pointk1.Fn.neg(n); + }, + adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()), + challenge(R, PK, msg) { + return challenge(pointToBytes(R), pointToBytes(PK), msg); + }, + adjustNonces: frostNoncesToEvenY, + adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare), + adjustPublic: frostPubToEvenY, + adjustSecret: frostSecretToEvenY, + adjustTx: { + // Compat with official implementation + encode: (tx) => tx.subarray(1), + decode: (tx) => concatBytes(Uint8Array.of(0x02), tx), + }, + adjustDKG: (k) => { + // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the + // empty Taproot merkle root, while dealer-generated keys stay untweaked. + const merkleRoot = new Uint8Array(0); + return { + public: frostTweakPublic(k.public, merkleRoot), + secret: frostTweakSecret(k.secret, k.public, merkleRoot), + }; + }, +}))(); +//# sourceMappingURL=secp256k1.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/secp256k1.js.map b/node_modules/@noble/curves/secp256k1.js.map new file mode 100644 index 0000000..983cf1e --- /dev/null +++ b/node_modules/@noble/curves/secp256k1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"secp256k1.js","sourceRoot":"","sources":["src/secp256k1.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,sEAAsE;AACtE,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAqB,MAAM,qBAAqB,CAAC;AACtE,OAAO,EACL,WAAW,GAKZ,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,YAAY,EAAkB,UAA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AAO,CAAC;IAC1F,YAAY,EAAE,eAAe;IAC7B,YAAY,EAAE,kBAAkB;IAChC,QAAQ,EAAE;QACR,sCAAsC;QACtC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAqB;QAClD,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,WAAW,CAAC,UAAU,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,EAAE,CAAqB;KACzE;IACD,SAAS,EAAE,CAAC,CAAC,EAAE,EAAE;QACf,6EAA6E;QAC7E,yEAAyE;QACzE,MAAM,UAAU,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;QACrC,OAAO;YACL,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC;YAC9C,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,UAAU,CAAC;SACzD,CAAC;IACJ,CAAC;CACF,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/src/abstract/bls.ts b/node_modules/@noble/curves/src/abstract/bls.ts new file mode 100644 index 0000000..bc575b8 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/bls.ts @@ -0,0 +1,887 @@ +/** + * BLS != BLS. + * The file implements BLS (Boneh-Lynn-Shacham) signatures. + * Used in both BLS (Barreto-Lynn-Scott) and BN (Barreto-Naehrig) + * families of pairing-friendly curves. + * Consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + * - Gt, created by bilinear (ate) pairing e(G1, G2), consists of p-th roots of unity in + * Fq^k where k is embedding degree. Only degree 12 is currently supported, 24 is not. + * Pairing is used to aggregate and verify signatures. + * There are two modes of operation: + * - Long signatures: X-byte keys + 2X-byte sigs (G1 keys + G2 sigs). + * - Short signatures: 2X-byte keys + X-byte sigs (G2 keys + G1 sigs). + * @module + **/ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { abytes, notImplemented, randomBytes, type TArg, type TRet } from '../utils.ts'; +import { type CurveLengths } from './curve.ts'; +import { + createHasher, + type H2CDSTOpts, + type H2CHasher, + type H2COpts, + type MapToCurve, +} from './hash-to-curve.ts'; +import { getMinHashLength, mapHashToField, type IField } from './modular.ts'; +import type { Fp12, Fp12Bls, Fp2, Fp2Bls, Fp6Bls } from './tower.ts'; +import { type WeierstrassPoint, type WeierstrassPointCons } from './weierstrass.ts'; + +type Fp = bigint; // Can be different field? + +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3); + +/** + * Twist convention used by the pairing formulas for a concrete curve family. + * BLS12-381 uses a multiplicative twist, while BN254 uses a divisive one. + */ +export type BlsTwistType = 'multiplicative' | 'divisive'; + +/** + * Codec exposed as `curve.shortSignatures.Signature`. + * Use it to parse or serialize G1 signatures in short-signature mode. + * In this mode, public keys live in G2. + */ +export type BlsShortSignatureCoder = { + /** + * Parse a compressed signature from raw bytes. + * @param bytes - Compressed signature bytes. + * @returns Parsed signature point. + */ + fromBytes(bytes: TArg): WeierstrassPoint; + /** + * Parse a compressed signature from a hex string. + * @param hex - Compressed signature hex string. + * @returns Parsed signature point. + */ + fromHex(hex: string): WeierstrassPoint; + /** + * Encode a signature point into compressed bytes. + * @param point - Signature point. + * @returns Compressed signature bytes. + */ + toBytes(point: WeierstrassPoint): TRet; + /** + * Encode a signature point into a hex string. + * @param point - Signature point. + * @returns Compressed signature hex. + */ + toHex(point: WeierstrassPoint): string; +}; + +/** + * Codec exposed as `curve.longSignatures.Signature`. + * Use it to parse or serialize G2 signatures in long-signature mode. + * In this mode, public keys live in G1. + */ +export type BlsLongSignatureCoder = { + /** + * Parse a compressed signature from raw bytes. + * @param bytes - Compressed signature bytes. + * @returns Parsed signature point. + */ + fromBytes(bytes: TArg): WeierstrassPoint; + /** + * Parse a compressed signature from a hex string. + * @param hex - Compressed signature hex string. + * @returns Parsed signature point. + */ + fromHex(hex: string): WeierstrassPoint; + /** + * Encode a signature point into compressed bytes. + * @param point - Signature point. + * @returns Compressed signature bytes. + */ + toBytes(point: WeierstrassPoint): TRet; + /** + * Encode a signature point into a hex string. + * @param point - Signature point. + * @returns Compressed signature hex. + */ + toHex(point: WeierstrassPoint): string; +}; + +/** Tower fields needed by pairing code, hash-to-curve, and subgroup arithmetic. */ +export type BlsFields = { + /** Base field of G1 coordinates. */ + Fp: IField; + /** Scalar field used for secret scalars and subgroup order arithmetic. */ + Fr: IField; + /** Quadratic extension field used by G2. */ + Fp2: Fp2Bls; + /** Sextic extension field used inside pairing arithmetic. */ + Fp6: Fp6Bls; + /** Degree-12 extension field that contains the GT target group. */ + Fp12: Fp12Bls; +}; + +/** + * Callback used by pairing post-processing hooks to add one more G2 point to the Miller-loop state. + * @param Rx - Current projective X coordinate. + * @param Ry - Current projective Y coordinate. + * @param Rz - Current projective Z coordinate. + * @param Qx - G2 affine x coordinate. + * @param Qy - G2 affine y coordinate. + * @returns Updated projective accumulator coordinates. + */ +export type BlsPostPrecomputePointAddFn = ( + Rx: Fp2, + Ry: Fp2, + Rz: Fp2, + Qx: Fp2, + Qy: Fp2 +) => { Rx: Fp2; Ry: Fp2; Rz: Fp2 }; +/** + * Hook for curve-specific pairing cleanup after the Miller loop precomputes are built. + * @param Rx - Current projective X coordinate. + * @param Ry - Current projective Y coordinate. + * @param Rz - Current projective Z coordinate. + * @param Qx - G2 affine x coordinate. + * @param Qy - G2 affine y coordinate. + * @param pointAdd - Callback used to fold one more point into the accumulator. + */ +export type BlsPostPrecomputeFn = ( + Rx: Fp2, + Ry: Fp2, + Rz: Fp2, + Qx: Fp2, + Qy: Fp2, + pointAdd: BlsPostPrecomputePointAddFn +) => void; +/** Low-level pairing helpers shared by BLS curve bundles. */ +export type BlsPairing = { + /** Byte lengths for keys and signatures exposed by this pairing family. */ + lengths: CurveLengths; + /** Scalar field used by the pairing and signing helpers. */ + Fr: IField; + /** Target field used for the GT result of pairings. */ + Fp12: Fp12Bls; + /** + * Build Miller-loop precomputes for one G2 point. + * @param p - G2 point to precompute. + * @returns Pairing precompute table. + */ + calcPairingPrecomputes: (p: WeierstrassPoint) => Precompute; + /** + * Evaluate a batch of Miller loops from precomputed line coefficients. + * @param pairs - Precomputed Miller-loop inputs. + * @returns Accumulated GT value before or after final exponentiation. + */ + millerLoopBatch: (pairs: [Precompute, Fp, Fp][]) => Fp12; + /** + * Pair one G1 point with one G2 point. + * @param P - G1 point. + * @param Q - G2 point. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. + * @throws If either point is the point at infinity. {@link Error} + */ + pairing: (P: WeierstrassPoint, Q: WeierstrassPoint, withFinalExponent?: boolean) => Fp12; + /** + * Pair many G1/G2 pairs in one batch. + * @param pairs - Point pairs to accumulate. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. Empty input returns the multiplicative identity in GT. + */ + pairingBatch: ( + pairs: { g1: WeierstrassPoint; g2: WeierstrassPoint }[], + withFinalExponent?: boolean + ) => Fp12; + /** + * Generate a random secret key for this pairing family. + * @param seed - Optional seed material. + * @returns Secret key bytes. + */ + randomSecretKey: (seed?: TArg) => TRet; +}; + +/** + * Parameters that define the Miller-loop shape and twist handling + * for a concrete pairing family. + */ +export type BlsPairingParams = { + // MSB is always ignored and used as marker for length, otherwise leading zeros will be lost. + // Can be different from `X` (seed) param. + /** Signed loop parameter used by the Miller loop. */ + ateLoopSize: bigint; + /** Whether the signed Miller-loop parameter is negative. */ + xNegative: boolean; + /** + * Twist convention used by the pairing formulas. + * BLS12-381 is multiplicative; BN254 is divisive. + */ + twistType: BlsTwistType; + /** + * Optional RNG override used by helper constructors. + * Receives the requested byte length and returns random bytes. + */ + randomBytes?: (len?: number) => TRet; + /** + * Optional hook for curve-specific untwisting after precomputation. + * Used by BN254 after the Miller loop. + */ + postPrecompute?: BlsPostPrecomputeFn; +}; +/** Hash-to-curve settings shared by the G1 and G2 hashers inside a BLS curve bundle. */ +export type BlsHasherParams = { + /** + * Optional map-to-curve override for G1. + * Receives the hash-to-field tuple and returns one affine G1 point. + */ + mapToG1?: MapToCurve; + /** + * Optional map-to-curve override for G2. + * Receives the hash-to-field tuple and returns one affine G2 point. + */ + mapToG2?: MapToCurve; + /** Shared baseline hash-to-curve options. */ + hasherOpts: H2COpts; + /** G1-specific hash-to-curve options merged on top of `hasherOpts`. */ + hasherOptsG1: H2COpts; + /** G2-specific hash-to-curve options merged on top of `hasherOpts`. */ + hasherOptsG2: H2COpts; +}; +type PrecomputeSingle = [Fp2, Fp2, Fp2][]; +type Precompute = PrecomputeSingle[]; + +/** + * BLS consists of two curves: G1 and G2: + * - G1 is a subgroup of (x, y) E(Fq) over y² = x³ + 4. + * - G2 is a subgroup of ((x₁, x₂+i), (y₁, y₂+i)) E(Fq²) over y² = x³ + 4(1 + i) where i is √-1 + */ +export interface BlsCurvePair { + /** Byte lengths for keys and signatures exposed by this curve family. */ + lengths: CurveLengths; + /** + * Shared Miller-loop batch evaluator. + * @param pairs - Precomputed Miller-loop inputs. + * @returns Accumulated GT value. + */ + millerLoopBatch: BlsPairing['millerLoopBatch']; + /** + * Pair one G1 point with one G2 point. + * @param P - G1 point. + * @param Q - G2 point. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. + * @throws If either point is the point at infinity. {@link Error} + */ + pairing: BlsPairing['pairing']; + /** + * Pair many G1/G2 pairs in one batch. + * @param pairs - Point pairs to accumulate. + * @param withFinalExponent - Whether to apply the final exponentiation step. + * @returns GT pairing result. Empty input returns the multiplicative identity in GT. + */ + pairingBatch: BlsPairing['pairingBatch']; + /** G1 point constructor for the base field subgroup. */ + G1: { Point: WeierstrassPointCons }; + /** G2 point constructor for the twist subgroup. */ + G2: { Point: WeierstrassPointCons }; + /** Tower fields exposed by the pairing implementation. */ + fields: { + Fp: IField; + Fp2: Fp2Bls; + Fp6: Fp6Bls; + Fp12: Fp12Bls; + Fr: IField; + }; + /** Utility helpers shared by hashers and signers. */ + utils: { + randomSecretKey: (seed?: TArg) => TRet; + calcPairingPrecomputes: BlsPairing['calcPairingPrecomputes']; + }; + /** Public pairing parameters exposed for introspection. */ + params: { + ateLoopSize: bigint; + twistType: BlsTwistType; + }; +} + +/** BLS curve bundle extended with hash-to-curve helpers for G1 and G2. */ +export interface BlsCurvePairWithHashers extends BlsCurvePair { + /** G1 hasher bundle with RFC 9380 helpers. */ + G1: H2CHasher>; + /** G2 hasher bundle with RFC 9380 helpers. */ + G2: H2CHasher>; +} + +/** BLS curve bundle extended with both hashers and signature helpers. */ +export interface BlsCurvePairWithSignatures extends BlsCurvePairWithHashers { + /** Long-signature mode: G1 public keys and G2 signatures. */ + longSignatures: BlsSigs; + /** Short-signature mode: G2 public keys and G1 signatures. */ + shortSignatures: BlsSigs; +} + +type BLSInput = TArg; +/** BLS signer helpers for one signature mode. */ +export interface BlsSigs { + /** Byte lengths for secret keys, public keys, and signatures. */ + lengths: CurveLengths; + /** + * Generate a secret/public key pair for this signature mode. + * @param seed - Optional seed material. + * @returns Secret and public key pair. + */ + keygen(seed?: TArg): { + secretKey: TRet; + publicKey: WeierstrassPoint

; + }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public-key point. + */ + getPublicKey(secretKey: TArg): WeierstrassPoint

; + /** + * Sign a message already hashed onto the signature subgroup. + * @param hashedMessage - Message mapped to the signature subgroup. + * @param secretKey - Secret key bytes. + * @returns Signature point. + */ + sign(hashedMessage: WeierstrassPoint, secretKey: TArg): WeierstrassPoint; + /** + * Verify one signature against one public key and hashed message. + * @param signature - Signature point or encoded signature. + * @param message - Hashed message point. + * @param publicKey - Public-key point or encoded key. + * @returns Whether the signature is valid. + */ + verify( + signature: WeierstrassPoint | BLSInput, + message: WeierstrassPoint, + publicKey: WeierstrassPoint

| BLSInput + ): boolean; + /** + * Verify one aggregated signature against many `(message, publicKey)` pairs. + * @param signature - Aggregated signature. + * @param items - Message/public-key pairs. + * @returns Whether the aggregated signature is valid. Same-message aggregate verification still + * requires proof of possession or another rogue-key defense from the caller. + */ + verifyBatch: ( + signature: WeierstrassPoint | BLSInput, + items: { message: WeierstrassPoint; publicKey: WeierstrassPoint

| BLSInput }[] + ) => boolean; + /** + * Add many public keys into one aggregate point. + * @param publicKeys - Public keys to aggregate. + * @returns Aggregated public-key point. This is raw point addition and does not add proof of + * possession or rogue-key protection on its own. + */ + aggregatePublicKeys(publicKeys: (WeierstrassPoint

| BLSInput)[]): WeierstrassPoint

; + /** + * Add many signatures into one aggregate point. + * @param signatures - Signatures to aggregate. + * @returns Aggregated signature point. This is raw point addition and does not change the proof + * of possession requirements of the aggregate-verification scheme. + */ + aggregateSignatures(signatures: (WeierstrassPoint | BLSInput)[]): WeierstrassPoint; + /** + * Hash an arbitrary message onto the signature subgroup. + * @param message - Message bytes. + * @param DST - Optional domain separation tag. + * @returns Curve point on the signature subgroup. + */ + hash(message: TArg, DST?: TArg): WeierstrassPoint; + /** Signature codec for this mode. */ + Signature: BlsLongSignatureCoder; +} + +// Signed non-adjacent decomposition of the spec-defined Miller-loop parameter. +// BN254 benefits most because `6x+2` has multiple adjacent `11` runs, but BLS12-381's +// stored `|x|` still starts with `11`, so the Miller loop must also handle one `-1` digit there. +function NAfDecomposition(a: bigint) { + const res = []; + // a>1 because of marker bit + for (; a > _1n; a >>= _1n) { + if ((a & _1n) === _0n) res.unshift(0); + else if ((a & _3n) === _3n) { + res.unshift(-1); + a += _1n; + } else res.unshift(1); + } + return res; +} +function aNonEmpty(arr: any[]) { + // Aggregate helpers use this to reject empty variable-length inputs consistently. + // Without the guard, each caller would fall through into a different empty-input / identity + // case and hide missing inputs behind outputs that still look structurally valid. + if (!Array.isArray(arr) || arr.length === 0) throw new Error('expected non-empty array'); +} + +// This should be enough for bn254, no need to export full stuff? +function createBlsPairing( + fields: TArg, + G1: WeierstrassPointCons, + G2: WeierstrassPointCons, + params: TArg +): BlsPairing { + const { Fr, Fp2, Fp12 } = fields; + const { twistType, ateLoopSize, xNegative, postPrecompute } = params; + type G1 = typeof G1.BASE; + type G2 = typeof G2.BASE; + // Applies sparse multiplication as line function + let lineFunction: (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => Fp12; + if (twistType === 'multiplicative') { + lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => + Fp12.mul014(f, c0, Fp2.mul(c1, Px), Fp2.mul(c2, Py)); + } else if (twistType === 'divisive') { + // NOTE: it should be [c0, c1, c2], but we use different order here to reduce complexity of + // precompute calculations. + lineFunction = (c0: Fp2, c1: Fp2, c2: Fp2, f: Fp12, Px: Fp, Py: Fp) => + Fp12.mul034(f, Fp2.mul(c2, Py), Fp2.mul(c1, Px), c0); + } else throw new Error('bls: unknown twist type'); + + const Fp2div2 = Fp2.div(Fp2.ONE, Fp2.mul(Fp2.ONE, _2n)); + function pointDouble(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2) { + const t0 = Fp2.sqr(Ry); // Ry² + const t1 = Fp2.sqr(Rz); // Rz² + const t2 = Fp2.mulByB(Fp2.mul(t1, _3n)); // 3 * T1 * B + const t3 = Fp2.mul(t2, _3n); // 3 * T2 + const t4 = Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(Ry, Rz)), t1), t0); // (Ry + Rz)² - T1 - T0 + const c0 = Fp2.sub(t2, t0); // T2 - T0 (i) + const c1 = Fp2.mul(Fp2.sqr(Rx), _3n); // 3 * Rx² + const c2 = Fp2.neg(t4); // -T4 (-h) + + ell.push([c0, c1, c2]); + + Rx = Fp2.mul(Fp2.mul(Fp2.mul(Fp2.sub(t0, t3), Rx), Ry), Fp2div2); // ((T0 - T3) * Rx * Ry) / 2 + // ((T0 + T3) / 2)² - 3 * T2² + Ry = Fp2.sub(Fp2.sqr(Fp2.mul(Fp2.add(t0, t3), Fp2div2)), Fp2.mul(Fp2.sqr(t2), _3n)); + Rz = Fp2.mul(t0, t4); // T0 * T4 + return { Rx, Ry, Rz }; + } + function pointAdd(ell: PrecomputeSingle, Rx: Fp2, Ry: Fp2, Rz: Fp2, Qx: Fp2, Qy: Fp2) { + // Addition + const t0 = Fp2.sub(Ry, Fp2.mul(Qy, Rz)); // Ry - Qy * Rz + const t1 = Fp2.sub(Rx, Fp2.mul(Qx, Rz)); // Rx - Qx * Rz + const c0 = Fp2.sub(Fp2.mul(t0, Qx), Fp2.mul(t1, Qy)); // T0 * Qx - T1 * Qy == Ry * Qx - Rx * Qy + const c1 = Fp2.neg(t0); // -T0 == Qy * Rz - Ry + const c2 = t1; // == Rx - Qx * Rz + + ell.push([c0, c1, c2]); + + const t2 = Fp2.sqr(t1); // T1² + const t3 = Fp2.mul(t2, t1); // T2 * T1 + const t4 = Fp2.mul(t2, Rx); // T2 * Rx + // T3 - 2 * T4 + T0² * Rz + const t5 = Fp2.add(Fp2.sub(t3, Fp2.mul(t4, _2n)), Fp2.mul(Fp2.sqr(t0), Rz)); + Rx = Fp2.mul(t1, t5); // T1 * T5 + Ry = Fp2.sub(Fp2.mul(Fp2.sub(t4, t5), t0), Fp2.mul(t3, Ry)); // (T4 - T5) * T0 - T3 * Ry + Rz = Fp2.mul(Rz, t3); // Rz * T3 + return { Rx, Ry, Rz }; + } + + // Pre-compute coefficients for sparse multiplication + // Point addition and point double calculations is reused for coefficients + // pointAdd happens only if bit set, so wNAF is reasonable. Unfortunately we cannot combine + // add + double in windowed precomputes here, otherwise it would be single op (since X is static) + const ATE_NAF = NAfDecomposition(ateLoopSize); + + const calcPairingPrecomputes = (point: G2) => { + const p = point; + const { x, y } = p.toAffine(); + // prettier-ignore + const Qx = x, Qy = y, negQy = Fp2.neg(y); + // prettier-ignore + let Rx = Qx, Ry = Qy, Rz = Fp2.ONE; + const ell: Precompute = []; + for (const bit of ATE_NAF) { + const cur: PrecomputeSingle = []; + ({ Rx, Ry, Rz } = pointDouble(cur, Rx, Ry, Rz)); + if (bit) ({ Rx, Ry, Rz } = pointAdd(cur, Rx, Ry, Rz, Qx, bit === -1 ? negQy : Qy)); + ell.push(cur); + } + if (postPrecompute) { + const last = ell[ell.length - 1]; + postPrecompute(Rx, Ry, Rz, Qx, Qy, pointAdd.bind(null, last)); + } + return ell; + }; + + // Main pairing logic is here. Computes product of miller loops + final exponentiate + // Applies calculated precomputes + type MillerInput = [Precompute, Fp, Fp][]; + function millerLoopBatch(pairs: MillerInput, withFinalExponent: boolean = false) { + let f12 = Fp12.ONE; + if (pairs.length) { + const ellLen = pairs[0][0].length; + for (let i = 0; i < ellLen; i++) { + f12 = Fp12.sqr(f12); // This allows us to do sqr only one time for all pairings + // NOTE: we apply multiple pairings in parallel here + for (const [ell, Px, Py] of pairs) { + for (const [c0, c1, c2] of ell[i]) f12 = lineFunction(c0, c1, c2, f12, Px, Py); + } + } + } + if (xNegative) f12 = Fp12.conjugate(f12); + return withFinalExponent ? Fp12.finalExponentiate(f12) : f12; + } + type PairingInput = { g1: G1; g2: G2 }; + // Calculates product of multiple pairings + // This up to x2 faster than just `map(({g1, g2})=>pairing({g1,g2}))` + function pairingBatch(pairs: PairingInput[], withFinalExponent: boolean = true) { + const res: MillerInput = []; + for (const { g1, g2 } of pairs) { + // Mathematically, a zero pairing term contributes GT.ONE. We still reject it here because + // this API mainly backs BLS verification, where ZERO inputs usually mean broken hash / + // wiring. Silently skipping them would turn those failures into a neutral pairing product. + // Callers that want the algebraic neutral-element behavior can filter ZERO terms first. + if (g1.is0() || g2.is0()) throw new Error('pairing is not available for ZERO point'); + // This uses toAffine inside + g1.assertValidity(); + g2.assertValidity(); + const Qa = g1.toAffine(); + res.push([calcPairingPrecomputes(g2), Qa.x, Qa.y]); + } + return millerLoopBatch(res, withFinalExponent); + } + // Calculates bilinear pairing + function pairing(Q: G1, P: G2, withFinalExponent: boolean = true): Fp12 { + return pairingBatch([{ g1: Q, g2: P }], withFinalExponent); + } + const lengths = { + seed: getMinHashLength(Fr.ORDER), + }; + const rand = params.randomBytes === undefined ? randomBytes : params.randomBytes; + // Seeded calls deterministically reduce exactly `lengths.seed` bytes into `1..Fr.ORDER-1`; + // omitting `seed` just fills that input buffer from the configured RNG first. + const randomSecretKey = (seed?: TArg): TRet => { + seed = seed === undefined ? rand(lengths.seed) : seed; + abytes(seed, lengths.seed, 'seed'); + return mapHashToField(seed, Fr.ORDER) as TRet; + }; + Object.freeze(lengths); + return { + lengths, + Fr, + Fp12, // NOTE: we re-export Fp12 here because pairing results are Fp12! + millerLoopBatch, + pairing, + pairingBatch, + calcPairingPrecomputes, + randomSecretKey, + }; +} + +function createBlsSig( + blsPairing: BlsPairing, + PubPoint: WeierstrassPointCons

, + SigPoint: WeierstrassPointCons, + isSigG1: boolean, + hashToSigCurve: (msg: TArg, options?: TArg) => WeierstrassPoint, + SignatureCoder?: BlsLongSignatureCoder +): BlsSigs { + const { Fr, Fp12, pairingBatch, randomSecretKey, lengths } = blsPairing; + if (!SignatureCoder) { + SignatureCoder = { + fromBytes: notImplemented, + fromHex: notImplemented, + toBytes: notImplemented, + toHex: notImplemented, + }; + } + type PubPoint = WeierstrassPoint

; + type SigPoint = WeierstrassPoint; + function normPub(point: PubPoint | BLSInput): PubPoint { + return point instanceof PubPoint ? (point as PubPoint) : PubPoint.fromBytes(point); + } + function normSig(point: SigPoint | BLSInput): SigPoint { + return point instanceof SigPoint ? (point as SigPoint) : SigPoint.fromBytes(point); + } + // Sign/verify here take points already hashed onto the signature subgroup. + // Raw bytes and points from the other subgroup must fail this constructor-brand + // check before later validity checks run. + function amsg(m: unknown): SigPoint { + if (!(m instanceof SigPoint)) + throw new Error(`expected valid message hashed to ${!isSigG1 ? 'G2' : 'G1'} curve`); + return m as SigPoint; + } + + type G1 = WeierstrassPoint; + type G2 = WeierstrassPoint; + type PairingInput = { g1: G1; g2: G2 }; + // What matters here is what point pairing API accepts as G1 or G2, not actual size or names + const pair: (a: PubPoint, b: SigPoint) => PairingInput = !isSigG1 + ? (a: PubPoint, b: SigPoint) => ({ g1: a, g2: b }) as PairingInput + : (a: PubPoint, b: SigPoint) => ({ g1: b, g2: a }) as PairingInput; + return Object.freeze({ + lengths: Object.freeze({ ...lengths, secretKey: Fr.BYTES }), + keygen(seed?: TArg) { + const secretKey = randomSecretKey(seed); + const publicKey = this.getPublicKey(secretKey); + return { secretKey, publicKey }; + }, + // P = pk x G + getPublicKey(secretKey: TArg): PubPoint { + let sec; + try { + sec = PubPoint.Fn.fromBytes(secretKey); + } catch (error) { + // @ts-ignore + throw new Error('invalid private key: ' + typeof secretKey, { cause: error }); + } + return PubPoint.BASE.multiply(sec); + }, + // S = pk x H(m) + sign(message: SigPoint, secretKey: TArg, unusedArg?: any): SigPoint { + if (unusedArg != null) throw new Error('sign() expects 2 arguments'); + const sec = PubPoint.Fn.fromBytes(secretKey); + amsg(message).assertValidity(); + return message.multiply(sec); + }, + // Checks if pairing of public key & hash is equal to pairing of generator & signature. + // e(P, H(m)) == e(G, S) + // e(S, G) == e(H(m), P) + verify( + signature: SigPoint | BLSInput, + message: SigPoint, + publicKey: PubPoint | BLSInput, + unusedArg?: any + ): boolean { + if (unusedArg != null) throw new Error('verify() expects 3 arguments'); + signature = normSig(signature); + publicKey = normPub(publicKey); + const P = publicKey.negate(); + const G = PubPoint.BASE; + const Hm = amsg(message); + const S = signature; + // This code was changed in 1.9.x: + // Before it was G.negate() in G2, now it's always pubKey.negate + // e(P, -Q)===e(-P, Q)==e(P, Q)^-1. Negate can be done anywhere (as long it is done once per pair). + // We just moving sign, but since pairing is multiplicative, we doing X * X^-1 = 1 + try { + const exp = pairingBatch([pair(P, Hm), pair(G, S)]); + return Fp12.eql(exp, Fp12.ONE); + } catch { + return false; + } + }, + // https://ethresear.ch/t/fast-verification-of-multiple-bls-signatures/5407 + // e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si)) + // TODO: maybe `{message: G2Hex, publicKey: G1Hex}[]` instead? + verifyBatch( + signature: SigPoint | BLSInput, + items: { message: SigPoint; publicKey: PubPoint | BLSInput }[] + ): boolean { + aNonEmpty(items); + const sig = normSig(signature); + const nMessages = items.map((i) => i.message); + const nPublicKeys = items.map((i) => normPub(i.publicKey)); + // NOTE: this works only for exact same object + const messagePubKeyMap = new Map(); + for (let i = 0; i < nPublicKeys.length; i++) { + const pub = nPublicKeys[i]; + const msg = nMessages[i]; + let keys = messagePubKeyMap.get(msg); + if (keys === undefined) { + keys = []; + messagePubKeyMap.set(msg, keys); + } + keys.push(pub); + } + const paired = []; + const G = PubPoint.BASE; + try { + for (const [msg, keys] of messagePubKeyMap) { + const groupPublicKey = keys.reduce((acc, msg) => acc.add(msg)); + paired.push(pair(groupPublicKey, msg)); + } + paired.push(pair(G.negate(), sig)); + return Fp12.eql(pairingBatch(paired), Fp12.ONE); + } catch { + return false; + } + }, + // Adds a bunch of public key points together. + // pk1 + pk2 + pk3 = pkA + aggregatePublicKeys(publicKeys: (PubPoint | BLSInput)[]): PubPoint { + aNonEmpty(publicKeys); + publicKeys = publicKeys.map((pub) => normPub(pub)); + const agg = (publicKeys as PubPoint[]).reduce((sum, p) => sum.add(p), PubPoint.ZERO); + agg.assertValidity(); + return agg; + }, + + // Adds a bunch of signature points together. + // pk1 + pk2 + pk3 = pkA + aggregateSignatures(signatures: (SigPoint | BLSInput)[]): SigPoint { + aNonEmpty(signatures); + signatures = signatures.map((sig) => normSig(sig)); + const agg = (signatures as SigPoint[]).reduce((sum, s) => sum.add(s), SigPoint.ZERO); + agg.assertValidity(); + return agg; + }, + + hash(messageBytes: TArg, DST?: TArg): SigPoint { + abytes(messageBytes); + const opts = DST ? { DST } : undefined; + return hashToSigCurve(messageBytes, opts); + }, + Signature: Object.freeze({ ...SignatureCoder }), + }) /*satisfies Signer */; +} + +type BlsSignatureCoders = Partial<{ + LongSignature: BlsLongSignatureCoder; + ShortSignature: BlsShortSignatureCoder; +}>; + +// NOTE: separate function instead of function override, so we don't depend on hasher in bn254. +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @returns Pairing-only BLS helpers. The returned pairing surface rejects infinity inputs, while + * empty `pairingBatch(...)` calls return the multiplicative identity in GT. This keeps the + * low-level pairing API fail-closed for BLS-style callers, where identity points usually signal + * broken hash / wiring instead of an intentionally neutral pairing term. This also eagerly + * precomputes the G1 base-point table as a performance side effect. + * @throws If the pairing parameters or underlying curve helpers are inconsistent. {@link Error} + * @example + * ```ts + * import { blsBasic } from '@noble/curves/abstract/bls.js'; + * import { bn254 } from '@noble/curves/bn254.js'; + * // Pair a G1 point with a G2 point without the higher-level signer helpers. + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +export function blsBasic( + fields: TArg, + G1_Point: WeierstrassPointCons, + G2_Point: WeierstrassPointCons, + params: TArg +): BlsCurvePair { + // Fields are specific for curve, so for now we'll need to pass them with opts + const { Fp, Fr, Fp2, Fp6, Fp12 } = fields; + // Point on G1 curve: (x, y) + // const G1_Point = weierstrass(CURVE.G1, { Fn: Fr }); + const G1 = { Point: G1_Point }; + // Point on G2 curve (complex numbers): (x₁, x₂+i), (y₁, y₂+i) + const G2 = { Point: G2_Point }; + + const pairingRes = createBlsPairing(fields, G1_Point, G2_Point, params); + const { + millerLoopBatch, + pairing, + pairingBatch, + calcPairingPrecomputes, + randomSecretKey, + lengths, + } = pairingRes; + + G1.Point.BASE.precompute(4); + Object.freeze(G1); + Object.freeze(G2); + return Object.freeze({ + lengths: Object.freeze(lengths), + millerLoopBatch, + pairing, + pairingBatch, + G1, + G2, + fields: Object.freeze({ Fr, Fp, Fp2, Fp6, Fp12 }), + params: Object.freeze({ + ateLoopSize: params.ateLoopSize, + twistType: params.twistType, + }), + utils: Object.freeze({ + randomSecretKey, + calcPairingPrecomputes, + }), + }); +} + +// We can export this too, but seems there is not much reasons for now? If user wants hasher, they can just create hasher. +function blsHashers( + fields: TArg, + G1_Point: WeierstrassPointCons, + G2_Point: WeierstrassPointCons, + params: TArg, + hasherParams: TArg +): BlsCurvePairWithHashers { + const base = blsBasic(fields, G1_Point, G2_Point, params); + // Missing map hooks intentionally fail closed via notImplemented on first hash use. + const G1Hasher = createHasher( + G1_Point, + hasherParams.mapToG1 === undefined ? notImplemented : hasherParams.mapToG1, + { + ...hasherParams.hasherOpts, + ...hasherParams.hasherOptsG1, + } + ); + const G2Hasher = createHasher( + G2_Point, + hasherParams.mapToG2 === undefined ? notImplemented : hasherParams.mapToG2, + { + ...hasherParams.hasherOpts, + ...hasherParams.hasherOptsG2, + } + ); + return Object.freeze({ ...base, G1: G1Hasher, G2: G2Hasher }); +} + +// G1_Point: ProjConstructor, G2_Point: ProjConstructor, +// Rename to blsSignatures? +/** + * @param fields - Tower field implementations. + * @param G1_Point - G1 point constructor. + * @param G2_Point - G2 point constructor. + * @param params - Pairing parameters. See {@link BlsPairingParams}. + * @param hasherParams - Hash-to-curve configuration. See {@link BlsHasherParams}. + * @param signatureCoders - Signature codecs. + * @returns BLS helpers with signers. The inherited pairing surface still rejects infinity inputs, + * and empty `pairingBatch(...)` calls still return the multiplicative identity in GT. Aggregate + * verification still requires proof of possession or another rogue-key defense from the caller. + * @throws If the pairing, hashing, or signature helpers are configured inconsistently. {@link Error} + * @example + * ```ts + * import { bls } from '@noble/curves/abstract/bls.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const sigs = bls12_381.longSignatures; + * // Use the full BLS helper set when you need hashing, keygen, signing, and verification. + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = sigs.hash(new TextEncoder().encode('hello noble')); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export function bls( + fields: TArg, + G1_Point: WeierstrassPointCons, + G2_Point: WeierstrassPointCons, + params: TArg, + hasherParams: TArg, + signatureCoders: BlsSignatureCoders +): BlsCurvePairWithSignatures { + const base = blsHashers(fields, G1_Point, G2_Point, params, hasherParams); + const pairingRes: BlsPairing = { + ...base, + Fr: base.fields.Fr, + Fp12: base.fields.Fp12, + calcPairingPrecomputes: base.utils.calcPairingPrecomputes, + randomSecretKey: base.utils.randomSecretKey, + }; + const longSignatures = createBlsSig( + pairingRes, + G1_Point, + G2_Point, + false, + base.G2.hashToCurve, + signatureCoders?.LongSignature + ); + const shortSignatures = createBlsSig( + pairingRes, + G2_Point, + G1_Point, + true, + base.G1.hashToCurve, + signatureCoders?.ShortSignature + ); + return Object.freeze({ ...base, longSignatures, shortSignatures }); +} diff --git a/node_modules/@noble/curves/src/abstract/curve.ts b/node_modules/@noble/curves/src/abstract/curve.ts new file mode 100644 index 0000000..c65e71d --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/curve.ts @@ -0,0 +1,916 @@ +/** + * Methods for elliptic curve multiplication by scalars. + * Contains wNAF, pippenger. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts'; +import { Field, FpInvertBatch, validateField, type IField } from './modular.ts'; + +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); + +/** Affine point coordinates without projective fields. */ +export type AffinePoint = { + /** Affine x coordinate. */ + x: T; + /** Affine y coordinate. */ + y: T; +} & { Z?: never }; + +// We can't "abstract out" coordinates (X, Y, Z; and T in Edwards): argument names of constructor +// are not accessible. See Typescript gh-56093, gh-41594. +// +// We have to use recursive types, so it will return actual point, not constained `CurvePoint`. +// If, at any point, P is `any`, it will erase all types and replace it +// with `any`, because of recursion, `any implements CurvePoint`, +// but we lose all constrains on methods. + +/** Base interface for all elliptic-curve point instances. */ +export interface CurvePoint> { + /** Affine x coordinate. Different from projective / extended X coordinate. */ + x: F; + /** Affine y coordinate. Different from projective / extended Y coordinate. */ + y: F; + /** Projective Z coordinate when the point keeps projective state. */ + Z?: F; + /** + * Double the point. + * @returns Doubled point. + */ + double(): P; + /** + * Negate the point. + * @returns Negated point. + */ + negate(): P; + /** + * Add another point from the same curve. + * @param other - Point to add. + * @returns Sum point. + */ + add(other: P): P; + /** + * Subtract another point from the same curve. + * @param other - Point to subtract. + * @returns Difference point. + */ + subtract(other: P): P; + /** + * Compare two points for equality. + * @param other - Point to compare. + * @returns Whether the points are equal. + */ + equals(other: P): boolean; + /** + * Multiply the point by a scalar in constant time. + * Implementations keep the subgroup-scalar contract strict and may reject + * `0` instead of returning the identity point. + * @param scalar - Scalar multiplier. + * @returns Product point. + */ + multiply(scalar: bigint): P; + /** Assert that the point satisfies the curve equation and subgroup checks. */ + assertValidity(): void; + /** + * Map the point into the prime-order subgroup when the curve requires it. + * @returns Prime-order point. + */ + clearCofactor(): P; + /** + * Check whether the point is the point at infinity. + * @returns Whether the point is zero. + */ + is0(): boolean; + /** + * Check whether the point belongs to the prime-order subgroup. + * @returns Whether the point is torsion-free. + */ + isTorsionFree(): boolean; + /** + * Check whether the point lies in a small torsion subgroup. + * @returns Whether the point has small order. + */ + isSmallOrder(): boolean; + /** + * Multiply the point by a scalar without constant-time guarantees. + * Public-scalar callers that need `0` should use this method instead of + * relying on `multiply(...)` to return the identity point. + * @param scalar - Scalar multiplier. + * @returns Product point. + */ + multiplyUnsafe(scalar: bigint): P; + /** + * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}. + * Cache state lives in internal WeakMaps keyed by point identity, not on the point object. + * Repeating `precompute(...)` for the same point identity replaces the remembered window size + * and forces table regeneration for that point. + * @param windowSize - Precompute window size. + * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()` + * @returns Same point instance with precompute tables attached. + */ + precompute(windowSize?: number, isLazy?: boolean): P; + /** + * Converts point to 2D xy affine coordinates. + * @param invertedZ - Optional inverted Z coordinate for batch normalization. + * @returns Affine x/y coordinates. + */ + toAffine(invertedZ?: F): AffinePoint; + /** + * Encode the point into the curve's canonical byte form. + * @returns Encoded point bytes. + */ + toBytes(): Uint8Array; + /** + * Encode the point into the curve's canonical hex form. + * @returns Encoded point hex. + */ + toHex(): string; +} + +/** Base interface for elliptic-curve point constructors. */ +export interface CurvePointCons

> { + /** + * Runtime brand check for points created by this constructor. + * @param item - Value to test. + * @returns Whether the value is a point from this constructor. + */ + [Symbol.hasInstance]: (item: unknown) => boolean; + /** Canonical subgroup generator. */ + BASE: P; + /** Point at infinity. */ + ZERO: P; + /** Field for basic curve math */ + Fp: IField>; + /** Scalar field, for scalars in multiply and others */ + Fn: IField; + /** + * Create one point from affine coordinates. + * Does NOT validate curve, subgroup, or wrapper invariants. + * Use `.assertValidity()` on adversarial inputs. + * @param p - Affine point coordinates. + * @returns Point instance. + */ + fromAffine(p: AffinePoint>): P; + /** + * Decode a point from the canonical byte encoding. + * @param bytes - Encoded point bytes. + * Implementations MUST treat `bytes` as read-only. + * @returns Point instance. + */ + fromBytes(bytes: Uint8Array): P; + /** + * Decode a point from the canonical hex encoding. + * @param hex - Encoded point hex. + * @returns Point instance. + */ + fromHex(hex: string): P; +} + +// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element +// Short names, because we use them a lot in result types: +// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything +// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types +// * `CurvePointCons

>` constraints from interface definition +// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect +// * PC could be super specific with super specific P, which implements CurvePoint. +// this means we need to do stuff like +// `function test

, PC extends CurvePointCons

>(` +// if we want type safety around P, otherwise PC_P will be any + +/** Returns the affine field type for a point instance (`P_F

== P.F`). */ +export type P_F

> = P extends CurvePoint ? F : never; +/** Returns the affine field type for a point constructor (`PC_F == PC.P.F`). */ +export type PC_F>> = PC['Fp']['ZERO']; +/** Returns the point instance type for a point constructor (`PC_P == PC.P`). */ +export type PC_P>> = PC['ZERO']; + +// Ugly hack to get proper type inference, because in typescript fails to infer resursively. +// The hack allows to do up to 10 chained operations without applying type erasure. +// +// Types which won't work: +// * `CurvePointCons>`, will return `any` after 1 operation +// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false` +// * `P extends CurvePoint, PC extends CurvePointCons

` +// * It can't infer P from PC alone +// * Too many relations between F, P & PC +// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic +// * It will work correctly if there is an additional argument of type P +// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate +// types, making them un-inferable +// prettier-ignore +/** Wide point-constructor type used when the concrete curve is not important. */ +export type PC_ANY = CurvePointCons< + CurvePoint + >>>>>>>>> +>; + +/** + * Validates the static surface of a point constructor. + * This is only a cheap sanity check for the constructor hooks and fields consumed by generic + * factories; it does not certify `BASE`/`ZERO` semantics or prove the curve implementation itself. + * @param Point - Runtime point constructor. + * @throws On missing constructor hooks or malformed field metadata. {@link TypeError} + * @example + * Check that one point constructor exposes the static hooks generic helpers need. + * + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { validatePointCons } from '@noble/curves/abstract/curve.js'; + * validatePointCons(ed25519.Point); + * ``` + */ +export function validatePointCons

>(Point: CurvePointCons

): void { + const pc = Point as unknown as CurvePointCons; + if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor'); + // validateObject only accepts plain objects, so copy the constructor statics into one bag first. + validateObject( + { + Fp: pc.Fp, + Fn: pc.Fn, + fromAffine: pc.fromAffine, + fromBytes: pc.fromBytes, + fromHex: pc.fromHex, + }, + { + Fp: 'object', + Fn: 'object', + fromAffine: 'function', + fromBytes: 'function', + fromHex: 'function', + } + ); + validateField(pc.Fp); + validateField(pc.Fn); +} + +/** Byte lengths used by one curve implementation. */ +export interface CurveLengths { + /** Secret-key length in bytes. */ + secretKey?: number; + /** Compressed public-key length in bytes. */ + publicKey?: number; + /** Uncompressed public-key length in bytes. */ + publicKeyUncompressed?: number; + /** Whether public-key encodings include a format prefix byte. */ + publicKeyHasPrefix?: boolean; + /** Signature length in bytes. */ + signature?: number; + /** Seed length in bytes when the curve exposes deterministic keygen from seed. */ + seed?: number; +} + +/** Reorders or otherwise remaps a batch while preserving its element type. */ +export type Mapper = (i: T[]) => T[]; + +/** + * Computes both candidates first, but the final selection still branches on `condition`, so this + * is not a strict constant-time CMOV primitive. + * @param condition - Whether to negate the point. + * @param item - Point-like value. + * @returns Original or negated value. + * @example + * Keep the point or return its negation based on one boolean branch. + * + * ```ts + * import { negateCt } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const maybeNegated = negateCt(true, p256.Point.BASE); + * ``` + */ +export function negateCt T }>(condition: boolean, item: T): T { + const neg = item.negate(); + return condition ? neg : item; +} + +/** + * Takes a bunch of Projective Points but executes only one + * inversion on all of them. Inversion is very slow operation, + * so this improves performance massively. + * Optimization: converts a list of projective points to a list of identical points with Z=1. + * Input points are left unchanged; the normalized points are returned as fresh instances. + * @param c - Point constructor. + * @param points - Projective points. + * @returns Fresh projective points reconstructed from normalized affine coordinates. + * @example + * Batch-normalize projective points with a single shared inversion. + * + * ```ts + * import { normalizeZ } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]); + * ``` + */ +export function normalizeZ

, PC extends CurvePointCons

>( + c: PC, + points: P[] +): P[] { + const invertedZs = FpInvertBatch( + c.Fp, + points.map((p) => p.Z!) + ); + return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); +} + +function validateW(W: number, bits: number) { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W); +} + +/** Internal wNAF opts for specific W and scalarBits. + * Zero digits are skipped, so tables store only the positive half-window and callers reserve one + * extra carry window. + */ +type WOpts = { + windows: number; + windowSize: number; + mask: bigint; + maxNumber: number; + shiftBy: bigint; +}; + +function calcWOpts(W: number, scalarBits: number): WOpts { + validateW(W, scalarBits); + const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero + const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero + const maxNumber = 2 ** W; // W=8 256 + const mask = bitMask(W); // W=8 255 == mask 0b11111111 + const shiftBy = BigInt(W); // W=8 8 + return { windows, windowSize, mask, maxNumber, shiftBy }; +} + +function calcOffsets(n: bigint, window: number, wOpts: WOpts) { + const { windowSize, mask, maxNumber, shiftBy } = wOpts; + let wbits = Number(n & mask); // extract W bits. + let nextN = n >> shiftBy; // shift number by W bits. + + // What actually happens here: + // const highestBit = Number(mask ^ (mask >> 1n)); + // let wbits2 = wbits - 1; // skip zero + // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~); + + // split if bits > max: +224 => 256-32 + if (wbits > windowSize) { + // we skip zero, which means instead of `>= size-1`, we do `> size` + wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here. + nextN += _1n; // +256 (carry) + } + const offsetStart = window * windowSize; + const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero + const isZero = wbits === 0; // is current window slice a 0? + const isNeg = wbits < 0; // is current window slice negative? + const isNegF = window % 2 !== 0; // fake branch noise only + const offsetF = offsetStart; // fake branch noise only + return { nextN, offset, isZero, isNeg, isNegF, offsetF }; +} + +function validateMSMPoints(points: any[], c: any) { + if (!Array.isArray(points)) throw new Error('array expected'); + points.forEach((p, i) => { + if (!(p instanceof c)) throw new Error('invalid point at index ' + i); + }); +} +function validateMSMScalars(scalars: any[], field: any) { + if (!Array.isArray(scalars)) throw new Error('array of scalars expected'); + scalars.forEach((s, i) => { + if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i); + }); +} + +// Since points in different groups cannot be equal (different object constructor), +// we can have single place to store precomputes. +// Allows to make points frozen / immutable. +const pointPrecomputes = new WeakMap(); +const pointWindowSizes = new WeakMap(); + +function getW(P: any): number { + // To disable precomputes: + // return 1; + // `1` is also the uncached sentinel: use the ladder / non-precomputed path. + return pointWindowSizes.get(P) || 1; +} + +function assert0(n: bigint): void { + // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop + // count is inconsistent, not that the original caller provided a bad scalar. + if (n !== _0n) throw new Error('invalid wNAF'); +} + +/** + * Elliptic curve multiplication of Point by scalar. Fragile. + * Table generation takes **30MB of ram and 10ms on high-end CPU**, + * but may take much longer on slow devices. Actual generation will happen on + * first call of `multiply()`. By default, `BASE` point is precomputed. + * + * Scalars should always be less than curve order: this should be checked inside of a curve itself. + * Creates precomputation tables for fast multiplication: + * - private scalar is split by fixed size windows of W bits + * - every window point is collected from window's table & added to accumulator + * - since windows are different, same point inside tables won't be accessed more than once per calc + * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar) + * - +1 window is neccessary for wNAF + * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication + * + * TODO: research returning a 2d JS array of windows instead of a single window. + * This would allow windows to be in different memory locations. + * @param Point - Point constructor. + * @param bits - Scalar bit length. + * @example + * Elliptic curve multiplication of Point by scalar. + * + * ```ts + * import { wNAF } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS); + * ``` + */ +export class wNAF { + private readonly BASE: PC_P; + private readonly ZERO: PC_P; + private readonly Fn: PC['Fn']; + readonly bits: number; + + // Parametrized with a given Point class (not individual point) + constructor(Point: PC, bits: number) { + this.BASE = Point.BASE; + this.ZERO = Point.ZERO; + this.Fn = Point.Fn; + this.bits = bits; + } + + // non-const time multiplication ladder + _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P { + let d: PC_P = elm; + while (n > _0n) { + if (n & _1n) p = p.add(d); + d = d.double(); + n >>= _1n; + } + return p; + } + + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param point - Point instance + * @param W - window size + * @returns precomputed point tables flattened to a single array + */ + private precomputeWindow(point: PC_P, W: number): PC_P[] { + const { windows, windowSize } = calcWOpts(W, this.bits); + const points: PC_P[] = []; + let p: PC_P = point; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + // i=1, bc we skip 0 + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * More compact implementation: + * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 + * @returns real and fake (for const-time) points + */ + private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } { + // Scalar should be smaller than field order + if (!this.Fn.isValid(n)) throw new Error('invalid scalar'); + // Accumulators + let p = this.ZERO; + let f = this.BASE; + // This code was first written with assumption that 'f' and 'p' will never be infinity point: + // since each addition is multiplied by 2 ** W, it cannot cancel each other. However, + // there is negate now: it is possible that negated element from low value + // would be the same as high element, which will create carry into next window. + // It's not obvious how this can fail, but still worth investigating later. + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise + const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + // bits are 0: add garbage to fake point + // Important part for const-time getPublicKey: add random "noise" point to f. + f = f.add(negateCt(isNegF, precomputes[offsetF])); + } else { + // bits are 1: add to result point + p = p.add(negateCt(isNeg, precomputes[offset])); + } + } + assert0(n); + // Return both real and fake points so JIT keeps the noise path alive. + // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not, + // which weakens the noise path and leaves this only "less const-time" by about one bigint mul. + return { p, f }; + } + + /** + * Implements unsafe EC multiplication using precomputed tables + * and w-ary non-adjacent form. + * @param acc - accumulator point to add result of multiplication + * @returns point + */ + private wNAFUnsafe( + W: number, + precomputes: PC_P[], + n: bigint, + acc: PC_P = this.ZERO + ): PC_P { + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + if (n === _0n) break; // Early-exit, skip 0 value + const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + // Window bits are 0: skip processing. + // Move to next window. + continue; + } else { + const item = precomputes[offset]; + acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM + } + } + assert0(n); + return acc; + } + + private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] { + // Cache key is only point identity plus the remembered window size; callers must not reuse the + // same point with incompatible `transform(...)` layouts and expect a separate cache entry. + let comp = pointPrecomputes.get(point); + if (!comp) { + comp = this.precomputeWindow(point, W) as PC_P[]; + if (W !== 1) { + // Doing transform outside of if brings 15% perf hit + if (typeof transform === 'function') comp = transform(comp); + pointPrecomputes.set(point, comp); + } + } + return comp; + } + + cached( + point: PC_P, + scalar: bigint, + transform?: Mapper> + ): { p: PC_P; f: PC_P } { + const W = getW(point); + return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar); + } + + unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P { + const W = getW(point); + if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster + return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev); + } + + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + createCache(P: PC_P, W: number): void { + validateW(W, this.bits); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + } + + hasCache(elm: PC_P): boolean { + return getW(elm) !== 1; + } +} + +/** + * Endomorphism-specific multiplication for Koblitz curves. + * Cost: 128 dbl, 0-256 adds. + * @param Point - Point constructor. + * @param point - Input point. + * @param k1 - First non-negative absolute scalar chunk. + * @param k2 - Second non-negative absolute scalar chunk. + * @returns Partial multiplication results. + * @example + * Endomorphism-specific multiplication for Koblitz curves. + * + * ```ts + * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js'; + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n); + * ``` + */ +export function mulEndoUnsafe

, PC extends CurvePointCons

>( + Point: PC, + point: P, + k1: bigint, + k2: bigint +): { p1: P; p2: P } { + let acc = point; + let p1 = Point.ZERO; + let p2 = Point.ZERO; + while (k1 > _0n || k2 > _0n) { + if (k1 & _1n) p1 = p1.add(acc); + if (k2 & _1n) p2 = p2.add(acc); + acc = acc.double(); + k1 >>= _1n; + k2 >>= _1n; + } + return { p1, p2 }; +} + +/** + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * 30x faster vs naive addition on L=4096, 10x faster than precomputes. + * For N=254bit, L=1, it does: 1024 ADD + 254 DBL. For L=5: 1536 ADD + 254 DBL. + * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0. + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param scalars - array of L scalars (aka secret keys / bigints) + * @returns MSM result point. Empty input is accepted and returns the identity. + * @throws If the point set, scalar set, or MSM sizing is invalid. {@link Error} + * @example + * Pippenger algorithm for multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { pippenger } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const point = pippenger(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()], [2n, 3n]); + * ``` + */ +export function pippenger

, PC extends CurvePointCons

>( + c: PC, + points: P[], + scalars: bigint[] +): P { + // If we split scalars by some window (let's say 8 bits), every chunk will only + // take 256 buckets even if there are 4096 scalars, also re-uses double. + // TODO: + // - https://eprint.iacr.org/2024/750.pdf + // - https://tches.iacr.org/index.php/TCHES/article/view/10287 + // 0 is accepted in scalars + const fieldN = c.Fn; + validateMSMPoints(points, c); + validateMSMScalars(scalars, fieldN); + const plength = points.length; + const slength = scalars.length; + if (plength !== slength) throw new Error('arrays of points and scalars must have equal length'); + // if (plength === 0) throw new Error('array must be of length >= 2'); + const zero = c.ZERO; + const wbits = bitLen(BigInt(plength)); + let windowSize = 1; // bits + if (wbits > 12) windowSize = wbits - 3; + else if (wbits > 4) windowSize = wbits - 2; + else if (wbits > 0) windowSize = 2; + const MASK = bitMask(windowSize); + const buckets = new Array(Number(MASK) + 1).fill(zero); // +1 for zero array + const lastBits = Math.floor((fieldN.BITS - 1) / windowSize) * windowSize; + let sum = zero; + for (let i = lastBits; i >= 0; i -= windowSize) { + buckets.fill(zero); + for (let j = 0; j < slength; j++) { + const scalar = scalars[j]; + const wbits = Number((scalar >> BigInt(i)) & MASK); + buckets[wbits] = buckets[wbits].add(points[j]); + } + let resI = zero; // not using this will do small speed-up, but will lose ct + // Skip first bucket, because it is zero + for (let j = buckets.length - 1, sumI = zero; j > 0; j--) { + sumI = sumI.add(buckets[j]); + resI = resI.add(sumI); + } + sum = sum.add(resI); + if (i !== 0) for (let j = 0; j < windowSize; j++) sum = sum.double(); + } + return sum as P; +} +/** + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * @param c - Curve Point constructor + * @param points - array of L curve points + * @param windowSize - Precompute window size. + * @returns Function which multiplies points with scalars. The closure accepts + * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero. + * @throws If the point set or precompute window is invalid. {@link Error} + * @example + * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...). + * + * ```ts + * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4); + * const point = msm([3n]); + * ``` + */ +export function precomputeMSMUnsafe

, PC extends CurvePointCons

>( + c: PC, + points: P[], + windowSize: number +): (scalars: bigint[]) => P { + /** + * Performance Analysis of Window-based Precomputation + * + * Base Case (256-bit scalar, 8-bit window): + * - Standard precomputation requires: + * - 31 additions per scalar × 256 scalars = 7,936 ops + * - Plus 255 summary additions = 8,191 total ops + * Note: Summary additions can be optimized via accumulator + * + * Chunked Precomputation Analysis: + * - Using 32 chunks requires: + * - 255 additions per chunk + * - 256 doublings + * - Total: (255 × 32) + 256 = 8,416 ops + * + * Memory Usage Comparison: + * Window Size | Standard Points | Chunked Points + * ------------|-----------------|--------------- + * 4-bit | 520 | 15 + * 8-bit | 4,224 | 255 + * 10-bit | 13,824 | 1,023 + * 16-bit | 557,056 | 65,535 + * + * Key Advantages: + * 1. Enables larger window sizes due to reduced memory overhead + * 2. More efficient for smaller scalar counts: + * - 16 chunks: (16 × 255) + 256 = 4,336 ops + * - ~2x faster than standard 8,191 ops + * + * Limitations: + * - Not suitable for plain precomputes (requires 256 constant doublings) + * - Performance degrades with larger scalar counts: + * - Optimal for ~256 scalars + * - Less efficient for 4096+ scalars (Pippenger preferred) + */ + const fieldN = c.Fn; + validateW(windowSize, fieldN.BITS); + validateMSMPoints(points, c); + const zero = c.ZERO; + const tableSize = 2 ** windowSize - 1; // table size (without zero) + const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item + const MASK = bitMask(windowSize); + const tables = points.map((p: P) => { + const res = []; + for (let i = 0, acc = p; i < tableSize; i++) { + res.push(acc); + acc = acc.add(p); + } + return res; + }); + return (scalars: bigint[]): P => { + validateMSMScalars(scalars, fieldN); + if (scalars.length > points.length) + throw new Error('array of scalars must be smaller than array of points'); + let res = zero; + for (let i = 0; i < chunks; i++) { + // No need to double if accumulator is still zero. + if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double(); + const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize); + for (let j = 0; j < scalars.length; j++) { + const n = scalars[j]; + const curr = Number((n >> shiftBy) & MASK); + if (!curr) continue; // skip zero scalars chunks + res = res.add(tables[j][curr - 1]); + } + } + return res; + }; +} + +/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */ +export type ValidCurveParams = { + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Cofactor. */ + h: bigint; + /** Curve parameter `a`. */ + a: T; + /** Weierstrass curve parameter `b`. */ + b?: T; + /** Edwards curve parameter `d`. */ + d?: T; + /** Generator x coordinate. */ + Gx: T; + /** Generator y coordinate. */ + Gy: T; +}; + +function createField(order: bigint, field?: TArg>, isLE?: boolean): TRet> { + if (field) { + // Reuse supplied field overrides as-is; `isLE` only affects freshly constructed fallback + // fields, and validateField() below only checks the arithmetic subset, not full byte/cmov + // behavior. + if (field.ORDER !== order) throw new Error('Field.ORDER must match order: Fp == p, Fn == n'); + validateField(field); + return field as TRet>; + } else { + return Field(order, { isLE }) as unknown as TRet>; + } +} +/** Pair of fields used by curve constructors. */ +export type FpFn = { + /** Base field used for curve coordinates. */ + Fp: IField; + /** Scalar field used for secret scalars and subgroup arithmetic. */ + Fn: IField; +}; + +/** + * Validates basic CURVE shape and field membership, then creates fields. + * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or + * that the curve equation itself is otherwise sane. + * @param type - Curve family. + * @param CURVE - Curve parameters. + * @param curveOpts - Optional field overrides: + * - `Fp` (optional): Optional base-field override. + * - `Fn` (optional): Optional scalar-field override. + * @param FpFnLE - Whether field encoding is little-endian. + * @returns Frozen curve parameters and fields. + * @throws If the curve parameters or field overrides are invalid. {@link Error} + * @example + * Build curve fields from raw constants before constructing a curve instance. + * + * ```ts + * const curve = createCurveFields('weierstrass', { + * p: 17n, + * n: 19n, + * h: 1n, + * a: 2n, + * b: 2n, + * Gx: 5n, + * Gy: 1n, + * }); + * ``` + */ +export function createCurveFields( + type: 'weierstrass' | 'edwards', + CURVE: ValidCurveParams, + curveOpts: TArg>> = {}, + FpFnLE?: boolean +): TRet & { CURVE: ValidCurveParams }> { + if (FpFnLE === undefined) FpFnLE = type === 'edwards'; + if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`); + for (const p of ['p', 'n', 'h'] as const) { + const val = CURVE[p]; + if (!(typeof val === 'bigint' && val > _0n)) + throw new Error(`CURVE.${p} must be positive bigint`); + } + const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); + const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE); + const _b: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd'; + const params = ['Gx', 'Gy', 'a', _b] as const; + for (const p of params) { + // @ts-ignore + if (!Fp.isValid(CURVE[p])) + throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); + } + CURVE = Object.freeze(Object.assign({}, CURVE)); + return { CURVE, Fp, Fn } as TRet & { CURVE: ValidCurveParams }>; +} + +type KeygenFn = ( + seed?: Uint8Array, + isCompressed?: boolean +) => { secretKey: Uint8Array; publicKey: Uint8Array }; +/** + * @param randomSecretKey - Secret-key generator. + * @param getPublicKey - Public-key derivation helper. + * @returns Keypair generator. + * @example + * Build a `keygen()` helper from existing secret-key and public-key primitives. + * + * ```ts + * import { createKeygen } from '@noble/curves/abstract/curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey); + * const pair = keygen(); + * ``` + */ +export function createKeygen( + randomSecretKey: Function, + getPublicKey: TArg +): TRet { + return function keygen(seed?: TArg) { + const secretKey = randomSecretKey(seed) as TRet; + return { secretKey, publicKey: getPublicKey(secretKey) as TRet }; + }; +} diff --git a/node_modules/@noble/curves/src/abstract/edwards.ts b/node_modules/@noble/curves/src/abstract/edwards.ts new file mode 100644 index 0000000..e5e278f --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/edwards.ts @@ -0,0 +1,1013 @@ +/** + * Twisted Edwards curve. The formula is: ax² + y² = 1 + dx²y². + * For design rationale of types / exports, see weierstrass module documentation. + * Untwisted Edwards curves exist, but they aren't used in real-world protocols. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + abool, + abytes, + aInRange, + asafenumber, + bytesToHex, + bytesToNumberLE, + concatBytes, + copyBytes, + hexToBytes, + isBytes, + notImplemented, + validateObject, + randomBytes as wcRandomBytes, + type FHash, + type Signer, + type TArg, + type TRet, +} from '../utils.ts'; +import { + createCurveFields, + createKeygen, + normalizeZ, + wNAF, + type AffinePoint, + type CurveLengths, + type CurvePoint, + type CurvePointCons, +} from './curve.ts'; +import { type IField } from './modular.ts'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _8n = /* @__PURE__ */ BigInt(8); + +/** Extended Edwards point with X/Y/Z/T coordinates. */ +export interface EdwardsPoint extends CurvePoint { + /** extended X coordinate. Different from affine x. */ + readonly X: bigint; + /** extended Y coordinate. Different from affine y. */ + readonly Y: bigint; + /** extended Z coordinate */ + readonly Z: bigint; + /** extended T coordinate */ + readonly T: bigint; +} +/** Constructor and decoding helpers for extended Edwards points. */ +export interface EdwardsPointCons extends CurvePointCons { + /** Create a point from extended X/Y/Z/T coordinates without validation. */ + new (X: bigint, Y: bigint, Z: bigint, T: bigint): EdwardsPoint; + /** + * Return the curve parameters used by this point constructor. + * @returns Curve parameters. + */ + CURVE(): EdwardsOpts; + /** + * Decode a point from bytes, optionally using ZIP-215 rules. + * @param bytes - Encoded point bytes. + * @param zip215 - Whether to accept ZIP-215 encodings. + * @returns Decoded Edwards point. + */ + fromBytes(bytes: Uint8Array, zip215?: boolean): EdwardsPoint; + /** + * Decode a point from hex, optionally using ZIP-215 rules. + * @param hex - Encoded point hex. + * @param zip215 - Whether to accept ZIP-215 encodings. + * @returns Decoded Edwards point. + */ + fromHex(hex: string, zip215?: boolean): EdwardsPoint; +} + +/** + * Twisted Edwards curve options. + * + * * a: formula param + * * d: formula param + * * p: prime characteristic (order) of finite field, in which arithmetics is done + * * n: order of prime subgroup a.k.a total amount of valid curve points + * * h: cofactor. h*n is group order; n is subgroup order + * * Gx: x coordinate of generator point a.k.a. base point + * * Gy: y coordinate of generator point + */ +export type EdwardsOpts = Readonly<{ + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Curve cofactor. */ + h: bigint; + /** Edwards curve parameter `a`. */ + a: bigint; + /** Edwards curve parameter `d`. */ + d: bigint; + /** Generator x coordinate. */ + Gx: bigint; + /** Generator y coordinate. */ + Gy: bigint; +}>; + +/** + * Extra curve options for Twisted Edwards. + * + * * Fp: redefined Field over curve.p + * * Fn: redefined Field over curve.n + * * uvRatio: helper function for decompression, calculating √(u/v) + */ +export type EdwardsExtraOpts = Partial<{ + /** Optional base-field override. */ + Fp: IField; + /** Optional scalar-field override. */ + Fn: IField; + /** Whether field encodings are little-endian. */ + FpFnLE: boolean; + /** Square-root ratio helper used during point decompression. */ + uvRatio: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; +}>; + +/** + * EdDSA (Edwards Digital Signature algorithm) options. + * + * * hash: hash function used to hash secret keys and messages + * * adjustScalarBytes: clears bits to get valid field element + * * domain: Used for hashing + * * mapToCurve: for hash-to-curve standard + * * prehash: RFC 8032 pre-hashing of messages to sign() / verify() + * * randomBytes: function generating random bytes, used for randomSecretKey + */ +export type EdDSAOpts = Partial<{ + /** Clamp or otherwise normalize secret-scalar bytes before reducing mod `n`. */ + adjustScalarBytes: (bytes: TArg) => TRet; + /** Domain-separation helper for contexts and prehash mode. */ + domain: (data: TArg, ctx: TArg, phflag: boolean) => TRet; + /** Optional hash-to-curve mapper for protocols like Ristretto hash-to-group. */ + mapToCurve: (scalar: bigint[]) => AffinePoint; + /** Optional prehash function used before signing or verifying messages. */ + prehash: FHash; + /** Default verification decoding policy. ZIP-215 is more permissive than RFC 8032 / NIST. */ + zip215: boolean; + /** RNG override used by helper constructors. */ + randomBytes: (bytesLength?: number) => TRet; +}>; + +/** + * EdDSA (Edwards Digital Signature algorithm) helper namespace. + * Allows creating and verifying signatures, and deriving public keys. + */ +export interface EdDSA { + /** + * Generate a secret/public key pair. + * @param seed - Optional seed material. + * @returns Secret/public key pair. + */ + keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Encoded public key. + */ + getPublicKey: (secretKey: TArg) => TRet; + /** + * Sign a message with an EdDSA secret key. + * @param message - Message bytes. + * @param secretKey - Secret key bytes. + * @param options - Optional signature tweaks: + * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448. + * @returns Encoded signature bytes. + */ + sign: ( + message: TArg, + secretKey: TArg, + options?: TArg<{ context?: Uint8Array }> + ) => TRet; + /** + * Verify a signature against a message and public key. + * @param sig - Encoded signature bytes. + * @param message - Message bytes. + * @param publicKey - Encoded public key. + * @param options - Optional verification tweaks: + * - `context` (optional): Domain-separation context for Ed25519ctx/Ed448. + * - `zip215` (optional): Whether to accept ZIP-215 encodings. + * @returns Whether the signature is valid. + */ + verify: ( + sig: TArg, + message: TArg, + publicKey: TArg, + options?: TArg<{ context?: Uint8Array; zip215?: boolean }> + ) => boolean; + /** Point constructor used by this signature scheme. */ + Point: EdwardsPointCons; + /** Helper utilities for key validation and Montgomery conversion. */ + utils: { + /** + * Generate a valid random secret key. + * Optional seed bytes are only length-checked and returned unchanged. + */ + randomSecretKey: (seed?: TArg) => TRet; + /** Check whether a secret key has the expected encoding. */ + isValidSecretKey: (secretKey: TArg) => boolean; + /** Check whether a public key decodes to a valid point. */ + isValidPublicKey: (publicKey: TArg, zip215?: boolean) => boolean; + + /** + * Converts ed public key to x public key. + * + * There is NO `fromMontgomery`: + * - There are 2 valid ed25519 points for every x25519, with flipped coordinate + * - Sometimes there are 0 valid ed25519 points, because x25519 *additionally* + * accepts inputs on the quadratic twist, which can't be moved to ed25519 + * + * @example + * Converts ed public key to x public key. + * + * ```js + * const someonesPub_ed = ed25519.getPublicKey(ed25519.utils.randomSecretKey()); + * const someonesPub = ed25519.utils.toMontgomery(someonesPub); + * const aPriv = x25519.utils.randomSecretKey(); + * const shared = x25519.getSharedSecret(aPriv, someonesPub) + * ``` + */ + toMontgomery: (publicKey: TArg) => TRet; + /** + * Converts ed secret key to x secret key. + * @example + * Converts ed secret key to x secret key. + * + * ```js + * const someonesPub = x25519.getPublicKey(x25519.utils.randomSecretKey()); + * const aPriv_ed = ed25519.utils.randomSecretKey(); + * const aPriv = ed25519.utils.toMontgomerySecret(aPriv_ed); + * const shared = x25519.getSharedSecret(aPriv, someonesPub) + * ``` + */ + toMontgomerySecret: (secretKey: TArg) => TRet; + /** Return the expanded private key components used by RFC8032 signing. */ + getExtendedPublicKey: (key: TArg) => { + head: TRet; + prefix: TRet; + scalar: bigint; + point: EdwardsPoint; + pointBytes: TRet; + }; + }; + /** Byte lengths for keys and signatures exposed by this scheme. */ + lengths: CurveLengths; +} + +// Affine Edwards-equation check only; this does not prove subgroup membership, canonical +// encoding, prime-order base-point requirements, or identity exclusion. +function isEdValidXY(Fp: TArg>, CURVE: EdwardsOpts, x: bigint, y: bigint): boolean { + const x2 = Fp.sqr(x); + const y2 = Fp.sqr(y); + const left = Fp.add(Fp.mul(CURVE.a, x2), y2); + const right = Fp.add(Fp.ONE, Fp.mul(CURVE.d, Fp.mul(x2, y2))); + return Fp.eql(left, right); +} + +/** + * @param params - Curve parameters. See {@link EdwardsOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link EdwardsExtraOpts}. + * @returns Edwards point constructor. Generator validation here only checks + * that `(Gx, Gy)` satisfies the affine Edwards equation. + * RFC 8032 base-point constraints like `B != (0,1)` and `[L]B = 0` + * are left to the caller's chosen parameters, since eager subgroup + * validation here adds about 10-15ms to heavyweight imports like ed448. + * The returned constructor also eagerly marks `Point.BASE` for W=8 + * precompute caching. Some code paths still assume + * `Fp.BYTES === Fn.BYTES`, so mismatched byte lengths are not fully audited here. + * @throws If the curve parameters or Edwards overrides are invalid. {@link Error} + * @example + * ```ts + * import { edwards } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * // Build a point constructor from explicit curve parameters, then use its base point. + * const Point = edwards(jubjub.Point.CURVE()); + * Point.BASE.toHex(); + * ``` + */ +export function edwards( + params: TArg, + extraOpts: TArg = {} +): EdwardsPointCons { + const opts = extraOpts as EdwardsExtraOpts; + const validated = createCurveFields('edwards', params as EdwardsOpts, opts, opts.FpFnLE); + const { Fp, Fn } = validated; + let CURVE = validated.CURVE as EdwardsOpts; + const { h: cofactor } = CURVE; + validateObject(opts, {}, { uvRatio: 'function' }); + + // Important: + // There are some places where Fp.BYTES is used instead of nByteLength. + // So far, everything has been tested with curves of Fp.BYTES == nByteLength. + // TODO: test and find curves which behave otherwise. + const MASK = _2n << (BigInt(Fn.BYTES * 8) - _1n); + const modP = (n: bigint) => Fp.create(n); // Function overrides + + // sqrt(u/v) + const uvRatio = + opts.uvRatio === undefined + ? (u: bigint, v: bigint) => { + try { + return { isValid: true, value: Fp.sqrt(Fp.div(u, v)) }; + } catch (e) { + return { isValid: false, value: _0n }; + } + } + : opts.uvRatio; + + // Validate whether the passed curve params are valid. + // equation ax² + y² = 1 + dx²y² should work for generator point. + if (!isEdValidXY(Fp, CURVE, CURVE.Gx, CURVE.Gy)) + throw new Error('bad curve params: generator point'); + + /** + * Asserts coordinate is valid: 0 <= n < MASK. + * Coordinates >= Fp.ORDER are allowed for zip215. + */ + function acoord(title: string, n: bigint, banZero = false) { + const min = banZero ? _1n : _0n; + aInRange('coordinate ' + title, n, min, MASK); + return n; + } + + function aedpoint(other: unknown) { + if (!(other instanceof Point)) throw new Error('EdwardsPoint expected'); + } + + // Extended Point works in extended coordinates: (X, Y, Z, T) ∋ (x=X/Z, y=Y/Z, T=xy). + // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates + class Point implements EdwardsPoint { + // base / generator point + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy)); + // zero / infinity / identity point + static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0 + // math field + static readonly Fp = Fp; + // scalar field + static readonly Fn = Fn; + + readonly X: bigint; + readonly Y: bigint; + readonly Z: bigint; + readonly T: bigint; + + constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) { + this.X = acoord('x', X); + this.Y = acoord('y', Y); + this.Z = acoord('z', Z, true); + this.T = acoord('t', T); + Object.freeze(this); + } + + static CURVE(): EdwardsOpts { + return CURVE; + } + + /** + * Create one extended Edwards point from affine coordinates. + * Does NOT validate that the point is on-curve or torsion-free. + * Use `.assertValidity()` on adversarial inputs. + */ + static fromAffine(p: AffinePoint): Point { + if (p instanceof Point) throw new Error('extended point not allowed'); + const { x, y } = p || {}; + acoord('x', x); + acoord('y', y); + return new Point(x, y, _1n, modP(x * y)); + } + + // Uses algo from RFC8032 5.1.3. + static fromBytes(bytes: Uint8Array, zip215 = false): Point { + const len = Fp.BYTES; + const { a, d } = CURVE; + bytes = copyBytes(abytes(bytes, len, 'point')); + abool(zip215, 'zip215'); + const normed = copyBytes(bytes); // copy again, we'll manipulate it + const lastByte = bytes[len - 1]; // select last byte + normed[len - 1] = lastByte & ~0x80; // clear last bit + const y = bytesToNumberLE(normed); + + // zip215=true is good for consensus-critical apps. =false follows RFC8032 / NIST186-5. + // RFC8032 prohibits >= p, but ZIP215 doesn't + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + const max = zip215 ? MASK : Fp.ORDER; + aInRange('point.y', y, _0n, max); + + // Ed25519: x² = (y²-1)/(dy²+1) mod p. Ed448: x² = (y²-1)/(dy²-1) mod p. Generic case: + // ax²+y²=1+dx²y² => y²-1=dx²y²-ax² => y²-1=x²(dy²-a) => x²=(y²-1)/(dy²-a) + const y2 = modP(y * y); // denominator is always non-0 mod p. + const u = modP(y2 - _1n); // u = y² - 1 + const v = modP(d * y2 - a); // v = d y² + 1. + let { isValid, value: x } = uvRatio(u, v); // √(u/v) + if (!isValid) throw new Error('bad point: invalid y coordinate'); + const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper + const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit + if (!zip215 && x === _0n && isLastByteOdd) + // if x=0 and x_0 = 1, fail + throw new Error('bad point: x=0 and x_0=1'); + if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x + return Point.fromAffine({ x, y }); + } + + static fromHex(hex: string, zip215 = false): Point { + return Point.fromBytes(hexToBytes(hex), zip215); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + precompute(windowSize: number = 8, isLazy = true) { + wnaf.createCache(this, windowSize); + if (!isLazy) this.multiply(_2n); // random number + return this; + } + + // Useful in fromAffine() - not for fromBytes(), which always created valid points. + assertValidity(): void { + const p = this; + const { a, d } = CURVE; + // Keep generic Edwards validation fail-closed on the neutral point. + // Even though ZERO is algebraically valid and can roundtrip through encodings, higher-level + // callers often reach it only through broken hash/scalar plumbing; rejecting it here avoids + // silently treating that degenerate state as an ordinary public point. + if (p.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below? + // Equation in affine coordinates: ax² + y² = 1 + dx²y² + // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y² + const { X, Y, Z, T } = p; + const X2 = modP(X * X); // X² + const Y2 = modP(Y * Y); // Y² + const Z2 = modP(Z * Z); // Z² + const Z4 = modP(Z2 * Z2); // Z⁴ + const aX2 = modP(X2 * a); // aX² + const left = modP(Z2 * modP(aX2 + Y2)); // (aX² + Y²)Z² + const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z⁴ + dX²Y² + if (left !== right) throw new Error('bad point: equation left != right (1)'); + // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T + const XY = modP(X * Y); + const ZT = modP(Z * T); + if (XY !== ZT) throw new Error('bad point: equation left != right (2)'); + } + + // Compare one point to another. + equals(other: Point): boolean { + aedpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + const X1Z2 = modP(X1 * Z2); + const X2Z1 = modP(X2 * Z1); + const Y1Z2 = modP(Y1 * Z2); + const Y2Z1 = modP(Y2 * Z1); + return X1Z2 === X2Z1 && Y1Z2 === Y2Z1; + } + + is0(): boolean { + return this.equals(Point.ZERO); + } + + negate(): Point { + // Flips point sign to a negative one (-x, y in affine coords) + return new Point(modP(-this.X), this.Y, this.Z, modP(-this.T)); + } + + // Fast algo for doubling Extended Point. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd + // Cost: 4M + 4S + 1*a + 6add + 1*2. + double(): Point { + const { a } = CURVE; + const { X: X1, Y: Y1, Z: Z1 } = this; + const A = modP(X1 * X1); // A = X12 + const B = modP(Y1 * Y1); // B = Y12 + const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12 + const D = modP(a * A); // D = a*A + const x1y1 = X1 + Y1; + const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B + const G = D + B; // G = D+B + const F = G - C; // F = G-C + const H = D - B; // H = D-B + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + // Fast algo for adding 2 Extended Points. + // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd + // Cost: 9M + 1*a + 1*d + 7add. + add(other: Point) { + aedpoint(other); + const { a, d } = CURVE; + const { X: X1, Y: Y1, Z: Z1, T: T1 } = this; + const { X: X2, Y: Y2, Z: Z2, T: T2 } = other; + const A = modP(X1 * X2); // A = X1*X2 + const B = modP(Y1 * Y2); // B = Y1*Y2 + const C = modP(T1 * d * T2); // C = T1*d*T2 + const D = modP(Z1 * Z2); // D = Z1*Z2 + const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B + const F = D - C; // F = D-C + const G = D + C; // G = D+C + const H = modP(B - a * A); // H = B-a*A + const X3 = modP(E * F); // X3 = E*F + const Y3 = modP(G * H); // Y3 = G*H + const T3 = modP(E * H); // T3 = E*H + const Z3 = modP(F * G); // Z3 = F*G + return new Point(X3, Y3, Z3, T3); + } + + subtract(other: Point): Point { + // Validate before calling `negate()` so wrong inputs fail with the point guard + // instead of leaking a foreign `negate()` error. + aedpoint(other); + return this.add(other.negate()); + } + + // Constant-time multiplication. + multiply(scalar: bigint): Point { + // 1 <= scalar < L + // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO. + // In keygen/signing-style callers, those values usually mean broken hash/scalar plumbing, + // and failing closed is safer than silently producing the identity point. + if (!Fn.isValidNot0(scalar)) + throw new RangeError('invalid scalar: expected 1 <= sc < curve.n'); + const { p, f } = wnaf.cached(this, scalar, (p) => normalizeZ(Point, p)); + return normalizeZ(Point, [p, f])[0]; + } + + // Non-constant-time multiplication. Uses double-and-add algorithm. + // It's faster, but should only be used when you don't care about + // an exposed private key e.g. sig verification. + // Keeps the same subgroup-scalar contract: 0 is allowed for public-scalar callers, but + // n and larger values are rejected instead of being reduced mod n to the identity point. + multiplyUnsafe(scalar: bigint): Point { + // 0 <= scalar < L + if (!Fn.isValid(scalar)) throw new RangeError('invalid scalar: expected 0 <= sc < curve.n'); + if (scalar === _0n) return Point.ZERO; + if (this.is0() || scalar === _1n) return this; + return wnaf.unsafe(this, scalar, (p) => normalizeZ(Point, p)); + } + + // Checks if point is of small order. + // If you add something to small order point, you will have "dirty" + // point with torsion component. + // Clears cofactor and checks if the result is 0. + isSmallOrder(): boolean { + return this.clearCofactor().is0(); + } + + // Multiplies point by curve order and checks if the result is 0. + // Returns `false` is the point is dirty. + isTorsionFree(): boolean { + return wnaf.unsafe(this, CURVE.n).is0(); + } + + // Converts Extended point to default (x, y) coordinates. + // Can accept precomputed Z^-1 - for example, from invertBatch. + toAffine(invertedZ?: bigint): AffinePoint { + const p = this; + let iz = invertedZ; + const { X, Y, Z } = p; + const is0 = p.is0(); + if (iz == null) iz = is0 ? _8n : (Fp.inv(Z) as bigint); // 8 was chosen arbitrarily + const x = modP(X * iz); + const y = modP(Y * iz); + const zz = Fp.mul(Z, iz); + if (is0) return { x: _0n, y: _1n }; + if (zz !== _1n) throw new Error('invZ was invalid'); + return { x, y }; + } + + clearCofactor(): Point { + if (cofactor === _1n) return this; + return this.multiplyUnsafe(cofactor); + } + + toBytes(): Uint8Array { + const { x, y } = this.toAffine(); + // Fp.toBytes() allows non-canonical encoding of y (>= p). + const bytes = Fp.toBytes(y); + // Each y has 2 valid points: (x, y), (x,-y). + // When compressing, it's enough to store y and use the last byte to encode sign of x + bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; + return bytes; + } + toHex(): string { + return bytesToHex(this.toBytes()); + } + + toString() { + return ``; + } + } + const wnaf = new wNAF(Point, Fn.BITS); + // Keep constructor work cheap: subgroup/generator validation belongs to the caller's curve + // parameters, and doing the extra checks here adds about 10-15ms to heavy module imports. + // Callers that construct custom curves are responsible for supplying the correct base point. + // try { + // Point.BASE.assertValidity(); + // if (!Point.BASE.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + // } catch { + // throw new Error('bad curve params: generator point'); + // } + // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the + // eager W=8 cache there instead of rejecting an otherwise valid constructor. + if (Fn.BITS >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + Object.freeze(Point.prototype); + Object.freeze(Point); + return Point; +} + +/** + * Base class for prime-order points like Ristretto255 and Decaf448. + * These points eliminate cofactor issues by representing equivalence classes + * of Edwards curve points. Multiple Edwards representatives can describe the + * same abstract wrapper element, so wrapper validity is not the same thing as + * the hidden representative being torsion-free. + * @param ep - Backing Edwards point. + * @example + * Base class for prime-order points like Ristretto255 and Decaf448. + * + * ```ts + * import { ristretto255 } from '@noble/curves/ed25519.js'; + * const point = ristretto255.Point.BASE.multiply(2n); + * ``` + */ +export abstract class PrimeEdwardsPoint> + implements CurvePoint +{ + static BASE: PrimeEdwardsPoint; + static ZERO: PrimeEdwardsPoint; + static Fp: IField; + static Fn: IField; + + protected readonly ep: EdwardsPoint; + + /** + * Wrap one internal Edwards representative directly. + * This is not a canonical encoding boundary: alternate Edwards + * representatives may still describe the same abstract wrapper element. + */ + constructor(ep: EdwardsPoint) { + this.ep = ep; + } + + // Abstract methods that must be implemented by subclasses + abstract toBytes(): Uint8Array; + abstract equals(other: T): boolean; + + // Static methods that must be implemented by subclasses + static fromBytes(_bytes: Uint8Array): any { + notImplemented(); + } + + static fromHex(_hex: string): any { + notImplemented(); + } + + get x(): bigint { + return this.toAffine().x; + } + get y(): bigint { + return this.toAffine().y; + } + + // Common implementations + clearCofactor(): T { + // no-op for the abstract prime-order wrapper group; this is about the + // wrapper element, not the hidden Edwards representative. + return this as any; + } + + assertValidity(): void { + // Keep wrapper validity at the abstract-group boundary. Canonical decode + // may choose Edwards representatives that differ by small torsion, so + // checking `this.ep.isTorsionFree()` here would reject valid wrapper points. + this.ep.assertValidity(); + } + + /** + * Return affine coordinates of the current internal Edwards representative. + * This is a convenience helper, not a canonical Ristretto/Decaf encoding. + * Equal abstract elements may expose different `x` / `y`; use + * `toBytes()` / `fromBytes()` for canonical roundtrips. + */ + toAffine(invertedZ?: bigint): AffinePoint { + return this.ep.toAffine(invertedZ); + } + + toHex(): string { + return bytesToHex(this.toBytes()); + } + + toString(): string { + return this.toHex(); + } + + isTorsionFree(): boolean { + // Abstract Ristretto/Decaf elements are already prime-order even when the + // hidden Edwards representative is not torsion-free. + return true; + } + + isSmallOrder(): boolean { + return false; + } + + add(other: T): T { + this.assertSame(other); + return this.init(this.ep.add(other.ep)); + } + + subtract(other: T): T { + this.assertSame(other); + return this.init(this.ep.subtract(other.ep)); + } + + multiply(scalar: bigint): T { + return this.init(this.ep.multiply(scalar)); + } + + multiplyUnsafe(scalar: bigint): T { + return this.init(this.ep.multiplyUnsafe(scalar)); + } + + double(): T { + return this.init(this.ep.double()); + } + + negate(): T { + return this.init(this.ep.negate()); + } + + precompute(windowSize?: number, isLazy?: boolean): T { + this.ep.precompute(windowSize, isLazy); + // Keep the wrapper identity stable like the backing Edwards API instead of + // allocating a fresh wrapper around the same cached point. + return this as unknown as T; + } + + // Helper methods + abstract is0(): boolean; + protected abstract assertSame(other: T): void; + protected abstract init(ep: EdwardsPoint): T; +} + +/** + * Initializes EdDSA signatures over given Edwards curve. + * @param Point - Edwards point constructor. + * @param cHash - Hash function. + * @param eddsaOpts - Optional signature helpers. See {@link EdDSAOpts}. + * @returns EdDSA helper namespace. + * @throws If the hash function, options, or derived point operations are invalid. {@link Error} + * @example + * Initializes EdDSA signatures over given Edwards curve. + * + * ```ts + * import { eddsa } from '@noble/curves/abstract/edwards.js'; + * import { jubjub } from '@noble/curves/misc.js'; + * import { sha512 } from '@noble/hashes/sha2.js'; + * const sigs = eddsa(jubjub.Point, sha512); + * const { secretKey, publicKey } = sigs.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = sigs.sign(msg, secretKey); + * const isValid = sigs.verify(sig, msg, publicKey); + * ``` + */ +export function eddsa( + Point: EdwardsPointCons, + cHash: TArg, + eddsaOpts: TArg = {} +): EdDSA { + if (typeof cHash !== 'function') throw new Error('"hash" function param is required'); + const hash = cHash as FHash; + const opts = eddsaOpts as EdDSAOpts; + validateObject( + opts, + {}, + { + adjustScalarBytes: 'function', + randomBytes: 'function', + domain: 'function', + prehash: 'function', + zip215: 'boolean', + mapToCurve: 'function', + } + ); + + const { prehash } = opts; + const { BASE, Fp, Fn } = Point; + const outputLen = (hash as FHash & { outputLen?: number }).outputLen; + const expectedLen = 2 * Fp.BYTES; + // When hash metadata is available, reject incompatible EdDSA wrappers at construction time + // instead of deferring the mismatch until the first keygen/sign call. + if (outputLen !== undefined) { + asafenumber(outputLen, 'hash.outputLen'); + if (outputLen !== expectedLen) + throw new Error(`hash.outputLen must be ${expectedLen}, got ${outputLen}`); + } + + const randomBytes = opts.randomBytes === undefined ? wcRandomBytes : opts.randomBytes; + const adjustScalarBytes = + opts.adjustScalarBytes === undefined + ? (bytes: TArg) => bytes as TRet + : opts.adjustScalarBytes; + const domain = + opts.domain === undefined + ? (data: TArg, ctx: TArg, phflag: boolean) => { + abool(phflag, 'phflag'); + if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported'); + return data as TRet; + } + : opts.domain; // NOOP + + // Parse an EdDSA digest as a little-endian integer and reduce it modulo the scalar field order. + function modN_LE(hash: TArg): bigint { + return Fn.create(bytesToNumberLE(hash)); // Not Fn.fromBytes: it has length limit + } + + // Get the hashed private scalar per RFC8032 5.1.5 + function getPrivateScalar(key: TArg) { + const len = lengths.secretKey; + abytes(key, lengths.secretKey, 'secretKey'); + // Hash private key with curve's hash function to produce uniformingly random input + // Check byte lengths: ensure(64, h(ensure(32, key))) + const hashed = abytes(hash(key), 2 * len, 'hashedSecretKey'); + // Slice before clamping so in-place adjustors don't corrupt the prefix half. + const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE + const prefix = hashed.slice(len, 2 * len) as TRet; // second half is called key prefix (5.1.6) + const scalar = modN_LE(head); // The actual private scalar + return { head, prefix, scalar }; + } + + /** Convenience method that creates public key from scalar. RFC8032 5.1.5 + * Also exposes the derived scalar/prefix tuple and point form reused by sign(). + */ + function getExtendedPublicKey(secretKey: TArg) { + const { head, prefix, scalar } = getPrivateScalar(secretKey); + const point = BASE.multiply(scalar); // Point on Edwards curve aka public key + const pointBytes = point.toBytes() as TRet; + return { head, prefix, scalar, point, pointBytes }; + } + + /** Calculates EdDSA pub key. RFC8032 5.1.5. */ + function getPublicKey(secretKey: TArg): TRet { + return getExtendedPublicKey(secretKey).pointBytes; + } + + // Hash domain-separated chunks into a little-endian scalar modulo the group order. + function hashDomainToScalar( + context: TArg = Uint8Array.of(), + ...msgs: TArg + ) { + const msg = concatBytes(...msgs); + return modN_LE(hash(domain(msg, abytes(context, undefined, 'context'), !!prehash))); + } + + /** Signs message with secret key. RFC8032 5.1.6 */ + function sign( + msg: TArg, + secretKey: TArg, + options: TArg<{ context?: Uint8Array }> = {} + ): TRet { + msg = abytes(msg, undefined, 'message'); + if (prehash) msg = prehash(msg); // for ed25519ph etc. + const { prefix, scalar, pointBytes } = getExtendedPublicKey(secretKey); + const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M) + // RFC 8032 5.1.6 allows r mod L = 0, and SUPERCOP ref10 accepts the resulting identity-point + // signature. + // We intentionally keep the safe multiply() rejection here so a miswired all-zero hash provider + // fails loudly instead of silently producing a degenerate signature. + const R = BASE.multiply(r).toBytes(); // R = rG + const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M) + const s = Fn.create(r + k * scalar); // S = (r + k * s) mod L + if (!Fn.isValid(s)) throw new Error('sign failed: invalid s'); // 0 <= s < L + const rs = concatBytes(R, Fn.toBytes(s)); + return abytes(rs, lengths.signature, 'result') as TRet; + } + + // Keep the shared helper strict by default: RFC 8032 / NIST-style wrappers should reject + // non-canonical encodings unless they explicitly opt into ZIP-215's more permissive decode rules. + const verifyOpts: TArg<{ context?: Uint8Array; zip215?: boolean }> = { + zip215: opts.zip215, + }; + + /** + * Verifies EdDSA signature against message and public key. RFC 8032 §§5.1.7 and 5.2.7. + * A cofactored verification equation is checked. + */ + function verify( + sig: TArg, + msg: TArg, + publicKey: TArg, + options = verifyOpts + ): boolean { + // Preserve the wrapper-selected default for `{}` / `{ zip215: undefined }`, not just omitted opts. + const { context } = options; + const zip215 = options.zip215 === undefined ? !!verifyOpts.zip215 : options.zip215; + const len = lengths.signature; + sig = abytes(sig, len, 'signature'); + msg = abytes(msg, undefined, 'message'); + publicKey = abytes(publicKey, lengths.publicKey, 'publicKey'); + if (zip215 !== undefined) abool(zip215, 'zip215'); + if (prehash) msg = prehash(msg); // for ed25519ph, etc + + const mid = len / 2; + const r = sig.subarray(0, mid); + const s = bytesToNumberLE(sig.subarray(mid, len)); + let A, R, SB; + try { + // ZIP-215 is more permissive than RFC 8032 / NIST186-5. Use it only for wrappers that + // explicitly want consensus-style unreduced encoding acceptance. + // zip215=true: 0 <= y < MASK (2^256 for ed25519) + // zip215=false: 0 <= y < P (2^255-19 for ed25519) + A = Point.fromBytes(publicKey, zip215); + R = Point.fromBytes(r, zip215); + SB = BASE.multiplyUnsafe(s); // 0 <= s < l is done inside + } catch (error) { + return false; + } + // RFC 8032 §§5.1.7/5.2.7 and FIPS 186-5 §§7.7.2/7.8.2 only decode A' and check the cofactored + // verification equation; they do not add a separate low-order-public-key rejection here. + // Strict mode still rejects small-order A' intentionally for SBS-style non-repudiation and to + // avoid ambiguous verification outcomes where unusual low-order keys can make distinct + // key/signature/message combinations verify. + if (!zip215 && A.isSmallOrder()) return false; + + // ZIP-215 accepts noncanonical / unreduced point encodings, so the challenge hash must use the + // exact signature/public-key bytes rather than canonicalized re-encodings of the decoded points. + const k = hashDomainToScalar(context, r, publicKey, msg); + const RkA = R.add(A.multiplyUnsafe(k)); + // Check the cofactored verification equation via the curve cofactor h. + // [h][S]B = [h]R + [h][k]A' + return RkA.subtract(SB).clearCofactor().is0(); + } + + const _size = Fp.BYTES; // 32 for ed25519, 57 for ed448 + const lengths = { + secretKey: _size, + publicKey: _size, + signature: 2 * _size, + seed: _size, + }; + function randomSecretKey(seed?: TArg): TRet { + seed = seed === undefined ? randomBytes(lengths.seed) : seed; + return abytes(seed, lengths.seed, 'seed') as TRet; + } + + function isValidSecretKey(key: TArg): boolean { + return isBytes(key) && key.length === lengths.secretKey; + } + + function isValidPublicKey(key: TArg, zip215?: boolean): boolean { + try { + // Preserve the wrapper-selected default for omitted / `undefined` ZIP-215 flags here too. + return !!Point.fromBytes(key, zip215 === undefined ? verifyOpts.zip215 : zip215); + } catch (error) { + return false; + } + } + + const utils = { + getExtendedPublicKey, + randomSecretKey, + isValidSecretKey, + isValidPublicKey, + /** + * Converts ed public key to x public key. Uses formula: + * - ed25519: + * - `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)` + * - `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))` + * - ed448: + * - `(u, v) = ((y-1)/(y+1), sqrt(156324)*u/x)` + * - `(x, y) = (sqrt(156324)*u/v, (1+u)/(1-u))` + */ + toMontgomery(publicKey: TArg): TRet { + const { y } = Point.fromBytes(publicKey); + const size = lengths.publicKey; + const is25519 = size === 32; + if (!is25519 && size !== 57) throw new Error('only defined for 25519 and 448'); + const u = is25519 ? Fp.div(_1n + y, _1n - y) : Fp.div(y - _1n, y + _1n); + return Fp.toBytes(u) as TRet; + }, + toMontgomerySecret(secretKey: TArg): TRet { + const size = lengths.secretKey; + abytes(secretKey, size); + const hashed = hash(secretKey.subarray(0, size)); + return adjustScalarBytes(hashed).subarray(0, size) as TRet; + }, + }; + Object.freeze(lengths); + Object.freeze(utils); + + return Object.freeze({ + keygen: createKeygen(randomSecretKey, getPublicKey), + getPublicKey, + sign, + verify, + utils, + Point, + lengths, + }) satisfies Signer; +} diff --git a/node_modules/@noble/curves/src/abstract/fft.ts b/node_modules/@noble/curves/src/abstract/fft.ts new file mode 100644 index 0000000..3edd51b --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/fft.ts @@ -0,0 +1,854 @@ +/** + * Experimental implementation of NTT / FFT (Fast Fourier Transform) over finite fields. + * API may change at any time. The code has not been audited. Feature requests are welcome. + * @module + */ +import type { TArg } from '../utils.ts'; +import type { IField } from './modular.ts'; + +/** Array-like coefficient storage that can be mutated in place. */ +export interface MutableArrayLike { + /** Element access by numeric index. */ + [index: number]: T; + /** Current amount of stored coefficients. */ + length: number; + /** + * Return a sliced copy using the same storage shape. + * @param start - Inclusive start index. + * @param end - Exclusive end index. + * @returns Sliced copy. + */ + slice(start?: number, end?: number): this; + /** + * Iterate over stored coefficients in order. + * @returns Coefficient iterator. + */ + [Symbol.iterator](): Iterator; +} + +/** + * Concrete polynomial containers accepted by the high-level `poly(...)` helpers. + * Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)` + * intentionally keeps runtime dispatch on plain arrays and typed-array views. + */ +export type PolyStorage = T[] | (MutableArrayLike & ArrayBufferView); + +function checkU32(n: number) { + // 0xff_ff_ff_ff + if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff) + throw new Error('wrong u32 integer:' + n); + return n; +} + +/** + * Checks if integer is in form of `1 << X`. + * @param x - Integer to inspect. + * @returns `true` when the value is a power of two. + * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Validate that an FFT size is a power of two. + * + * ```ts + * isPowerOfTwo(8); + * ``` + */ +export function isPowerOfTwo(x: number): boolean { + checkU32(x); + return (x & (x - 1)) === 0 && x !== 0; +} + +/** + * @param n - Input value. + * @returns Next power of two within the u32/array-length domain. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Round an integer up to the FFT size it needs. + * + * ```ts + * nextPowerOfTwo(9); + * ``` + */ +export function nextPowerOfTwo(n: number): number { + checkU32(n); + if (n <= 1) return 1; + // FFT sizes here are used as JS array lengths, so `2^32` is not a meaningful result: + // keep the fast u32 bit-twiddling path and fail explicitly instead of wrapping to 1. + if (n > 0x8000_0000) throw new Error('nextPowerOfTwo overflow: result does not fit u32'); + return (1 << (log2(n - 1) + 1)) >>> 0; +} + +/** + * @param n - Value to reverse. + * @param bits - Number of bits to use. + * @returns Bit-reversed integer. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Reverse the low `bits` bits of one index. + * + * ```ts + * reverseBits(3, 3); + * ``` + */ +export function reverseBits(n: number, bits: number): number { + checkU32(n); + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`); + let reversed = 0; + for (let i = 0; i < bits; i++, n >>>= 1) reversed = (reversed << 1) | (n & 1); + // JS bitwise ops are signed i32; cast back so 32-bit reversals stay in the unsigned u32 domain. + return reversed >>> 0; +} + +/** + * Similar to `bitLen(x)-1` but much faster for small integers, like indices. + * @param n - Input value. + * @returns Base-2 logarithm. For `n = 0`, the current implementation returns `-1`. + * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error} + * @example + * Compute the radix-2 stage count for one transform size. + * + * ```ts + * log2(8); + * ``` + */ +export function log2(n: number): number { + checkU32(n); + return 31 - Math.clz32(n); +} + +/** + * Moves lowest bit to highest position, which at first step splits + * array on even and odd indices, then it applied again to each part, + * which is core of fft + * @param values - Mutable coefficient array. + * @returns Mutated input array. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Reorder coefficients into bit-reversed order in place. + * + * ```ts + * const values = Uint8Array.from([0, 1, 2, 3]); + * bitReversalInplace(values); + * ``` + */ +export function bitReversalInplace>(values: T): T { + const n = values.length; + // Size-1 FFT is the identity, so bit-reversal must stay a no-op there instead of rejecting it. + if (!isPowerOfTwo(n)) throw new Error('expected positive power-of-two length, got ' + n); + const bits = log2(n); + for (let i = 0; i < n; i++) { + const j = reverseBits(i, bits); + if (i < j) { + const tmp = values[i]; + values[i] = values[j]; + values[j] = tmp; + } + } + return values; +} + +/** + * @param values - Input values. + * @returns Reordered copy. + * @throws If the array length is not a positive power of two. {@link Error} + * @example + * Return a reordered copy instead of mutating the input in place. + * + * ```ts + * const reordered = bitReversalPermutation([0, 1, 2, 3]); + * ``` + */ +export function bitReversalPermutation(values: T[]): T[] { + return bitReversalInplace(values.slice()) as T[]; +} + +const _1n = /** @__PURE__ */ BigInt(1); +function findGenerator(field: TArg>) { + let G = BigInt(2); + for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++); + return G; +} + +/** Cached roots-of-unity tables derived from one finite field. */ +export type RootsOfUnity = { + /** Generator and 2-adicity metadata for the cached field. */ + info: { G: bigint; oddFactor: bigint; powerOfTwo: number }; + /** + * Return the natural-order roots of unity for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Natural-order roots for that size. + */ + roots: (bits: number) => bigint[]; + /** + * Return the bit-reversal permutation of the roots for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Bit-reversed roots. + */ + brp(bits: number): bigint[]; + /** + * Return the inverse roots of unity for one radix-2 size. + * @param bits - Transform size as `log2(N)`. + * @returns Inverse roots. + */ + inverse(bits: number): bigint[]; + /** + * Return one primitive root used by a radix-2 stage. + * @param bits - Transform size as `log2(N)`. + * @returns Primitive root for that stage. + */ + omega: (bits: number) => bigint; + /** + * Drop all cached root tables. + * @returns Nothing. + */ + clear: () => void; +}; +/** + * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare. + * @param field - Field implementation. + * @param generator - Optional generator override. + * @returns Roots-of-unity cache. + * @example + * Cache roots once, then ask for the omega table of one FFT size. + * + * ```ts + * import { rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const roots = rootsOfUnity(Field(17n)); + * const omega = roots.omega(4); + * ``` + */ +export function rootsOfUnity(field: TArg>, generator?: bigint): RootsOfUnity { + // Factor field.ORDER-1 as oddFactor * 2^powerOfTwo + let oddFactor = field.ORDER - _1n; + let powerOfTwo = 0; + for (; (oddFactor & _1n) !== _1n; powerOfTwo++, oddFactor >>= _1n); + + // Find non quadratic residue + let G = generator !== undefined ? BigInt(generator) : findGenerator(field); + // Powers of generator + const omegas: bigint[] = new Array(powerOfTwo + 1); + omegas[powerOfTwo] = field.pow(G, oddFactor); + for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]); + // Compute all roots of unity for powers up to maxPower + const rootsCache: bigint[][] = []; + const checkBits = (bits: number) => { + checkU32(bits); + if (bits > 31 || bits > powerOfTwo) + throw new Error('rootsOfUnity: wrong bits ' + bits + ' powerOfTwo=' + powerOfTwo); + return bits; + }; + const precomputeRoots = (maxPower: number) => { + checkBits(maxPower); + for (let power = maxPower; power >= 0; power--) { + if (rootsCache[power]) continue; // Skip if we've already computed roots for this power + const rootsAtPower: bigint[] = []; + for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power])) + rootsAtPower.push(cur); + rootsCache[power] = rootsAtPower; + } + return rootsCache[maxPower]; + }; + const brpCache = new Map(); + const inverseCache = new Map(); + // roots()/brp()/inverse() expose shared cached arrays by reference for speed; callers must treat them as read-only. + + // NOTE: we use bits instead of power, because power = 2**bits, + // but power is not neccesary isPowerOfTwo(power)! + return { + info: { G, powerOfTwo, oddFactor }, + roots: (bits: number): bigint[] => { + const b = checkBits(bits); + return precomputeRoots(b); + }, + brp(bits: number): bigint[] { + const b = checkBits(bits); + if (brpCache.has(b)) return brpCache.get(b)!; + else { + const res = bitReversalPermutation(this.roots(b)); + brpCache.set(b, res); + return res; + } + }, + inverse(bits: number): bigint[] { + const b = checkBits(bits); + if (inverseCache.has(b)) return inverseCache.get(b)!; + else { + const res = field.invertBatch(this.roots(b)); + inverseCache.set(b, res); + return res; + } + }, + omega: (bits: number): bigint => omegas[checkBits(bits)], + clear: (): void => { + rootsCache.splice(0, rootsCache.length); + brpCache.clear(); + inverseCache.clear(); + }, + }; +} + +/** Polynomial coefficient container used by the FFT helpers. */ +export type Polynomial = MutableArrayLike; + +/** + * Arithmetic operations used by the generic FFT implementation. + * + * Maps great to Field, but not to Group (EC points): + * - inv from scalar field + * - we need multiplyUnsafe here, instead of multiply for speed + * - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse + */ +export type FFTOpts = { + /** + * Add two coefficients. + * @param a - Left coefficient. + * @param b - Right coefficient. + * @returns Sum coefficient. + */ + add: (a: T, b: T) => T; + /** + * Subtract two coefficients. + * @param a - Left coefficient. + * @param b - Right coefficient. + * @returns Difference coefficient. + */ + sub: (a: T, b: T) => T; + /** + * Multiply one coefficient by a scalar/root factor. + * @param a - Coefficient value. + * @param scalar - Scalar/root factor. + * @returns Scaled coefficient. + */ + mul: (a: T, scalar: R) => T; + /** + * Invert one scalar/root factor. + * @param a - Scalar/root factor. + * @returns Inverse factor. + */ + inv: (a: R) => R; +}; + +/** Configuration for one low-level FFT loop. */ +export type FFTCoreOpts = { + /** Transform size. Must be a power of two. */ + N: number; + /** Stage roots for the selected transform size. */ + roots: Polynomial; + /** Whether to run the DIT variant instead of DIF. */ + dit: boolean; + /** Whether to invert butterfly placement for decode-oriented layouts. */ + invertButterflies?: boolean; + /** Number of initial stages to skip. */ + skipStages?: number; + /** Whether to apply bit-reversal permutation at the boundary. */ + brp?: boolean; +}; + +/** + * Callable low-level FFT loop over one polynomial storage shape. + * @param values - Polynomial coefficients to transform in place. + * @returns The mutated input polynomial. + */ +export type FFTCoreLoop =

>(values: P) => P; + +/** + * Constructs different flavors of FFT. radix2 implementation of low level mutating API. Flavors: + * + * - DIT (Decimation-in-Time): Bottom-Up (leaves to root), Cool-Turkey + * - DIF (Decimation-in-Frequency): Top-Down (root to leaves), Gentleman-Sande + * + * DIT takes brp input, returns natural output. + * DIF takes natural input, returns brp output. + * + * The output is actually identical. Time / frequence distinction is not meaningful + * for Polynomial multiplication in fields. + * Which means if protocol supports/needs brp output/inputs, then we can skip this step. + * + * Cyclic NTT: Rq = Zq[x]/(x^n-1). butterfly_DIT+loop_DIT OR butterfly_DIF+loop_DIT, roots are omega + * Negacyclic NTT: Rq = Zq[x]/(x^n+1). butterfly_DIT+loop_DIF, at least for mlkem / mldsa + * @param F - Field operations. + * @param coreOpts - FFT configuration: + * - `N`: Transform size. Must be a power of two. + * - `roots`: Stage roots for the selected transform size. + * - `dit`: Whether to run the DIT variant instead of DIF. + * - `invertButterflies` (optional): Whether to invert butterfly placement. + * - `skipStages` (optional): Number of initial stages to skip. + * - `brp` (optional): Whether to apply bit-reversal permutation at the boundary. + * @returns Low-level FFT loop. + * @throws If the FFT options or cached roots are invalid for the requested size. {@link Error} + * @example + * Constructs different flavors of FFT. + * + * ```ts + * import { FFTCore, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const roots = rootsOfUnity(Fp).roots(2); + * const loop = FFTCore(Fp, { N: 4, roots, dit: true }); + * const values = loop([1n, 2n, 3n, 4n]); + * ``` + */ +export const FFTCore = (F: FFTOpts, coreOpts: FFTCoreOpts): FFTCoreLoop => { + const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts; + const bits = log2(N); + if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two'); + // Wrong-sized root tables can stay in-bounds for some loop shapes and silently compute nonsense. + if (roots.length !== N) + throw new Error(`FFT: wrong roots length: expected ${N}, got ${roots.length}`); + const isDit = dit !== invertButterflies; + isDit; + return

>(values: P): P => { + if (values.length !== N) throw new Error('FFT: wrong Polynomial length'); + if (dit && brp) bitReversalInplace(values); + for (let i = 0, g = 1; i < bits - skipStages; i++) { + // For each stage s (sub-FFT length m = 2^s) + const s = dit ? i + 1 + skipStages : bits - i; + const m = 1 << s; + const m2 = m >> 1; + const stride = N >> s; + // Loop over each subarray of length m + for (let k = 0; k < N; k += m) { + // Loop over each butterfly within the subarray + for (let j = 0, grp = g++; j < m2; j++) { + const rootPos = invertButterflies ? (dit ? N - grp : grp) : j * stride; + const i0 = k + j; + const i1 = k + j + m2; + const omega = roots[rootPos]; + const b = values[i1]; + const a = values[i0]; + // Inlining gives us 10% perf in kyber vs functions + if (isDit) { + const t = F.mul(b, omega); // Standard DIT butterfly + values[i0] = F.add(a, t); + values[i1] = F.sub(a, t); + } else if (invertButterflies) { + values[i0] = F.add(b, a); // DIT loop + inverted butterflies (Kyber decode) + values[i1] = F.mul(F.sub(b, a), omega); + } else { + values[i0] = F.add(a, b); // Standard DIF butterfly + values[i1] = F.mul(F.sub(a, b), omega); + } + } + } + } + if (!dit && brp) bitReversalInplace(values); + return values; + }; +}; + +/** Forward and inverse FFT helpers for one coefficient domain. */ +export type FFTMethods = { + /** + * Apply the forward transform. + * @param values - Polynomial coefficients to transform. + * @param brpInput - Whether the input is already bit-reversed. + * @param brpOutput - Whether to keep the output bit-reversed. + * @returns Transformed copy. + */ + direct

>(values: P, brpInput?: boolean, brpOutput?: boolean): P; + /** + * Apply the inverse transform. + * @param values - Polynomial coefficients to transform. + * @param brpInput - Whether the input is already bit-reversed. + * @param brpOutput - Whether to keep the output bit-reversed. + * @returns Inverse-transformed copy. + */ + inverse

>(values: P, brpInput?: boolean, brpOutput?: boolean): P; +}; + +/** + * NTT aka FFT over finite field (NOT over complex numbers). + * Naming mirrors other libraries. + * @param roots - Roots-of-unity cache. + * @param opts - Field operations. See {@link FFTOpts}. + * @returns Forward and inverse FFT helpers. + * @example + * NTT aka FFT over finite field (NOT over complex numbers). + * + * ```ts + * import { FFT, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const fft = FFT(rootsOfUnity(Fp), Fp); + * const values = fft.direct([1n, 2n, 3n, 4n]); + * ``` + */ +export function FFT(roots: RootsOfUnity, opts: FFTOpts): FFTMethods { + const getLoop = ( + N: number, + roots: Polynomial, + brpInput = false, + brpOutput = false + ): (

>(values: P) => P) => { + if (brpInput && brpOutput) { + // we cannot optimize this case, but lets support it anyway + return (values) => + FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values)); + } + if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false }); + if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false }); + return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural + }; + return { + direct

>(values: P, brpInput = false, brpOutput = false): P { + const N = values.length; + if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two'); + const bits = log2(N); + return getLoop(N, roots.roots(bits), brpInput, brpOutput)

(values.slice()); + }, + inverse

>(values: P, brpInput = false, brpOutput = false): P { + const N = values.length; + if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two'); + const bits = log2(N); + const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(values.slice()); + const ivm = opts.inv(BigInt(values.length)); // scale + // we can get brp output if we use dif instead of dit! + for (let i = 0; i < res.length; i++) res[i] = opts.mul(res[i], ivm); + // Allows to re-use non-inverted roots, but is VERY fragile + // return [res[0]].concat(res.slice(1).reverse()); + // inverse calculated as pow(-1), which transforms into ω^{-kn} (-> reverses indices) + return res; + }, + }; +} + +/** + * Factory that allocates one polynomial storage container. + * Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted, + * because the quadratic `mul()` / `convolve()` paths and the Kronecker-δ shortcut in + * `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly. + * @param len - Requested amount of coefficients. + * @param elm - Optional fill value. + * @returns Newly allocated polynomial container. + */ +export type CreatePolyFn

, T> = (len: number, elm?: T) => P; + +/** High-level polynomial helpers layered on top of FFT and field arithmetic. */ +export type PolyFn

, T> = { + /** Roots-of-unity cache used by the helper namespace. */ + roots: RootsOfUnity; + /** Factory used to allocate new polynomial containers. */ + create: CreatePolyFn; + /** Optional enforced polynomial length. */ + length?: number; + + /** + * Compute the polynomial degree. + * @param a - Polynomial coefficients. + * @returns Polynomial degree. + */ + degree: (a: P) => number; + /** + * Extend or truncate one polynomial to a requested length. + * @param a - Polynomial coefficients. + * @param len - Target length. + * @returns Resized polynomial. + */ + extend: (a: P, len: number) => P; + /** + * Add two polynomials coefficient-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Sum polynomial. + */ + add: (a: P, b: P) => P; + /** + * Subtract two polynomials coefficient-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Difference polynomial. + */ + sub: (a: P, b: P) => P; + /** + * Multiply by another polynomial or by one scalar. + * @param a - Left polynomial. + * @param b - Right polynomial or scalar. + * @returns Product polynomial. + */ + mul: (a: P, b: P | T) => P; + /** + * Multiply coefficients point-wise. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Point-wise product polynomial. + */ + dot: (a: P, b: P) => P; + /** + * Multiply two polynomials with convolution. + * @param a - Left polynomial. + * @param b - Right polynomial. + * @returns Convolution product. + */ + convolve: (a: P, b: P) => P; + /** + * Apply a point-wise coefficient shift by powers of one factor. + * @param p - Polynomial coefficients. + * @param factor - Shift factor. + * @returns Shifted polynomial. + */ + shift: (p: P, factor: bigint) => P; + /** + * Clone one polynomial container. + * @param a - Polynomial coefficients. + * @returns Cloned polynomial. + */ + clone: (a: P) => P; + /** + * Evaluate one polynomial on a basis vector. + * @param a - Polynomial coefficients. + * @param basis - Basis vector. + * @returns Evaluated field element. + */ + eval: (a: P, basis: P) => T; + /** Helpers for monomial-basis polynomials. */ + monomial: { + /** Build the monomial basis vector for one evaluation point. */ + basis: (x: T, n: number) => P; + /** Evaluate a polynomial in the monomial basis. */ + eval: (a: P, x: T) => T; + }; + /** Helpers for Lagrange-basis polynomials. */ + lagrange: { + /** Build the Lagrange basis vector for one evaluation point. */ + basis: (x: T, n: number, brp?: boolean) => P; + /** Evaluate a polynomial in the Lagrange basis. */ + eval: (a: P, x: T, brp?: boolean) => T; + }; + /** + * Build the vanishing polynomial for a root set. + * @param roots - Root set. + * @returns Vanishing polynomial. + */ + vanishing: (roots: P) => P; +}; + +/** + * Poly wants a cracker. + * + * Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is + * function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways: + * + * - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))` + * - **Basis** is array of functions + * - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers) + * - **Array size** is domain size + * - **Lattice** is matrix (Polynomial of Polynomials) + * @param field - Field implementation. + * @param roots - Roots-of-unity cache. + * @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array` + * and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected. + * @param fft - Optional FFT implementation. + * @param length - Optional fixed polynomial length. + * @returns Polynomial helper namespace. + * @example + * Build polynomial helpers, then convolve two coefficient arrays. + * + * ```ts + * import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const poly17 = poly(Fp, rootsOfUnity(Fp)); + * const product = poly17.convolve([1n, 2n], [3n, 4n]); + * ``` + */ +export function poly( + field: TArg>, + roots: RootsOfUnity, + create?: undefined, + fft?: FFTMethods, + length?: number +): PolyFn; +export function poly>( + field: TArg>, + roots: RootsOfUnity, + create: CreatePolyFn, + fft?: FFTMethods, + length?: number +): PolyFn; +export function poly>( + field: TArg>, + roots: RootsOfUnity, + create?: CreatePolyFn, + fft?: FFTMethods, + length?: number +): PolyFn { + const F = field as IField; + const _create = + create || + (((len: number, elm?: T): T[] => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn); + + // `poly.mul(a, b)` distinguishes polynomial-vs-scalar at runtime, so keep accepted + // polynomial containers concrete instead of trying to support arbitrary wrappers. + const isPoly = (x: any): x is P => { + if (Array.isArray(x)) return true; + if (!ArrayBuffer.isView(x)) return false; + const v = x as unknown as ArrayLike & { slice?: unknown; [Symbol.iterator]?: unknown }; + return ( + typeof v.length === 'number' && + typeof v.slice === 'function' && + typeof v[Symbol.iterator] === 'function' + ); + }; + const checkLength = (...lst: P[]): number => { + if (!lst.length) return 0; + for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i); + const L = lst[0].length; + for (let i = 1; i < lst.length; i++) + if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`); + if (length !== undefined && L !== length) + throw new Error(`poly: expected fixed length ${length}, got ${L}`); + return L; + }; + function findOmegaIndex(x: T, n: number, brp = false): number { + const bits = log2(n); + const omega = brp ? roots.brp(bits) : roots.roots(bits); + for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) return i; + return -1; + } + // TODO: mutating versions for mlkem/mldsa + return { + roots, + create: _create, + length, + extend: (a: P, len: number): P => { + checkLength(a); + const out = _create(len, F.ZERO); + // Plain arrays grow when writing past `out.length`, so cap the copy explicitly to keep + // `extend()` consistent with typed arrays and with its documented truncate behavior. + for (let i = 0; i < Math.min(a.length, len); i++) out[i] = a[i]; + return out; + }, + degree: (a: P): number => { + checkLength(a); + for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i; + return -1; + }, + add: (a: P, b: P): P => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]); + return out; + }, + sub: (a: P, b: P): P => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]); + return out; + }, + dot: (a: P, b: P): P => { + const len = checkLength(a, b); + const out = _create(len); + for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]); + return out; + }, + mul: (a: P, b: P | T): P => { + if (isPoly(b)) { + const len = checkLength(a, b); + if (fft) { + const A = fft.direct(a, false, true); + const B = fft.direct(b, false, true); + for (let i = 0; i < A.length; i++) A[i] = F.mul(A[i], B[i]); + return fft.inverse(A, true, false) as P; + } else { + // NOTE: this is quadratic and mostly for compat tests with FFT + const res = _create(len); + for (let i = 0; i < len; i++) { + for (let j = 0; j < len; j++) { + const k = (i + j) % len; // wrap mod length + res[k] = F.add(res[k], F.mul(a[i], b[j])); + } + } + return res; + } + } else { + const out = _create(checkLength(a)); + for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b); + return out; + } + }, + convolve(a: P, b: P): P { + const len = nextPowerOfTwo(a.length + b.length - 1); + return this.mul(this.extend(a, len), this.extend(b, len)); + }, + shift(p: P, factor: bigint): P { + const out = _create(checkLength(p)); + out[0] = p[0]; + for (let i = 1, power = F.ONE; i < p.length; i++) { + power = F.mul(power, factor); + out[i] = F.mul(p[i], power); + } + return out; + }, + clone: (a: P): P => { + checkLength(a); + const out = _create(a.length); + for (let i = 0; i < a.length; i++) out[i] = a[i]; + return out; + }, + eval: (a: P, basis: P): T => { + checkLength(a, basis); + let acc = F.ZERO; + for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i])); + return acc; + }, + monomial: { + basis: (x: T, n: number): P => { + const out = _create(n); + let pow = F.ONE; + for (let i = 0; i < n; i++) { + out[i] = pow; + pow = F.mul(pow, x); + } + return out; + }, + eval: (a: P, x: T): T => { + checkLength(a); + // Same as eval(a, monomialBasis(x, a.length)), but it is faster this way + let acc = F.ZERO; + for (let i = a.length - 1; i >= 0; i--) acc = F.add(F.mul(acc, x), a[i]); + return acc; + }, + }, + lagrange: { + basis: (x: T, n: number, brp = false, weights?: P): P => { + const bits = log2(n); + const cache = weights || (brp ? roots.brp(bits) : roots.roots(bits)); // [ω⁰, ω¹, ..., ωⁿ⁻¹] + const out = _create(n); + // Fast Kronecker-δ shortcut + const idx = findOmegaIndex(x, n, brp); + if (idx !== -1) { + out[idx] = F.ONE; + return out; + } + const tm = F.pow(x, BigInt(n)); + const c = F.mul(F.sub(tm, F.ONE), F.inv(BigInt(n) as T)); // c = (xⁿ - 1)/n + const denom = _create(n); + for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T); + const inv = F.invertBatch(denom as any as T[]); + for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i])); + return out; + }, + eval(a: P, x: T, brp = false): T { + checkLength(a); + const idx = findOmegaIndex(x, a.length, brp); + if (idx !== -1) return a[idx]; // fast path + const L = this.basis(x, a.length, brp); // Lᵢ(x) + let acc = F.ZERO; + for (let i = 0; i < a.length; i++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i])); + return acc; + }, + }, + vanishing(roots: P): P { + checkLength(roots); + const out = _create(roots.length + 1, F.ZERO); + out[0] = F.ONE; + for (const r of roots) { + const neg = F.neg(r); + for (let j = out.length - 1; j > 0; j--) out[j] = F.add(F.mul(out[j], neg), out[j - 1]); + out[0] = F.mul(out[0], neg); + } + return out; + }, + }; +} diff --git a/node_modules/@noble/curves/src/abstract/frost.ts b/node_modules/@noble/curves/src/abstract/frost.ts new file mode 100644 index 0000000..6189b51 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/frost.ts @@ -0,0 +1,1092 @@ +/** + * FROST: Flexible Round-Optimized Schnorr Threshold Protocol for Two-Round Schnorr Signatures. + * + * See [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/) and [frost.zfnd.org](https://frost.zfnd.org). + * @module + */ +import { utf8ToBytes } from '@noble/hashes/utils.js'; +import { + bytesToHex, + bytesToNumberBE, + bytesToNumberLE, + concatBytes, + hexToBytes, + randomBytes, + validateObject, + type TArg, + type TRet, +} from '../utils.ts'; +import { pippenger, validatePointCons, type CurvePoint, type CurvePointCons } from './curve.ts'; +import { poly, type RootsOfUnity } from './fft.ts'; +import { type H2CDSTOpts } from './hash-to-curve.ts'; +import { getMinHashLength, mapHashToField, type IField } from './modular.ts'; + +export type RNG = typeof randomBytes; +export type Identifier = string; // Identifiers are hex to make comparison easier +export type Commitment = Uint8Array; // serialized point +export type Coefficient = Uint8Array; // serialized scalar +export type Signature = Uint8Array; +export type Signers = { min: number; max: number }; +export type SecretKey = Uint8Array; // Secret key +export type Bytes = Uint8Array; +type Point = Uint8Array; + +export type DKG_Round1 = { + // If identifiers were assigned via fromNumber before, it is worth checking + // that a party doesn't impersonate another one. + // But we throw on duplicate identifiers. + identifier: Identifier; + commitment: TRet; // sender identifier + proofOfKnowledge: TRet; +}; +export type DKG_Round2 = { + identifier: Identifier; // sender identifier + signingShare: TRet; +}; +// This is internal, so we can use bigints +export type DKG_Secret = { + identifier: bigint; + coefficients?: bigint[]; + commitment: TRet; + signers: Signers; + // Keep the local polynomial until round3 succeeds so late DKG failures can be retried. + step?: 1 | 2 | 3; +}; + +export type FrostPublic = { + signers: Signers; + commitments: TRet; // Point[], where commitments[0] is the group public key + verifyingShares: TRet>; // id -> Point +}; +export type FrostSecret = { + identifier: Identifier; + signingShare: TRet; // Scalar +}; +export type Key = { public: FrostPublic; secret: FrostSecret }; +export type DealerShares = { + public: FrostPublic; + secretShares: Record; +}; +// Sign stuff +export type Nonces = { + hiding: TRet; // Scalar + binding: TRet; // Scalar +}; +export type NonceCommitments = { + identifier: Identifier; + hiding: TRet; // Point + binding: TRet; // Point +}; +export type GenNonce = { + nonces: Nonces; + commitments: NonceCommitments; +}; + +export interface FROSTPoint> extends CurvePoint { + add(rhs: T): T; + multiply(rhs: bigint): T; + equals(rhs: T): boolean; + toBytes(compressed?: boolean): Bytes; + clearCofactor(): T; +} +export interface FROSTPointConstructor> extends CurvePointCons { + fromBytes(a: Bytes): T; + Fn: IField; +} + +// Opts +export type FrostOpts

> = { + readonly name: string; + readonly Point: FROSTPointConstructor

; + readonly Fn?: IField; + /** Optional suite hook that tightens canonical decoding with subgroup / identity checks. */ + readonly validatePoint?: (p: P) => void; + /** Optional public-key parser. Implementations MUST preserve the same subgroup / identity policy + * as `validatePoint`, because this bypasses generic canonical decoding in `parsePoint()`. */ + readonly parsePublicKey?: (bytes: TArg) => P; + readonly hash: (msg: TArg) => TRet; + /** Custom scalar hash hook. Implementations MUST treat `msg` and `options` as read-only. */ + readonly hashToScalar?: (msg: TArg, options?: TArg) => bigint; + // Hacks for taproot support + readonly adjustScalar?: (n: bigint) => bigint; + readonly adjustPoint?: (n: P) => P; + readonly challenge?: (R: P, PK: P, msg: TArg) => bigint; + readonly adjustNonces?: (PK: P, nonces: TArg) => TRet; + readonly adjustSecret?: (secret: TArg, pub: TArg) => TRet; + readonly adjustPublic?: (pub: TArg) => TRet; + readonly adjustGroupCommitmentShare?: (GC: P, GCShare: P) => P; + readonly adjustTx?: { + readonly encode: (tx: TArg) => TRet; + readonly decode: (tx: TArg) => TRet; + }; + readonly adjustDKG?: (k: TArg) => TRet; + // Hash function prefixes + readonly H1?: string; + readonly H2?: string; + readonly H3?: string; + readonly H4?: string; + readonly H5?: string; + readonly HDKG?: string; + readonly HID?: string; +}; + +/** + * FROST: Threshold Protocol for Two‑Round Schnorr Signatures + * from [RFC 9591](https://datatracker.ietf.org/doc/rfc9591/). + */ +export type FROST = { + /** + * Methods to construct participant identifiers. + */ + Identifier: { + /** + * Constructs an identifier from a numeric index. + * @param n - A positive integer. + * @returns A canonical serialized Identifier. + */ + fromNumber(n: number): Identifier; + /** + * Derives an identifier deterministically from a string (e.g. an email). + * @param s - Arbitrary string. + * @returns A canonical serialized Identifier. + */ + derive(s: string): Identifier; + }; + /** + * Distributed Key Generation (DKG) protocol interface. + * RFC 9591 leaves DKG out of scope; Appendix C only specifies dealer/VSS key generation. + * These helpers follow the split-round API used by frost-rs for interoperable testing. + */ + DKG: { + /** + * Generates the first round of DKG. + * @param id - Participant's identifier. + * @param signers - Set of all participants (min/max threshold). + * @param secret - Optional initial secret scalar. + * @param rng - Optional RNG for nonce generation. + * @returns Public broadcast and private DKG state. The returned `secret` package is mutable + * round state that will be consumed by `round2()` and `round3()`. + */ + round1: ( + id: Identifier, + signers: Signers, + secret?: TArg, + rng?: RNG + ) => { + public: DKG_Round1; + secret: DKG_Secret; + }; + /** + * Executes DKG round 2 given public round1 data from others. + * @param secret - Private DKG state from round1. This mutates `secret.step` in place. + * @param others - Public round1 broadcasts from other participants. + * @returns A map of round2 messages to be sent to others. + */ + round2: ( + secret: TArg, + others: TArg + ) => TRet>; + /** + * Finalizes key generation in round3 using received round1 + round2 messages. + * @param secret - Private DKG state. This consumes the remaining local polynomial coefficients + * and transitions the package to its final post-round3 state. + * @param round1 - Public round1 broadcasts from all participants. + * @param round2 - Round2 messages received from others. + * @returns Final secret/public key information for the participant. + * Callers MUST pass the same verified remote `round1` package set that was already + * accepted in `round2()`, rather than re-fetching or rebuilding it from the network. + */ + round3: ( + secret: TArg, + round1: TArg, + round2: TArg + ) => TRet; + /** + * Best-effort erasure of internal secret state. Bigint/JIT copies may still survive outside the + * local object even after cleanup. + * @param secret - Private DKG state from round1. + */ + clean(secret: TArg): void; + }; + /** + * Trusted dealer mode: generates key shares from a central trusted authority. + * Mirrors RFC 9591 Appendix C and returns one shared VSS commitment package + * plus per-participant shares. + * @param signers - Threshold parameters (min/max). + * @param identifiers - Optional explicit participant list. + * @param secret - Optional secret scalar. + * @param rng - Optional RNG. + * @returns One shared public package plus the participant secret-share packages. + */ + trustedDealer( + signers: Signers, + identifiers?: Identifier[], + secret?: TArg, + rng?: RNG + ): TRet; + /** + * Validates the consistency of a secret share against the shared public commitments. + * This is the RFC 9591 Appendix C.2 `vss_verify` check against the shared dealer/DKG commitment. + * It does not relax RFC 9591 Section 3.1: public identity elements are still invalid even when + * the scalar/share algebra would otherwise be self-consistent. + * Throws if invalid. + * @param secret - A FrostSecret containing identifier and signing share. + * @param pub - Shared public package containing commitments. + */ + validateSecret(secret: TArg, pub: TArg): void; + /** + * Produces nonces and public commitments used in signing. + * RFC 9591 Section 5.1 `commit()`. + * @param secret - Participant's secret share. + * @param rng - Optional RNG. + * @returns Nonce values and their public commitments. + * Returned nonces are one-time-use and MUST NOT be reused across signing sessions. + * This API does not mutate or zeroize caller-owned nonce objects. + */ + commit(secret: TArg, rng?: RNG): TRet; + /** + * Signs a message using the participant's secret and nonce. + * @param secret - Participant's secret share. + * @param pub - Shared public package containing commitments. + * @param nonces - Participant's nonce pair. + * @param commitmentList - Commitments from all signing participants. + * @param msg - Message to be signed. + * @returns Signature share as a byte array. + * RFC 9591 Sections 4.1/5.1 require round-one commitments to be one-time-use, and + * Section 5.2 signs with the nonce corresponding to that published commitment. + * The caller MUST pass fresh nonces from `commit()`. On successful signing, this helper + * consumes the caller-owned nonce object by zeroing both nonce byte arrays in place. + * Later calls reject an all-zero nonce package, so same-object reuse fails closed and an + * accidentally generated zero nonce package is not silently used for signing. + */ + signShare( + secret: TArg, + pub: TArg, + nonces: TArg, + commitmentList: TArg, + msg: TArg + ): TRet; + /** + * Verifies a signature share against public commitments. + * Matches the coordinator-side individual-share verification from RFC 9591 Section 5.4. + * @param pub - Group public key information. + * @param commitmentList - Commitments from all signing participants. + * @param msg - Message being signed. + * @param identifier - Identifier of the signer whose share is being verified. + * @param sigShare - Signature share to verify. + * @returns True if valid, false otherwise. + */ + verifyShare( + pub: TArg, + commitmentList: TArg, + msg: TArg, + identifier: Identifier, + sigShare: TArg + ): boolean; + /** + * Aggregates signature shares into a full signature. + * RFC 9591 Section 5.3 `aggregate()`. + * @param pub - Group public key. + * @param commitmentList - Nonce commitments from all signers. + * @param msg - Message to sign. + * @param sigShares - Map from identifier to their signature share. + * @returns Final aggregated signature. + */ + aggregate( + pub: TArg, + commitmentList: TArg, + msg: TArg, + sigShares: TArg> + ): TRet; + /** + * Signs a message using a raw secret key (e.g. from combineSecret). + * @param msg - Message to sign. + * @param secretKey - Group secret key as bytes. + * @returns Signature bytes. + */ + sign(msg: TArg, secretKey: TArg): TRet; + /** + * Verifies a full signature against the group public key. + * @param sig - Signature bytes. + * @param msg - Message that was signed. + * @param publicKey - Group public key. + * @returns True if valid, false otherwise. + */ + verify(sig: TArg, msg: TArg, publicKey: TArg): boolean; + /** + * Combines multiple secret shares into a single secret key (e.g. for recovery). + * @param shares - Set of FrostSecret shares. + * @param signers - Threshold parameters. + * @returns Group secret key as bytes. + */ + combineSecret(shares: TArg, signers: Signers): TRet; + /** + * Low-level helper utilities (field arithmetic and polynomial tools). + */ + utils: { + /** + * Finite field used for scalars. + */ + Fn: IField; + /** + * Generates a random scalar (private key). + * @param rng - Optional RNG source. + * @returns Scalar as 32-byte Uint8Array. + */ + randomScalar: (rng?: RNG) => TRet; + /** + * Generates a secret-sharing polynomial and its public commitments. + * @param signers - Threshold parameters. + * @param secret - Optional initial secret scalar. + * @param coeffs - Optional manual coefficients. + * @param rng - Optional RNG. + * @returns Polynomial coefficients, commitments, and secret value. + */ + generateSecretPolynomial: ( + signers: Signers, + secret?: TArg, + coeffs?: bigint[], + rng?: RNG + ) => { + coefficients: bigint[]; + commitment: TRet; + secret: bigint; + }; + }; +}; + +// PubKey = commitments, verifyingShares +// PrivKey = id, signingShare, commitment + +const validateSigners = (signers: Signers) => { + if (!Number.isSafeInteger(signers.min) || !Number.isSafeInteger(signers.max)) + throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max); + // Compatibility with frost-rs intentionally narrows RFC 9591's positive-nonzero threshold rule + // to `min >= 2`, even though the RFC text itself allows `MIN_PARTICIPANTS = 1`. + // This API is for actual threshold signing across participants; 1-of-n degenerates to ordinary + // single-signer mode, which does not need FROST's network/coordination machinery at all. + if (signers.min < 2 || signers.max < 2 || signers.min > signers.max) + throw new Error('Wrong signers info: min=' + signers.min + ' max=' + signers.max); +}; +const validateCommitmentsNum = (signers: Signers, len: number) => { + // RFC 9591 Sections 5.2/5.3 require MIN_PARTICIPANTS <= NUM_PARTICIPANTS <= MAX_PARTICIPANTS. + if (len < signers.min || len > signers.max) throw new Error('Wrong number of commitments=' + len); +}; + +class AggErr extends Error { + // Empty means aggregation failed before per-share verification could attribute a signer. + public cheaters: Identifier[]; + constructor(msg: string, cheaters: Identifier[]) { + super(msg); + this.cheaters = cheaters; + } +} + +export function createFROST

>(opts: FrostOpts

): TRet { + validateObject( + opts, + { + name: 'string', + hash: 'function', + }, + { + hashToScalar: 'function', + validatePoint: 'function', + parsePublicKey: 'function', + adjustScalar: 'function', + adjustPoint: 'function', + challenge: 'function', + adjustNonces: 'function', + adjustSecret: 'function', + adjustPublic: 'function', + adjustGroupCommitmentShare: 'function', + adjustDKG: 'function', + } + ); + // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that + // FROST consumes, but it does not certify point semantics like BASE/ZERO correctness. + validatePointCons(opts.Point); + const { Point } = opts; + const Fn = opts.Fn === undefined ? Point.Fn : opts.Fn; + // Hashes + const hashBytes = opts.hash; + const hashToScalar = + opts.hashToScalar === undefined + ? (msg: TArg, opts: TArg = { DST: new Uint8Array() }) => { + const t = hashBytes(concatBytes(opts.DST as Uint8Array, msg)); + return Fn.create(Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t)); + } + : opts.hashToScalar; + const H1Prefix = utf8ToBytes(opts.H1 !== undefined ? opts.H1 : opts.name + 'rho'); + const H2Prefix = utf8ToBytes(opts.H2 !== undefined ? opts.H2 : opts.name + 'chal'); + const H3Prefix = utf8ToBytes(opts.H3 !== undefined ? opts.H3 : opts.name + 'nonce'); + const H4Prefix = utf8ToBytes(opts.H4 !== undefined ? opts.H4 : opts.name + 'msg'); + const H5Prefix = utf8ToBytes(opts.H5 !== undefined ? opts.H5 : opts.name + 'com'); + const HDKGPrefix = utf8ToBytes(opts.HDKG !== undefined ? opts.HDKG : opts.name + 'dkg'); + const HIDPrefix = utf8ToBytes(opts.HID !== undefined ? opts.HID : opts.name + 'id'); + const H1 = (msg: TArg) => hashToScalar(msg, { DST: H1Prefix }); + // Empty H2 still passes `{ DST: new Uint8Array() }` into custom hashToScalar hooks. + // The built-in fallback hashes that identically to omitted DST, which is how + // the Ed25519 suite models RFC 9591's undecorated H2 challenge hash. + const H2 = (msg: TArg) => hashToScalar(msg, { DST: H2Prefix }); + const H3 = (msg: TArg) => hashToScalar(msg, { DST: H3Prefix }); + const H4 = (msg: TArg) => hashBytes(concatBytes(H4Prefix, msg)); + const H5 = (msg: TArg) => hashBytes(concatBytes(H5Prefix, msg)); + const HDKG = (msg: TArg) => hashToScalar(msg, { DST: HDKGPrefix }); + const HID = (msg: TArg) => hashToScalar(msg, { DST: HIDPrefix }); + // /Hashes + const randomScalar = (rng: RNG = randomBytes) => { + // Intentional divergence from RFC 9591 §4.1 / §5.1: the RFC nonce_generate helper outputs a + // Scalar in [0, p-1], but round-one commit publishes ScalarBaseMult(nonce) values and §3.1 + // requires SerializeElement / DeserializeElement to reject the identity element. Keep noble's + // mapHashToField generation here so round-one public nonce commitments stay in 1..n-1. + const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE); + // We cannot use Fn.fromBytes here because the field can have a different + // byte width, like ed448. + return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t); + }; + const serializePoint = (p: P) => p.toBytes(); + const parsePoint = (bytes: TArg) => { + // RFC 9591 Section 3.1 requires DeserializeElement validation. Suite-specific validatePoint + // hooks tighten this further for ciphersuites in Section 6. Bare createFROST(...) only gets + // canonical point decoding unless the caller installs those extra subgroup / identity checks. + const p = Point.fromBytes(bytes); + if (opts.validatePoint) opts.validatePoint(p); + return p; + }; + // RFC 9591 Sections 4.1/5.1 model each participant's round-one output as two public commitments. + const nonceCommitments = (identifier: Identifier, nonces: TArg): TRet => + ({ + identifier, + hiding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.hiding))), + binding: serializePoint(Point.BASE.multiply(Fn.fromBytes(nonces.binding))), + }) as TRet; + const adjustPoint = opts.adjustPoint === undefined ? (n: P) => n : opts.adjustPoint; + // We use hex to make it easier to use inside objects + const validateIdentifier = (n: bigint) => { + // Identifiers are canonical non-zero scalars. Custom / derived identifiers are allowed, so this + // is intentionally not bounded by the current signers.max slot count. + if (!Fn.isValid(n) || Fn.is0(n)) throw new Error('Invalid identifier ' + n); + return n; + }; + const serializeIdentifier = (id: bigint) => bytesToHex(Fn.toBytes(validateIdentifier(id))); + const parseIdentifier = (id: string) => { + const n = validateIdentifier(Fn.fromBytes(hexToBytes(id))); + // Keep string-keyed maps stable by accepting only the canonical serialized form. + if (serializeIdentifier(n) !== id) throw new Error('expected canonical identifier hex'); + return n; + }; + + const Signature = { + // RFC 9591 Appendix A encodes signatures canonically as + // SerializeElement(R) || SerializeScalar(z). + encode: (R: P, z: bigint): TRet => { + let res: Uint8Array = concatBytes(serializePoint(R), Fn.toBytes(z)); + if (opts.adjustTx) res = opts.adjustTx.encode(res); + return res as TRet; + }, + decode: (sig: TArg) => { + if (opts.adjustTx) sig = opts.adjustTx.decode(sig); + // We don't know size of point, but we know size of scalar + const R = parsePoint(sig.subarray(0, -Fn.BYTES)); + const z = Fn.fromBytes(sig.subarray(-Fn.BYTES)); + return { R, z }; + }, + }; + // Generates pair of (scalar, point) + const genPointScalarPair = (rng: RNG = randomBytes) => { + let n = randomScalar(rng); + if (opts.adjustScalar) n = opts.adjustScalar(n); + let p = Point.BASE.multiply(n); + return { scalar: n, point: p }; + }; + // No roots here: root-based methods will throw. + // `poly` expects a structured roots-of-unity domain, but FROST uses an + // arbitrary domain and only needs the non-root operations below. + const nrErr = 'roots are unavailable in FROST polynomial mode'; + const noRoots: RootsOfUnity = { + info: { G: Fn.ZERO, oddFactor: Fn.ZERO, powerOfTwo: 0 }, + roots() { + throw new Error(nrErr); + }, + brp() { + throw new Error(nrErr); + }, + inverse() { + throw new Error(nrErr); + }, + omega() { + throw new Error(nrErr); + }, + clear() {}, + }; + const Poly = poly(Fn, noRoots); + const msm = (points: P[], scalars: bigint[]) => pippenger(Point, points, scalars); + + // Internal stuff uses bigints & Points, external Uint8Arrays + const polynomialEvaluate = (x: bigint, coeffs: bigint[]): bigint => { + if (!coeffs.length) throw new Error('empty coefficients'); + return Poly.monomial.eval(coeffs, x); + }; + const deriveInterpolatingValue = (L: bigint[], xi: bigint): bigint => { + const err = 'invalid parameters'; + // Generates lagrange coefficient + if (!L.some((x) => Fn.eql(x, xi))) throw new Error(err); + // Throws error if any x-coordinate is represented more than once in L. + const Lset = new Set(L); + if (Lset.size !== L.length) throw new Error(err); + // Or if xi is missing + if (!Lset.has(xi)) throw new Error(err); + let num = Fn.ONE; + let den = Fn.ONE; + for (const x of L) { + if (Fn.eql(x, xi)) continue; + num = Fn.mul(num, x); // num *= x + den = Fn.mul(den, Fn.sub(x, xi)); // RFC 9591 §4.2: denominator *= x_j - x_i + } + return Fn.div(num, den); + }; + const evalutateVSS = (identifier: bigint, commitment: P[]) => { + // RFC 9591 Appendix C.2: S_i' = Σ_j ScalarMult(vss_commitment[j], i^j). + const monomial = Poly.monomial.basis(identifier, commitment.length); + return msm(commitment, monomial); + }; + // High-level internal stuff + const generateSecretPolynomial = ( + signers: Signers, + secret?: TArg, + coeffs?: bigint[], + rng: RNG = randomBytes + ) => { + validateSigners(signers); + // Dealer/DKG polynomial sampling reuses the same hardened scalar derivation as round-one + // nonces: overriding `rng` only swaps the entropy source, not the non-zero `1..n-1` policy. + const secretScalar = secret === undefined ? randomScalar(rng) : Fn.fromBytes(secret); + if (!coeffs) { + coeffs = []; + for (let i = 0; i < signers.min - 1; i++) coeffs.push(randomScalar(rng)); + } + if (coeffs.length !== signers.min - 1) throw new Error('wrong coefficients length'); + const coefficients: bigint[] = [secretScalar, ...coeffs]; + // RFC 9591 Appendix C.2 commits to every polynomial coefficient with ScalarBaseMult. + const commitment = coefficients.map((i) => Point.BASE.multiply(i)); + return { coefficients, commitment, secret: secretScalar }; + }; + // Pretty much sign+verify, same as basic + const ProofOfKnowledge = { + challenge: (id: bigint, verKey: P, R: P) => + HDKG(concatBytes(Fn.toBytes(id), serializePoint(verKey), serializePoint(R))), + compute(id: bigint, coefficents: bigint[], commitments: P[], rng: RNG = randomBytes) { + if (coefficents.length < 1) throw new Error('coefficients should have at least one element'); + const { point: R, scalar: k } = genPointScalarPair(rng); + const verKey = commitments[0]; // verify key is first one + const c = this.challenge(id, verKey, R); + const mu = Fn.add(k, Fn.mul(coefficents[0], c)); // mu = k + coeff[0] * c + return Signature.encode(R, mu); + }, + validate(id: bigint, commitment: TArg, proof: TArg) { + if (commitment.length < 1) throw new Error('commitment should have at least one element'); + const { R, z } = Signature.decode(proof); + const phi = parsePoint(commitment[0]); + const c = this.challenge(id, phi, R); + // R === z*G - phi*c + if (!R.equals(Point.BASE.multiply(z).subtract(phi.multiply(c)))) + throw new Error('invalid proof of knowledge'); + }, + }; + const Basic = { + challenge: (R: P, PK: P, msg: TArg) => { + if (opts.challenge) return opts.challenge(R, PK, msg); + return H2(concatBytes(serializePoint(R), serializePoint(PK), msg)); + }, + sign(msg: TArg, sk: bigint, rng: RNG = randomBytes): [P, bigint] { + const { point: R, scalar: r } = genPointScalarPair(rng); + const PK = Point.BASE.multiply(sk); // sk*G + const c = this.challenge(R, PK, msg); + const z = Fn.add(r, Fn.mul(c, sk)); // r + c * sk + return [R, z]; + }, + verify(msg: TArg, R: P, z: bigint, PK: P): boolean { + if (opts.adjustPoint) PK = opts.adjustPoint(PK); + if (opts.adjustPoint) R = opts.adjustPoint(R); + const c = this.challenge(R, PK, msg); + const zB = Point.BASE.multiply(z); // z*G + const cA = PK.multiply(c); // c*PK + let check = zB.subtract(cA).subtract(R); // zB - cA - R + // No clearCoffactor on ristretto + if (check.clearCofactor) check = check.clearCofactor(); + return Point.ZERO.equals(check); + }, + }; + // === vssVerify + const validateSecretShare = (identifier: bigint, commitment: P[], signingShare: bigint) => { + // RFC 9591 Appendix C.2 `vss_verify(share_i, vss_commitment)` is purely algebraic. + // Public FROST packages still go through Section 3.1 element encoding, + // which rejects identity points, so a zero share or commitment does not + // become valid wire data just because VSS matches. + if (!Point.BASE.multiply(signingShare).equals(evalutateVSS(identifier, commitment))) + throw new Error('invalid secret share'); + }; + const Identifier = { + fromNumber(n: number): Identifier { + if (!Number.isSafeInteger(n)) throw new Error('expected safe interger'); + return serializeIdentifier(BigInt(n)); + }, + // Not in spec, but in FROST implementation, + // seems useful and nice, no need to sync identifiers (would require more interactions) + derive(s: string): Identifier { + if (typeof s !== 'string') throw new Error('wrong identifier string: ' + s); + // Derived identifiers may land anywhere in the scalar field; they are not restricted to + // sequential `1..max_signers` values. + return serializeIdentifier(HID(utf8ToBytes(s))); + }, + }; + // RFC 9591 §4.1: nonce_generate() hashes 32 fresh RNG bytes with SerializeScalar(secret). + const generateNonce = (secret: bigint, rng: RNG = randomBytes) => + H3(concatBytes(rng(32), Fn.toBytes(secret))); + + const getGroupCommitment = ( + GPK: P, + commitmentList: TArg, + msg: TArg + ) => { + const CL = commitmentList.map((i) => [ + i.identifier, + parseIdentifier(i.identifier), + parsePoint(i.hiding), + parsePoint(i.binding), + ]) as [Identifier, bigint, P, P][]; + // RFC 9591 Sections 4.3/4.4/4.5 and 5.2/5.3 treat commitment_list as sorted by identifier. + CL.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)); + // Encode commitment list + const Cbytes = []; + for (const [_, id, hC, bC] of CL) + Cbytes.push(Fn.toBytes(id), serializePoint(hC), serializePoint(bC)); + const encodedCommitmentHash = H5(concatBytes(...Cbytes)); + const rhoPrefix = concatBytes(serializePoint(GPK), H4(msg), encodedCommitmentHash); + // Compute binding factors + const bindingFactors: Record = {}; + for (const [i, id] of CL) { + bindingFactors[i] = H1(concatBytes(rhoPrefix, Fn.toBytes(id))); + } + const points: P[] = []; + const scalars: bigint[] = []; + for (const [i, _, hC, bC] of CL) { + if (Point.ZERO.equals(hC) || Point.ZERO.equals(bC)) throw new Error('infinity commitment'); + points.push(hC, bC); + scalars.push(Fn.ONE, bindingFactors[i]); + } + const groupCommitment = msm(points, scalars); // GC += hC + bC*bindingFactor + const identifiers = CL.map((i) => i[1]); + return { identifiers, groupCommitment, bindingFactors }; + }; + const prepareShare = ( + PK: TArg, + commitmentList: TArg, + msg: TArg, + identifier: Identifier + ) => { + // RFC 9591 Sections 4.4/4.5/4.6 feed directly into the Section 5.2 signer computation. + const GPK = adjustPoint(parsePoint(PK)); + const id = parseIdentifier(identifier); + const { identifiers, groupCommitment, bindingFactors } = getGroupCommitment( + GPK, + commitmentList, + msg + ); + const bindingFactor = bindingFactors[identifier]; + const lambda = deriveInterpolatingValue(identifiers, id); + const challenge = Basic.challenge(groupCommitment, GPK, msg); + return { lambda, challenge, bindingFactor, groupCommitment }; + }; + Object.freeze(Identifier); + const frost = { + Identifier, + // DKG is Distributed Key Generation, not Trusted Dealer Key Generation. + DKG: Object.freeze({ + // NOTE: we allow to pass secret scalar from user side, + // this way it can be derived, instead of random generation + round1: ( + id: Identifier, + signers: Signers, + secret?: TArg, + rng: RNG = randomBytes + ) => { + validateSigners(signers); + const idNum = parseIdentifier(id); + const { coefficients, commitment } = generateSecretPolynomial( + signers, + secret, + undefined, + rng + ); + const proofOfKnowledge = ProofOfKnowledge.compute(idNum, coefficients, commitment, rng); + const commitmentBytes = commitment.map(serializePoint) as TRet; + const round1Public: DKG_Round1 = { + identifier: serializeIdentifier(idNum), + commitment: commitmentBytes, + proofOfKnowledge, + }; + // store secret information for signing + const round1Secret: DKG_Secret = { + identifier: idNum, + coefficients, + commitment: commitment.map(serializePoint) as TRet, + // Copy threshold metadata instead of retaining the caller-owned object by reference. + signers: { min: signers.min, max: signers.max }, + step: 1, + }; + return { public: round1Public, secret: round1Secret }; + }, + round2: ( + secret: TArg, + others: TArg + ): TRet> => { + if (others.length !== secret.signers.max - 1) + throw new Error('wrong number of round1 packages'); + if (!secret.coefficients || secret.step === 3) + throw new Error('round3 package used in round2'); + const res: Record = {}; + for (const p of others) { + if (p.commitment.length !== secret.signers.min) + throw new Error('wrong number of commitments'); + const id = parseIdentifier(p.identifier); + if (id === secret.identifier) throw new Error('duplicate id=' + serializeIdentifier(id)); + + ProofOfKnowledge.validate(id, p.commitment, p.proofOfKnowledge); + for (const c of p.commitment) parsePoint(c); + if (res[p.identifier]) throw new Error('Duplicate id=' + id); + const signingShare = Fn.toBytes(polynomialEvaluate(id, secret.coefficients)); + res[p.identifier] = { + identifier: serializeIdentifier(secret.identifier), + signingShare: signingShare as TRet, + }; + } + secret.step = 2; + return res as TRet>; + }, + round3: ( + secret: TArg, + round1: TArg, + round2: TArg + ): TRet => { + // DKG is outside RFC 9591's signing flow; callers are expected to reuse the same + // remote round1 packages already accepted in round2, like frost-rs documents. + if (round1.length !== secret.signers.max - 1) + throw new Error('wrong length of round1 packages'); + if (!secret.coefficients || secret.step !== 2) + throw new Error('round2 package used in round3'); + if (round2.length !== round1.length) throw new Error('wrong length of round2 packages'); + const merged: Record & { signingShare?: TArg }> = {}; + for (const r1 of round1) { + if (!r1.identifier || !r1.commitment) throw new Error('wrong round1 share'); + merged[r1.identifier] = { ...r1 }; + } + for (const r2 of round2) { + if (!r2.identifier || !r2.signingShare) throw new Error('wrong round2 share'); + if (!merged[r2.identifier]) + throw new Error('round1 share for ' + r2.identifier + ' is missing'); + merged[r2.identifier].signingShare = r2.signingShare; + } + if (Object.keys(merged).length !== round1.length) + throw new Error('mismatch identifiers between rounds'); + let signingShare = Fn.ZERO; + if (secret.commitment.length !== secret.signers.min) + throw new Error('wrong commitments length'); + const localCommitment = secret.commitment.map(parsePoint); + const localShare = polynomialEvaluate(secret.identifier, secret.coefficients); + validateSecretShare(secret.identifier, localCommitment, localShare); + const localCommitmentBytes = localCommitment.map(serializePoint); + const commitments: Record> = { + [serializeIdentifier(secret.identifier)]: localCommitmentBytes, + }; + for (const k in merged) { + const v = merged[k]; + if (!v.signingShare || !v.commitment) throw new Error('mismatch identifiers'); + const id = parseIdentifier(k); // from + const signingSharePart = Fn.fromBytes(v.signingShare); + const commitment = v.commitment.map(parsePoint); + validateSecretShare(secret.identifier, commitment, signingSharePart); + signingShare = Fn.add(signingShare, signingSharePart); + const idSer = serializeIdentifier(id); + if (commitments[idSer]) throw new Error('duplicated id=' + idSer); + commitments[idSer] = v.commitment; + } + signingShare = Fn.add(signingShare, localShare); + const mergedCommitment = new Array(secret.signers.min).fill(Point.ZERO); + for (const k in commitments) { + const v = commitments[k]; + if (v.length !== secret.signers.min) throw new Error('wrong commitments length'); + for (let i = 0; i < v.length; i++) + mergedCommitment[i] = mergedCommitment[i].add(parsePoint(v[i])); + } + const mergedCommitmentBytes = mergedCommitment.map(serializePoint) as TRet; + const verifyingShares: Record = {}; + for (const k in commitments) + verifyingShares[k] = serializePoint(evalutateVSS(parseIdentifier(k), mergedCommitment)); + // This is enough to sign stuff + let res: TRet = { + public: { + signers: { min: secret.signers.min, max: secret.signers.max }, + commitments: mergedCommitmentBytes, + verifyingShares: Object.fromEntries( + Object.entries(verifyingShares).map(([k, v]) => [k, v.slice()]) + ), + }, + secret: { + identifier: serializeIdentifier(secret.identifier), + signingShare: Fn.toBytes(signingShare) as TRet, + }, + }; + if (opts.adjustDKG) res = opts.adjustDKG(res); + for (let i = 0; i < secret.coefficients.length; i++) + secret.coefficients[i] -= secret.coefficients[i]; + delete secret.coefficients; + secret.step = 3; + return res; + }, + clean(secret: TArg) { + // Instead of replacing secret bigint with another (zero?), we subtract it from itself + // in the hope that JIT will modify it inplace, instead of creating new value. + // This is unverified and may not work, but it is best we can do in regard of bigints. + secret.identifier -= secret.identifier; + if (secret.coefficients) { + for (let i = 0; i < secret.coefficients.length; i++) + secret.coefficients[i] -= secret.coefficients[i]; + } + // for (const c of secret.commitment) c.fill(0); + secret.step = 3; + }, + }), + // Trusted dealer setup + // Generates keys for all participants + trustedDealer( + signers: Signers, + identifiers?: Identifier[], + secret?: TArg, + rng: RNG = randomBytes + ): TRet { + // if no identifiers provided, we generated default identifiers + validateSigners(signers); + if (identifiers === undefined) { + identifiers = []; + for (let i = 1; i <= signers.max; i++) identifiers.push(Identifier.fromNumber(i)); + } else { + if (!Array.isArray(identifiers) || identifiers.length !== signers.max) + throw new Error('identifiers should be array of ' + signers.max); + } + const identifierNums: Record = {}; + for (const id of identifiers) { + const idNum = parseIdentifier(id); + if (id in identifierNums) throw new Error('duplicated id=' + id); + identifierNums[id] = idNum; + } + const sp = generateSecretPolynomial(signers, secret, undefined, rng); + const commitmentBytes = sp.commitment.map(serializePoint); + const secretShares: Record = {}; + const verifyingShares: Record = {}; + for (const id of identifiers) { + const signingShare = polynomialEvaluate(identifierNums[id], sp.coefficients); + verifyingShares[id] = serializePoint(Point.BASE.multiply(signingShare)); + secretShares[id] = { + identifier: id, + signingShare: Fn.toBytes(signingShare) as TRet, + }; + } + return { + public: { + signers: { min: signers.min, max: signers.max }, + commitments: commitmentBytes, + verifyingShares, + }, + secretShares, + } as TRet; + }, + // Validate secret (from trusted dealer or DKG) + validateSecret(secret: TArg, pub: TArg) { + const id = parseIdentifier(secret.identifier); + const commitment = pub.commitments.map(parsePoint); + const signingShare = Fn.fromBytes(secret.signingShare); + validateSecretShare(id, commitment, signingShare); + }, + // Actual signing + // Round 1: each participant commit to nonces + // Nonces kept private, commitments sent to coordinator (or every other participant) + // NOTE: we don't need the message at this point, which lets a coordinator + // keep multiple nonce commitments per participant in advance and skip + // round1 for signing. + // But then each participant needs to remember generated shares + commit(secret: TArg, rng: RNG = randomBytes): TRet { + const secretScalar = Fn.fromBytes(secret.signingShare); + const hiding = generateNonce(secretScalar, rng); + const binding = generateNonce(secretScalar, rng); + const nonces = { hiding: Fn.toBytes(hiding), binding: Fn.toBytes(binding) }; + return { nonces, commitments: nonceCommitments(secret.identifier, nonces) } as TRet; + }, + // Round2: sign. Each participant creates a signature share from the secret + // and the selected nonce commitments. + signShare( + secret: TArg, + pub: TArg, + nonces: TArg, + commitmentList: TArg, + msg: TArg + ): TRet { + validateCommitmentsNum(pub.signers, commitmentList.length); + const hidingNonce0 = Fn.fromBytes(nonces.hiding); + const bindingNonce0 = Fn.fromBytes(nonces.binding); + if (Fn.is0(hidingNonce0) || Fn.is0(bindingNonce0)) + throw new Error('signing nonces already used'); + // Reject a coordinator-assigned commitment pair that does not match the signer's own nonce + // pair. This must happen before suite-specific nonce adjustment; secp256k1-tr may negate the + // actual signing nonces later, but the coordinator still assigns the original commitments. + const expectedCommitment = { + identifier: secret.identifier, + hiding: serializePoint(Point.BASE.multiply(hidingNonce0)), + binding: serializePoint(Point.BASE.multiply(bindingNonce0)), + }; + const commitment = commitmentList.find((i) => i.identifier === secret.identifier); + if (!commitment) throw new Error('missing signer commitment'); + if ( + bytesToHex(commitment.hiding) !== bytesToHex(expectedCommitment.hiding) || + bytesToHex(commitment.binding) !== bytesToHex(expectedCommitment.binding) + ) + throw new Error('incorrect signer commitment'); + if (opts.adjustSecret) secret = opts.adjustSecret(secret, pub); + if (opts.adjustPublic) pub = opts.adjustPublic(pub); + const SK = Fn.fromBytes(secret.signingShare); + const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare( + pub.commitments[0], + commitmentList, + msg, + secret.identifier + ); + const N = opts.adjustNonces ? opts.adjustNonces(groupCommitment, nonces) : nonces; + const hidingNonce = opts.adjustNonces ? Fn.fromBytes(N.hiding) : hidingNonce0; + const bindingNonce = opts.adjustNonces ? Fn.fromBytes(N.binding) : bindingNonce0; + const t = Fn.mul(Fn.mul(lambda, SK), challenge); // challenge * lambda * SK + const t2 = Fn.mul(bindingNonce, bindingFactor); // bindingNonce * bindingFactor + const r = Fn.toBytes(Fn.add(Fn.add(hidingNonce, t2), t)); // t + t2 + hidingNonce + // RFC 9591 round-one commitments are one-time-use, and round two must use the nonce + // corresponding to the published commitment. This API returns mutable local nonce bytes, + // so consume them after a successful signShare() call: later all-zero reuse fails closed. + nonces.hiding.fill(0); + nonces.binding.fill(0); + return r as TRet; + }, + // Each participant (or coordinator) can verify signatures from other participants + verifyShare( + pub: TArg, + commitmentList: TArg, + msg: TArg, + identifier: Identifier, + sigShare: TArg + ) { + if (opts.adjustPublic) pub = opts.adjustPublic(pub); + const comm = commitmentList.find((i) => i.identifier === identifier); + if (!comm) throw new Error('cannot find identifier commitment'); + const PK = parsePoint(pub.verifyingShares[identifier]); + const hidingNonceCommitment = parsePoint(comm.hiding); + const bindingNonceCommitment = parsePoint(comm.binding); + const { lambda, challenge, bindingFactor, groupCommitment } = prepareShare( + pub.commitments[0], + commitmentList, + msg, + identifier + ); + // hC + bC * bF + let commShare = hidingNonceCommitment.add(bindingNonceCommitment.multiply(bindingFactor)); + if (opts.adjustGroupCommitmentShare) + commShare = opts.adjustGroupCommitmentShare(groupCommitment, commShare); + const l = Point.BASE.multiply(Fn.fromBytes(sigShare)); // sigShare*G + // commShare + PK * (challenge * lambda) + const r = commShare.add(PK.multiply(Fn.mul(challenge, lambda))); + return l.equals(r); + }, + // Aggregate multiple signature shares into groupSignature + aggregate( + pub: TArg, + commitmentList: TArg, + msg: TArg, + sigShares: TArg> + ): TRet { + if (opts.adjustPublic) pub = opts.adjustPublic(pub); + try { + validateCommitmentsNum(pub.signers, commitmentList.length); + } catch { + throw new AggErr('aggregation failed', []); + } + const ids = commitmentList.map((i) => i.identifier); + if (ids.length !== Object.keys(sigShares).length) throw new AggErr('aggregation failed', []); + for (const id of ids) { + if (!(id in sigShares) || !(id in pub.verifyingShares)) + throw new AggErr('aggregation failed', []); + } + const GPK = parsePoint(pub.commitments[0]); + const { groupCommitment } = getGroupCommitment(GPK, commitmentList, msg); + let z = Fn.ZERO; + // RFC 9591 Section 5.3 aggregates by summing the validated signature shares. + for (const id of ids) z = Fn.add(z, Fn.fromBytes(sigShares[id])); // z += zi + if (!Basic.verify(msg, groupCommitment, z, GPK)) { + const cheaters = []; + for (const id of ids) { + if (!this.verifyShare(pub, commitmentList, msg, id, sigShares[id])) cheaters.push(id); + } + throw new AggErr('aggregation failed', cheaters); + } + return Signature.encode(groupCommitment, z); + }, + // Basic sign/verify using single key + sign(msg: TArg, secretKey: TArg): TRet { + let sk = Fn.fromBytes(secretKey); + // Taproot single-key signing needs the same scalar normalization as threshold keys. + if (opts.adjustScalar) sk = opts.adjustScalar(sk); + const [R, z] = Basic.sign(msg, sk); + return Signature.encode(R, z); + }, + verify(sig: TArg, msg: TArg, publicKey: TArg) { + const PK = opts.parsePublicKey ? opts.parsePublicKey(publicKey) : parsePoint(publicKey); + const { R, z } = Signature.decode(sig); + return Basic.verify(msg, R, z, PK); + }, + // Combine multiple secret shares to restore secret + combineSecret(shares: TArg, signers: Signers): TRet { + validateSigners(signers); + if (!Array.isArray(shares) || shares.length < signers.min) + throw new Error('wrong secret shares array'); + const points = []; + const seen: Record = {}; + // Interpolate over the full provided share set and reject duplicate identifiers. + for (const s of shares) { + const idNum = parseIdentifier(s.identifier); + const id = serializeIdentifier(idNum); + if (seen[id]) throw new Error('duplicated id=' + id); + seen[id] = true; + points.push([idNum, Fn.fromBytes(s.signingShare)]); + } + const xCoords = points.map(([x]) => x); + let res = Fn.ZERO; + for (const [x, y] of points) + res = Fn.add(res, Fn.mul(y, deriveInterpolatingValue(xCoords, x))); + return Fn.toBytes(res) as TRet; + }, + // Utils + utils: Object.freeze({ + Fn, // NOTE: we re-export it here because it may be different from Point.Fn (ed448 is fun!) + // Test RNG overrides still go through noble's non-zero scalar derivation; this is not a raw + // "bytes become scalar" escape hatch. + randomScalar: (rng: RNG = randomBytes) => + Fn.toBytes(genPointScalarPair(rng).scalar) as TRet, + generateSecretPolynomial: ( + signers: Signers, + secret?: TArg, + coeffs?: bigint[], + rng?: RNG + ) => { + const res = generateSecretPolynomial(signers, secret, coeffs, rng); + return { ...res, commitment: res.commitment.map(serializePoint) as TRet }; + }, + }), + }; + return Object.freeze(frost) as TRet; +} diff --git a/node_modules/@noble/curves/src/abstract/hash-to-curve.ts b/node_modules/@noble/curves/src/abstract/hash-to-curve.ts new file mode 100644 index 0000000..3ce6dd4 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/hash-to-curve.ts @@ -0,0 +1,491 @@ +/** + * hash-to-curve from RFC 9380. + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + * https://www.rfc-editor.org/rfc/rfc9380 + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { CHash, TArg, TRet } from '../utils.ts'; +import { + abytes, + asafenumber, + asciiToBytes, + bytesToNumberBE, + copyBytes, + concatBytes, + isBytes, + validateObject, +} from '../utils.ts'; +import type { AffinePoint, PC_ANY, PC_F, PC_P } from './curve.ts'; +import { FpInvertBatch, mod, type IField } from './modular.ts'; + +/** ASCII domain-separation tag or raw bytes. */ +export type AsciiOrBytes = string | Uint8Array; +type H2CDefaults = { + DST: AsciiOrBytes; + expand: 'xmd' | 'xof'; + hash: CHash; + p: bigint; + m: number; + k: number; + encodeDST?: AsciiOrBytes; +}; + +/** + * * `DST` is a domain separation tag, defined in section 2.2.5 + * * `p` characteristic of F, where F is a finite field of characteristic p and order q = p^m + * * `m` is extension degree (1 for prime fields) + * * `k` is the target security target in bits (e.g. 128), from section 5.1 + * * `expand` is `xmd` (SHA2, SHA3, BLAKE) or `xof` (SHAKE, BLAKE-XOF) + * * `hash` conforming to `utils.CHash` interface, with `outputLen` / `blockLen` props + */ +export type H2COpts = { + /** Domain separation tag. */ + DST: AsciiOrBytes; + /** Expander family used by RFC 9380. */ + expand: 'xmd' | 'xof'; + /** Hash or XOF implementation used by the expander. */ + hash: CHash; + /** Base-field characteristic. */ + p: bigint; + /** Extension degree (`1` for prime fields). */ + m: number; + /** Target security level in bits. */ + k: number; +}; +/** Hash-only subset of RFC 9380 options used by per-call overrides. */ +export type H2CHashOpts = { + /** Expander family used by RFC 9380. */ + expand: 'xmd' | 'xof'; + /** Hash or XOF implementation used by the expander. */ + hash: CHash; +}; +/** + * Map one hash-to-field output tuple onto affine curve coordinates. + * Implementations receive the validated scalar tuple by reference for performance and MUST treat it + * as read-only. Callers that need scratch space should copy before mutating. + * @param scalar - Field-element tuple produced by `hash_to_field`. + * @returns Affine point before subgroup clearing. + */ +export type MapToCurve = (scalar: bigint[]) => AffinePoint; + +// Separated from initialization opts, so users won't accidentally change per-curve parameters +// (changing DST is ok!) +/** Per-call override for the domain-separation tag. */ +export type H2CDSTOpts = { + /** Domain-separation tag override. */ + DST: AsciiOrBytes; +}; +/** Base hash-to-curve helpers shared by `hashToCurve` and `encodeToCurve`. */ +export type H2CHasherBase = { + /** + * Hash arbitrary bytes to one curve point. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Curve point after hash-to-curve. + */ + hashToCurve(msg: TArg, options?: TArg): PC_P; + /** + * Hash arbitrary bytes to one scalar. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Scalar reduced into the target field. + */ + hashToScalar(msg: TArg, options?: TArg): bigint; + /** + * Derive one curve point from non-uniform bytes without the random-oracle + * guarantees of `hashToCurve`. + * Accepts the same arguments as `hashToCurve`, but runs the encode-to-curve + * path instead of the random-oracle construction. + */ + deriveToCurve?(msg: TArg, options?: TArg): PC_P; + /** Point constructor for the target curve. */ + Point: PC; +}; +/** + * RFC 9380 methods, with cofactor clearing. See {@link https://www.rfc-editor.org/rfc/rfc9380#section-3 | RFC 9380 section 3}. + * + * * hashToCurve: `map(hash(input))`, encodes RANDOM bytes to curve (WITH hashing) + * * encodeToCurve: `map(hash(input))`, encodes NON-UNIFORM bytes to curve (WITH hashing) + * * mapToCurve: `map(scalars)`, encodes NON-UNIFORM scalars to curve (NO hashing) + */ +export type H2CHasher = H2CHasherBase & { + /** + * Encode non-uniform bytes to one curve point. + * @param msg - Input message bytes. + * @param options - Optional domain-separation override. See {@link H2CDSTOpts}. + * @returns Curve point after encode-to-curve. + */ + encodeToCurve(msg: TArg, options?: TArg): PC_P; + /** Deterministic map from `hash_to_field` tuples into affine coordinates. */ + mapToCurve: MapToCurve>; + /** Default RFC 9380 options captured by this hasher bundle. */ + defaults: H2CDefaults; +}; + +// Octet Stream to Integer. "spec" implementation of os2ip is 2.5x slower vs bytesToNumberBE. +const os2ip = bytesToNumberBE; + +// Integer to Octet Stream (numberToBytesBE). +function i2osp(value: number, length: number): TRet { + asafenumber(value); + asafenumber(length); + // This helper stays on the JS bitwise/u32 fast-path. Callers that need wider encodings should + // use bigint + numberToBytesBE instead of routing large widths through this small helper. + if (length < 0 || length > 4) throw new Error('invalid I2OSP length: ' + length); + if (value < 0 || value > 2 ** (8 * length) - 1) throw new Error('invalid I2OSP input: ' + value); + const res = Array.from({ length }).fill(0) as number[]; + for (let i = length - 1; i >= 0; i--) { + res[i] = value & 0xff; + value >>>= 8; + } + return new Uint8Array(res) as TRet; +} + +// RFC 9380 only applies strxor() to equal-length strings; callers must preserve that invariant. +function strxor(a: TArg, b: TArg): TRet { + const arr = new Uint8Array(a.length); + for (let i = 0; i < a.length; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr as TRet; +} + +// User can always use utf8 if they want, by passing Uint8Array. +// If string is passed, we treat it as ASCII: other formats are likely a mistake. +function normDST(DST: TArg): TRet { + if (!isBytes(DST) && typeof DST !== 'string') + throw new Error('DST must be Uint8Array or ascii string'); + const dst = typeof DST === 'string' ? asciiToBytes(DST) : DST; + // RFC 9380 §3.1 requirement 2: tags "MUST have nonzero length". + if (dst.length === 0) throw new Error('DST must be non-empty'); + return dst as TRet; +} + +/** + * Produces a uniformly random byte string using a cryptographic hash + * function H that outputs b bits. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.1 | RFC 9380 section 5.3.1}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param H - Hash function. + * @returns Uniform byte string. + * @throws If the message, DST, hash, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XMD construction. + * + * ```ts + * import { expand_message_xmd } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const uniform = expand_message_xmd(new TextEncoder().encode('hello noble'), 'DST', 32, sha256); + * ``` + */ +export function expand_message_xmd( + msg: TArg, + DST: TArg, + lenInBytes: number, + H: TArg +): TRet { + abytes(msg); + asafenumber(lenInBytes); + DST = normDST(DST); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + if (DST.length > 255) DST = H(concatBytes(asciiToBytes('H2C-OVERSIZE-DST-'), DST)); + const { outputLen: b_in_bytes, blockLen: r_in_bytes } = H; + const ell = Math.ceil(lenInBytes / b_in_bytes); + if (lenInBytes > 65535 || ell > 255) throw new Error('expand_message_xmd: invalid lenInBytes'); + const DST_prime = concatBytes(DST, i2osp(DST.length, 1)); + const Z_pad = new Uint8Array(r_in_bytes); // RFC 9380: Z_pad = I2OSP(0, s_in_bytes) + const l_i_b_str = i2osp(lenInBytes, 2); // len_in_bytes_str + const b = new Array(ell); + const b_0 = H(concatBytes(Z_pad, msg, l_i_b_str, i2osp(0, 1), DST_prime)); + b[0] = H(concatBytes(b_0, i2osp(1, 1), DST_prime)); + // `b[0]` already stores RFC `b_1`, so only derive `b_2..b_ell` here. The old `<= ell` + // loop computed one extra tail block, which was usually sliced away but broke at max `ell=255` + // by reaching `I2OSP(256, 1)`. + for (let i = 1; i < ell; i++) { + const args = [strxor(b_0, b[i - 1]), i2osp(i + 1, 1), DST_prime]; + b[i] = H(concatBytes(...args)); + } + const pseudo_random_bytes = concatBytes(...b); + return pseudo_random_bytes.slice(0, lenInBytes); +} + +/** + * Produces a uniformly random byte string using an extendable-output function (XOF) H. + * 1. The collision resistance of H MUST be at least k bits. + * 2. H MUST be an XOF that has been proved indifferentiable from + * a random oracle under a reasonable cryptographic assumption. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.3.2 | RFC 9380 section 5.3.2}. + * @param msg - Input message. + * @param DST - Domain separation tag. This helper normalizes DST, rejects empty DSTs, and + * oversize-hashes DST when needed. + * @param lenInBytes - Output length. + * @param k - Target security level. + * @param H - XOF hash function. + * @returns Uniform byte string. + * @throws If the message, DST, XOF, or output length is invalid. {@link Error} + * @example + * Expand one message into uniform bytes with the XOF construction. + * + * ```ts + * import { expand_message_xof } from '@noble/curves/abstract/hash-to-curve.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * const uniform = expand_message_xof( + * new TextEncoder().encode('hello noble'), + * 'DST', + * 32, + * 128, + * shake256 + * ); + * ``` + */ +export function expand_message_xof( + msg: TArg, + DST: TArg, + lenInBytes: number, + k: number, + H: TArg +): TRet { + abytes(msg); + asafenumber(lenInBytes); + DST = normDST(DST); + // https://www.rfc-editor.org/rfc/rfc9380#section-5.3.3 + // RFC 9380 §5.3.3: DST = H("H2C-OVERSIZE-DST-" || a_very_long_DST, ceil(2 * k / 8)). + if (DST.length > 255) { + const dkLen = Math.ceil((2 * k) / 8); + DST = H.create({ dkLen }).update(asciiToBytes('H2C-OVERSIZE-DST-')).update(DST).digest(); + } + if (lenInBytes > 65535 || DST.length > 255) + throw new Error('expand_message_xof: invalid lenInBytes'); + return ( + H.create({ dkLen: lenInBytes }) + .update(msg) + .update(i2osp(lenInBytes, 2)) + // 2. DST_prime = DST || I2OSP(len(DST), 1) + .update(DST) + .update(i2osp(DST.length, 1)) + .digest() + ); +} + +/** + * Hashes arbitrary-length byte strings to a list of one or more elements of a finite field F. + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-5.2 | RFC 9380 section 5.2}. + * @param msg - Input message bytes. + * @param count - Number of field elements to derive. Must be `>= 1`. + * @param options - RFC 9380 options. See {@link H2COpts}. `m` must be `>= 1`. + * @returns `[u_0, ..., u_(count - 1)]`, a list of field elements. + * @throws If the expander choice or RFC 9380 options are invalid. {@link Error} + * @example + * Hash one message into field elements before mapping it onto a curve. + * + * ```ts + * import { hash_to_field } from '@noble/curves/abstract/hash-to-curve.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const scalars = hash_to_field(new TextEncoder().encode('hello noble'), 2, { + * DST: 'DST', + * p: 17n, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * ``` + */ +export function hash_to_field( + msg: TArg, + count: number, + options: TArg +): bigint[][] { + validateObject(options, { + p: 'bigint', + m: 'number', + k: 'number', + hash: 'function', + }); + const { p, k, m, hash, expand, DST } = options; + asafenumber(hash.outputLen, 'valid hash'); + abytes(msg); + asafenumber(count); + // RFC 9380 §5.2 defines hash_to_field over a list of one or more field elements and requires + // extension degree `m >= 1`; rejecting here avoids degenerate `[]` / `[[]]` helper outputs. + if (count < 1) throw new Error('hash_to_field: expected count >= 1'); + if (m < 1) throw new Error('hash_to_field: expected m >= 1'); + const log2p = p.toString(2).length; + const L = Math.ceil((log2p + k) / 8); // section 5.1 of ietf draft link above + const len_in_bytes = count * m * L; + let prb; // pseudo_random_bytes + if (expand === 'xmd') { + prb = expand_message_xmd(msg, DST, len_in_bytes, hash); + } else if (expand === 'xof') { + prb = expand_message_xof(msg, DST, len_in_bytes, k, hash); + } else if (expand === '_internal_pass') { + // for internal tests only + prb = msg; + } else { + throw new Error('expand must be "xmd" or "xof"'); + } + const u = new Array(count); + for (let i = 0; i < count; i++) { + const e = new Array(m); + for (let j = 0; j < m; j++) { + const elm_offset = L * (j + i * m); + const tv = prb.subarray(elm_offset, elm_offset + L); + e[j] = mod(os2ip(tv), p); + } + u[i] = e; + } + return u; +} + +type XY = (x: T, y: T) => { x: T; y: T }; +type XYRatio = [T[], T[], T[], T[]]; // xn/xd, yn/yd +/** + * @param field - Field implementation. + * @param map - Isogeny coefficients. + * @returns Isogeny mapping helper. + * @example + * Build one rational isogeny map, then apply it to affine x/y coordinates. + * + * ```ts + * import { isogenyMap } from '@noble/curves/abstract/hash-to-curve.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const iso = isogenyMap(Fp, [[0n, 1n], [1n], [1n], [1n]]); + * const point = iso(3n, 5n); + * ``` + */ +export function isogenyMap>(field: F, map: XYRatio): XY { + // Make same order as in spec + const coeff = map.map((i) => Array.from(i).reverse()); + return (x: T, y: T) => { + const [xn, xd, yn, yd] = coeff.map((val) => + val.reduce((acc, i) => field.add(field.mul(acc, x), i)) + ); + // RFC 9380 §6.6.3 / Appendix E: denominator-zero exceptional cases must + // return the identity on E. + // Shipped Weierstrass consumers encode that affine identity as all-zero + // coordinates, so `passZero=true` intentionally collapses zero + // denominators to `{ x: 0, y: 0 }`. + const [xd_inv, yd_inv] = FpInvertBatch(field, [xd, yd], true); + x = field.mul(xn, xd_inv); // xNum / xDen + y = field.mul(y, field.mul(yn, yd_inv)); // y * (yNum / yDev) + return { x, y }; + }; +} + +// Keep the shared DST removable when the selected bundle never hashes to scalar. +// Callers that need protocol-specific scalar domain separation must override this generic default. +// RFC 9497 §§4.1-4.5 use this ASCII prefix before appending the ciphersuite context string. +// Export a string instead of mutable bytes so callers cannot poison default hash-to-scalar behavior +// by mutating a shared Uint8Array in place. +export const _DST_scalar = 'HashToScalar-' as const; + +/** + * Creates hash-to-curve methods from EC Point and mapToCurve function. See {@link H2CHasher}. + * @param Point - Point constructor. + * @param mapToCurve - Map-to-curve function. + * @param defaults - Default hash-to-curve options. This object is frozen in place and reused as + * the shared defaults bundle for the returned helpers. + * @returns Hash-to-curve helper namespace. + * @throws If the map-to-curve callback or default hash-to-curve options are invalid. {@link Error} + * @example + * Bundle hash-to-curve, hash-to-scalar, and encode-to-curve helpers for one curve. + * + * ```ts + * import { createHasher } from '@noble/curves/abstract/hash-to-curve.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hasher = createHasher(p256.Point, () => p256.Point.BASE.toAffine(), { + * DST: 'P256_XMD:SHA-256_SSWU_RO_', + * encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + * p: p256.Point.Fp.ORDER, + * m: 1, + * k: 128, + * expand: 'xmd', + * hash: sha256, + * }); + * const point = hasher.encodeToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export function createHasher( + Point: PC, + mapToCurve: MapToCurve>, + defaults: TArg +): H2CHasher { + if (typeof mapToCurve !== 'function') throw new Error('mapToCurve() must be defined'); + // `Point` is intentionally not shape-validated eagerly here: point constructors vary across + // curve families, so this helper only checks the hooks it can validate cheaply. Misconfigured + // suites fail later when hashing first touches Point.fromAffine / Point.ZERO / clearCofactor(). + const snapshot = (src: TArg): TRet => + Object.freeze({ + ...src, + DST: isBytes(src.DST) ? copyBytes(src.DST) : src.DST, + ...(src.encodeDST === undefined + ? {} + : { encodeDST: isBytes(src.encodeDST) ? copyBytes(src.encodeDST) : src.encodeDST }), + }) as TRet; + // Keep one private defaults snapshot for actual hashing and expose fresh + // detached snapshots via the public getter. + // Otherwise a caller could mutate `hasher.defaults.DST` in place and poison + // the singleton hasher for every other consumer in the same process. + const safeDefaults = snapshot(defaults); + function map(num: bigint[]): PC_P { + return Point.fromAffine(mapToCurve(num)) as PC_P; + } + function clear(initial: PC_P): PC_P { + const P = initial.clearCofactor(); + // Keep ZERO as the algebraic cofactor-clearing result here; strict public point-validity + // surfaces may still reject it later, but createHasher.clear() itself is not that boundary. + if (P.equals(Point.ZERO)) return Point.ZERO as PC_P; + P.assertValidity(); + return P as PC_P; + } + + return Object.freeze({ + get defaults() { + return snapshot(safeDefaults); + }, + Point, + + hashToCurve(msg: TArg, options?: TArg): PC_P { + const opts = Object.assign({}, safeDefaults, options); + const u = hash_to_field(msg, 2, opts); + const u0 = map(u[0]); + const u1 = map(u[1]); + return clear(u0.add(u1) as PC_P); + }, + encodeToCurve(msg: TArg, options?: TArg): PC_P { + const optsDst = safeDefaults.encodeDST ? { DST: safeDefaults.encodeDST } : {}; + const opts = Object.assign({}, safeDefaults, optsDst, options); + const u = hash_to_field(msg, 1, opts); + const u0 = map(u[0]); + return clear(u0); + }, + /** See {@link H2CHasher} */ + mapToCurve(scalars: bigint | bigint[]): PC_P { + // Curves with m=1 accept only single scalar + if (safeDefaults.m === 1) { + if (typeof scalars !== 'bigint') throw new Error('expected bigint (m=1)'); + return clear(map([scalars])); + } + if (!Array.isArray(scalars)) throw new Error('expected array of bigints'); + for (const i of scalars) + if (typeof i !== 'bigint') throw new Error('expected array of bigints'); + return clear(map(scalars)); + }, + + // hash_to_scalar can produce 0: https://www.rfc-editor.org/errata/eid8393 + // RFC 9380, draft-irtf-cfrg-bbs-signatures-08. Default scalar DST is the shared generic + // `HashToScalar-` prefix above unless the caller overrides it per invocation. + hashToScalar(msg: TArg, options?: TArg): bigint { + // @ts-ignore + const N = Point.Fn.ORDER; + const opts = Object.assign({}, safeDefaults, { p: N, m: 1, DST: _DST_scalar }, options); + return hash_to_field(msg, 1, opts)[0][0]; + }, + }); +} diff --git a/node_modules/@noble/curves/src/abstract/modular.ts b/node_modules/@noble/curves/src/abstract/modular.ts new file mode 100644 index 0000000..f40eca0 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/modular.ts @@ -0,0 +1,1068 @@ +/** + * Utils for modular division and fields. + * Field over 11 is a finite (Galois) field is integer number operations `mod 11`. + * There is no division: it is replaced by modular multiplicative inverse. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + abool, + abytes, + anumber, + asafenumber, + bitLen, + bytesToNumberBE, + bytesToNumberLE, + numberToBytesBE, + numberToBytesLE, + validateObject, + type TArg, + type TRet, +} from '../utils.ts'; + +// Numbers aren't used in x25519 / x448 builds +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2); +// prettier-ignore +const _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _5n = /* @__PURE__ */ BigInt(5); +// prettier-ignore +const _7n = /* @__PURE__ */ BigInt(7), _8n = /* @__PURE__ */ BigInt(8), _9n = /* @__PURE__ */ BigInt(9); +const _16n = /* @__PURE__ */ BigInt(16); + +/** + * @param a - Dividend value. + * @param b - Positive modulus. + * @returns Reduced value in `[0, b)` only when `b` is positive. + * @throws If the modulus is not positive. {@link Error} + * @example + * Normalize a bigint into one field residue. + * + * ```ts + * mod(-1n, 5n); + * ``` + */ +export function mod(a: bigint, b: bigint): bigint { + if (b <= _0n) throw new Error('mod: expected positive modulus, got ' + b); + const result = a % b; + return result >= _0n ? result : b + result; +} +/** + * Efficiently raise num to a power with modular reduction. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * Low-level helper: callers that need canonical residues must pass a valid `num` for the chosen + * modulus instead of relying on the `power===0/1` fast paths to normalize it. + * @param num - Base value. + * @param power - Exponent value. + * @param modulo - Reduction modulus. + * @returns Modular exponentiation result. + * @throws If the modulus or exponent is invalid. {@link Error} + * @example + * Raise one bigint to a modular power. + * + * ```ts + * pow(2n, 6n, 11n) // 64n % 11n == 9n + * ``` + */ +export function pow(num: bigint, power: bigint, modulo: bigint): bigint { + return FpPow(Field(modulo), num, power); +} + +/** + * Does `x^(2^power)` mod p. `pow2(30, 4)` == `30^(2^4)`. + * Low-level helper: callers that need canonical residues must pass a valid `x` for the chosen + * modulus; the `power===0` fast path intentionally returns the input unchanged. + * @param x - Base value. + * @param power - Number of squarings. + * @param modulo - Reduction modulus. + * @returns Repeated-squaring result. + * @throws If the exponent is negative. {@link Error} + * @example + * Apply repeated squaring inside one field. + * + * ```ts + * pow2(3n, 2n, 11n); + * ``` + */ +export function pow2(x: bigint, power: bigint, modulo: bigint): bigint { + if (power < _0n) throw new Error('pow2: expected non-negative exponent, got ' + power); + let res = x; + while (power-- > _0n) { + res *= res; + res %= modulo; + } + return res; +} + +/** + * Inverses number over modulo. + * Implemented using the {@link https://brilliant.org/wiki/extended-euclidean-algorithm/ | extended Euclidean algorithm}. + * @param number - Value to invert. + * @param modulo - Positive modulus. + * @returns Multiplicative inverse. + * @throws If the modulus is invalid or the inverse does not exist. {@link Error} + * @example + * Compute one modular inverse with the extended Euclidean algorithm. + * + * ```ts + * invert(3n, 11n); + * ``` + */ +export function invert(number: bigint, modulo: bigint): bigint { + if (number === _0n) throw new Error('invert: expected non-zero number'); + if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo); + // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower. + let a = mod(number, modulo); + let b = modulo; + // prettier-ignore + let x = _0n, y = _1n, u = _1n, v = _0n; + while (a !== _0n) { + const q = b / a; + const r = b - a * q; + const m = x - u * q; + const n = y - v * q; + // prettier-ignore + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd = b; + if (gcd !== _1n) throw new Error('invert: does not exist'); + return mod(x, modulo); +} + +function assertIsSquare(Fp: TArg>, root: T, n: T): void { + const F = Fp as IField; + if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root'); +} + +// Not all roots are possible! Example which will throw: +// const NUM = +// n = 72057594037927816n; +// Fp = Field(BigInt('0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab')); +function sqrt3mod4(Fp: TArg>, n: T) { + const F = Fp as IField; + const p1div4 = (F.ORDER + _1n) / _4n; + const root = F.pow(n, p1div4); + assertIsSquare(F, root, n); + return root; +} + +// Equivalent `q = 5 (mod 8)` square-root formula (Atkin-style), not the RFC Appendix I.2 CMOV +// pseudocode verbatim. +function sqrt5mod8(Fp: TArg>, n: T) { + const F = Fp as IField; + const p5div8 = (F.ORDER - _5n) / _8n; + const n2 = F.mul(n, _2n); + const v = F.pow(n2, p5div8); + const nv = F.mul(n, v); + const i = F.mul(F.mul(nv, _2n), v); + const root = F.mul(nv, F.sub(i, F.ONE)); + assertIsSquare(F, root, n); + return root; +} + +// Based on RFC9380, Kong algorithm +// prettier-ignore +function sqrt9mod16(P: bigint): TRet<(Fp: IField, n: T) => T> { + const Fp_ = Field(P); + const tn = tonelliShanks(P); + const c1 = tn(Fp_, Fp_.neg(Fp_.ONE));// 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F + const c2 = tn(Fp_, c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F + const c3 = tn(Fp_, Fp_.neg(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F + const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic + return ((Fp: TArg>, n: T): T => { + const F = Fp as IField; + let tv1 = F.pow(n, c4); // 1. tv1 = x^c4 + let tv2 = F.mul(tv1, c1); // 2. tv2 = c1 * tv1 + const tv3 = F.mul(tv1, c2); // 3. tv3 = c2 * tv1 + const tv4 = F.mul(tv1, c3); // 4. tv4 = c3 * tv1 + const e1 = F.eql(F.sqr(tv2), n); // 5. e1 = (tv2^2) == x + const e2 = F.eql(F.sqr(tv3), n); // 6. e2 = (tv3^2) == x + tv1 = F.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x + tv2 = F.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x + const e3 = F.eql(F.sqr(tv2), n); // 9. e3 = (tv2^2) == x + const root = F.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select sqrt from tv1 & tv2 + assertIsSquare(F, root, n); + return root; + }) as TRet<(Fp: IField, n: T) => T>; +} + +/** + * Tonelli-Shanks square root search algorithm. + * This implementation is variable-time: it searches data-dependently for the first non-residue `Z` + * and for the smallest `i` in the main loop, unlike RFC 9380 Appendix I.4's constant-time shape. + * 1. {@link https://eprint.iacr.org/2012/685.pdf | eprint 2012/685}, page 12 + * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks + * @param P - field order + * @returns function that takes field Fp (created from P) and number n + * @throws If the field is too small, non-prime, or the square root does not exist. {@link Error} + * @example + * Construct a square-root helper for primes that need Tonelli-Shanks. + * + * ```ts + * import { Field, tonelliShanks } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = tonelliShanks(17n)(Fp, 4n); + * ``` + */ +export function tonelliShanks(P: bigint): TRet<(Fp: IField, n: T) => T> { + // Initialization (precomputation). + // Caching initialization could boost perf by 7%. + if (P < _3n) throw new Error('sqrt is not defined for small field'); + // Factor P - 1 = Q * 2^S, where Q is odd + let Q = P - _1n; + let S = 0; + while (Q % _2n === _0n) { + Q /= _2n; + S++; + } + + // Find the first quadratic non-residue Z >= 2 + let Z = _2n; + const _Fp = Field(P); + while (FpLegendre(_Fp, Z) === 1) { + // Basic primality test for P. After x iterations, chance of + // not finding quadratic non-residue is 2^x, so 2^1000. + if (Z++ > 1000) throw new Error('Cannot find square root: probably non-prime P'); + } + // Fast-path; usually done before Z, but we do "primality test". + if (S === 1) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>; + + // Slow-path + // TODO: test on Fp2 and others + let cc = _Fp.pow(Z, Q); // c = z^Q + const Q1div2 = (Q + _1n) / _2n; + return function tonelliSlow(Fp: TArg>, n: T): T { + const F = Fp as IField; + if (F.is0(n)) return n; + // Check if n is a quadratic residue using Legendre symbol + if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root'); + + // Initialize variables for the main loop + let M = S; + let c = F.mul(F.ONE, cc); // c = z^Q, move cc from field _Fp into field Fp + let t = F.pow(n, Q); // t = n^Q, first guess at the fudge factor + let R = F.pow(n, Q1div2); // R = n^((Q+1)/2), first guess at the square root + + // Main loop + // while t != 1 + while (!F.eql(t, F.ONE)) { + if (F.is0(t)) return F.ZERO; // if t=0 return R=0 + let i = 1; + + // Find the smallest i >= 1 such that t^(2^i) ≡ 1 (mod P) + let t_tmp = F.sqr(t); // t^(2^1) + while (!F.eql(t_tmp, F.ONE)) { + i++; + t_tmp = F.sqr(t_tmp); // t^(2^2)... + if (i === M) throw new Error('Cannot find square root'); + } + + // Calculate the exponent for b: 2^(M - i - 1) + const exponent = _1n << BigInt(M - i - 1); // bigint is important + const b = F.pow(c, exponent); // b = 2^(M - i - 1) + + // Update variables + M = i; + c = F.sqr(b); // c = b^2 + t = F.mul(t, c); // t = (t * b^2) + R = F.mul(R, b); // R = R*b + } + return R; + } as TRet<(Fp: IField, n: T) => T>; +} + +/** + * Square root for a finite field. Will try optimized versions first: + * + * 1. P ≡ 3 (mod 4) + * 2. P ≡ 5 (mod 8) + * 3. P ≡ 9 (mod 16) + * 4. Tonelli-Shanks algorithm + * + * Different algorithms can give different roots, it is up to user to decide which one they want. + * For example there is FpSqrtOdd/FpSqrtEven to choose a root by oddness + * (used for hash-to-curve). + * @param P - Field order. + * @returns Square-root helper. The generic fallback inherits Tonelli-Shanks' variable-time + * behavior and this selector assumes prime-field-style integer moduli. + * @throws If the field is unsupported or the square root does not exist. {@link Error} + * @example + * Choose the square-root helper appropriate for one field modulus. + * + * ```ts + * import { Field, FpSqrt } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrt = FpSqrt(17n)(Fp, 4n); + * ``` + */ +export function FpSqrt(P: bigint): TRet<(Fp: IField, n: T) => T> { + // P ≡ 3 (mod 4) => √n = n^((P+1)/4) + if (P % _4n === _3n) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>; + // P ≡ 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf + if (P % _8n === _5n) return sqrt5mod8 as TRet<(Fp: IField, n: T) => T>; + // P ≡ 9 (mod 16) => Kong algorithm, page 11 of https://eprint.iacr.org/2012/685.pdf (algorithm 4) + if (P % _16n === _9n) return sqrt9mod16(P); + // Tonelli-Shanks algorithm + return tonelliShanks(P); +} + +/** + * @param num - Value to inspect. + * @param modulo - Field modulus. + * @returns `true` when the least-significant little-endian bit is set. + * @throws If the modulus is invalid for `mod(...)`. {@link Error} + * @example + * Inspect the low bit used by little-endian sign conventions. + * + * ```ts + * isNegativeLE(3n, 11n); + * ``` + */ +export const isNegativeLE = (num: bigint, modulo: bigint): boolean => + (mod(num, modulo) & _1n) === _1n; + +/** Generic field interface used by prime and extension fields alike. + * Generic helpers treat field operations as pure functions: implementations MUST treat provided + * values/byte buffers as read-only and return detached results instead of mutating arguments. + */ +export interface IField { + /** Field order `q`, which may be prime or a prime power. */ + ORDER: bigint; + /** Canonical encoded byte length. */ + BYTES: number; + /** Canonical encoded bit length. */ + BITS: number; + /** Whether encoded field elements use little-endian bytes. */ + isLE: boolean; + /** Additive identity. */ + ZERO: T; + /** Multiplicative identity. */ + ONE: T; + // 1-arg + /** + * Normalize one value into the field. + * @param num - Input value. + * @returns Normalized field value. + */ + create: (num: T) => T; + /** + * Check whether one value already belongs to the field. + * @param num - Input value. + * Implementations may throw `TypeError` on malformed input types instead of returning `false`. + * @returns Whether the value already belongs to the field. + */ + isValid: (num: T) => boolean; + /** + * Check whether one value is zero. + * @param num - Input value. + * @returns Whether the value is zero. + */ + is0: (num: T) => boolean; + /** + * Check whether one value is non-zero and belongs to the field. + * @param num - Input value. + * Implementations may throw `TypeError` on malformed input types instead of returning `false`. + * @returns Whether the value is non-zero and valid. + */ + isValidNot0: (num: T) => boolean; + /** + * Negate one value. + * @param num - Input value. + * @returns Negated value. + */ + neg(num: T): T; + /** + * Invert one value multiplicatively. + * @param num - Input value. + * @returns Multiplicative inverse. + */ + inv(num: T): T; + /** + * Compute one square root when it exists. + * @param num - Input value. + * @returns Square root. + */ + sqrt(num: T): T; + /** + * Square one value. + * @param num - Input value. + * @returns Squared value. + */ + sqr(num: T): T; + // 2-args + /** + * Compare two field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Whether both values are equal. + */ + eql(lhs: T, rhs: T): boolean; + /** + * Add two normalized field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Sum value. + */ + add(lhs: T, rhs: T): T; + /** + * Subtract two normalized field values. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Difference value. + */ + sub(lhs: T, rhs: T): T; + /** + * Multiply two field values. + * @param lhs - Left value. + * @param rhs - Right value or scalar. + * @returns Product value. + */ + mul(lhs: T, rhs: T | bigint): T; + /** + * Raise one field value to a power. + * @param lhs - Base value. + * @param power - Exponent. + * @returns Power value. + */ + pow(lhs: T, power: bigint): T; + /** + * Divide one field value by another. + * @param lhs - Dividend. + * @param rhs - Divisor or scalar. + * @returns Quotient value. + */ + div(lhs: T, rhs: T | bigint): T; + // N for NonNormalized (for now) + /** + * Add two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Non-normalized sum. + */ + addN(lhs: T, rhs: T): T; + /** + * Subtract two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value. + * @returns Non-normalized difference. + */ + subN(lhs: T, rhs: T): T; + /** + * Multiply two values without re-normalizing the result. + * @param lhs - Left value. + * @param rhs - Right value or scalar. + * @returns Non-normalized product. + */ + mulN(lhs: T, rhs: T | bigint): T; + /** + * Square one value without re-normalizing the result. + * @param num - Input value. + * @returns Non-normalized square. + */ + sqrN(num: T): T; + + // Optional + // Should be same as sgn0 function in + // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1). + // NOTE: sgn0 is "negative in LE", which is the same as odd. + // Negative in LE is a somewhat strange definition anyway. + /** + * Return the RFC 9380 `sgn0`-style oddness bit when supported. + * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook. + * Returns whether the value is odd under the field encoding. + */ + isOdd?(num: T): boolean; + // legendre?(num: T): T; + /** + * Invert many field elements in one batch. + * @param lst - Values to invert. + * @returns Batch of inverses. + */ + invertBatch: (lst: T[]) => T[]; + /** + * Encode one field value into fixed-width bytes. + * Callers that need canonical encodings MUST supply a valid field element. + * Low-level protocols may also use this to serialize raw / non-canonical residues. + * @param num - Input value. + * @returns Fixed-width byte encoding. + */ + toBytes(num: T): Uint8Array; + /** + * Decode one field value from fixed-width bytes. + * @param bytes - Fixed-width byte encoding. + * @param skipValidation - Whether to skip range validation. + * Implementations MUST treat `bytes` as read-only. + * @returns Decoded field value. + */ + fromBytes(bytes: Uint8Array, skipValidation?: boolean): T; + // If c is False, CMOV returns a, otherwise it returns b. + /** + * Constant-time conditional move. + * @param a - Value used when the condition is false. + * @param b - Value used when the condition is true. + * @param c - Selection bit. + * @returns Selected value. + */ + cmov(a: T, b: T, c: boolean): T; +} +// prettier-ignore +// Arithmetic-only subset checked by validateField(). This is intentionally not the full runtime +// IField contract: helpers like `isValidNot0`, `invertBatch`, `toBytes`, `fromBytes`, `cmov`, and +// field-specific extras like `isOdd` are left to the callers that actually need them. +const FIELD_FIELDS = [ + 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr', + 'eql', 'add', 'sub', 'mul', 'pow', 'div', + 'addN', 'subN', 'mulN', 'sqrN' +] as const; +/** + * @param field - Field implementation. + * @returns Validated field. This only checks the arithmetic subset needed by generic helpers; it + * does not guarantee full runtime-method coverage for serialization, batching, `cmov`, or + * field-specific extras beyond positive `BYTES` / `BITS`. + * @throws If the field shape or numeric metadata are invalid. {@link Error} + * @example + * Check that a field implementation exposes the operations curve code expects. + * + * ```ts + * import { Field, validateField } from '@noble/curves/abstract/modular.js'; + * const Fp = validateField(Field(17n)); + * ``` + */ +export function validateField(field: TArg>): TRet> { + const initial = { + ORDER: 'bigint', + BYTES: 'number', + BITS: 'number', + } as Record; + const opts = FIELD_FIELDS.reduce((map, val: string) => { + map[val] = 'function'; + return map; + }, initial); + validateObject(field, opts); + // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN / + // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches. + asafenumber(field.BYTES, 'BYTES'); + asafenumber(field.BITS, 'BITS'); + // Runtime field implementations must expose positive byte/bit sizes; zero leaks through the + // numeric shape checks above but still breaks encoding helpers and cached-length assumptions. + if (field.BYTES < 1 || field.BITS < 1) throw new Error('invalid field: expected BYTES/BITS > 0'); + if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER); + return field as TRet>; +} + +// Generic field functions + +/** + * Same as `pow` but for Fp: non-constant-time. + * Unsafe in some contexts: uses ladder, so can expose bigint bits. + * @param Fp - Field implementation. + * @param num - Base value. + * @param power - Exponent value. + * @returns Powered field element. + * @throws If the exponent is negative. {@link Error} + * @example + * Raise one field element to a public exponent. + * + * ```ts + * import { Field, FpPow } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpPow(Fp, 3n, 5n); + * ``` + */ +export function FpPow(Fp: TArg>, num: T, power: bigint): T { + const F = Fp as IField; + if (power < _0n) throw new Error('invalid exponent, negatives unsupported'); + if (power === _0n) return F.ONE; + if (power === _1n) return num; + let p = F.ONE; + let d = num; + while (power > _0n) { + if (power & _1n) p = F.mul(p, d); + d = F.sqr(d); + power >>= _1n; + } + return p; +} + +/** + * Efficiently invert an array of Field elements. + * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled. + * @param Fp - Field implementation. + * @param nums - Values to invert. + * @param passZero - map 0 to 0 (instead of undefined) + * @returns Inverted values. + * @example + * Invert several field elements with one shared inversion. + * + * ```ts + * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]); + * ``` + */ +export function FpInvertBatch(Fp: TArg>, nums: T[], passZero = false): T[] { + const F = Fp as IField; + const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[]; + // Walk from first to last, multiply them by each other MOD p + const multipliedAcc = nums.reduce((acc, num, i) => { + if (F.is0(num)) return acc; + inverted[i] = acc; + return F.mul(acc, num); + }, F.ONE); + // Invert last element + const invertedAcc = F.inv(multipliedAcc); + // Walk from last to first, multiply them by inverted each other MOD p + nums.reduceRight((acc, num, i) => { + if (F.is0(num)) return acc; + inverted[i] = F.mul(acc, inverted[i]); + return F.mul(acc, num); + }, invertedAcc); + return inverted; +} + +/** + * @param Fp - Field implementation. + * @param lhs - Dividend value. + * @param rhs - Divisor value. + * @returns Division result. + * @throws If the divisor is non-invertible. {@link Error} + * @example + * Divide one field element by another. + * + * ```ts + * import { Field, FpDiv } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const x = FpDiv(Fp, 6n, 3n); + * ``` + */ +export function FpDiv(Fp: TArg>, lhs: T, rhs: T | bigint): T { + const F = Fp as IField; + return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs)); +} + +/** + * Legendre symbol. + * Legendre constant is used to calculate Legendre symbol (a | p) + * which denotes the value of a^((p-1)/2) (mod p). + * + * * (a | p) ≡ 1 if a is a square (mod p), quadratic residue + * * (a | p) ≡ -1 if a is not a square (mod p), quadratic non residue + * * (a | p) ≡ 0 if a ≡ 0 (mod p) + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns Legendre symbol. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Compute the Legendre symbol of one field element. + * + * ```ts + * import { Field, FpLegendre } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const symbol = FpLegendre(Fp, 4n); + * ``` + */ +export function FpLegendre(Fp: TArg>, n: T): -1 | 0 | 1 { + const F = Fp as IField; + // We can use 3rd argument as optional cache of this value + // but seems unneeded for now. The operation is very fast. + const p1mod2 = (F.ORDER - _1n) / _2n; + const powered = F.pow(n, p1mod2); + const yes = F.eql(powered, F.ONE); + const zero = F.eql(powered, F.ZERO); + const no = F.eql(powered, F.neg(F.ONE)); + if (!yes && !zero && !no) throw new Error('invalid Legendre symbol result'); + return yes ? 1 : zero ? 0 : -1; +} + +/** + * @param Fp - Field implementation. + * @param n - Value to inspect. + * @returns `true` when `Fp.sqrt(n)` exists. This includes `0`, even though strict "quadratic + * residue" terminology often reserves that name for the non-zero square class. + * @throws If the field returns an invalid Legendre symbol value. {@link Error} + * @example + * Check whether one field element has a square root in the field. + * + * ```ts + * import { Field, FpIsSquare } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const isSquare = FpIsSquare(Fp, 4n); + * ``` + */ +export function FpIsSquare(Fp: TArg>, n: T): boolean { + const l = FpLegendre(Fp as IField, n); + // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0. + return l !== -1; +} + +/** Byte and bit lengths derived from one scalar order. */ +export type NLength = { + /** Canonical byte length. */ + nByteLength: number; + /** Canonical bit length. */ + nBitLength: number; +}; +/** + * @param n - Curve order. Callers are expected to pass a positive order. + * @param nBitLength - Optional cached bit length. Callers are expected to pass a positive cached + * value when overriding the derived bit length. + * @returns Byte and bit lengths. + * @throws If the order or cached bit length is invalid. {@link Error} + * @example + * Measure the encoding sizes needed for one modulus. + * + * ```ts + * nLength(255n); + * ``` + */ +export function nLength(n: bigint, nBitLength?: number): NLength { + // Bit size, byte size of CURVE.n + if (nBitLength !== undefined) anumber(nBitLength); + if (n <= _0n) throw new Error('invalid n length: expected positive n, got ' + n); + if (nBitLength !== undefined && nBitLength < 1) + throw new Error('invalid n length: expected positive bit length, got ' + nBitLength); + const bits = bitLen(n); + // Cached bit lengths smaller than ORDER would truncate serialized scalars/elements and poison + // any math that relies on the derived field metadata. + if (nBitLength !== undefined && nBitLength < bits) + throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`); + const _nBitLength = nBitLength !== undefined ? nBitLength : bits; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} + +type FpField = IField & Required, 'isOdd'>>; +type SqrtFn = (n: bigint) => bigint; +type FieldOpts = Partial<{ + isLE: boolean; + BITS: number; + sqrt: SqrtFn; + allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0 + modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n +}>; +// Keep the lazy sqrt cache off-instance so Field(...) can return a frozen object. Otherwise the +// cached helper write would keep the field surface externally mutable. +const FIELD_SQRT = new WeakMap>(); +class _Field implements IField { + readonly ORDER: bigint; + readonly BITS: number; + readonly BYTES: number; + readonly isLE: boolean; + readonly ZERO = _0n; + readonly ONE = _1n; + readonly _lengths?: readonly number[]; + private readonly _mod?: boolean; + constructor(ORDER: bigint, opts: FieldOpts = {}) { + // ORDER <= 1 is degenerate: ONE would not be a valid field element and helpers like pow/inv + // would stop modeling field arithmetic. + if (ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER); + let _nbitLength: number | undefined = undefined; + this.isLE = false; + if (opts != null && typeof opts === 'object') { + // Cached bit lengths are trusted here and should already be positive / consistent with ORDER. + if (typeof opts.BITS === 'number') _nbitLength = opts.BITS; + if (typeof opts.sqrt === 'function') + // `_Field.prototype` is frozen below, so custom sqrt hooks must become own properties + // explicitly instead of relying on writable prototype shadowing via assignment. + Object.defineProperty(this, 'sqrt', { value: opts.sqrt, enumerable: true }); + if (typeof opts.isLE === 'boolean') this.isLE = opts.isLE; + if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice()); + if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes; + } + const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength); + if (nByteLength > 2048) throw new Error('invalid field: expected ORDER of <= 2048 bytes'); + this.ORDER = ORDER; + this.BITS = nBitLength; + this.BYTES = nByteLength; + Object.freeze(this); + } + + create(num: bigint) { + return mod(num, this.ORDER); + } + isValid(num: bigint) { + if (typeof num !== 'bigint') + throw new TypeError('invalid field element: expected bigint, got ' + typeof num); + return _0n <= num && num < this.ORDER; // 0 is valid element, but it's not invertible + } + is0(num: bigint) { + return num === _0n; + } + // is valid and invertible + isValidNot0(num: bigint) { + return !this.is0(num) && this.isValid(num); + } + isOdd(num: bigint) { + return (num & _1n) === _1n; + } + neg(num: bigint) { + return mod(-num, this.ORDER); + } + eql(lhs: bigint, rhs: bigint) { + return lhs === rhs; + } + + sqr(num: bigint) { + return mod(num * num, this.ORDER); + } + add(lhs: bigint, rhs: bigint) { + return mod(lhs + rhs, this.ORDER); + } + sub(lhs: bigint, rhs: bigint) { + return mod(lhs - rhs, this.ORDER); + } + mul(lhs: bigint, rhs: bigint) { + return mod(lhs * rhs, this.ORDER); + } + pow(num: bigint, power: bigint): bigint { + return FpPow(this, num, power); + } + div(lhs: bigint, rhs: bigint) { + return mod(lhs * invert(rhs, this.ORDER), this.ORDER); + } + + // Same as above, but doesn't normalize + sqrN(num: bigint) { + return num * num; + } + addN(lhs: bigint, rhs: bigint) { + return lhs + rhs; + } + subN(lhs: bigint, rhs: bigint) { + return lhs - rhs; + } + mulN(lhs: bigint, rhs: bigint) { + return lhs * rhs; + } + + inv(num: bigint) { + return invert(num, this.ORDER); + } + sqrt(num: bigint): bigint { + // Caching sqrt helpers speeds up sqrt9mod16 by 5x and Tonelli-Shanks by about 10% without keeping + // the field instance itself mutable. + let sqrt = FIELD_SQRT.get(this); + if (!sqrt) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER))); + return sqrt(this, num); + } + toBytes(num: bigint) { + // Serialize fixed-width limbs without re-validating the field range. Callers that need a + // canonical encoding must pass a valid element; some protocols intentionally serialize raw + // residues here and reduce or validate them elsewhere. + return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES); + } + fromBytes(bytes: Uint8Array, skipValidation = false) { + abytes(bytes); + const { _lengths: allowedLengths, BYTES, isLE, ORDER, _mod: modFromBytes } = this; + if (allowedLengths) { + // `allowedLengths` must list real positive byte lengths; otherwise empty input would get + // padded into zero and silently decode as a field element. + if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) { + throw new Error( + 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length + ); + } + const padded = new Uint8Array(BYTES); + // isLE add 0 to right, !isLE to the left. + padded.set(bytes, isLE ? 0 : padded.length - bytes.length); + bytes = padded; + } + if (bytes.length !== BYTES) + throw new Error('Field.fromBytes: expected ' + BYTES + ' bytes, got ' + bytes.length); + let scalar = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + if (modFromBytes) scalar = mod(scalar, ORDER); + if (!skipValidation) + if (!this.isValid(scalar)) + throw new Error('invalid field element: outside of range 0..ORDER'); + // Range validation is optional here because some protocols intentionally decode raw residues + // and reduce or validate them elsewhere. + return scalar; + } + // TODO: we don't need it here, move out to separate fn + invertBatch(lst: bigint[]): bigint[] { + return FpInvertBatch(this, lst); + } + // We can't move this out because Fp6, Fp12 implement it + // and it's unclear what to return in there. + cmov(a: bigint, b: bigint, condition: boolean) { + // Field elements have `isValid(...)`; the CMOV branch bit is a direct runtime input, so reject + // non-boolean selectors here instead of letting JS truthiness silently change arithmetic. + abool(condition, 'condition'); + return condition ? b : a; + } +} +// Freeze the shared method surface too; otherwise callers can still poison every Field instance by +// monkey-patching `_Field.prototype` even if each instance is frozen. +Object.freeze(_Field.prototype); + +/** + * Creates a finite field. Major performance optimizations: + * * 1. Denormalized operations like mulN instead of mul. + * * 2. Identical object shape: never add or remove keys. + * * 3. Frozen stable object shape; the lazy sqrt cache lives in a module-level `WeakMap`. + * Fragile: always run a benchmark on a change. + * Security note: operations and low-level serializers like `toBytes` don't check `isValid` for + * all elements for performance and protocol-flexibility reasons; callers are responsible for + * supplying valid elements when they need canonical field behavior. + * This is low-level code, please make sure you know what you're doing. + * + * Note about field properties: + * * CHARACTERISTIC p = prime number, number of elements in main subgroup. + * * ORDER q = similar to cofactor in curves, may be composite `q = p^m`. + * + * @param ORDER - field order, probably prime, or could be composite + * @param opts - Field options such as bit length or endianness. See {@link FieldOpts}. + * @returns Frozen field instance with a stable object shape. This wrapper forwards `opts` straight + * into `_Field`, so it inherits `_Field`'s assumptions about cached sizes and `allowedLengths`. + * @example + * Construct one prime field with optional overrides. + * + * ```ts + * Field(11n); + * ``` + */ +export function Field(ORDER: bigint, opts: FieldOpts = {}): TRet> { + return new _Field(ORDER, opts); +} + +// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)? +// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG). +// which mean we cannot force this via opts. +// Not sure what to do with randomBytes, we can accept it inside opts if wanted. +// Probably need to export getMinHashLength somewhere? +// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) { +// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES; +// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes? +// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); +// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 +// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n; +// return reduced; +// }, + +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Odd square root when two roots exist. The special case `elm = 0` still returns `0`, + * which is the only square root but is not odd. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the odd square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtOdd } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtOdd(Fp, 4n); + * ``` + */ +export function FpSqrtOdd(Fp: TArg>, elm: T): T { + const F = Fp as IField; + if (!F.isOdd) throw new Error("Field doesn't have isOdd"); + const root = F.sqrt(elm); + return F.isOdd(root) ? root : F.neg(root); +} + +/** + * @param Fp - Field implementation. + * @param elm - Value to square-root. + * @returns Even square root. + * @throws If the field lacks oddness checks or the square root does not exist. {@link Error} + * @example + * Select the even square root when two roots exist. + * + * ```ts + * import { Field, FpSqrtEven } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const root = FpSqrtEven(Fp, 4n); + * ``` + */ +export function FpSqrtEven(Fp: TArg>, elm: T): T { + const F = Fp as IField; + if (!F.isOdd) throw new Error("Field doesn't have isOdd"); + const root = F.sqrt(elm); + return F.isOdd(root) ? F.neg(root) : root; +} + +/** + * Returns total number of bytes consumed by the field element. + * For example, 32 bytes for usual 256-bit weierstrass curve. + * @param fieldOrder - number of field elements, usually CURVE.n. Callers are expected to pass an + * order greater than 1. + * @returns byte length of field + * @throws If the field order is not a bigint. {@link Error} + * @example + * Read the fixed-width byte length of one field. + * + * ```ts + * getFieldBytesLength(255n); + * ``` + */ +export function getFieldBytesLength(fieldOrder: bigint): number { + if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint'); + // Valid field elements are in 0..ORDER-1, so ORDER <= 1 would make the encoded range degenerate. + if (fieldOrder <= _1n) throw new Error('field order must be greater than 1'); + // Valid field elements are < ORDER, so the maximal encoded element is ORDER - 1. + const bitLength = bitLen(fieldOrder - _1n); + return Math.ceil(bitLength / 8); +} + +/** + * Returns minimal amount of bytes that can be safely reduced + * by field order. + * Should be 2^-128 for 128-bit curve such as P256. + * This is the reduction / modulo-bias lower bound; higher-level helpers may still impose a larger + * absolute floor for policy reasons. + * @param fieldOrder - number of field elements greater than 1, usually CURVE.n. + * @returns byte length of target hash + * @throws If the field order is invalid. {@link Error} + * @example + * Compute the minimum hash length needed for field reduction. + * + * ```ts + * getMinHashLength(255n); + * ``` + */ +export function getMinHashLength(fieldOrder: bigint): number { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} + +/** + * "Constant-time" private key generation utility. + * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF + * and convert them into private scalar, with the modulo bias being negligible. + * Needs at least 48 bytes of input for 32-byte private key. The implementation also keeps a hard + * 16-byte minimum even when `getMinHashLength(...)` is smaller, so toy-small inputs do not look + * accidentally acceptable for real scalar derivation. + * 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}, + * {@link https://csrc.nist.gov/publications/detail/fips/186/5/final | FIPS 186-5 appendix A.2}, and + * {@link https://www.rfc-editor.org/rfc/rfc9380#section-5 | RFC 9380 section 5}. Unlike RFC 9380 + * `hash_to_field`, this helper intentionally maps into the non-zero private-scalar range `1..n-1`. + * @param key - Uniform input bytes. + * @param fieldOrder - Size of subgroup. + * @param isLE - interpret hash bytes as LE num + * @returns valid private scalar + * @throws If the hash length or field order is invalid for scalar reduction. {@link Error} + * @example + * Map hash output into a private scalar range. + * + * ```ts + * mapHashToField(new Uint8Array(48).fill(1), 255n); + * ``` + */ +export function mapHashToField( + key: TArg, + fieldOrder: bigint, + isLE = false +): TRet { + abytes(key); + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = Math.max(getMinHashLength(fieldOrder), 16); + // No toy-small inputs: the helper is for real scalar derivation, not tiny test curves. No huge + // inputs: easier to reason about JS timing / allocation behavior. + if (len < minLen || len > 1024) + throw new Error('expected ' + minLen + '-1024 bytes of input, got ' + len); + const num = isLE ? bytesToNumberLE(key) : bytesToNumberBE(key); + // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0 + const reduced = mod(num, fieldOrder - _1n) + _1n; + return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} diff --git a/node_modules/@noble/curves/src/abstract/montgomery.ts b/node_modules/@noble/curves/src/abstract/montgomery.ts new file mode 100644 index 0000000..cf49cd5 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/montgomery.ts @@ -0,0 +1,271 @@ +/** + * Montgomery curve methods. It's not really whole montgomery curve, + * just bunch of very specific methods for X25519 / X448 from + * [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748) + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + abytes, + aInRange, + bytesToNumberLE, + copyBytes, + numberToBytesLE, + randomBytes, + validateObject, + type CryptoKeys, + type TArg, + type TRet, +} from '../utils.ts'; +import { createKeygen, type CurveLengths } from './curve.ts'; +import { mod } from './modular.ts'; + +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); + +/** Curve-specific hooks required to build one X25519/X448 helper. */ +export type MontgomeryOpts = { + /** Prime field modulus. */ + P: bigint; + /** RFC 7748 variant name. */ + type: 'x25519' | 'x448'; + /** + * Clamp or otherwise normalize one scalar byte string before use. + * @param bytes - Raw secret scalar bytes. + * @returns Adjusted scalar bytes ready for Montgomery multiplication. + */ + adjustScalarBytes: (bytes: TArg) => TRet; + /** + * Invert one field element with exponentiation by `p - 2`. + * @param x - Field element to invert. + * @returns Multiplicative inverse of `x`. + */ + powPminus2: (x: bigint) => bigint; + /** + * Optional randomness source for `keygen()` and `utils.randomSecretKey()`. + * Receives the requested byte length and returns fresh random bytes. + */ + randomBytes?: (bytesLength?: number) => TRet; +}; + +/** Public X25519/X448 ECDH API built on a Montgomery ladder. */ +export type MontgomeryECDH = { + /** + * Multiply one scalar by one Montgomery `u` coordinate. + * @param scalar - Secret scalar bytes. + * @param u - Public Montgomery `u` coordinate. + * @returns Shared point encoded as bytes. + */ + scalarMult: (scalar: TArg, u: TArg) => TRet; + /** + * Multiply one scalar by the curve base point. + * @param scalar - Secret scalar bytes. + * @returns Public key bytes. + */ + scalarMultBase: (scalar: TArg) => TRet; + /** + * Derive a shared secret from a local secret key and peer public key. + * @param secretKeyA - Local secret key bytes. + * @param publicKeyB - Peer public key bytes. + * Rejects low-order public inputs instead of returning the all-zero shared secret. + * @returns Shared secret bytes. + */ + getSharedSecret: (secretKeyA: TArg, publicKeyB: TArg) => TRet; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: TArg) => TRet; + /** Utility helpers for secret-key generation. */ + utils: { + /** Generate one random secret key with the curve's expected byte length. */ + randomSecretKey: () => TRet; + }; + /** Encoded Montgomery base point `u`. */ + GuBytes: TRet; + /** Public lengths for keys and seeds. */ + lengths: CurveLengths; + /** + * Generate one random secret/public keypair. + * @param seed - Optional seed bytes to use instead of random generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; +}; + +function validateOpts(curve: TArg) { + // Validate constructor config eagerly, but do not call user-provided hooks here: + // `randomBytes` may be transcript-backed or otherwise contextual. Runtime type checks are + // enough to fail fast on malformed configs without consuming user state. + validateObject( + curve, + { + P: 'bigint', + type: 'string', + adjustScalarBytes: 'function', + powPminus2: 'function', + }, + { + randomBytes: 'function', + } + ); + return Object.freeze({ ...curve } as const); +} + +/** + * @param curveDef - Montgomery curve definition. + * @returns ECDH helper namespace. + * @throws If the curve definition or derived shared point is invalid. {@link Error} + * @example + * Perform one X25519 key exchange through the generic Montgomery helper. + * + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export function montgomery(curveDef: TArg): TRet { + const CURVE = validateOpts(curveDef); + const { P, type, adjustScalarBytes, powPminus2, randomBytes: rand } = CURVE; + const is25519 = type === 'x25519'; + if (!is25519 && type !== 'x448') throw new Error('invalid type'); + const randomBytes_ = rand === undefined ? randomBytes : rand; + + const montgomeryBits = is25519 ? 255 : 448; + const fieldLen = is25519 ? 32 : 56; + const Gu = is25519 ? BigInt(9) : BigInt(5); + // RFC 7748 #5: + // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 and + // (156326 - 2) / 4 = 39081 for curve448/X448 + // const a = is25519 ? 486662n : 156326n; + const a24 = is25519 ? BigInt(121665) : BigInt(39081); + // RFC: x25519 "the resulting integer is of the form 2^254 plus + // eight times a value between 0 and 2^251 - 1 (inclusive)" + // x448: "2^447 plus four times a value between 0 and 2^445 - 1 (inclusive)" + const minScalar = is25519 ? _2n ** BigInt(254) : _2n ** BigInt(447); + const maxAdded = is25519 + ? BigInt(8) * _2n ** BigInt(251) - _1n + : BigInt(4) * _2n ** BigInt(445) - _1n; + const maxScalar = minScalar + maxAdded + _1n; // (inclusive) + const modP = (n: bigint) => mod(n, P); + const GuBytes = encodeU(Gu); + function encodeU(u: bigint): TRet { + return numberToBytesLE(modP(u), fieldLen); + } + function decodeU(u: TArg): bigint { + const _u = copyBytes(abytes(u, fieldLen, 'uCoordinate')); + // RFC: When receiving such an array, implementations of X25519 + // (but not X448) MUST mask the most significant bit in the final byte. + if (is25519) _u[31] &= 127; // 0b0111_1111 + // RFC: Implementations MUST accept non-canonical values and process them as + // if they had been reduced modulo the field prime. The non-canonical + // values are 2^255 - 19 through 2^255 - 1 for X25519 and 2^448 - 2^224 + // - 1 through 2^448 - 1 for X448. + return modP(bytesToNumberLE(_u)); + } + function decodeScalar(scalar: TArg): bigint { + return bytesToNumberLE(adjustScalarBytes(copyBytes(abytes(scalar, fieldLen, 'scalar')))); + } + function scalarMult(scalar: TArg, u: TArg): TRet { + const pu = montgomeryLadder(decodeU(u), decodeScalar(scalar)); + // Some public keys are useless, of low-order. Curve author doesn't think + // it needs to be validated, but we do it nonetheless. + // https://cr.yp.to/ecdh.html#validate + if (pu === _0n) throw new Error('invalid private or public key received'); + return encodeU(pu); + } + // Computes public key from private. By doing scalar multiplication of base point. + function scalarMultBase(scalar: TArg): TRet { + return scalarMult(scalar, GuBytes); + } + const getPublicKey = scalarMultBase; + const getSharedSecret = scalarMult; + + // cswap from RFC7748 "example code" + function cswap(swap: bigint, x_2: bigint, x_3: bigint): { x_2: bigint; x_3: bigint } { + // dummy = mask(swap) AND (x_2 XOR x_3) + // Where mask(swap) is the all-1 or all-0 word of the same length as x_2 + // and x_3, computed, e.g., as mask(swap) = 0 - swap. + const dummy = modP(swap * (x_2 - x_3)); + x_2 = modP(x_2 - dummy); // x_2 = x_2 XOR dummy + x_3 = modP(x_3 + dummy); // x_3 = x_3 XOR dummy + return { x_2, x_3 }; + } + + /** + * Montgomery x-only multiplication ladder for the selected X25519/X448 curve. + * @param pointU - decoded Montgomery u coordinate for the selected curve + * @param scalar - decoded clamped scalar by which the point is multiplied + * @returns resulting Montgomery u coordinate for the selected curve + */ + function montgomeryLadder(u: bigint, scalar: bigint): bigint { + aInRange('u', u, _0n, P); + aInRange('scalar', scalar, minScalar, maxScalar); + const k = scalar; + const x_1 = u; + let x_2 = _1n; + let z_2 = _0n; + let x_3 = u; + let z_3 = _1n; + let swap = _0n; + for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) { + const k_t = (k >> t) & _1n; + swap ^= k_t; + ({ x_2, x_3 } = cswap(swap, x_2, x_3)); + ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3)); + swap = k_t; + + const A = x_2 + z_2; + const AA = modP(A * A); + const B = x_2 - z_2; + const BB = modP(B * B); + const E = AA - BB; + const C = x_3 + z_3; + const D = x_3 - z_3; + const DA = modP(D * A); + const CB = modP(C * B); + const dacb = DA + CB; + const da_cb = DA - CB; + x_3 = modP(dacb * dacb); + z_3 = modP(x_1 * modP(da_cb * da_cb)); + x_2 = modP(AA * BB); + z_2 = modP(E * (AA + modP(a24 * E))); + } + ({ x_2, x_3 } = cswap(swap, x_2, x_3)); + ({ x_2: z_2, x_3: z_3 } = cswap(swap, z_2, z_3)); + const z2 = powPminus2(z_2); // `Fp.pow(x, P - _2n)` is much slower equivalent + return modP(x_2 * z2); // Return x_2 * (z_2^(p - 2)) + } + const lengths = { + secretKey: fieldLen, + publicKey: fieldLen, + seed: fieldLen, + }; + const randomSecretKey = (seed?: TArg): TRet => { + seed = seed === undefined ? randomBytes_(fieldLen) : seed; + abytes(seed, lengths.seed, 'seed'); + // Reuse caller-supplied seed bytes verbatim; clamping is deferred until + // decodeScalar(...) when the secret key is actually used. + return seed as TRet; + }; + const utils = { randomSecretKey }; + Object.freeze(lengths); + Object.freeze(utils); + + return Object.freeze({ + keygen: createKeygen(randomSecretKey, getPublicKey), + getSharedSecret, + getPublicKey, + scalarMult, + scalarMultBase, + utils, + GuBytes: GuBytes.slice() as TRet, + lengths, + }) satisfies CryptoKeys; +} diff --git a/node_modules/@noble/curves/src/abstract/oprf.ts b/node_modules/@noble/curves/src/abstract/oprf.ts new file mode 100644 index 0000000..32dab93 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/oprf.ts @@ -0,0 +1,789 @@ +/** + * RFC 9497: Oblivious Pseudorandom Functions (OPRFs) Using Prime-Order Groups. + * https://www.rfc-editor.org/rfc/rfc9497 + * + +OPRF allows to interactively create an `Output = PRF(Input, serverSecretKey)`: + +- Server cannot calculate Output by itself: it doesn't know Input +- Client cannot calculate Output by itself: it doesn't know server secretKey +- An attacker interception the communication can't restore Input/Output/serverSecretKey and can't + link Input to some value. + +## Issues + +- Low-entropy inputs (e.g. password '123') enable brute-forced dictionary attacks by the server + (solveable by domain separation in POPRF) +- High-level protocol needs to be constructed on top, because OPRF is low-level + +## Use cases + +1. **Password-Authenticated Key Exchange (PAKE):** Enables secure password login (e.g., OPAQUE) + without revealing the password to the server. +2. **Private Set Intersection (PSI):** Allows two parties to compute the intersection of their + private sets without revealing non-intersecting elements. +3. **Anonymous Credential Systems:** Supports issuance of anonymous, unlinkable credentials + (e.g., Privacy Pass) using blind OPRF evaluation. +4. **Private Information Retrieval (PIR):** Helps users query databases without revealing which + item they accessed. +5. **Encrypted Search / Secure Indexing:** Enables keyword search over encrypted data while keeping + queries private. +6. **Spam Prevention and Rate-Limiting:** Issues anonymous tokens to prevent abuse + (e.g., CAPTCHA bypass) without compromising user privacy. + +## Modes + +- OPRF: simple mode, client doesn't need to know server public key +- VOPRF: verifiable mode. It lets the client verify that the server used the + secret key corresponding to a known public key +- POPRF: partially oblivious mode, VOPRF + domain separation + +There is also non-interactive mode (Evaluate), which creates Output +non-interactively with knowledge of the secret key. + +Flow: +- (once) Server generates secret and public keys, distributes public keys to clients + - deterministically: `deriveKeyPair` or just random: `generateKeyPair` +- Client blinds input: `blind(secretInput)` +- Server evaluates blinded input: `blindEvaluate` generated by client, sends result to client +- Client creates output using result of evaluation via 'finalize' + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + abytes, + asciiToBytes, + bytesToNumberBE, + bytesToNumberLE, + concatBytes, + numberToBytesBE, + randomBytes, + validateObject, + type TArg, + type TRet, +} from '../utils.ts'; +import { pippenger, validatePointCons, type CurvePoint, type CurvePointCons } from './curve.ts'; +import { _DST_scalar, type H2CDSTOpts } from './hash-to-curve.ts'; +import { getMinHashLength, mapHashToField } from './modular.ts'; + +// OPRF is designed to be used across network, so we default to serialized values. +/** Serialized group element passed between OPRF participants. */ +export type PointBytes = Uint8Array; +/** Serialized scalar used for blinds and server secret keys. */ +export type ScalarBytes = Uint8Array; +/** Arbitrary byte input or output used by the OPRF protocol. */ +export type Bytes = Uint8Array; +const _DST_scalarBytes = /* @__PURE__ */ asciiToBytes(_DST_scalar); +/** Cryptographically secure byte generator used for blinds and proofs. */ +export type RNG = typeof randomBytes; + +/** Curve and hash hooks required to instantiate one OPRF ciphersuite. */ +export type OPRFOpts

> = { + /** Human-readable suite identifier used for domain separation. */ + name: string; + /** + * Prime-order group used by the OPRF construction. + * Kept generic because the suite returns serialized points. + */ + Point: CurvePointCons

; + // Fn: IField; + /** + * Hash function used for transcripts, proofs, and outputs. + * @param msg - Message bytes to hash. + * @returns Digest bytes. + */ + hash(msg: TArg): TRet; + /** + * Hash arbitrary bytes into one scalar in the suite order. + * @param msg - Message bytes to map. + * @param options - Hash-to-field domain-separation options. See {@link H2CDSTOpts}. + * Implementations MUST treat `msg` and `options` as read-only. + * @returns Scalar in the suite order. + */ + hashToScalar(msg: TArg, options: TArg): bigint; + /** + * Hash arbitrary bytes directly onto one curve point. + * @param msg - Message bytes to map. + * @param options - Hash-to-curve domain-separation options. See {@link H2CDSTOpts}. + * Implementations MUST treat `msg` and `options` as read-only. + * @returns Point on the suite curve. + */ + hashToGroup(msg: TArg, options: TArg): P; +}; + +/** Server keypair for one OPRF suite. */ +export type OPRFKeys = { + /** Secret scalar kept by the server. */ + secretKey: TRet; + /** Public point distributed to clients in verifiable modes. */ + publicKey: TRet; +}; +/** Result of the client-side blind step. */ +export type OPRFBlind = { + /** Secret blind scalar that the client keeps locally. */ + blind: TRet; + /** Blinded group element sent to the server. */ + blinded: TRet; +}; +/** Server response for one verifiable OPRF evaluation. */ +export type OPRFBlindEval = { + /** Evaluated group element returned by the server. */ + evaluated: TRet; + /** DLEQ proof binding the evaluation to the server public key. */ + proof: TRet; +}; +/** Server response for a batch of verifiable OPRF evaluations. */ +export type OPRFBlindEvalBatch = { + /** Evaluated group elements returned for each blinded input. */ + evaluated: TRet; + /** Batch proof covering all evaluated elements. */ + proof: TRet; +}; +/** One finalized transcript item used by batch verification helpers. */ +export type OPRFFinalizeItem = { + /** Original client input. */ + input: Bytes; + /** Secret blind scalar used for the input. */ + blind: ScalarBytes; + /** Evaluated point returned by the server. */ + evaluated: PointBytes; + /** Blinded point originally sent to the server. */ + blinded: PointBytes; +}; +/** Result of the POPRF client-side blind step with the tweaked server public key. */ +export type OPRFBlindTweaked = OPRFBlind & { tweakedKey: TRet }; + +/** + * Represents a full OPRF ciphersuite implementation according to RFC 9497. + * This object bundles the three protocol variants (OPRF, VOPRF, POPRF) for a specific + * prime-order group and hash function combination. + * + * @see https://www.rfc-editor.org/rfc/rfc9497.html + */ +export type OPRF = { + /** + * The unique identifier for the ciphersuite, e.g., "ristretto255-SHA512". + * This name is used for domain separation to prevent cross-protocol attacks. + */ + readonly name: string; + + /** + * The base Oblivious Pseudorandom Function (OPRF) mode (mode 0x00). + * This is a two-party protocol between a client and a server to compute F(k, x) + * where 'k' is the server's key and 'x' is the client's input. + * + * The client learns the output F(k, x) but nothing about 'k'. + * The server learns nothing about 'x' or F(k, x). + * This mode is NOT verifiable; the client cannot prove the server used a specific key. + */ + readonly oprf: { + /** + * (Server-side) Generates a new random private/public key pair for the server. + * @returns A new key pair. + */ + generateKeyPair(): TRet; + + /** + * (Server-side) Deterministically derives a private/public key pair from a seed. + * @param seed - A 32-byte cryptographically secure random seed. + * @param keyInfo - An optional byte string for domain separation. + * @returns The derived key pair. + */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + + /** + * (Client-side) The first step of the protocol. The client blinds its private input. + * @param input - The client's private input bytes. + * @param rng - An optional cryptographically secure random number generator. + * @returns An object containing the `blind` scalar (which the client MUST keep secret) + * and the `blinded` element (which the client sends to the server). + */ + blind(input: TArg, rng?: RNG): TRet; + + /** + * (Server-side) The second step. The server evaluates the client's blinded element + * using its secret key. + * @param secretKey - The server's private key. + * @param blinded - The blinded group element received from the client. + * @returns The evaluated group element, to be sent back to the client. + */ + blindEvaluate(secretKey: TArg, blinded: TArg): TRet; + + /** + * (Client-side) The final step. The client unblinds the server's response to + * compute the final OPRF output. + * @param input - The original private input from the `blind` step. + * @param blind - The secret scalar from the `blind` step. + * @param evaluated - The evaluated group element received from the server. + * @returns The final OPRF output, `Hash(len(input)||input||len(unblinded)||unblinded||"Finalize")`. + */ + finalize( + input: TArg, + blind: TArg, + evaluated: TArg + ): TRet; + }; + + /** + * The Verifiable Oblivious Pseudorandom Function (VOPRF) mode (mode 0x01). + * This mode extends the base OPRF by providing a proof that the server used the + * secret key corresponding to its known public key. + */ + readonly voprf: { + /** (Server-side) Generates a key pair for the VOPRF mode. */ + generateKeyPair(): TRet; + /** (Server-side) Deterministically derives a key pair for the VOPRF mode. */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + /** (Client-side) Blinds the client's private input for the VOPRF protocol. */ + blind(input: TArg, rng?: RNG): TRet; + + /** + * (Server-side) Evaluates the client's blinded element and generates a DLEQ proof + * of correctness. + * @param secretKey - The server's private key. + * @param publicKey - The server's public key, used in proof generation. + * @param blinded - The blinded group element received from the client. + * @param rng - An optional cryptographically secure random number generator for the proof. + * @returns The evaluated element and a proof of correct computation. + */ + blindEvaluate( + secretKey: TArg, + publicKey: TArg, + blinded: TArg, + rng?: RNG + ): TRet; + + /** + * (Server-side) An optimized batch version of `blindEvaluate`. It evaluates multiple + * blinded elements and produces a single, constant-size proof for the entire batch, + * amortizing the cost of proof generation. + * @param secretKey - The server's private key. + * @param publicKey - The server's public key. + * @param blinded - An array of blinded group elements from one or more clients. + * @param rng - An optional cryptographically secure random number generator for the proof. + * @returns An array of evaluated elements and a single proof for the batch. + */ + blindEvaluateBatch( + secretKey: TArg, + publicKey: TArg, + blinded: TArg, + rng?: RNG + ): TRet; + + /** + * (Client-side) The final step. The client verifies the server's proof, and if valid, + * unblinds the result to compute the final VOPRF output. + * @param input - The original private input. + * @param blind - The secret scalar from the `blind` step. + * @param evaluated - The evaluated element from the server. + * @param blinded - The blinded element sent to the server (needed for proof verification). + * @param publicKey - The server's public key against which the proof is verified. + * @param proof - The DLEQ proof from the server. + * @returns The final VOPRF output. + * @throws If the proof verification fails. {@link Error} + */ + finalize( + input: TArg, + blind: TArg, + evaluated: TArg, + blinded: TArg, + publicKey: TArg, + proof: TArg + ): TRet; + + /** + * (Client-side) The batch-aware version of `finalize`. It verifies a single batch proof + * against a list of corresponding inputs and outputs. + * @param items - An array of objects, each containing the parameters for a single finalization. + * @param publicKey - The server's public key. + * @param proof - The single DLEQ proof for the entire batch. + * @returns An array of final VOPRF outputs, one for each item in the input. + * @throws If the proof verification fails. {@link Error} + */ + finalizeBatch( + items: TArg, + publicKey: TArg, + proof: TArg + ): TRet; + }; + + /** + * A factory for the Partially Oblivious Pseudorandom Function (POPRF) mode (mode 0x02). + * This mode extends VOPRF to include a public `info` parameter, known to both client and + * server, which is cryptographically bound to the final output. + * This is useful for domain separation at the application level. + * @param info - A public byte string to be mixed into the computation. + * @returns An object with the POPRF protocol functions. + */ + readonly poprf: (info: TArg) => { + /** (Server-side) Generates a key pair for the POPRF mode. */ + generateKeyPair(): TRet; + /** (Server-side) Deterministically derives a key pair for the POPRF mode. */ + deriveKeyPair(seed: TArg, keyInfo: TArg): TRet; + + /** + * (Client-side) Blinds the client's private input and computes the "tweaked key". + * The tweaked key is a public value derived from the server's public key and the public `info`. + * @param input - The client's private input. + * @param publicKey - The server's public key. + * @param rng - An optional cryptographically secure random number generator. + * @returns The `blind`, `blinded` element, and the `tweakedKey` + * the client uses for verification. + */ + blind(input: TArg, publicKey: TArg, rng?: RNG): TRet; + + /** + * (Server-side) Evaluates the blinded element using a key derived from + * its secret key and the public `info`. + * It generates a DLEQ proof against the tweaked key. + * @param secretKey - The server's private key. + * @param blinded - The blinded element from the client. + * @param rng - An optional RNG for the proof. + * @returns The evaluated element and a proof of correct computation. + */ + blindEvaluate( + secretKey: TArg, + blinded: TArg, + rng?: RNG + ): TRet; + + /** + * (Server-side) A batch-aware version of `blindEvaluate` for the POPRF mode. + * @param secretKey - The server's private key. + * @param blinded - An array of blinded elements. + * @param rng - An optional RNG for the proof. + * @returns An array of evaluated elements and a single proof for the batch. + */ + blindEvaluateBatch( + secretKey: TArg, + blinded: TArg, + rng: RNG + ): TRet; + + /** + * (Client-side) A batch-aware version of `finalize` for the POPRF mode. + * It verifies the proof against the tweaked key. + * @param items - An array containing the parameters for each finalization. + * @param proof - The single DLEQ proof for the batch. + * @param tweakedKey - The tweaked key corresponding to the proof. + * All items must share the same `info` and `publicKey`. + * @returns An array of final POPRF outputs. + * @throws If proof verification fails. {@link Error} + */ + finalizeBatch( + items: TArg, + proof: TArg, + tweakedKey: TArg + ): TRet; + + /** + * (Client-side) Finalizes the POPRF protocol. It verifies the server's proof against the + * `tweakedKey` computed in the `blind` step. The final output is bound to the public `info`. + * @param input - The original private input. + * @param blind - The secret scalar. + * @param evaluated - The evaluated element from the server. + * @param blinded - The blinded element sent to the server. + * @param proof - The DLEQ proof from the server. + * @param tweakedKey - The public tweaked key computed by the client during the `blind` step. + * @returns The final POPRF output. + * @throws If proof verification fails. {@link Error} + */ + finalize( + input: TArg, + blind: TArg, + evaluated: TArg, + blinded: TArg, + proof: TArg, + tweakedKey: TArg + ): TRet; + + /** + * A non-interactive evaluation function for an entity that knows all inputs. + * Computes the final POPRF output directly. Useful for testing or specific applications + * where the server needs to compute the output for a known input. + * @param secretKey - The server's private key. + * @param input - The client's private input. + * @returns The final POPRF output. + */ + evaluate(secretKey: TArg, input: TArg): TRet; + }; +}; + +// welcome to generic hell +/** + * @param opts - OPRF ciphersuite options. See {@link OPRFOpts}. + * @returns OPRF helper namespace. + * @example + * Instantiate an OPRF suite from curve-specific hashing hooks. + * + * ```ts + * import { createOPRF } from '@noble/curves/abstract/oprf.js'; + * import { p256, p256_hasher } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const oprf = createOPRF({ + * name: 'P256-SHA256', + * Point: p256.Point, + * hash: sha256, + * hashToGroup: p256_hasher.hashToCurve, + * hashToScalar: p256_hasher.hashToScalar, + * }); + * const keys = oprf.oprf.generateKeyPair(); + * ``` + */ +export function createOPRF

>(opts: OPRFOpts

): TRet { + validateObject(opts, { + name: 'string', + hash: 'function', + hashToScalar: 'function', + hashToGroup: 'function', + }); + // Cheap constructor-surface sanity check only: this verifies the generic static hooks/fields that + // OPRF consumes, but it does not certify point semantics like BASE/ZERO correctness. + validatePointCons(opts.Point); + const { name, Point, hash } = opts; + const { Fn } = Point; + + const hashToGroup = (msg: TArg, ctx: TArg) => + opts.hashToGroup(msg, { + DST: concatBytes(asciiToBytes('HashToGroup-'), ctx), + }) as P; + const hashToScalarPrefixed = (msg: TArg, ctx: TArg) => + opts.hashToScalar(msg, { DST: concatBytes(_DST_scalarBytes, ctx) }); + const randomScalar = (rng: RNG = randomBytes) => { + // RFC 9497 §2.1 defines RandomScalar as nonzero; blind inversion and generated public keys + // both rely on keeping this helper in the `1..n-1` range. + const t = mapHashToField(rng(getMinHashLength(Fn.ORDER)), Fn.ORDER, Fn.isLE); + // We cannot use Fn.fromBytes here, because field + // can have different number of bytes (like ed448) + return Fn.isLE ? bytesToNumberLE(t) : bytesToNumberBE(t); + }; + + const msm = (points: P[], scalars: bigint[]) => pippenger(Point, points, scalars); + + const getCtx = (mode: number) => + concatBytes(asciiToBytes('OPRFV1-'), new Uint8Array([mode]), asciiToBytes('-' + name)); + const ctxOPRF = getCtx(0x00); + const ctxVOPRF = getCtx(0x01); + const ctxPOPRF = getCtx(0x02); + + function encode(...args: TArg<(Uint8Array | number | string)[]>): TRet { + const res = []; + for (const a of args) { + if (typeof a === 'number') res.push(numberToBytesBE(a, 2)); + else if (typeof a === 'string') res.push(asciiToBytes(a)); + else { + abytes(a); + res.push(numberToBytesBE(a.length, 2), a); + } + } + // No wipe here, since will modify actual bytes + return concatBytes(...res) as TRet; + } + const inputBytes = (title: string, bytes: TArg) => { + abytes(bytes, undefined, title); + // RFC 9497 §1.2 limits PrivateInput/PublicInput to 2^16 - 1 bytes because these values are + // length-prefixed with two bytes before use throughout the protocol. + if (bytes.length > 0xffff) + throw new Error( + `"${title}" expected Uint8Array of length <= 65535, got length=${bytes.length}` + ); + return bytes; + }; + const hashInput = (...bytes: TArg): TRet => + hash(encode(...bytes, 'Finalize')) as TRet; + + function getTranscripts(B: P, C: P[], D: P[], ctx: TArg) { + const Bm = B.toBytes(); + const seed = hash(encode(Bm, concatBytes(asciiToBytes('Seed-'), ctx))); + const res: bigint[] = []; + for (let i = 0; i < C.length; i++) { + const Ci = C[i].toBytes(); + const Di = D[i].toBytes(); + const di = hashToScalarPrefixed(encode(seed, i, Ci, Di, 'Composite'), ctx); + res.push(di); + } + return res; + } + + function computeComposites(B: P, C: P[], D: P[], ctx: TArg) { + const T = getTranscripts(B, C, D, ctx); + const M = msm(C, T); + const Z = msm(D, T); + return { M, Z }; + } + + function computeCompositesFast( + k: bigint, + B: P, + C: P[], + D: P[], + ctx: TArg + ): { M: P; Z: P } { + const T = getTranscripts(B, C, D, ctx); + const M = msm(C, T); + // RFC 9497 §2.2.1 ComputeCompositesFast derives weights from both C and D in getTranscripts(), + // then uses the server shortcut Z = k * M instead of a second MSM over D. + const Z = M.multiply(k); + return { M, Z }; + } + + function challengeTranscript(B: P, M: P, Z: P, t2: P, t3: P, ctx: TArg) { + const [Bm, a0, a1, a2, a3] = [B, M, Z, t2, t3].map((i) => i.toBytes()); + return hashToScalarPrefixed(encode(Bm, a0, a1, a2, a3, 'Challenge'), ctx); + } + + function generateProof(ctx: TArg, k: bigint, B: P, C: P[], D: P[], rng: RNG): TRet { + const { M, Z } = computeCompositesFast(k, B, C, D, ctx); + const r = randomScalar(rng); + const t2 = Point.BASE.multiply(r); + const t3 = M.multiply(r); + const c = challengeTranscript(B, M, Z, t2, t3, ctx); + const s = Fn.sub(r, Fn.mul(c, k)); // r - c*k + return concatBytes(...[c, s].map((i) => Fn.toBytes(i))) as TRet; + } + + function verifyProof(ctx: TArg, B: P, C: P[], D: P[], proof: TArg) { + abytes(proof, 2 * Fn.BYTES); + const { M, Z } = computeComposites(B, C, D, ctx); + const [c, s] = [proof.subarray(0, Fn.BYTES), proof.subarray(Fn.BYTES)].map((f) => + Fn.fromBytes(f) + ); + const t2 = Point.BASE.multiply(s).add(B.multiply(c)); // s*G + c*B + const t3 = M.multiply(s).add(Z.multiply(c)); // s*M + c*Z + const expectedC = challengeTranscript(B, M, Z, t2, t3, ctx); + if (!Fn.eql(c, expectedC)) throw new Error('proof verification failed'); + } + + function generateKeyPair(): TRet { + const skS = randomScalar(); + const pkS = Point.BASE.multiply(skS); + return { secretKey: Fn.toBytes(skS), publicKey: pkS.toBytes() } as TRet; + } + + function deriveKeyPair(ctx: TArg, seed: TArg, info: TArg): TRet { + // RFC 9497 §3.2.1 defines `seed[32]`; reject other sizes here because this public API already + // documents a 32-byte seed instead of generic input keying material. + abytes(seed, 32, 'seed'); + info = inputBytes('keyInfo', info); + const dst = concatBytes(asciiToBytes('DeriveKeyPair'), ctx); + const msg = concatBytes(seed, encode(info), Uint8Array.of(0)); + for (let counter = 0; counter <= 255; counter++) { + msg[msg.length - 1] = counter; + const skS = opts.hashToScalar(msg, { DST: dst }); + if (Fn.is0(skS)) continue; // should not happen + return { + secretKey: Fn.toBytes(skS), + publicKey: Point.BASE.multiply(skS).toBytes(), + } as TRet; + } + throw new Error('Cannot derive key'); + } + const wirePoint = (label: string, bytes: TArg) => { + const point = Point.fromBytes(bytes); + // RFC 9497 §3.3 says applications MUST reject group-identity Elements received over the wire + // after deserialization, even if the suite decoder itself accepts the identity encoding. + if (point.equals(Point.ZERO)) throw new Error(label + ' point at infinity'); + return point; + }; + function blind( + ctx: TArg, + input: TArg, + rng: RNG = randomBytes + ): TRet { + input = inputBytes('input', input); + const blind = randomScalar(rng); + const inputPoint = hashToGroup(input, ctx); + if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity'); + const blinded = inputPoint.multiply(blind); + return { blind: Fn.toBytes(blind), blinded: blinded.toBytes() } as TRet; + } + function evaluate( + ctx: TArg, + secretKey: TArg, + input: TArg + ): TRet { + input = inputBytes('input', input); + const skS = Fn.fromBytes(secretKey); + const inputPoint = hashToGroup(input, ctx); + if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity'); + const unblinded = inputPoint.multiply(skS).toBytes(); + return hashInput(input, unblinded); + } + const oprf = Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed: TArg, keyInfo: TArg) => + deriveKeyPair(ctxOPRF, seed, keyInfo), + blind: (input: TArg, rng: RNG = randomBytes) => blind(ctxOPRF, input, rng), + blindEvaluate(secretKey: TArg, blindedPoint: TArg): TRet { + const skS = Fn.fromBytes(secretKey); + const elm = wirePoint('blinded', blindedPoint); + return elm.multiply(skS).toBytes() as TRet; + }, + finalize( + input: TArg, + blindBytes: TArg, + evaluatedBytes: TArg + ): TRet { + input = inputBytes('input', input); + const blind = Fn.fromBytes(blindBytes); + const evalPoint = wirePoint('evaluated', evaluatedBytes); + const unblinded = evalPoint.multiply(Fn.inv(blind)).toBytes(); + return hashInput(input, unblinded); + }, + evaluate: (secretKey: TArg, input: TArg) => + evaluate(ctxOPRF, secretKey, input), + }); + + const voprf = Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed: TArg, keyInfo: TArg) => + deriveKeyPair(ctxVOPRF, seed, keyInfo), + blind: (input: TArg, rng: RNG = randomBytes) => blind(ctxVOPRF, input, rng), + blindEvaluateBatch( + secretKey: TArg, + publicKey: TArg, + blinded: TArg, + rng: RNG = randomBytes + ): TRet { + if (!Array.isArray(blinded)) throw new Error('expected array'); + const skS = Fn.fromBytes(secretKey); + const pkS = wirePoint('public key', publicKey); + const blindedPoints = blinded.map((i) => wirePoint('blinded', i)); + const evaluated = blindedPoints.map((i) => i.multiply(skS)); + const proof = generateProof(ctxVOPRF, skS, pkS, blindedPoints, evaluated, rng); + return { evaluated: evaluated.map((i) => i.toBytes()), proof } as TRet; + }, + blindEvaluate( + secretKey: TArg, + publicKey: TArg, + blinded: TArg, + rng: RNG = randomBytes + ): TRet { + const res = this.blindEvaluateBatch(secretKey, publicKey, [blinded], rng); + return { evaluated: res.evaluated[0], proof: res.proof } as TRet; + }, + finalizeBatch( + items: TArg, + publicKey: TArg, + proof: TArg + ): TRet { + if (!Array.isArray(items)) throw new Error('expected array'); + const pkS = wirePoint('public key', publicKey); + const blindedPoints = items.map((i) => wirePoint('blinded', i.blinded)); + const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated)); + verifyProof(ctxVOPRF, pkS, blindedPoints, evalPoints, proof); + return items.map((i) => oprf.finalize(i.input, i.blind, i.evaluated)) as TRet; + }, + finalize( + input: TArg, + blind: TArg, + evaluated: TArg, + blinded: TArg, + publicKey: TArg, + proof: TArg + ): TRet { + return this.finalizeBatch([{ input, blind, evaluated, blinded }], publicKey, proof)[0]; + }, + evaluate: (secretKey: TArg, input: TArg) => + evaluate(ctxVOPRF, secretKey, input), + }); + // NOTE: info is domain separation + const poprf = (info: TArg) => { + info = inputBytes('info', info); + const m = hashToScalarPrefixed(encode('Info', info), ctxPOPRF); + const T = Point.BASE.multiply(m); + return Object.freeze({ + generateKeyPair, + deriveKeyPair: (seed: TArg, keyInfo: TArg) => + deriveKeyPair(ctxPOPRF, seed, keyInfo), + blind( + input: TArg, + publicKey: TArg, + rng: RNG = randomBytes + ): TRet { + input = inputBytes('input', input); + const pkS = wirePoint('public key', publicKey); + const tweakedKey = T.add(pkS); + if (tweakedKey.equals(Point.ZERO)) throw new Error('tweakedKey point at infinity'); + const blind = randomScalar(rng); + const inputPoint = hashToGroup(input, ctxPOPRF); + if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity'); + const blindedPoint = inputPoint.multiply(blind); + return { + blind: Fn.toBytes(blind), + blinded: blindedPoint.toBytes(), + tweakedKey: tweakedKey.toBytes(), + } as TRet; + }, + blindEvaluateBatch( + secretKey: TArg, + blinded: TArg, + rng: RNG = randomBytes + ): TRet { + if (!Array.isArray(blinded)) throw new Error('expected array'); + const skS = Fn.fromBytes(secretKey); + const t = Fn.add(skS, m); + // "Hence, this error can be a signal for the server to replace its + // private key". We throw inside; this should be impossible. + const invT = Fn.inv(t); + const blindedPoints = blinded.map((i) => wirePoint('blinded', i)); + const evalPoints = blindedPoints.map((i) => i.multiply(invT)); + const tweakedKey = Point.BASE.multiply(t); + const proof = generateProof(ctxPOPRF, t, tweakedKey, evalPoints, blindedPoints, rng); + return { evaluated: evalPoints.map((i) => i.toBytes()), proof } as TRet; + }, + blindEvaluate( + secretKey: TArg, + blinded: TArg, + rng: RNG = randomBytes + ): TRet { + const res = this.blindEvaluateBatch(secretKey, [blinded], rng); + return { evaluated: res.evaluated[0], proof: res.proof } as TRet; + }, + finalizeBatch( + items: TArg, + proof: TArg, + tweakedKey: TArg + ): TRet { + if (!Array.isArray(items)) throw new Error('expected array'); + const inputs = items.map((i) => inputBytes('input', i.input)); + const evalPoints = items.map((i) => wirePoint('evaluated', i.evaluated)); + verifyProof( + ctxPOPRF, + wirePoint('tweakedKey', tweakedKey), + evalPoints, + items.map((i) => wirePoint('blinded', i.blinded)), + proof + ); + return items.map((i, j) => { + const blind = Fn.fromBytes(i.blind); + const point = evalPoints[j].multiply(Fn.inv(blind)).toBytes(); + return hashInput(inputs[j], info, point); + }) as TRet; + }, + finalize( + input: TArg, + blind: TArg, + evaluated: TArg, + blinded: TArg, + proof: TArg, + tweakedKey: TArg + ): TRet { + return this.finalizeBatch([{ input, blind, evaluated, blinded }], proof, tweakedKey)[0]; + }, + evaluate(secretKey: TArg, input: TArg): TRet { + input = inputBytes('input', input); + const skS = Fn.fromBytes(secretKey); + const inputPoint = hashToGroup(input, ctxPOPRF); + if (inputPoint.equals(Point.ZERO)) throw new Error('Input point at infinity'); + const t = Fn.add(skS, m); + const invT = Fn.inv(t); + const unblinded = inputPoint.multiply(invT).toBytes(); + return hashInput(input, info, unblinded); + }, + }); + }; + const res = { name, oprf, voprf, poprf, __tests: Object.freeze({ Fn }) }; + return Object.freeze(res) as TRet; +} diff --git a/node_modules/@noble/curves/src/abstract/poseidon.ts b/node_modules/@noble/curves/src/abstract/poseidon.ts new file mode 100644 index 0000000..c927e86 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/poseidon.ts @@ -0,0 +1,533 @@ +/** + * Implements [Poseidon](https://www.poseidon-hash.info) ZK-friendly hash. + * + * There are many poseidon variants with different constants. + * We don't provide them: you should construct them manually. + * Check out [micro-starknet](https://github.com/paulmillr/micro-starknet) package for a proper example. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { asafenumber, bitGet, validateObject, type TArg, type TRet } from '../utils.ts'; +import { FpInvertBatch, FpPow, type IField, validateField } from './modular.ts'; + +// Grain LFSR (Linear-Feedback Shift Register): https://eprint.iacr.org/2009/109.pdf +function grainLFSR(state: number[]): () => boolean { + // Advances the caller-provided 80-entry state array in place; only the length + // is checked here, so entries are assumed to already be bits. + let pos = 0; + if (state.length !== 80) throw new Error('grainLFRS: wrong state length, should be 80 bits'); + const getBit = (): boolean => { + const r = (offset: number) => state[(pos + offset) % 80]; + const bit = r(62) ^ r(51) ^ r(38) ^ r(23) ^ r(13) ^ r(0); + state[pos] = bit; + pos = ++pos % 80; + return !!bit; + }; + for (let i = 0; i < 160; i++) getBit(); + return () => { + // https://en.wikipedia.org/wiki/Shrinking_generator + while (true) { + const b1 = getBit(); + const b2 = getBit(); + if (!b1) continue; + return b2; + } + }; +} + +/** Core Poseidon permutation parameters shared by all variants. */ +export type PoseidonBasicOpts = { + /** Prime field used by the permutation. */ + Fp: IField; + /** Poseidon width `t = rate + capacity`. */ + t: number; + /** Number of full S-box rounds. */ + roundsFull: number; + /** Number of partial S-box rounds. */ + roundsPartial: number; + /** Whether to use the inverse S-box variant. */ + isSboxInverse?: boolean; +}; + +function assertValidPosOpts(opts: TArg) { + const { Fp, roundsFull } = opts; + validateField(Fp); + validateObject( + opts, + { + t: 'number', + roundsFull: 'number', + roundsPartial: 'number', + }, + { + isSboxInverse: 'boolean', + } + ); + for (const k of ['t', 'roundsFull', 'roundsPartial'] as const) { + asafenumber(opts[k], k); + if (opts[k] < 1) throw new Error('invalid number ' + k); + } + // Poseidon splits full rounds as `R_F / 2`, then partial rounds, then `R_F / 2` again. + if (roundsFull & 1) throw new Error('roundsFull is not even' + roundsFull); +} + +function poseidonGrain(opts: TArg) { + assertValidPosOpts(opts); + const { Fp } = opts; + const state = Array(80).fill(1); + let pos = 0; + const writeBits = (value: bigint, bitCount: number) => { + for (let i = bitCount - 1; i >= 0; i--) state[pos++] = Number(bitGet(value, i)); + }; + const _0n = BigInt(0); + const _1n = BigInt(1); + // The Grain seed layout is fixed-width: `Fp.BITS` and `t` use 12 bits, + // `roundsFull` and `roundsPartial` use 10, so larger values are truncated here. + // This is intentional for compatibility with snarkVM / arkworks PoseidonGrainLFSR: + // they write the same fixed-width seed fields without range checks, then still consume + // the LFSR using the caller-provided round count for ARK/MDS generation. + // Normalizing or rejecting here would diverge from those implementations. + writeBits(_1n, 2); // prime field + writeBits(opts.isSboxInverse ? _1n : _0n, 4); // b2..b5 + writeBits(BigInt(Fp.BITS), 12); // b6..b17 + writeBits(BigInt(opts.t), 12); // b18..b29 + writeBits(BigInt(opts.roundsFull), 10); // b30..b39 + writeBits(BigInt(opts.roundsPartial), 10); // b40..b49 + + const getBit = grainLFSR(state); + return (count: number, reject: boolean): bigint[] => { + const res: bigint[] = []; + for (let i = 0; i < count; i++) { + while (true) { + let num = _0n; + for (let i = 0; i < Fp.BITS; i++) { + num <<= _1n; + if (getBit()) num |= _1n; + } + if (reject && num >= Fp.ORDER) continue; // rejection sampling + res.push(Fp.create(num)); + break; + } + } + return res; + }; +} + +/** Poseidon settings used by the Grain-LFSR constant generator. */ +export type PoseidonGrainOpts = PoseidonBasicOpts & { + /** S-box power used while generating constants. */ + sboxPower?: number; +}; + +type PoseidonConstants = { mds: bigint[][]; roundConstants: bigint[][] }; + +// NOTE: this is not standard but used often for constant generation for poseidon +// (grain LFRS-like structure) +/** + * @param opts - Poseidon grain options. See {@link PoseidonGrainOpts}. + * @param skipMDS - Number of MDS samples to skip. + * @returns Generated constants. + * @throws If the generated MDS matrix contains a zero denominator. {@link Error} + * @example + * Generate Poseidon round constants and an MDS matrix from the Grain LFSR. + * + * ```ts + * import { grainGenConstants } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * ``` + */ +export function grainGenConstants( + opts: TArg, + skipMDS: number = 0 +): PoseidonConstants { + const { Fp, t, roundsFull, roundsPartial } = opts; + // `skipMDS` counts how many candidate matrices to discard before taking one. + asafenumber(skipMDS, 'skipMDS'); + if (skipMDS < 0) throw new Error('invalid number skipMDS'); + const rounds = roundsFull + roundsPartial; + // `sboxPower` is carried in the opts shape for Poseidon compatibility, but + // Grain constant generation here only depends on field/size/round counts/inverse flag. + const sample = poseidonGrain(opts); + const roundConstants: bigint[][] = []; + for (let r = 0; r < rounds; r++) roundConstants.push(sample(t, true)); + if (skipMDS > 0) for (let i = 0; i < skipMDS; i++) sample(2 * t, false); + const xs = sample(t, false); + const ys = sample(t, false); + // Construct MDS Matrix M[i][j] = 1 / (xs[i] + ys[j]) + const mds: bigint[][] = []; + for (let i = 0; i < t; i++) { + const row: bigint[] = []; + for (let j = 0; j < t; j++) { + const xy = Fp.add(xs[i], ys[j]); + if (Fp.is0(xy)) + throw new Error(`Error generating MDS matrix: xs[${i}] + ys[${j}] resulted in zero.`); + row.push(xy); + } + mds.push(FpInvertBatch(Fp, row)); + } + + return { roundConstants, mds }; +} + +/** Fully specified Poseidon permutation options with explicit constants. */ +export type PoseidonOpts = PoseidonBasicOpts & + PoseidonConstants & { + /** S-box power used by the permutation. */ + sboxPower?: number; + /** Whether to reverse the partial-round S-box index. */ + reversePartialPowIdx?: boolean; // Hack for stark + }; + +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Normalized poseidon options. + * @throws If the Poseidon options, constants, or MDS matrix are invalid. {@link Error} + * @example + * Validate generated constants before constructing a permutation. + * + * ```ts + * import { grainGenConstants, validateOpts } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const opts = validateOpts({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * ``` + */ +export function validateOpts(opts: TArg): TRet< + Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; // Hack for stark + }> +> { + // This only normalizes shapes and field membership for the provided constants; + // it does not prove the stronger MDS/security criteria discussed in the specs. + assertValidPosOpts(opts); + const { Fp, mds, reversePartialPowIdx: rev, roundConstants: rc } = opts; + const { roundsFull, roundsPartial, sboxPower, t } = opts; + + // MDS is TxT matrix + if (!Array.isArray(mds) || mds.length !== t) throw new Error('Poseidon: invalid MDS matrix'); + const _mds = mds.map((mdsRow) => { + if (!Array.isArray(mdsRow) || mdsRow.length !== t) + throw new Error('invalid MDS matrix row: ' + mdsRow); + return mdsRow.map((i) => { + if (typeof i !== 'bigint') throw new Error('invalid MDS matrix bigint: ' + i); + // Hardcoded Poseidon MDS matrices often use signed entries like `-1`; + // accept bigint representatives here and reduce them into the field. + return Fp.create(i); + }); + }); + + if (rev !== undefined && typeof rev !== 'boolean') + throw new Error('invalid param reversePartialPowIdx=' + rev); + + if (roundsFull & 1) throw new Error('roundsFull is not even' + roundsFull); + const rounds = roundsFull + roundsPartial; + + if (!Array.isArray(rc) || rc.length !== rounds) + throw new Error('Poseidon: invalid round constants'); + const roundConstants = rc.map((rc) => { + if (!Array.isArray(rc) || rc.length !== t) throw new Error('invalid round constants'); + return rc.map((i) => { + if (typeof i !== 'bigint' || !Fp.isValid(i)) throw new Error('invalid round constant'); + return Fp.create(i); + }); + }); + // Freeze nested constants so exported handles cannot retune a live permutation instance. + const freezeRows = (rows: bigint[][]) => + Object.freeze(rows.map((row) => Object.freeze(row))) as unknown as bigint[][]; + + if (!sboxPower || ![3, 5, 7, 17].includes(sboxPower)) throw new Error('invalid sboxPower'); + const _sboxPower = BigInt(sboxPower); + let sboxFn = (n: bigint) => FpPow(Fp, n, _sboxPower); + // Unwrapped sbox power for common cases (195->142μs) + if (sboxPower === 3) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(n), n); + else if (sboxPower === 5) sboxFn = (n: bigint) => Fp.mul(Fp.sqrN(Fp.sqrN(n)), n); + + return Object.freeze({ + ...opts, + rounds, + sboxFn, + roundConstants: freezeRows(roundConstants), + mds: freezeRows(_mds), + }) as TRet< + Readonly<{ + rounds: number; + sboxFn: (n: bigint) => bigint; + roundConstants: bigint[][]; + mds: bigint[][]; + Fp: IField; + t: number; + roundsFull: number; + roundsPartial: number; + sboxPower?: number; + reversePartialPowIdx?: boolean; + }> + >; +} + +/** + * @param rc - Flattened round constants. + * @param t - Poseidon width. + * @returns Constants grouped by round. + * @throws If the width or flattened constant array is invalid. {@link Error} + * @example + * Regroup a flat constant list into per-round chunks. + * + * ```ts + * const rounds = splitConstants([1n, 2n, 3n, 4n], 2); + * ``` + */ +export function splitConstants(rc: bigint[], t: number): bigint[][] { + asafenumber(t, 't'); + if (t < 1) throw new Error('poseidonSplitConstants: invalid t'); + if (!Array.isArray(rc) || rc.length % t) throw new Error('poseidonSplitConstants: invalid rc'); + const res = []; + let tmp = []; + for (let i = 0; i < rc.length; i++) { + const c = rc[i]; + if (typeof c !== 'bigint') throw new Error('invalid bigint=' + c); + tmp.push(c); + if (tmp.length === t) { + res.push(tmp); + tmp = []; + } + } + return res; +} + +/** + * Poseidon permutation callable. + * @param values - Poseidon state vector. Non-canonical bigints are normalized with `Fp.create(...)`. + * @returns Permuted state vector. + */ +export type PoseidonFn = { + (values: bigint[]): bigint[]; + /** Round constants captured by the permutation instance. */ + roundConstants: bigint[][]; +}; +/** Poseidon NTT-friendly hash. */ +/** + * @param opts - Poseidon options. See {@link PoseidonOpts}. + * @returns Poseidon permutation. + * @throws If the Poseidon options or state vector are invalid. {@link Error} + * @example + * Build a Poseidon permutation from validated parameters and constants. + * + * ```ts + * import { grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const state = hash([1n, 2n]); + * ``` + */ +export function poseidon(opts: TArg): PoseidonFn { + const _opts = validateOpts(opts); + const { Fp, mds, roundConstants, rounds: totalRounds, roundsPartial, sboxFn, t } = _opts; + const halfRoundsFull = _opts.roundsFull / 2; + const partialIdx = _opts.reversePartialPowIdx ? t - 1 : 0; + const poseidonRound = (values: bigint[], isFull: boolean, idx: number) => { + values = values.map((i, j) => Fp.add(i, roundConstants[idx][j])); + + if (isFull) values = values.map((i) => sboxFn(i)); + else values[partialIdx] = sboxFn(values[partialIdx]); + // Matrix multiplication + values = mds.map((i) => i.reduce((acc, i, j) => Fp.add(acc, Fp.mulN(i, values[j])), Fp.ZERO)); + return values; + }; + const poseidonHash = function poseidonHash(values: bigint[]) { + if (!Array.isArray(values) || values.length !== t) + throw new Error('invalid values, expected array of bigints with length ' + t); + // `.map()` skips sparse holes, which would leak `undefined` into round math below. + values = values.slice(); + for (let j = 0; j < values.length; j++) { + const i = values[j]; + if (typeof i !== 'bigint') throw new Error('invalid bigint=' + i); + values[j] = Fp.create(i); + } + let lastRound = 0; + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, lastRound++); + // Apply r_p partial rounds. + for (let i = 0; i < roundsPartial; i++) values = poseidonRound(values, false, lastRound++); + // Apply r_f/2 full rounds. + for (let i = 0; i < halfRoundsFull; i++) values = poseidonRound(values, true, lastRound++); + + if (lastRound !== totalRounds) throw new Error('invalid number of rounds'); + return values; + } as PoseidonFn; + // For verification in tests + Object.defineProperty(poseidonHash, 'roundConstants', { + value: roundConstants, + enumerable: true, + }); + return poseidonHash; +} + +/** + * @param Fp - Field implementation. + * @param rate - Sponge rate. + * @param capacity - Sponge capacity. + * @param hash - Poseidon permutation. + * @example + * Wrap one Poseidon permutation in a sponge interface. + * + * ```ts + * import { PoseidonSponge, grainGenConstants, poseidon } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const hash = poseidon({ ...constants, Fp, t: 2, roundsFull: 8, roundsPartial: 8, sboxPower: 3 }); + * const sponge = new PoseidonSponge(Fp, 1, 1, hash); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export class PoseidonSponge { + private Fp: IField; + readonly rate: number; + readonly capacity: number; + readonly hash: PoseidonFn; + private state: bigint[]; // [...capacity, ...rate] + private pos = 0; + private isAbsorbing = true; + + constructor(Fp: IField, rate: number, capacity: number, hash: PoseidonFn) { + const width = spongeShape(rate, capacity); + // The direct constructor accepts an arbitrary permutation hook, but callers still + // need to preserve the `PoseidonFn.roundConstants` width metadata. Reject width + // mismatches here instead of deferring them until the first `process()` call. + if (width !== hash.roundConstants[0]?.length) + throw new Error( + `invalid sponge width: expected ${hash.roundConstants[0]?.length}, got ${width}` + ); + this.Fp = Fp; + this.hash = hash; + this.rate = rate; + this.capacity = capacity; + this.state = new Array(width); + this.clean(); + } + private process(): void { + // The permutation is expected to return an owned state array. If callers inject a custom + // hook that reuses external storage, `clean()` will zero that shared buffer too. + this.state = this.hash(this.state); + } + absorb(input: bigint[]): void { + for (const i of input) + if (typeof i !== 'bigint' || !this.Fp.isValid(i)) throw new Error('invalid input: ' + i); + for (let i = 0; i < input.length; ) { + if (!this.isAbsorbing || this.pos === this.rate) { + this.process(); + this.pos = 0; + this.isAbsorbing = true; + } + const chunk = Math.min(this.rate - this.pos, input.length - i); + for (let j = 0; j < chunk; j++) { + const idx = this.capacity + this.pos++; + this.state[idx] = this.Fp.add(this.state[idx], input[i++]); + } + } + } + squeeze(count: number): bigint[] { + // Rust oracles use unsigned counts. In JS we keep `squeeze(0) => []` for + // compatibility, but still reject negative/fractional counts explicitly. + asafenumber(count, 'count'); + if (count < 0) throw new Error('invalid number count'); + const res: bigint[] = []; + while (res.length < count) { + if (this.isAbsorbing || this.pos === this.rate) { + this.process(); + this.pos = 0; + this.isAbsorbing = false; + } + const chunk = Math.min(this.rate - this.pos, count - res.length); + for (let i = 0; i < chunk; i++) res.push(this.state[this.capacity + this.pos++]); + } + return res; + } + clean(): void { + this.state.fill(this.Fp.ZERO); + this.isAbsorbing = true; + this.pos = 0; + } + clone(): PoseidonSponge { + const c = new PoseidonSponge(this.Fp, this.rate, this.capacity, this.hash); + c.pos = this.pos; + c.isAbsorbing = this.isAbsorbing; + c.state = [...this.state]; + return c; + } +} + +/** Options for the non-standard but commonly used Poseidon sponge wrapper. */ +export type PoseidonSpongeOpts = Omit & { + /** Sponge rate. */ + rate: number; + /** Sponge capacity. */ + capacity: number; +}; + +const spongeShape = (rate: number, capacity: number) => { + asafenumber(rate, 'rate'); + asafenumber(capacity, 'capacity'); + // A sponge with zero rate cannot absorb or squeeze any field elements. + if (rate < 1) throw new Error('invalid number rate'); + // Negative capacity can accidentally keep `rate + capacity` coherent while still + // producing a nonsensical sponge shape. + if (capacity < 0) throw new Error('invalid number capacity'); + return rate + capacity; +}; + +/** + * The method is not defined in spec, but nevertheless used often. + * Check carefully for compatibility: there are many edge cases, like absorbing an empty array. + * We cross-test against: + * - {@link https://github.com/ProvableHQ/snarkVM/tree/staging/algorithms | snarkVM algorithms} + * - {@link https://github.com/arkworks-rs/crypto-primitives/tree/main | arkworks crypto-primitives} + * @param opts - Sponge options. See {@link PoseidonSpongeOpts}. + * @returns Factory for sponge instances. + * @throws If the sponge dimensions or backing permutation options are invalid. {@link Error} + * @example + * Use the sponge helper to absorb several field elements and squeeze one digest. + * + * ```ts + * import { grainGenConstants, poseidonSponge } from '@noble/curves/abstract/poseidon.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const constants = grainGenConstants({ Fp, t: 2, roundsFull: 8, roundsPartial: 8 }); + * const makeSponge = poseidonSponge({ + * ...constants, + * Fp, + * rate: 1, + * capacity: 1, + * roundsFull: 8, + * roundsPartial: 8, + * sboxPower: 3, + * }); + * const sponge = makeSponge(); + * sponge.absorb([1n]); + * const out = sponge.squeeze(1); + * ``` + */ +export function poseidonSponge(opts: TArg): TRet<() => PoseidonSponge> { + const { rate, capacity } = opts; + const t = spongeShape(rate, capacity); + // Re-use one hash instance between sponge instances; isolation depends on + // poseidon(...) itself staying immutable and not carrying mutable call state. + const hash = poseidon({ ...opts, t }); + const { Fp } = opts; + return (() => new PoseidonSponge(Fp, rate, capacity, hash)) as TRet<() => PoseidonSponge>; +} diff --git a/node_modules/@noble/curves/src/abstract/tower.ts b/node_modules/@noble/curves/src/abstract/tower.ts new file mode 100644 index 0000000..51ba82a --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/tower.ts @@ -0,0 +1,1133 @@ +/** + * Towered extension fields. + * Rather than implementing a massive 12th-degree extension directly, it is more efficient + * to build it up from smaller extensions: a tower of extensions. + * + * For BLS12-381, the Fp12 field is implemented as a quadratic (degree two) extension, + * on top of a cubic (degree three) extension, on top of a quadratic extension of Fp. + * + * For more info: "Pairings for beginners" by Costello, section 7.3. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + abytes, + aInRange, + asafenumber, + bitGet, + bitLen, + concatBytes, + notImplemented, + validateObject, + type TArg, + type TRet, +} from '../utils.ts'; +import * as mod from './modular.ts'; +import type { WeierstrassPoint, WeierstrassPointCons } from './weierstrass.ts'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _6n = /* @__PURE__ */ BigInt(6), _12n = /* @__PURE__ */ BigInt(12); + +// Fp₂ over complex plane +/** Pair of bigints used for quadratic-extension tuples. */ +export type BigintTuple = [bigint, bigint]; +/** Prime-field element. */ +export type Fp = bigint; +// Finite extension field over irreducible polynominal. +// Fp(u) / (u² - β) where β = -1 +/** Quadratic-extension field element `c0 + c1 * u`. */ +export type Fp2 = { + /** Real component. */ + c0: bigint; + /** Imaginary component. */ + c1: bigint; +}; +/** Six bigints used for sextic-extension tuples. */ +export type BigintSix = [bigint, bigint, bigint, bigint, bigint, bigint]; +/** Sextic-extension field element `c0 + c1 * v + c2 * v^2`. */ +export type Fp6 = { + /** Constant coefficient. */ + c0: Fp2; + /** Linear coefficient. */ + c1: Fp2; + /** Quadratic coefficient. */ + c2: Fp2; +}; +/** + * Degree-12 extension field element `c0 + c1 * w`. + * Fp₁₂ = Fp₆² over Fp₂³, with Fp₆(w) / (w² - γ) where γ = v. + */ +export type Fp12 = { + /** Constant coefficient. */ + c0: Fp6; + /** Linear coefficient. */ + c1: Fp6; +}; +// prettier-ignore +/** Twelve bigints used for degree-12 extension tuples. */ +export type BigintTwelve = [ + bigint, bigint, bigint, bigint, bigint, bigint, + bigint, bigint, bigint, bigint, bigint, bigint +]; + +const isObj = (value: unknown): value is Record => + !!value && typeof value === 'object'; + +/** BLS-friendly helpers on top of the quadratic extension field. */ +export type Fp2Bls = mod.IField & { + /** Underlying prime field. */ + Fp: mod.IField; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp2, power: number): Fp2; + /** Build one field element from a raw bigint tuple. */ + fromBigTuple(num: BigintTuple): Fp2; + /** Multiply by the curve `b` constant. */ + mulByB: (num: Fp2) => Fp2; + /** Multiply by the quadratic non-residue. */ + mulByNonresidue: (num: Fp2) => Fp2; + /** Split one quadratic element into real and imaginary components. */ + reim: (num: Fp2) => { re: Fp; im: Fp }; + /** Specialized helper used by sextic squaring formulas. */ + Fp4Square: (a: Fp2, b: Fp2) => { first: Fp2; second: Fp2 }; + /** Quadratic non-residue used by the extension. */ + NONRESIDUE: Fp2; +}; + +/** BLS-friendly helpers on top of the sextic extension field. */ +export type Fp6Bls = mod.IField & { + /** Underlying quadratic extension field. */ + Fp2: Fp2Bls; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp6, power: number): Fp6; + /** Build one field element from a raw six-bigint tuple. */ + fromBigSix: (tuple: BigintSix) => Fp6; + /** Multiply by a sparse `(0, b1, 0)` sextic element. */ + mul1(num: Fp6, b1: Fp2): Fp6; + /** Multiply by a sparse `(b0, b1, 0)` sextic element. */ + mul01(num: Fp6, b0: Fp2, b1: Fp2): Fp6; + /** Multiply by one quadratic-extension element. */ + mulByFp2(lhs: Fp6, rhs: Fp2): Fp6; + /** Multiply by the sextic non-residue. */ + mulByNonresidue: (num: Fp6) => Fp6; +}; + +/** BLS-friendly helpers on top of the degree-12 extension field. */ +export type Fp12Bls = mod.IField & { + /** Underlying sextic extension field. */ + Fp6: Fp6Bls; + /** Apply one Frobenius map. */ + frobeniusMap(num: Fp12, power: number): Fp12; + /** Build one field element from a raw twelve-bigint tuple. */ + fromBigTwelve: (t: BigintTwelve) => Fp12; + /** Multiply by a sparse `(o0, o1, 0, 0, o4, 0)` element. */ + mul014(num: Fp12, o0: Fp2, o1: Fp2, o4: Fp2): Fp12; + /** Multiply by a sparse `(o0, 0, 0, o3, o4, 0)` element. */ + mul034(num: Fp12, o0: Fp2, o3: Fp2, o4: Fp2): Fp12; + /** Multiply by one quadratic-extension element. */ + mulByFp2(lhs: Fp12, rhs: Fp2): Fp12; + /** Conjugate one degree-12 element. */ + conjugate(num: Fp12): Fp12; + /** Apply the final exponentiation from pairing arithmetic. */ + finalExponentiate(num: Fp12): Fp12; + /** Apply one cyclotomic square. */ + _cyclotomicSquare(num: Fp12): Fp12; + /** Apply one cyclotomic exponentiation. */ + _cyclotomicExp(num: Fp12, n: bigint): Fp12; +}; + +function calcFrobeniusCoefficients( + Fp: TArg>, + nonResidue: T, + modulus: bigint, + degree: number, + num: number = 1, + divisor?: number +): T[][] { + asafenumber(num, 'num'); + const F = Fp as mod.IField; + // Generic callers can hit empty / fractional row counts through `__TEST`; fail closed instead of + // silently returning `[]` or deriving extra Frobenius rows from a truncated loop bound. + if (num <= 0) + throw new Error('calcFrobeniusCoefficients: expected positive row count, got ' + num); + const _divisor = BigInt(divisor === undefined ? degree : divisor); + const towerModulus: any = modulus ** BigInt(degree); + const res: T[][] = []; + // Derive tower-basis multipliers for the `p^k` Frobenius action. The + // divisions below are expected to be exact for the chosen tower parameters. + for (let i = 0; i < num; i++) { + const a = BigInt(i + 1); + const powers: T[] = []; + for (let j = 0, qPower = _1n; j < degree; j++) { + const numer = a * qPower - a; + // Shipped towers divide cleanly here, but generic callers can pick bad + // params. Bigint division would floor and derive the wrong Frobenius table. + if (numer % _divisor) throw new Error('calcFrobeniusCoefficients: inexact tower exponent'); + const power = (numer / _divisor) % towerModulus; + powers.push(F.pow(nonResidue, power)); + qPower *= modulus; + } + res.push(powers); + } + return res; +} + +export const __TEST: { calcFrobeniusCoefficients: typeof calcFrobeniusCoefficients } = + /* @__PURE__ */ Object.freeze({ + calcFrobeniusCoefficients, + }); + +// This works same at least for bls12-381, bn254 and bls12-377 +/** + * @param Fp - Base field implementation. + * @param Fp2 - Quadratic extension field. + * @param base - Twist-specific Frobenius base whose powers yield the `c1` / `c2` constants. + * BLS12-381 uses `1 / NONRESIDUE`; BN254 uses `NONRESIDUE`. + * @returns Frobenius endomorphism helpers. + * @throws If the derived Frobenius constants are inconsistent for the tower. {@link Error} + * @example + * Build Frobenius endomorphism helpers for a BLS extension tower. + * + * ```ts + * import { psiFrobenius } from '@noble/curves/abstract/tower.js'; + * import { bls12_381 } from '@noble/curves/bls12-381.js'; + * const Fp = bls12_381.fields.Fp; + * const Fp2 = bls12_381.fields.Fp2; + * const frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE)); + * const point = frob.G2psi(bls12_381.G2.Point, bls12_381.G2.Point.BASE); + * ``` + */ +export function psiFrobenius( + Fp: TArg>, + Fp2: TArg, + base: TArg +): { + psi: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + psi2: (x: Fp2, y: Fp2) => [Fp2, Fp2]; + G2psi: (c: WeierstrassPointCons, P: WeierstrassPoint) => WeierstrassPoint; + G2psi2: (c: WeierstrassPointCons, P: WeierstrassPoint) => WeierstrassPoint; + PSI_X: Fp2; + PSI_Y: Fp2; + PSI2_X: Fp2; + PSI2_Y: Fp2; +} { + // GLV endomorphism Ψ(P) + const PSI_X = Fp2.pow(base, (Fp.ORDER - _1n) / _3n); // u^((p-1)/3) + const PSI_Y = Fp2.pow(base, (Fp.ORDER - _1n) / _2n); // u^((p-1)/2) + function psi(x: Fp2, y: Fp2): [Fp2, Fp2] { + // This x10 faster than previous version in bls12-381 + const x2 = Fp2.mul(Fp2.frobeniusMap(x, 1), PSI_X); + const y2 = Fp2.mul(Fp2.frobeniusMap(y, 1), PSI_Y); + return [x2, y2]; + } + // Ψ²(P) endomorphism (psi2(x) = psi(psi(x))) + const PSI2_X = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _3n); // u^((p^2 - 1)/3) + // Current towers rely on this landing on `-1`, which lets psi2 map `y` with + // one negation instead of carrying a separate Frobenius multiplier. + const PSI2_Y = Fp2.pow(base, (Fp.ORDER ** _2n - _1n) / _2n); // u^((p^2 - 1)/2) + if (!Fp2.eql(PSI2_Y, Fp2.neg(Fp2.ONE))) throw new Error('psiFrobenius: PSI2_Y!==-1'); + function psi2(x: Fp2, y: Fp2): [Fp2, Fp2] { + return [Fp2.mul(x, PSI2_X), Fp2.neg(y)]; + } + // Map points + const mapAffine = + (fn: (x: T, y: T) => [T, T]) => + (c: WeierstrassPointCons, P: WeierstrassPoint) => { + const affine = P.toAffine(); + const p = fn(affine.x, affine.y); + return c.fromAffine({ x: p[0], y: p[1] }); + }; + const G2psi = mapAffine(psi); + const G2psi2 = mapAffine(psi2); + return { psi, psi2, G2psi, G2psi2, PSI_X, PSI_Y, PSI2_X, PSI2_Y }; +} + +/** Construction options for the BLS-style degree-12 tower. */ +export type Tower12Opts = { + /** Prime-field order. */ + ORDER: bigint; + /** Bit length of the BLS parameter `x`. */ + X_LEN: number; + /** Prime-field non-residue used by the quadratic extension. */ + NONRESIDUE?: Fp; + /** Quadratic-extension non-residue used by the sextic tower. */ + FP2_NONRESIDUE: BigintTuple; + /** + * Optional custom quadratic square-root helper. + * Receives one quadratic-extension element and returns one square root. + */ + Fp2sqrt?: (num: Fp2) => Fp2; + /** + * Multiply one quadratic element by the curve `b` constant. + * @param num - Quadratic-extension element to scale. + * @returns Product by the curve `b` constant. + */ + Fp2mulByB: (num: Fp2) => Fp2; + /** + * Final exponentiation used by pairing arithmetic. + * @param num - Degree-12 field element to exponentiate. + * @returns Pairing result after final exponentiation. + */ + Fp12finalExponentiate: (num: Fp12) => Fp12; +}; + +class _Field2 implements mod.IField { + readonly ORDER: bigint; + readonly BITS: number; + readonly BYTES: number; + readonly isLE: boolean; + + readonly ZERO: Fp2; + readonly ONE: Fp2; + readonly Fp: mod.IField; + + readonly NONRESIDUE: Fp2; + readonly mulByB: Tower12Opts['Fp2mulByB']; + readonly Fp_NONRESIDUE: bigint; + readonly Fp_div2: bigint; + readonly FROBENIUS_COEFFICIENTS: readonly Fp[]; + + constructor( + Fp: mod.IField, + opts: Partial<{ + NONRESIDUE: bigint; + FP2_NONRESIDUE: BigintTuple; + Fp2mulByB: Tower12Opts['Fp2mulByB']; + }> = {} + ) { + const { NONRESIDUE = BigInt(-1), FP2_NONRESIDUE, Fp2mulByB } = opts; + const ORDER = Fp.ORDER; + const FP2_ORDER = ORDER * ORDER; + this.Fp = Fp; + this.ORDER = FP2_ORDER; + this.BITS = bitLen(FP2_ORDER); + this.BYTES = Math.ceil(bitLen(FP2_ORDER) / 8); + this.isLE = Fp.isLE; + this.ZERO = this.create({ c0: Fp.ZERO, c1: Fp.ZERO }); + this.ONE = this.create({ c0: Fp.ONE, c1: Fp.ZERO }); + + // These knobs only swap constants for the shipped quadratic tower shape: + // arithmetic below assumes `u^2 = -1`, and bytes are handled as two adjacent + // `Fp` limbs (`fromBytes` / `toBytes` expect the shipped `2 * Fp.BYTES` layout). + this.Fp_NONRESIDUE = Fp.create(NONRESIDUE); + this.Fp_div2 = Fp.div(Fp.ONE, _2n); // 1/2 + this.NONRESIDUE = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] }); + // const Fp2Nonresidue = this.create({ c0: FP2_NONRESIDUE![0], c1: FP2_NONRESIDUE![1] }); + this.FROBENIUS_COEFFICIENTS = Object.freeze( + calcFrobeniusCoefficients(Fp, this.Fp_NONRESIDUE, Fp.ORDER, 2)[0] + ); + this.mulByB = (num) => { + // This config hook is trusted to return a canonical Fp2 value already. + // Copy+freeze it to keep the tower immutability invariant without mutating caller objects. + const { c0, c1 } = Fp2mulByB!(num); + return Object.freeze({ c0, c1 }); + }; + Object.freeze(this); + } + fromBigTuple(tuple: BigintTuple) { + if (!Array.isArray(tuple) || tuple.length !== 2) throw new Error('invalid Fp2.fromBigTuple'); + const [c0, c1] = tuple; + if (typeof c0 !== 'bigint' || typeof c1 !== 'bigint') + throw new Error('invalid Fp2.fromBigTuple'); + return this.create({ c0, c1 }); + } + create(num: Fp2) { + const { Fp } = this; + const c0 = Fp.create(num.c0); + const c1 = Fp.create(num.c1); + // Bigint field elements are immutable values, and higher-level code relies on + // that invariant. Copy+freeze tower values too without mutating caller-owned objects. + return Object.freeze({ c0, c1 }); + } + isValid(num: Fp2) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1 } = num; + const { Fp } = this; + // Match base-field `isValid(...)`: malformed coordinate types are errors, not a `false` + // predicate result. + return Fp.isValid(c0) && Fp.isValid(c1); + } + is0(num: Fp2) { + if (!isObj(num)) return false; + const { c0, c1 } = num; + const { Fp } = this; + return Fp.is0(c0) && Fp.is0(c1); + } + isValidNot0(num: Fp2) { + return !this.is0(num) && this.isValid(num); + } + eql({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) { + const { Fp } = this; + return Fp.eql(c0, r0) && Fp.eql(c1, r1); + } + neg({ c0, c1 }: Fp2) { + const { Fp } = this; + return Object.freeze({ c0: Fp.neg(c0), c1: Fp.neg(c1) }); + } + pow(num: Fp2, power: bigint): Fp2 { + return mod.FpPow(this, num, power); + } + invertBatch(nums: Fp2[]): Fp2[] { + return mod.FpInvertBatch(this, nums); + } + // Normalized + add(f1: Fp2, f2: Fp2): Fp2 { + const { Fp } = this; + const { c0, c1 } = f1; + const { c0: r0, c1: r1 } = f2; + return Object.freeze({ + c0: Fp.add(c0, r0), + c1: Fp.add(c1, r1), + }); + } + sub({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2) { + const { Fp } = this; + return Object.freeze({ + c0: Fp.sub(c0, r0), + c1: Fp.sub(c1, r1), + }); + } + mul({ c0, c1 }: Fp2, rhs: Fp2) { + const { Fp } = this; + if (typeof rhs === 'bigint') return Object.freeze({ c0: Fp.mul(c0, rhs), c1: Fp.mul(c1, rhs) }); + // (a+bi)(c+di) = (ac−bd) + (ad+bc)i + const { c0: r0, c1: r1 } = rhs; + let t1 = Fp.mul(c0, r0); // c0 * o0 + let t2 = Fp.mul(c1, r1); // c1 * o1 + // (T1 - T2) + ((c0 + c1) * (r0 + r1) - (T1 + T2))*i + const o0 = Fp.sub(t1, t2); + const o1 = Fp.sub(Fp.mul(Fp.add(c0, c1), Fp.add(r0, r1)), Fp.add(t1, t2)); + return Object.freeze({ c0: o0, c1: o1 }); + } + sqr({ c0, c1 }: Fp2) { + const { Fp } = this; + const a = Fp.add(c0, c1); + const b = Fp.sub(c0, c1); + const c = Fp.add(c0, c0); + return Object.freeze({ c0: Fp.mul(a, b), c1: Fp.mul(c, c1) }); + } + // NonNormalized stuff + addN(a: Fp2, b: Fp2): Fp2 { + return this.add(a, b); + } + subN(a: Fp2, b: Fp2): Fp2 { + return this.sub(a, b); + } + mulN(a: Fp2, b: Fp2): Fp2 { + return this.mul(a, b); + } + sqrN(a: Fp2): Fp2 { + return this.sqr(a); + } + // Why inversion for bigint inside Fp instead of Fp2? it is even used in that context? + div(lhs: Fp2, rhs: Fp2): Fp2 { + const { Fp } = this; + // @ts-ignore + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + inv({ c0: a, c1: b }: Fp2): Fp2 { + // We wish to find the multiplicative inverse of a nonzero + // element a + bu in Fp2. We leverage an identity + // + // (a + bu)(a - bu) = a² + b² + // + // which holds because u² = -1. This can be rewritten as + // + // (a + bu)(a - bu)/(a² + b²) = 1 + // + // because a² + b² = 0 has no nonzero solutions for (a, b). + // This gives that (a - bu)/(a² + b²) is the inverse + // of (a + bu). Importantly, this can be computing using + // only a single inversion in Fp. + const { Fp } = this; + const factor = Fp.inv(Fp.create(a * a + b * b)); + return Object.freeze({ c0: Fp.mul(factor, Fp.create(a)), c1: Fp.mul(factor, Fp.create(-b)) }); + } + sqrt(num: Fp2) { + // This is generic for all quadratic extensions (Fp2) + const { Fp } = this; + const Fp2 = this; + const { c0, c1 } = num; + if (Fp.is0(c1)) { + // if c0 is quadratic residue + if (mod.FpLegendre(Fp, c0) === 1) return Fp2.create({ c0: Fp.sqrt(c0), c1: Fp.ZERO }); + else return Fp2.create({ c0: Fp.ZERO, c1: Fp.sqrt(Fp.div(c0, this.Fp_NONRESIDUE)) }); + } + const a = Fp.sqrt(Fp.sub(Fp.sqr(c0), Fp.mul(Fp.sqr(c1), this.Fp_NONRESIDUE))); + let d = Fp.mul(Fp.add(a, c0), this.Fp_div2); + const legendre = mod.FpLegendre(Fp, d); + // -1, Quadratic non residue + if (legendre === -1) d = Fp.sub(d, a); + const a0 = Fp.sqrt(d); + const candidateSqrt = Fp2.create({ c0: a0, c1: Fp.div(Fp.mul(c1, this.Fp_div2), a0) }); + if (!Fp2.eql(Fp2.sqr(candidateSqrt), num)) throw new Error('Cannot find square root'); + // Normalize root: at this point candidateSqrt ** 2 = num, but also -candidateSqrt ** 2 = num + const x1 = candidateSqrt; + const x2 = Fp2.neg(x1); + const { re: re1, im: im1 } = Fp2.reim(x1); + const { re: re2, im: im2 } = Fp2.reim(x2); + if (im1 > im2 || (im1 === im2 && re1 > re2)) return x1; + return x2; + } + // Same as sgn0_m_eq_2 in RFC 9380 + isOdd(x: Fp2) { + const { re: x0, im: x1 } = this.reim(x); + const sign_0 = x0 % _2n; + const zero_0 = x0 === _0n; + const sign_1 = x1 % _2n; + return BigInt(sign_0 || (zero_0 && sign_1)) == _1n; + } + // Bytes util + fromBytes(b: Uint8Array): Fp2 { + const { Fp } = this; + abytes(b); + if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length); + return this.create({ + c0: Fp.fromBytes(b.subarray(0, Fp.BYTES)), + c1: Fp.fromBytes(b.subarray(Fp.BYTES)), + }); + } + toBytes({ c0, c1 }: Fp2): Uint8Array { + return concatBytes(this.Fp.toBytes(c0), this.Fp.toBytes(c1)); + } + cmov({ c0, c1 }: Fp2, { c0: r0, c1: r1 }: Fp2, c: boolean) { + const { Fp } = this; + return this.create({ + c0: Fp.cmov(c0, r0, c), + c1: Fp.cmov(c1, r1, c), + }); + } + reim({ c0, c1 }: Fp2) { + return { re: c0, im: c1 }; + } + Fp4Square(a: Fp2, b: Fp2): { first: Fp2; second: Fp2 } { + const Fp2 = this; + const a2 = Fp2.sqr(a); + const b2 = Fp2.sqr(b); + return { + first: Fp2.add(Fp2.mulByNonresidue(b2), a2), // b² * Nonresidue + a² + second: Fp2.sub(Fp2.sub(Fp2.sqr(Fp2.add(a, b)), a2), b2), // (a + b)² - a² - b² + }; + } + // multiply by u + 1 + mulByNonresidue({ c0, c1 }: Fp2) { + return this.mul({ c0, c1 }, this.NONRESIDUE); + } + frobeniusMap({ c0, c1 }: Fp2, power: number): Fp2 { + return Object.freeze({ + c0, + c1: this.Fp.mul(c1, this.FROBENIUS_COEFFICIENTS[power % 2]), + }); + } +} + +class _Field6 implements Fp6Bls { + readonly ORDER: bigint; + readonly BITS: number; + readonly BYTES: number; + readonly isLE: boolean; + + readonly ZERO: Fp6; + readonly ONE: Fp6; + readonly Fp2: Fp2Bls; + + constructor(Fp2: Fp2Bls) { + this.Fp2 = Fp2; + // `IField.ORDER` is the field cardinality `q`; for sextic extensions that is `p^6`. + // Generic helpers like Frobenius-style `x^q = x` checks rely on the literal field size here. + this.ORDER = Fp2.Fp.ORDER ** _6n; + this.BITS = 3 * Fp2.BITS; + this.BYTES = 3 * Fp2.BYTES; + this.isLE = Fp2.isLE; + this.ZERO = this.create({ c0: Fp2.ZERO, c1: Fp2.ZERO, c2: Fp2.ZERO }); + this.ONE = this.create({ c0: Fp2.ONE, c1: Fp2.ZERO, c2: Fp2.ZERO }); + Object.freeze(this); + } + // Most callers never touch Frobenius maps, so keep the sextic tables lazy: + // eagerly deriving them dominates `bls12-381.js` / `bn254.js` import time. + get FROBENIUS_COEFFICIENTS_1(): readonly Fp2[] { + const frob = _FROBENIUS_COEFFICIENTS_6.get(this); + if (frob) return frob[0]; + const { Fp2 } = this; + const { Fp } = Fp2; + const rows = calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 6, 2, 3); + const cache = [Object.freeze(rows[0]), Object.freeze(rows[1])] as const; + _FROBENIUS_COEFFICIENTS_6.set(this, cache); + return cache[0]; + } + get FROBENIUS_COEFFICIENTS_2(): readonly Fp2[] { + const frob = _FROBENIUS_COEFFICIENTS_6.get(this); + if (frob) return frob[1]; + void this.FROBENIUS_COEFFICIENTS_1; + return _FROBENIUS_COEFFICIENTS_6.get(this)![1]; + } + add({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.add(c0, r0), + c1: Fp2.add(c1, r1), + c2: Fp2.add(c2, r2), + }); + } + sub({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.sub(c0, r0), + c1: Fp2.sub(c1, r1), + c2: Fp2.sub(c2, r2), + }); + } + mul({ c0, c1, c2 }: Fp6, rhs: Fp6 | bigint) { + const { Fp2 } = this; + if (typeof rhs === 'bigint') { + return Object.freeze({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }); + } + const { c0: r0, c1: r1, c2: r2 } = rhs; + const t0 = Fp2.mul(c0, r0); // c0 * o0 + const t1 = Fp2.mul(c1, r1); // c1 * o1 + const t2 = Fp2.mul(c2, r2); // c2 * o2 + return Object.freeze({ + // t0 + (c1 + c2) * (r1 * r2) - (T1 + T2) * (u + 1) + c0: Fp2.add( + t0, + Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), Fp2.add(r1, r2)), Fp2.add(t1, t2))) + ), + // (c0 + c1) * (r0 + r1) - (T0 + T1) + T2 * (u + 1) + c1: Fp2.add( + Fp2.sub(Fp2.mul(Fp2.add(c0, c1), Fp2.add(r0, r1)), Fp2.add(t0, t1)), + Fp2.mulByNonresidue(t2) + ), + // T1 + (c0 + c2) * (r0 + r2) - T0 + T2 + c2: Fp2.sub(Fp2.add(t1, Fp2.mul(Fp2.add(c0, c2), Fp2.add(r0, r2))), Fp2.add(t0, t2)), + }); + } + sqr({ c0, c1, c2 }: Fp6) { + const { Fp2 } = this; + let t0 = Fp2.sqr(c0); // c0² + let t1 = Fp2.mul(Fp2.mul(c0, c1), _2n); // 2 * c0 * c1 + let t3 = Fp2.mul(Fp2.mul(c1, c2), _2n); // 2 * c1 * c2 + let t4 = Fp2.sqr(c2); // c2² + return Object.freeze({ + c0: Fp2.add(Fp2.mulByNonresidue(t3), t0), // T3 * (u + 1) + T0 + c1: Fp2.add(Fp2.mulByNonresidue(t4), t1), // T4 * (u + 1) + T1 + // T1 + (c0 - c1 + c2)² + T3 - T0 - T4 + c2: Fp2.sub(Fp2.sub(Fp2.add(Fp2.add(t1, Fp2.sqr(Fp2.add(Fp2.sub(c0, c1), c2))), t3), t0), t4), + }); + } + addN(a: Fp6, b: Fp6): Fp6 { + return this.add(a, b); + } + subN(a: Fp6, b: Fp6): Fp6 { + return this.sub(a, b); + } + mulN(a: Fp6, b: Fp6): Fp6 { + return this.mul(a, b); + } + sqrN(a: Fp6): Fp6 { + return this.sqr(a); + } + + create(num: Fp6) { + const { Fp2 } = this; + const c0 = Fp2.create(num.c0); + const c1 = Fp2.create(num.c1); + const c2 = Fp2.create(num.c2); + return Object.freeze({ c0, c1, c2 }); + } + + isValid(num: Fp6) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1, c2 } = num; + const { Fp2 } = this; + return Fp2.isValid(c0) && Fp2.isValid(c1) && Fp2.isValid(c2); + } + is0(num: Fp6) { + if (!isObj(num)) return false; + const { c0, c1, c2 } = num; + const { Fp2 } = this; + return Fp2.is0(c0) && Fp2.is0(c1) && Fp2.is0(c2); + } + isValidNot0(num: Fp6) { + return !this.is0(num) && this.isValid(num); + } + neg({ c0, c1, c2 }: Fp6) { + const { Fp2 } = this; + return Object.freeze({ c0: Fp2.neg(c0), c1: Fp2.neg(c1), c2: Fp2.neg(c2) }); + } + eql({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6) { + const { Fp2 } = this; + return Fp2.eql(c0, r0) && Fp2.eql(c1, r1) && Fp2.eql(c2, r2); + } + sqrt(_: Fp6) { + // Sextic extensions can use generic odd-field Tonelli-Shanks, but the helper must work + // over `IField` with a quadratic non-residue from Fp6 itself. The current + // `mod.tonelliShanks(P)` precomputation only searches integer residues in the base field. + return notImplemented(); + } + // Do we need division by bigint at all? Should be done via order: + div(lhs: Fp6, rhs: Fp6) { + const { Fp2 } = this; + const { Fp } = Fp2; + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + pow(num: Fp6, power: Fp): Fp6 { + return mod.FpPow(this, num, power); + } + invertBatch(nums: Fp6[]): Fp6[] { + return mod.FpInvertBatch(this, nums); + } + + inv({ c0, c1, c2 }: Fp6) { + const { Fp2 } = this; + let t0 = Fp2.sub(Fp2.sqr(c0), Fp2.mulByNonresidue(Fp2.mul(c2, c1))); // c0² - c2 * c1 * (u + 1) + let t1 = Fp2.sub(Fp2.mulByNonresidue(Fp2.sqr(c2)), Fp2.mul(c0, c1)); // c2² * (u + 1) - c0 * c1 + let t2 = Fp2.sub(Fp2.sqr(c1), Fp2.mul(c0, c2)); // c1² - c0 * c2 + // 1/(((c2 * T1 + c1 * T2) * v) + c0 * T0) + let t4 = Fp2.inv( + Fp2.add(Fp2.mulByNonresidue(Fp2.add(Fp2.mul(c2, t1), Fp2.mul(c1, t2))), Fp2.mul(c0, t0)) + ); + return Object.freeze({ c0: Fp2.mul(t4, t0), c1: Fp2.mul(t4, t1), c2: Fp2.mul(t4, t2) }); + } + // Bytes utils + fromBytes(b: Uint8Array): Fp6 { + const { Fp2 } = this; + abytes(b); + if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length); + const B2 = Fp2.BYTES; + return this.create({ + c0: Fp2.fromBytes(b.subarray(0, B2)), + c1: Fp2.fromBytes(b.subarray(B2, B2 * 2)), + c2: Fp2.fromBytes(b.subarray(2 * B2)), + }); + } + toBytes({ c0, c1, c2 }: Fp6): Uint8Array { + const { Fp2 } = this; + return concatBytes(Fp2.toBytes(c0), Fp2.toBytes(c1), Fp2.toBytes(c2)); + } + cmov({ c0, c1, c2 }: Fp6, { c0: r0, c1: r1, c2: r2 }: Fp6, c: boolean) { + const { Fp2 } = this; + return this.create({ + c0: Fp2.cmov(c0, r0, c), + c1: Fp2.cmov(c1, r1, c), + c2: Fp2.cmov(c2, r2, c), + }); + } + fromBigSix(tuple: BigintSix): Fp6 { + const { Fp2 } = this; + if (!Array.isArray(tuple) || tuple.length !== 6) throw new Error('invalid Fp6.fromBigSix'); + for (let i = 0; i < 6; i++) + if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp6.fromBigSix'); + const t = tuple; + return this.create({ + c0: Fp2.fromBigTuple(t.slice(0, 2) as BigintTuple), + c1: Fp2.fromBigTuple(t.slice(2, 4) as BigintTuple), + c2: Fp2.fromBigTuple(t.slice(4, 6) as BigintTuple), + }); + } + frobeniusMap({ c0, c1, c2 }: Fp6, power: number) { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.frobeniusMap(c0, power), + c1: Fp2.mul(Fp2.frobeniusMap(c1, power), this.FROBENIUS_COEFFICIENTS_1[power % 6]), + c2: Fp2.mul(Fp2.frobeniusMap(c2, power), this.FROBENIUS_COEFFICIENTS_2[power % 6]), + }); + } + mulByFp2({ c0, c1, c2 }: Fp6, rhs: Fp2): Fp6 { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.mul(c0, rhs), + c1: Fp2.mul(c1, rhs), + c2: Fp2.mul(c2, rhs), + }); + } + mulByNonresidue({ c0, c1, c2 }: Fp6) { + const { Fp2 } = this; + return Object.freeze({ c0: Fp2.mulByNonresidue(c2), c1: c0, c2: c1 }); + } + // Sparse multiplication + mul1({ c0, c1, c2 }: Fp6, b1: Fp2): Fp6 { + const { Fp2 } = this; + return Object.freeze({ + c0: Fp2.mulByNonresidue(Fp2.mul(c2, b1)), + c1: Fp2.mul(c0, b1), + c2: Fp2.mul(c1, b1), + }); + } + // Sparse multiplication + mul01({ c0, c1, c2 }: Fp6, b0: Fp2, b1: Fp2): Fp6 { + const { Fp2 } = this; + let t0 = Fp2.mul(c0, b0); // c0 * b0 + let t1 = Fp2.mul(c1, b1); // c1 * b1 + return Object.freeze({ + // ((c1 + c2) * b1 - T1) * (u + 1) + T0 + c0: Fp2.add(Fp2.mulByNonresidue(Fp2.sub(Fp2.mul(Fp2.add(c1, c2), b1), t1)), t0), + // (b0 + b1) * (c0 + c1) - T0 - T1 + c1: Fp2.sub(Fp2.sub(Fp2.mul(Fp2.add(b0, b1), Fp2.add(c0, c1)), t0), t1), + // (c0 + c2) * b0 - T0 + T1 + c2: Fp2.add(Fp2.sub(Fp2.mul(Fp2.add(c0, c2), b0), t0), t1), + }); + } +} + +// Keep lazy tower caches off-object: field instances stay frozen, and debugger output +// stays readable without JS private slots while second/subsequent lookups still hit cache. +const _FROBENIUS_COEFFICIENTS_6 = new WeakMap<_Field6, readonly [readonly Fp2[], readonly Fp2[]]>(); + +class _Field12 implements Fp12Bls { + readonly ORDER: bigint; + readonly BITS: number; + readonly BYTES: number; + readonly isLE: boolean; + + readonly ZERO: Fp12; + readonly ONE: Fp12; + + readonly Fp6: Fp6Bls; + readonly X_LEN: number; + readonly finalExponentiate: Tower12Opts['Fp12finalExponentiate']; + + constructor(Fp6: Fp6Bls, opts: Tower12Opts) { + const { X_LEN, Fp12finalExponentiate } = opts; + const { Fp2 } = Fp6; + const { Fp } = Fp2; + this.Fp6 = Fp6; + + // `IField.ORDER` is the field cardinality `q`; for degree-12 extensions that is `p^12`. + // Keeping `p^2` here breaks generic field identities like `x^q = x` on Fp12. + this.ORDER = Fp.ORDER ** _12n; + this.BITS = 2 * Fp6.BITS; + this.BYTES = 2 * Fp6.BYTES; + this.isLE = Fp6.isLE; + // Returned tower values are frozen, so larger constants can safely reuse + // already-frozen child coefficients instead of cloning them. + this.ZERO = this.create({ c0: Fp6.ZERO, c1: Fp6.ZERO }); + this.ONE = this.create({ c0: Fp6.ONE, c1: Fp6.ZERO }); + this.X_LEN = X_LEN; + this.finalExponentiate = (num) => { + const copy2 = ({ c0, c1 }: Fp2): Fp2 => Object.freeze({ c0, c1 }); + const copy6 = ({ c0, c1, c2 }: Fp6): Fp6 => + Object.freeze({ c0: copy2(c0), c1: copy2(c1), c2: copy2(c2) }); + // This config hook is trusted to return a canonical Fp12 value already. + // Copy+freeze it to keep the tower immutability invariant without mutating caller objects. + const res = Fp12finalExponentiate(num); + return Object.freeze({ c0: copy6(res.c0), c1: copy6(res.c1) }); + }; + Object.freeze(this); + } + // Keep the degree-12 Frobenius row lazy too; after the first lookup the cached + // array is reused exactly like the old eager table. + get FROBENIUS_COEFFICIENTS(): readonly Fp2[] { + const frob = _FROBENIUS_COEFFICIENTS_12.get(this); + if (frob) return frob; + const { Fp2 } = this.Fp6; + const { Fp } = Fp2; + const cache = Object.freeze( + calcFrobeniusCoefficients(Fp2, Fp2.NONRESIDUE, Fp.ORDER, 12, 1, 6)[0] + ); + _FROBENIUS_COEFFICIENTS_12.set(this, cache); + return cache; + } + create(num: Fp12) { + const { Fp6 } = this; + const c0 = Fp6.create(num.c0); + const c1 = Fp6.create(num.c1); + return Object.freeze({ c0, c1 }); + } + isValid(num: Fp12) { + if (!isObj(num)) + throw new TypeError('invalid field element: expected object, got ' + typeof num); + const { c0, c1 } = num; + const { Fp6 } = this; + return Fp6.isValid(c0) && Fp6.isValid(c1); + } + is0(num: Fp12) { + if (!isObj(num)) return false; + const { c0, c1 } = num; + const { Fp6 } = this; + return Fp6.is0(c0) && Fp6.is0(c1); + } + isValidNot0(num: Fp12) { + return !this.is0(num) && this.isValid(num); + } + neg({ c0, c1 }: Fp12) { + const { Fp6 } = this; + return Object.freeze({ c0: Fp6.neg(c0), c1: Fp6.neg(c1) }); + } + eql({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) { + const { Fp6 } = this; + return Fp6.eql(c0, r0) && Fp6.eql(c1, r1); + } + sqrt(_: Fp12): Fp12 { + // Fp12 is quadratic over Fp6, so a dedicated quadratic-extension sqrt is possible here + // once Fp6.sqrt() exists. Without that lower-level sqrt, only a field-generic + // Tonelli-Shanks path over Fp12 itself would work. + return notImplemented(); + } + inv({ c0, c1 }: Fp12) { + const { Fp6 } = this; + let t = Fp6.inv(Fp6.sub(Fp6.sqr(c0), Fp6.mulByNonresidue(Fp6.sqr(c1)))); // 1 / (c0² - c1² * v) + // ((C0 * T) * T) + (-C1 * T) * w + return Object.freeze({ c0: Fp6.mul(c0, t), c1: Fp6.neg(Fp6.mul(c1, t)) }); + } + div(lhs: Fp12, rhs: Fp12) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { Fp } = Fp2; + return this.mul(lhs, typeof rhs === 'bigint' ? Fp.inv(Fp.create(rhs)) : this.inv(rhs)); + } + pow(num: Fp12, power: bigint): Fp12 { + return mod.FpPow(this, num, power); + } + invertBatch(nums: Fp12[]): Fp12[] { + return mod.FpInvertBatch(this, nums); + } + + // Normalized + add({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.add(c0, r0), + c1: Fp6.add(c1, r1), + }); + } + sub({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12) { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.sub(c0, r0), + c1: Fp6.sub(c1, r1), + }); + } + mul({ c0, c1 }: Fp12, rhs: Fp12 | bigint) { + const { Fp6 } = this; + if (typeof rhs === 'bigint') + return Object.freeze({ c0: Fp6.mul(c0, rhs), c1: Fp6.mul(c1, rhs) }); + let { c0: r0, c1: r1 } = rhs; + let t1 = Fp6.mul(c0, r0); // c0 * r0 + let t2 = Fp6.mul(c1, r1); // c1 * r1 + return Object.freeze({ + c0: Fp6.add(t1, Fp6.mulByNonresidue(t2)), // T1 + T2 * v + // (c0 + c1) * (r0 + r1) - (T1 + T2) + c1: Fp6.sub(Fp6.mul(Fp6.add(c0, c1), Fp6.add(r0, r1)), Fp6.add(t1, t2)), + }); + } + sqr({ c0, c1 }: Fp12) { + const { Fp6 } = this; + let ab = Fp6.mul(c0, c1); // c0 * c1 + return Object.freeze({ + // (c1 * v + c0) * (c0 + c1) - AB - AB * v + c0: Fp6.sub( + Fp6.sub(Fp6.mul(Fp6.add(Fp6.mulByNonresidue(c1), c0), Fp6.add(c0, c1)), ab), + Fp6.mulByNonresidue(ab) + ), + c1: Fp6.add(ab, ab), + }); // AB + AB + } + // NonNormalized stuff + addN(a: Fp12, b: Fp12): Fp12 { + return this.add(a, b); + } + subN(a: Fp12, b: Fp12): Fp12 { + return this.sub(a, b); + } + mulN(a: Fp12, b: Fp12): Fp12 { + return this.mul(a, b); + } + sqrN(a: Fp12): Fp12 { + return this.sqr(a); + } + + // Bytes utils + fromBytes(b: Uint8Array): Fp12 { + const { Fp6 } = this; + abytes(b); + if (b.length !== this.BYTES) throw new Error('fromBytes invalid length=' + b.length); + return this.create({ + c0: Fp6.fromBytes(b.subarray(0, Fp6.BYTES)), + c1: Fp6.fromBytes(b.subarray(Fp6.BYTES)), + }); + } + toBytes({ c0, c1 }: Fp12): Uint8Array { + const { Fp6 } = this; + return concatBytes(Fp6.toBytes(c0), Fp6.toBytes(c1)); + } + cmov({ c0, c1 }: Fp12, { c0: r0, c1: r1 }: Fp12, c: boolean) { + const { Fp6 } = this; + return this.create({ + c0: Fp6.cmov(c0, r0, c), + c1: Fp6.cmov(c1, r1, c), + }); + } + // Utils + // toString() { + // return '' + 'Fp12(' + this.c0 + this.c1 + '* w'); + // }, + // fromTuple(c: [Fp6, Fp6]) { + // return new Fp12(...c); + // } + fromBigTwelve(tuple: BigintTwelve): Fp12 { + const { Fp6 } = this; + if (!Array.isArray(tuple) || tuple.length !== 12) throw new Error('invalid Fp12.fromBigTwelve'); + for (let i = 0; i < 12; i++) + if (typeof tuple[i] !== 'bigint') throw new Error('invalid Fp12.fromBigTwelve'); + const t = tuple; + return this.create({ + c0: Fp6.fromBigSix(t.slice(0, 6) as BigintSix), + c1: Fp6.fromBigSix(t.slice(6, 12) as BigintSix), + }); + } + // Raises to q**i -th power + frobeniusMap(lhs: Fp12, power: number) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { c0, c1, c2 } = Fp6.frobeniusMap(lhs.c1, power); + const coeff = this.FROBENIUS_COEFFICIENTS[power % 12]; + return Object.freeze({ + c0: Fp6.frobeniusMap(lhs.c0, power), + c1: Object.freeze({ + c0: Fp2.mul(c0, coeff), + c1: Fp2.mul(c1, coeff), + c2: Fp2.mul(c2, coeff), + }), + }); + } + mulByFp2({ c0, c1 }: Fp12, rhs: Fp2): Fp12 { + const { Fp6 } = this; + return Object.freeze({ + c0: Fp6.mulByFp2(c0, rhs), + c1: Fp6.mulByFp2(c1, rhs), + }); + } + conjugate({ c0, c1 }: Fp12): Fp12 { + // Reuse `c0` by reference and only negate the `w` coefficient. + return Object.freeze({ c0, c1: this.Fp6.neg(c1) }); + } + // Sparse multiplication + mul014({ c0, c1 }: Fp12, o0: Fp2, o1: Fp2, o4: Fp2) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + let t0 = Fp6.mul01(c0, o0, o1); + let t1 = Fp6.mul1(c1, o4); + return Object.freeze({ + c0: Fp6.add(Fp6.mulByNonresidue(t1), t0), // T1 * v + T0 + // (c1 + c0) * [o0, o1+o4] - T0 - T1 + c1: Fp6.sub(Fp6.sub(Fp6.mul01(Fp6.add(c1, c0), o0, Fp2.add(o1, o4)), t0), t1), + }); + } + mul034({ c0, c1 }: Fp12, o0: Fp2, o3: Fp2, o4: Fp2) { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const a = Object.freeze({ + c0: Fp2.mul(c0.c0, o0), + c1: Fp2.mul(c0.c1, o0), + c2: Fp2.mul(c0.c2, o0), + }); + const b = Fp6.mul01(c1, o3, o4); + const e = Fp6.mul01(Fp6.add(c0, c1), Fp2.add(o0, o3), o4); + return Object.freeze({ + c0: Fp6.add(Fp6.mulByNonresidue(b), a), + c1: Fp6.sub(e, Fp6.add(a, b)), + }); + } + + // A cyclotomic group is a subgroup of Fp^n defined by + // GΦₙ(p) = {α ∈ Fpⁿ : α^Φₙ(p) = 1} + // The result of any pairing is in a cyclotomic subgroup + // https://eprint.iacr.org/2009/565.pdf + // https://eprint.iacr.org/2010/354.pdf + _cyclotomicSquare({ c0, c1 }: Fp12): Fp12 { + const { Fp6 } = this; + const { Fp2 } = Fp6; + const { c0: c0c0, c1: c0c1, c2: c0c2 } = c0; + const { c0: c1c0, c1: c1c1, c2: c1c2 } = c1; + const { first: t3, second: t4 } = Fp2.Fp4Square(c0c0, c1c1); + const { first: t5, second: t6 } = Fp2.Fp4Square(c1c0, c0c2); + const { first: t7, second: t8 } = Fp2.Fp4Square(c0c1, c1c2); + const t9 = Fp2.mulByNonresidue(t8); // T8 * (u + 1) + return Object.freeze({ + c0: Object.freeze({ + c0: Fp2.add(Fp2.mul(Fp2.sub(t3, c0c0), _2n), t3), // 2 * (T3 - c0c0) + T3 + c1: Fp2.add(Fp2.mul(Fp2.sub(t5, c0c1), _2n), t5), // 2 * (T5 - c0c1) + T5 + c2: Fp2.add(Fp2.mul(Fp2.sub(t7, c0c2), _2n), t7), + }), // 2 * (T7 - c0c2) + T7 + c1: Object.freeze({ + c0: Fp2.add(Fp2.mul(Fp2.add(t9, c1c0), _2n), t9), // 2 * (T9 + c1c0) + T9 + c1: Fp2.add(Fp2.mul(Fp2.add(t4, c1c1), _2n), t4), // 2 * (T4 + c1c1) + T4 + c2: Fp2.add(Fp2.mul(Fp2.add(t6, c1c2), _2n), t6), + }), + }); // 2 * (T6 + c1c2) + T6 + } + // https://eprint.iacr.org/2009/565.pdf + _cyclotomicExp(num: Fp12, n: bigint): Fp12 { + // The loop only consumes `X_LEN` bits, so out-of-range exponents would otherwise get silently + // truncated (or sign-extended for negatives) instead of matching the caller's requested power. + aInRange('cyclotomic exponent', n, _0n, _1n << BigInt(this.X_LEN)); + let z = this.ONE; + for (let i = this.X_LEN - 1; i >= 0; i--) { + z = this._cyclotomicSquare(z); + if (bitGet(n, i)) z = this.mul(z, num); + } + return z; + } +} + +const _FROBENIUS_COEFFICIENTS_12 = new WeakMap<_Field12, readonly Fp2[]>(); + +/** + * @param opts - Tower construction options. See {@link Tower12Opts}. + * @returns BLS tower fields. + * @throws If the tower options or derived Frobenius helpers are invalid. {@link Error} + * @example + * Construct the Fp2/Fp6/Fp12 tower used by a pairing-friendly curve. + * + * ```ts + * const fields = tower12({ + * ORDER: 17n, + * X_LEN: 4, + * FP2_NONRESIDUE: [1n, 1n], + * Fp2mulByB: (num) => num, + * Fp12finalExponentiate: (num) => num, + * }); + * const fp12 = fields.Fp12.ONE; + * ``` + */ +export function tower12(opts: TArg): TRet<{ + Fp: Readonly & Required, 'isOdd'>>>; + Fp2: Fp2Bls; + Fp6: Fp6Bls; + Fp12: Fp12Bls; +}> { + validateObject( + opts, + { + ORDER: 'bigint', + X_LEN: 'number', + FP2_NONRESIDUE: 'object', + Fp2mulByB: 'function', + Fp12finalExponentiate: 'function', + }, + { NONRESIDUE: 'bigint' } + ); + asafenumber(opts.X_LEN, 'X_LEN'); + if (opts.X_LEN < 1) throw new Error('invalid X_LEN'); + const nonresidue = opts.FP2_NONRESIDUE as bigint[]; + if (!Array.isArray(nonresidue) || nonresidue.length !== 2) + throw new Error('invalid FP2_NONRESIDUE'); + if (typeof nonresidue[0] !== 'bigint' || typeof nonresidue[1] !== 'bigint') + throw new Error('invalid FP2_NONRESIDUE'); + const Fp = mod.Field(opts.ORDER); + const Fp2 = new _Field2(Fp, opts); + const Fp6 = new _Field6(Fp2); + const Fp12 = new _Field12(Fp6, opts); + return { Fp, Fp2, Fp6, Fp12 } as TRet<{ + Fp: Readonly & Required, 'isOdd'>>>; + Fp2: Fp2Bls; + Fp6: Fp6Bls; + Fp12: Fp12Bls; + }>; +} diff --git a/node_modules/@noble/curves/src/abstract/weierstrass.ts b/node_modules/@noble/curves/src/abstract/weierstrass.ts new file mode 100644 index 0000000..62ae5b4 --- /dev/null +++ b/node_modules/@noble/curves/src/abstract/weierstrass.ts @@ -0,0 +1,1960 @@ +/** + * Short Weierstrass curve methods. The formula is: y² = x³ + ax + b. + * + * ### Design rationale for types + * + * * Interaction between classes from different curves should fail: + * `k256.Point.BASE.add(p256.Point.BASE)` + * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime + * * Different calls of `curve()` would return different classes - + * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve, + * it won't affect others + * + * TypeScript can't infer types for classes created inside a function. Classes is one instance + * of nominative types in TypeScript and interfaces only check for shape, so it's hard to create + * unique type for every function call. + * + * We can use generic types via some param, like curve opts, but that would: + * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params) + * which is hard to debug. + * 2. Params can be generic and we can't enforce them to be constant value: + * if somebody creates curve from non-constant params, + * it would be allowed to interact with other curves with non-constant params + * + * @todo https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { hmac as nobleHmac } from '@noble/hashes/hmac.js'; +import { ahash } from '@noble/hashes/utils.js'; +import { + abignumber, + abool, + abytes, + aInRange, + asafenumber, + bitLen, + bitMask, + bytesToHex, + bytesToNumberBE, + concatBytes, + createHmacDrbg, + hexToBytes, + isBytes, + numberToHexUnpadded, + validateObject, + randomBytes as wcRandomBytes, + type CHash, + type HmacFn, + type Signer, + type TArg, + type TRet, +} from '../utils.ts'; +import { + createCurveFields, + createKeygen, + mulEndoUnsafe, + negateCt, + normalizeZ, + wNAF, + type AffinePoint, + type CurveLengths, + type CurvePoint, + type CurvePointCons, +} from './curve.ts'; +import { + FpInvertBatch, + FpIsSquare, + getMinHashLength, + mapHashToField, + validateField, + type IField, +} from './modular.ts'; + +/** Shared affine point shape used by Weierstrass helpers. */ +export type { AffinePoint }; + +type EndoBasis = [[bigint, bigint], [bigint, bigint]]; +/** + * When Weierstrass curve has `a=0`, it becomes Koblitz curve. + * Koblitz curves allow using **efficiently-computable GLV endomorphism ψ**. + * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%. + * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit. + * + * Endomorphism consists of beta, lambda and splitScalar: + * + * 1. GLV endomorphism ψ transforms a point: `P = (x, y) ↦ ψ(P) = (β·x mod p, y)` + * 2. GLV scalar decomposition transforms a scalar: `k ≡ k₁ + k₂·λ (mod n)` + * 3. Then these are combined: `k·P = k₁·P + k₂·ψ(P)` + * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than + * one 256-bit multiplication. + * + * where + * * beta: β ∈ Fₚ with β³ = 1, β ≠ 1 + * * lambda: λ ∈ Fₙ with λ³ = 1, λ ≠ 1 + * * splitScalar decomposes k ↦ k₁, k₂, by using reduced basis vectors. + * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-λ, 0)` + * + * Check out `test/misc/endomorphism.js` and + * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}. + */ +export type EndomorphismOpts = { + /** Cube root of unity used by the GLV endomorphism. */ + beta: bigint; + /** Reduced lattice basis used for scalar splitting. */ + basises?: EndoBasis; + /** + * Optional custom scalar-splitting helper. + * Receives one scalar and returns two half-sized scalar components. + */ + splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint }; +}; +// We construct the basis so `den` is always positive and equals `n`, +// but the `num` sign depends on the basis, not on the secret value. +// Exact half-way cases round away from zero, which keeps the split symmetric +// around the reduced-basis boundaries used by endomorphism decomposition. +const divNearest = (num: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den; + +/** Two half-sized scalar components returned by endomorphism splitting. */ +export type ScalarEndoParts = { + /** Whether the first split scalar should be negated. */ + k1neg: boolean; + /** Absolute value of the first split scalar. */ + k1: bigint; + /** Whether the second split scalar should be negated. */ + k2neg: boolean; + /** Absolute value of the second split scalar. */ + k2: bigint; +}; + +/** Splits scalar for GLV endomorphism. */ +export function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts { + // Split scalar into two such that part is ~half bits: `abs(part) < sqrt(N)` + // Since part can be negative, we need to do this on point. + // Callers must provide a reduced GLV basis whose vectors satisfy + // `a + b * lambda ≡ 0 (mod n)`; this helper only sees the basis and `n`. + // Reject unreduced scalars instead of silently treating them mod n. + aInRange('scalar', k, _0n, n); + // TODO: verifyScalar function which consumes lambda + const [[a1, b1], [a2, b2]] = basis; + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + // |k1|/|k2| is < sqrt(N), but can be negative. + // If we do `k1 mod N`, we'll get big scalar (`> sqrt(N)`): so, we do cheaper negation instead. + let k1 = k - c1 * a1 - c2 * a2; + let k2 = -c1 * b1 - c2 * b2; + const k1neg = k1 < _0n; + const k2neg = k2 < _0n; + if (k1neg) k1 = -k1; + if (k2neg) k2 = -k2; + // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail. + // This should only happen on wrong bases. + // Also, the math inside is complex enough that this guard is worth keeping. + const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n; // Half bits of N + if (k1 < _0n || k1 >= MAX_NUM || k2 < _0n || k2 >= MAX_NUM) { + throw new Error('splitScalar (endomorphism): failed for k'); + } + return { k1neg, k1, k2neg, k2 }; +} + +/** + * Option to enable hedged signatures with improved security. + * + * * Randomly generated k is bad, because broken CSPRNG would leak private keys. + * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks. + * + * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness + * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure + * as ordinary sig without ExtraEntropy. + * + * * `true` means "fetch data, from CSPRNG, incorporate it into k generation" + * * `false` means "disable extra entropy, use purely deterministic k" + * * `Uint8Array` passed means "incorporate following data into k generation" + * + * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}. + */ +export type ECDSAExtraEntropy = boolean | Uint8Array; +/** + * - `compact` is the default format + * - `recovered` is the same as compact, but with an extra byte indicating recovery byte + * - `der` is ASN.1 DER encoding + */ +export type ECDSASignatureFormat = 'compact' | 'recovered' | 'der'; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + */ +export type ECDSARecoverOpts = { + /** Whether to hash the message before signature recovery. */ + prehash?: boolean; +}; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`. + * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures, + * which is default openssl behavior. + * Non-malleable signatures can still be successfully verified in openssl. + * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte + */ +export type ECDSAVerifyOpts = { + /** Whether to hash the message before verification. */ + prehash?: boolean; + /** Whether to reject high-S signatures. */ + lowS?: boolean; + /** Signature encoding to accept. */ + format?: ECDSASignatureFormat; +}; +/** + * - `prehash`: (default: true) indicates whether to do sha256(message). + * When a custom hash is used, it must be set to `false`. + * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`. + * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures, + * which is default openssl behavior. + * Non-malleable signatures can still be successfully verified in openssl. + * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte + * - `extraEntropy`: (default: false) creates signatures with increased + * security, see {@link ECDSAExtraEntropy} + */ +export type ECDSASignOpts = { + /** Whether to hash the message before signing. */ + prehash?: boolean; + /** Whether to normalize signatures into the low-S half-order. */ + lowS?: boolean; + /** Signature encoding to produce. */ + format?: ECDSASignatureFormat; + /** Optional hedging input for deterministic k generation. */ + extraEntropy?: ECDSAExtraEntropy; +}; + +function validateSigFormat(format: string): ECDSASignatureFormat { + if (!['compact', 'recovered', 'der'].includes(format)) + throw new Error('Signature format must be "compact", "recovered", or "der"'); + return format as ECDSASignatureFormat; +} + +function validateSigOpts>( + opts: T, + def: D +): D { + validateObject(opts); + const optsn = {} as D; + // Normalize only the declared option subset from `def`; unknown keys are + // intentionally ignored so shared / superset option bags stay valid here too. + // `extraEntropy` stays an opaque payload until the signing path consumes it. + for (let optName of Object.keys(def) as (keyof D)[]) { + // @ts-ignore + optsn[optName] = opts[optName] === undefined ? def[optName] : opts[optName]; + } + abool(optsn.lowS!, 'lowS'); + abool(optsn.prehash!, 'prehash'); + if (optsn.format !== undefined) validateSigFormat(optsn.format); + return optsn; +} + +/** Projective XYZ point used by short Weierstrass curves. */ +export interface WeierstrassPoint extends CurvePoint> { + /** projective X coordinate. Different from affine x. */ + readonly X: T; + /** projective Y coordinate. Different from affine y. */ + readonly Y: T; + /** projective z coordinate */ + readonly Z: T; + /** affine x coordinate. Different from projective X. */ + get x(): T; + /** affine y coordinate. Different from projective Y. */ + get y(): T; + /** + * Encode the point into compressed or uncompressed SEC1 bytes. + * @param isCompressed - Whether to use the compressed form. + * @returns Encoded point bytes. + */ + toBytes(isCompressed?: boolean): TRet; + /** + * Encode the point into compressed or uncompressed SEC1 hex. + * @param isCompressed - Whether to use the compressed form. + * @returns Encoded point hex. + */ + toHex(isCompressed?: boolean): string; +} + +/** Constructor and metadata helpers for Weierstrass points. */ +export interface WeierstrassPointCons extends CurvePointCons> { + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + new (X: T, Y: T, Z: T): WeierstrassPoint; + /** + * Return the curve parameters captured by this point constructor. + * @returns Curve parameters. + */ + CURVE(): WeierstrassOpts; +} + +/** + * Weierstrass curve options. + * + * * p: prime characteristic (order) of finite field, in which arithmetics is done + * * n: order of prime subgroup a.k.a total amount of valid curve points + * * h: cofactor, usually 1. h*n is group order; n is subgroup order + * * a: formula param, must be in field of p + * * b: formula param, must be in field of p + * * Gx: x coordinate of generator point a.k.a. base point + * * Gy: y coordinate of generator point + */ +export type WeierstrassOpts = Readonly<{ + /** Base-field modulus. */ + p: bigint; + /** Prime subgroup order. */ + n: bigint; + /** Curve cofactor. */ + h: bigint; + /** Weierstrass curve parameter `a`. */ + a: T; + /** Weierstrass curve parameter `b`. */ + b: T; + /** Generator x coordinate. */ + Gx: T; + /** Generator y coordinate. */ + Gy: T; +}>; + +/** + * Optional helpers and overrides for a Weierstrass point constructor. + * + * When a cofactor != 1, there can be effective methods to: + * 1. Determine whether a point is torsion-free + * 2. Clear torsion component + */ +export type WeierstrassExtraOpts = Partial<{ + /** Optional base-field override. */ + Fp: IField; + /** Optional scalar-field override. */ + Fn: IField; + /** Whether the point constructor accepts infinity points. */ + allowInfinityPoint: boolean; + /** Optional GLV endomorphism data. */ + endo: EndomorphismOpts; + /** Optional torsion-check override. */ + isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean; + /** Optional cofactor-clearing override. */ + clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint; + /** Optional custom point decoder. */ + fromBytes: (bytes: TArg) => AffinePoint; + /** Optional custom point encoder. */ + toBytes: ( + c: WeierstrassPointCons, + point: WeierstrassPoint, + isCompressed: boolean + ) => TRet; +}>; + +/** + * Options for ECDSA signatures over a Weierstrass curve. + * + * * lowS: (default: true) whether produced or verified signatures occupy the + * low half of `ecdsaOpts.n`. Prevents malleability. + * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation. + * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness. + * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are + * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or + * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in + * `[0..Point.Fn.ORDER-1]`. + */ +export type ECDSAOpts = Partial<{ + /** Default low-S policy for this ECDSA instance. */ + lowS: boolean; + /** HMAC implementation used by RFC6979 DRBG. */ + hmac: HmacFn; + /** RNG override used by helper constructors. */ + randomBytes: (bytesLength?: number) => TRet; + /** Hash-to-integer conversion override. */ + bits2int: (bytes: TArg) => bigint; + /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */ + bits2int_modN: (bytes: TArg) => bigint; +}>; + +/** Elliptic Curve Diffie-Hellman helper namespace. */ +export interface ECDH { + /** + * Generate a secret/public key pair. + * @param seed - Optional seed material. + * @returns Secret/public key pair. + */ + keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet }; + /** + * Derive the public key from a secret key. + * @param secretKey - Secret key bytes. + * @param isCompressed - Whether to emit compressed SEC1 bytes. + * @returns Encoded public key. + */ + getPublicKey: (secretKey: TArg, isCompressed?: boolean) => TRet; + /** + * Compute the shared secret point from a secret key and peer public key. + * @param secretKeyA - Local secret key bytes. + * @param publicKeyB - Peer public key bytes. + * @param isCompressed - Whether to emit compressed SEC1 bytes. + * @returns Encoded shared point. + */ + getSharedSecret: ( + secretKeyA: TArg, + publicKeyB: TArg, + isCompressed?: boolean + ) => TRet; + /** Point constructor used by this ECDH instance. */ + Point: WeierstrassPointCons; + /** Validation and random-key helpers. */ + utils: { + /** Check whether a secret key has the expected encoding. */ + isValidSecretKey: (secretKey: TArg) => boolean; + /** Check whether a public key decodes to a valid point. */ + isValidPublicKey: (publicKey: TArg, isCompressed?: boolean) => boolean; + /** Generate a valid random secret key. */ + randomSecretKey: (seed?: TArg) => TRet; + }; + /** Byte lengths for keys and signatures exposed by this curve. */ + lengths: CurveLengths; +} + +/** + * ECDSA interface. + * Only supported for prime fields, not Fp2 (extension fields). + */ +export interface ECDSA extends ECDH { + /** + * Sign a message with the given secret key. + * @param message - Message bytes. + * @param secretKey - Secret key bytes. + * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}. + * @returns Encoded signature bytes. + */ + sign: ( + message: TArg, + secretKey: TArg, + opts?: TArg + ) => TRet; + /** + * Verify a signature against a message and public key. + * @param signature - Encoded signature bytes. + * @param message - Message bytes. + * @param publicKey - Encoded public key. + * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}. + * @returns Whether the signature is valid. + */ + verify: ( + signature: TArg, + message: TArg, + publicKey: TArg, + opts?: TArg + ) => boolean; + /** + * Recover the public key encoded into a recoverable signature. + * @param signature - Recoverable signature bytes. + * @param message - Message bytes. + * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}. + * @returns Encoded recovered public key. + */ + recoverPublicKey( + signature: TArg, + message: TArg, + opts?: TArg + ): TRet; + /** Signature constructor and parser helpers. */ + Signature: ECDSASignatureCons; +} +/** + * @param m - Error message. + * @example + * Throw a DER-specific error when signature parsing encounters invalid bytes. + * + * ```ts + * new DERErr('bad der'); + * ``` + */ +export class DERErr extends Error { + constructor(m = '') { + super(m); + } +} +/** DER helper namespace used by ECDSA signature parsing and encoding. */ +export type IDER = { + // asn.1 DER encoding utils + /** + * DER-specific error constructor. + * @param m - Error message. + * @returns DER-specific error instance. + */ + Err: typeof DERErr; + // Basic building block is TLV (Tag-Length-Value) + /** Low-level tag-length-value helpers used by DER encoders. */ + _tlv: { + /** + * Encode one TLV record. + * @param tag - ASN.1 tag byte. + * @param data - Hex-encoded value payload. + * @returns Encoded TLV string. + */ + encode: (tag: number, data: string) => string; + // v - value, l - left bytes (unparsed) + /** + * Decode one TLV record and return the value plus leftover bytes. + * @param tag - Expected ASN.1 tag byte. + * @param data - Remaining DER bytes. + * @returns Parsed value plus leftover bytes. + */ + decode(tag: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }>; + }; + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + /** Positive-integer DER helpers used by ECDSA signature encoding. */ + _int: { + /** + * Encode one positive bigint as a DER INTEGER. + * @param num - Positive integer to encode. + * @returns Encoded DER INTEGER. + */ + encode(num: bigint): string; + /** + * Decode one DER INTEGER into a bigint. + * @param data - DER INTEGER bytes. + * @returns Decoded bigint. + */ + decode(data: TArg): bigint; + }; + /** + * Parse a DER signature into `{ r, s }`. + * @param bytes - DER signature bytes. + * @returns Parsed signature components. + */ + toSig(bytes: TArg): { r: bigint; s: bigint }; + /** + * Encode `{ r, s }` as a DER signature. + * @param sig - Signature components. + * @returns DER-encoded signature hex. + */ + hexFromSig(sig: { r: bigint; s: bigint }): string; +}; +/** + * ASN.1 DER encoding utilities. ASN is very complex & fragile. Format: + * + * [0x30 (SEQUENCE), bytelength, 0x02 (INTEGER), intLength, R, 0x02 (INTEGER), intLength, S] + * + * Docs: {@link https://letsencrypt.org/docs/a-warm-welcome-to-asn1-and-der/ | Let's Encrypt ASN.1 guide} and + * {@link https://luca.ntop.org/Teaching/Appunti/asn1.html | Luca Deri's ASN.1 notes}. + * @example + * ASN.1 DER encoding utilities. + * + * ```ts + * const der = DER.hexFromSig({ r: 1n, s: 2n }); + * ``` + */ +export const DER: IDER = { + // asn.1 DER encoding utils + Err: DERErr, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag: number, data: string): string => { + const { Err: E } = DER; + asafenumber(tag, 'tag'); + if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag'); + if (typeof data !== 'string') + throw new TypeError('"data" expected string, got type=' + typeof data); + // Internal helper: callers hand this already-validated hex payload, so we only enforce + // byte alignment here instead of re-validating every nibble. + if (data.length & 1) throw new E('tlv.encode: unpadded data'); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if ((len.length / 2) & 0b1000_0000) throw new E('tlv.encode: long form length too big'); + // length of length with long form flag + const lenLen = dataLen > 127 ? numberToHexUnpadded((len.length / 2) | 0b1000_0000) : ''; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }> { + const { Err: E } = DER; + data = abytes(data, undefined, 'DER data'); + let pos = 0; + if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag'); + if (data.length < 2 || data[pos++] !== tag) throw new E('tlv.decode: wrong tlv'); + const first = data[pos++]; + // First bit of first length byte is the short/long form flag. + const isLong = !!(first & 0b1000_0000); + let length = 0; + if (!isLong) length = first; + else { + // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)] + const lenLen = first & 0b0111_1111; + if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported'); + // This would overflow u32 in JS. + if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big'); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete'); + if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte'); + for (const b of lengthBytes) length = (length << 8) | b; + pos += lenLen; + if (length < 128) throw new E('tlv.decode(long): not minimal encoding'); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) throw new E('tlv.decode: wrong value length'); + return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>; + }, + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num: bigint): string { + const { Err: E } = DER; + abignumber(num); + if (num < _0n) throw new E('integer: negative integers are not allowed'); + let hex = numberToHexUnpadded(num); + // Pad with zero byte if negative flag is present + if (Number.parseInt(hex[0], 16) & 0b1000) hex = '00' + hex; + if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex'); + return hex; + }, + decode(data: TArg): bigint { + const { Err: E } = DER; + if (data.length < 1) throw new E('invalid signature integer: empty'); + if (data[0] & 0b1000_0000) throw new E('invalid signature integer: negative'); + // Single-byte zero `00` is the canonical DER INTEGER encoding for zero. + if (data.length > 1 && data[0] === 0x00 && !(data[1] & 0b1000_0000)) + throw new E('invalid signature integer: unnecessary leading zero'); + return bytesToNumberBE(data); + }, + }, + toSig(bytes: TArg): { r: bigint; s: bigint } { + // parse DER signature + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = abytes(bytes, undefined, 'signature'); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data); + if (seqLeftBytes.length) throw new E('invalid signature: left bytes after parsing'); + const { v: rBytes, l: rLeftBytes } = tlv.decode(0x02, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(0x02, rLeftBytes); + if (sLeftBytes.length) throw new E('invalid signature: left bytes after parsing'); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig: { r: bigint; s: bigint }): string { + const { _tlv: tlv, _int: int } = DER; + const rs = tlv.encode(0x02, int.encode(sig.r)); + const ss = tlv.encode(0x02, int.encode(sig.s)); + const seq = rs + ss; + return tlv.encode(0x30, seq); + }, +}; +Object.freeze(DER._tlv); +Object.freeze(DER._int); +Object.freeze(DER); + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4); + +/** + * Creates weierstrass Point constructor, based on specified curve options. + * + * See {@link WeierstrassOpts}. + * @param params - Curve parameters. See {@link WeierstrassOpts}. + * @param extraOpts - Optional helpers and overrides. See {@link WeierstrassExtraOpts}. + * @returns Weierstrass point constructor. + * @throws If the curve parameters, overrides, or point codecs are invalid. {@link Error} + * + * @example + * Construct a point type from explicit Weierstrass curve parameters. + * + * ```js + * const opts = { + * p: 0xfffffffffffffffffffffffffffffffeffffac73n, + * n: 0x100000000000000000001b8fa16dfab9aca16b6b3n, + * h: 1n, + * a: 0n, + * b: 7n, + * Gx: 0x3b4c382ce37aa192a4019e763036f4f5dd4d7ebbn, + * Gy: 0x938cf935318fdced6bc28286531733c3f03c4feen, + * }; + * const secp160k1_Point = weierstrass(opts); + * ``` + */ +export function weierstrass( + params: WeierstrassOpts, + extraOpts: WeierstrassExtraOpts = {} +): WeierstrassPointCons { + const validated = createCurveFields('weierstrass', params, extraOpts); + const Fp = validated.Fp as IField; + const Fn = validated.Fn as IField; + let CURVE = validated.CURVE as WeierstrassOpts; + const { h: cofactor, n: CURVE_ORDER } = CURVE; + validateObject( + extraOpts, + {}, + { + allowInfinityPoint: 'boolean', + clearCofactor: 'function', + isTorsionFree: 'function', + fromBytes: 'function', + toBytes: 'function', + endo: 'object', + } + ); + + // Snapshot constructor-time flags whose later mutation would otherwise change + // validity semantics of an already-built point type. + const { endo, allowInfinityPoint } = extraOpts; + if (endo) { + // validateObject(endo, { beta: 'bigint', splitScalar: 'function' }); + if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) { + throw new Error('invalid endo: expected "beta": bigint and "basises": array'); + } + } + + const lengths = getWLengths(Fp as TArg>, Fn); + + function assertCompressionIsSupported() { + if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()'); + } + + // Implements IEEE P1363 point encoding + function pointToBytes( + _c: WeierstrassPointCons, + point: WeierstrassPoint, + isCompressed: boolean + ): TRet { + // SEC 1 v2.0 §2.3.3 encodes infinity as the single octet 0x00. Only curves + // that opt into infinity as a public point value should expose that byte form. + if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet; + const { x, y } = point.toAffine(); + const bx = Fp.toBytes(x); + abool(isCompressed, 'isCompressed'); + if (isCompressed) { + assertCompressionIsSupported(); + const hasEvenY = !Fp.isOdd!(y); + return concatBytes(pprefix(hasEvenY), bx) as TRet; + } else { + return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet; + } + } + function pointFromBytes(bytes: TArg) { + abytes(bytes, undefined, 'Point'); + const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; // e.g. for 32-byte: 33, 65 + const length = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO }; + // SEC 1 v2.0 §2.3.4 decodes 0x00 as infinity, but §3.2.2 public-key validation + // rejects infinity. We therefore keep 0x00 rejected by default because callers + // reuse this parser as the strict public-key boundary, and only admit it when + // the curve explicitly opts into infinity as a public point value. secp256k1 + // crosstests show OpenSSL raw point codecs accept 0x00 too. + // No actual validation is done here: use .assertValidity() + if (length === comp && (head === 0x02 || head === 0x03)) { + const x = Fp.fromBytes(tail); + if (!Fp.isValid(x)) throw new Error('bad point: is not on curve, wrong x'); + const y2 = weierstrassEquation(x); // y² = x³ + ax + b + let y: T; + try { + y = Fp.sqrt(y2); // y = y² ^ (p+1)/4 + } catch (sqrtError) { + const err = sqrtError instanceof Error ? ': ' + sqrtError.message : ''; + throw new Error('bad point: is not on curve, sqrt error' + err); + } + assertCompressionIsSupported(); + const evenY = Fp.isOdd!(y); + const evenH = (head & 1) === 1; // ECDSA-specific + if (evenH !== evenY) y = Fp.neg(y); + return { x, y }; + } else if (length === uncomp && head === 0x04) { + // TODO: more checks + const L = Fp.BYTES; + const x = Fp.fromBytes(tail.subarray(0, L)); + const y = Fp.fromBytes(tail.subarray(L, L * 2)); + if (!isValidXY(x, y)) throw new Error('bad point: is not on curve'); + return { x, y }; + } else { + throw new Error( + `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}` + ); + } + } + + const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes; + const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes; + function weierstrassEquation(x: T): T { + const x2 = Fp.sqr(x); // x * x + const x3 = Fp.mul(x2, x); // x² * x + return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x³ + a * x + b + } + + // TODO: move top-level + /** Checks whether equation holds for given x, y: y² == x³ + ax + b */ + function isValidXY(x: T, y: T): boolean { + const left = Fp.sqr(y); // y² + const right = weierstrassEquation(x); // x³ + ax + b + return Fp.eql(left, right); + } + + // Keep constructor-time generator validation cheap: callers are responsible for supplying the + // correct prime-order base point, while eager subgroup checks here would slow heavy module imports. + // Test 1: equation y² = x³ + ax + b should work for generator point. + if (!isValidXY(CURVE.Gx, CURVE.Gy)) throw new Error('bad curve params: generator point'); + + // Test 2: discriminant Δ part should be non-zero: 4a³ + 27b² != 0. + // Guarantees curve is genus-1, smooth (non-singular). + const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n), _4n); + const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); + if (Fp.is0(Fp.add(_4a3, _27b2))) throw new Error('bad curve params: a or b'); + + /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */ + function acoord(title: string, n: T, banZero = false) { + if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`); + return n; + } + + function aprjpoint(other: unknown): asserts other is Point { + if (!(other instanceof Point)) throw new Error('Weierstrass Point expected'); + } + + function splitEndoScalarN(k: bigint) { + if (!endo || !endo.basises) throw new Error('no endo'); + return _splitEndoScalar(k, endo.basises, Fn.ORDER); + } + + function finishEndo( + endoBeta: EndomorphismOpts['beta'], + k1p: Point, + k2p: Point, + k1neg: boolean, + k2neg: boolean + ) { + k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); + k1p = negateCt(k1neg, k1p); + k2p = negateCt(k2neg, k2p); + return k1p.add(k2p); + } + + /** + * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) ∋ (x=X/Z, y=Y/Z). + * Default Point works in 2d / affine coordinates: (x, y). + * We're doing calculations in projective, because its operations don't require costly inversion. + */ + class Point implements WeierstrassPoint { + // base / generator point + static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE); + // zero / infinity / identity point + static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0 + // math field + static readonly Fp = Fp; + // scalar field + static readonly Fn = Fn; + + readonly X: T; + readonly Y: T; + readonly Z: T; + + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + constructor(X: T, Y: T, Z: T) { + this.X = acoord('x', X); + // This is not just about ZERO / infinity: ambient curves can have real + // finite points with y=0. Those points are 2-torsion, so they cannot lie + // in the odd prime-order subgroups this point type is meant to represent. + this.Y = acoord('y', Y, true); + this.Z = acoord('z', Z); + Object.freeze(this); + } + + static CURVE(): WeierstrassOpts { + return CURVE; + } + + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + static fromAffine(p: AffinePoint): Point { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point'); + if (p instanceof Point) throw new Error('projective point not allowed'); + // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0) + if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO; + return new Point(x, y, Fp.ONE); + } + + static fromBytes(bytes: TArg): Point { + const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point'))); + P.assertValidity(); + return P; + } + + static fromHex(hex: string): Point { + return Point.fromBytes(hexToBytes(hex)); + } + + get x(): T { + return this.toAffine().x; + } + get y(): T { + return this.toAffine().y; + } + + /** + * + * @param windowSize + * @param isLazy - true will defer table computation until the first multiplication + * @returns + */ + precompute(windowSize: number = 8, isLazy = true): Point { + wnaf.createCache(this, windowSize); + if (!isLazy) this.multiply(_3n); // random number + return this; + } + + // TODO: return `this` + /** A point on curve is valid if it conforms to equation. */ + assertValidity(): void { + const p = this; + if (p.is0()) { + // (0, 1, 0) aka ZERO is invalid in most contexts. + // In BLS, ZERO can be serialized, so we allow it. + // Keep the accepted infinity encoding canonical: projective-equivalent (X, Y, 0) points + // like (1, 1, 0) compare equal to ZERO, but only (0, 1, 0) should pass this guard. + if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) + return; + throw new Error('bad point: ZERO'); + } + // Some 3rd-party test vectors require different wording between here & `fromCompressedHex` + const { x, y } = p.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not field elements'); + if (!isValidXY(x, y)) throw new Error('bad point: equation left != right'); + if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup'); + } + + hasEvenY(): boolean { + const { y } = this.toAffine(); + if (!Fp.isOdd) throw new Error("Field doesn't support isOdd"); + return !Fp.isOdd(y); + } + + /** Compare one point to another. */ + equals(other: WeierstrassPoint): boolean { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + + /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ + negate(): Point { + return new Point(this.X, Fp.neg(this.Y), this.Z); + } + + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n); + const { X: X1, Y: Y1, Z: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + let t0 = Fp.mul(X1, X1); // step 1 + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); // step 5 + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); // step 10 + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); // step 15 + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); // step 20 + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); // step 25 + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); // step 30 + Z3 = Fp.add(Z3, Z3); + return new Point(X3, Y3, Z3); + } + + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other: WeierstrassPoint): Point { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n); + let t0 = Fp.mul(X1, X2); // step 1 + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); // step 5 + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); // step 10 + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); // step 15 + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); // step 20 + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); // step 25 + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); // step 30 + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); // step 35 + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); // step 40 + return new Point(X3, Y3, Z3); + } + + subtract(other: WeierstrassPoint) { + // Validate before calling `negate()` so wrong inputs fail with the point guard + // instead of leaking a foreign `negate()` error. + aprjpoint(other); + return this.add(other.negate()); + } + + is0(): boolean { + return this.equals(Point.ZERO); + } + + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar - by which the point would be multiplied + * @returns New point + */ + multiply(scalar: bigint): Point { + const { endo } = extraOpts; + // Keep the subgroup-scalar contract strict instead of reducing 0 / n to ZERO. + // In key/signature-style callers, those values usually mean broken hash/scalar plumbing, + // and failing closed is safer than silently producing the identity point. + if (!Fn.isValidNot0(scalar)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid + let point: Point, fake: Point; // Fake point is used to const-time mult + const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p)); + /** See docs for {@link EndomorphismOpts} */ + if (endo) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); + const { p: k1p, f: k1f } = mul(k1); + const { p: k2p, f: k2f } = mul(k2); + fake = k1f.add(k2f); + point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg); + } else { + const { p, f } = mul(scalar); + point = p; + fake = f; + } + // Normalize `z` for both points, but return only real one + return normalizeZ(Point, [point, fake])[0]; + } + + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed secret key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(scalar: bigint): Point { + const { endo } = extraOpts; + const p = this as Point; + const sc = scalar; + // Public-scalar callers may need 0, but n and larger values stay rejected here too. + // Reducing them mod n would turn bad caller input into an accidental identity point. + if (!Fn.isValid(sc)) throw new RangeError('invalid scalar: out of range'); // 0 is valid + if (sc === _0n || p.is0()) return Point.ZERO; // 0 + if (sc === _1n) return p; // 1 + if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes + // We don't have method for double scalar multiplication (aP + bQ): + // Even with using Strauss-Shamir trick, it's 35% slower than naïve mul+add. + if (endo) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); + const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe + return finishEndo(endo.beta, p1, p2, k1neg, k2neg); + } else { + return wnaf.unsafe(p, sc); + } + } + + /** + * Converts Projective point to affine (x, y) coordinates. + * (X, Y, Z) ∋ (x=X/Z, y=Y/Z). + * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch + */ + toAffine(invertedZ?: T): AffinePoint { + const p = this; + let iz = invertedZ; + const { X, Y, Z } = p; + // Fast-path for normalized points + if (Fp.eql(Z, Fp.ONE)) return { x: X, y: Y }; + const is0 = p.is0(); + // If invZ was 0, we return zero point. However we still want to execute + // all operations, so we replace invZ with a random number, 1. + if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(Z); + const x = Fp.mul(X, iz); + const y = Fp.mul(Y, iz); + const zz = Fp.mul(Z, iz); + if (is0) return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid'); + return { x, y }; + } + + /** + * Checks whether Point is free of torsion elements (is in prime subgroup). + * Always torsion-free for cofactor=1 curves. + */ + isTorsionFree(): boolean { + const { isTorsionFree } = extraOpts; + if (cofactor === _1n) return true; + if (isTorsionFree) return isTorsionFree(Point, this); + return wnaf.unsafe(this, CURVE_ORDER).is0(); + } + + clearCofactor(): Point { + const { clearCofactor } = extraOpts; + if (cofactor === _1n) return this; // Fast-path + if (clearCofactor) return clearCofactor(Point, this) as Point; + // Default fallback assumes the cofactor fits the usual subgroup-scalar + // multiplyUnsafe() contract. Curves with larger / structured cofactors + // should define a clearCofactor override anyway (e.g. psi/Frobenius maps). + return this.multiplyUnsafe(cofactor); + } + + isSmallOrder(): boolean { + if (cofactor === _1n) return this.is0(); // Fast-path + return this.clearCofactor().is0(); + } + + toBytes(isCompressed = true): TRet { + abool(isCompressed, 'isCompressed'); + // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because + // callers use these encodings as public keys, where SEC 1 validation rejects infinity. + this.assertValidity(); + return encodePoint(Point, this, isCompressed); + } + + toHex(isCompressed = true): string { + return bytesToHex(this.toBytes(isCompressed)); + } + + toString() { + return ``; + } + } + const bits = Fn.BITS; + const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits); + // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the + // eager W=8 cache there instead of rejecting an otherwise valid constructor. + if (bits >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms. + Object.freeze(Point.prototype); + Object.freeze(Point); + return Point; +} + +/** Parsed ECDSA signature with helpers for recovery and re-encoding. */ +export interface ECDSASignature { + /** Signature component `r`. */ + readonly r: bigint; + /** Signature component `s`. */ + readonly s: bigint; + /** Optional recovery bit for recoverable signatures. */ + readonly recovery?: number; + /** + * Return a copy of the signature with a recovery bit attached. + * @param recovery - Recovery bit to attach. + * @returns Signature with an attached recovery bit. + */ + addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number }; + /** + * Check whether the signature uses the high-S half-order. + * @returns Whether the signature uses the high-S half-order. + */ + hasHighS(): boolean; + /** + * Recover the public key from the hashed message and recovery bit. + * @param messageHash - Hashed message bytes. + * @returns Recovered public-key point. + */ + recoverPublicKey(messageHash: TArg): WeierstrassPoint; + /** + * Encode the signature into bytes. + * @param format - Signature encoding to produce. + * @returns Encoded signature bytes. + */ + toBytes(format?: string): TRet; + /** + * Encode the signature into hex. + * @param format - Signature encoding to produce. + * @returns Encoded signature hex. + */ + toHex(format?: string): string; +} +/** Constructor and decoding helpers for ECDSA signatures. */ +export type ECDSASignatureCons = { + /** Create a signature from `r`, `s`, and an optional recovery bit. */ + new (r: bigint, s: bigint, recovery?: number): ECDSASignature; + /** + * Decode a signature from bytes. + * @param bytes - Encoded signature bytes. + * @param format - Signature encoding to parse. + * @returns Parsed signature. + */ + fromBytes(bytes: TArg, format?: ECDSASignatureFormat): ECDSASignature; + /** + * Decode a signature from hex. + * @param hex - Encoded signature hex. + * @param format - Signature encoding to parse. + * @returns Parsed signature. + */ + fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature; +}; + +// Points start with byte 0x02 when y is even; otherwise 0x03 +function pprefix(hasEvenY: boolean): TRet { + return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet; +} + +/** + * Implementation of the Shallue and van de Woestijne method for any weierstrass curve. + * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular. + * b = True and y = sqrt(u / v) if (u / v) is square in F, and + * b = False and y = sqrt(Z * (u / v)) otherwise. + * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it. + * @param Fp - Field implementation. + * @param Z - Simplified SWU map parameter. + * @returns Square-root ratio helper. + * @example + * Build the square-root ratio helper used by SWU map implementations. + * + * ```ts + * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n); + * const out = sqrtRatio(4n, 1n); + * ``` + */ +export function SWUFpSqrtRatio( + Fp: TArg>, + Z: T +): (u: T, v: T) => { isValid: boolean; value: T } { + // Fail with the usual field-shape error before touching pow/cmov on malformed field shims. + const F = validateField(Fp as IField) as IField; + // Generic implementation + const q = F.ORDER; + let l = _0n; + for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n; + const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1. + // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<. + // 2n ** c1 == 2n << (c1-1) + const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n); + const _2n_pow_c1 = _2n_pow_c1_1 * _2n; + const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic + const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic + const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic + const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic + const c6 = F.pow(Z, c2); // 6. c6 = Z^c2 + const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2) + // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0. + // We keep v=0 on the regular result path with isValid=false instead of + // throwing so the helper stays closer to the RFC's fixed control flow. + let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => { + let tv1 = c6; // 1. tv1 = c6 + let tv2 = F.pow(v, c4); // 2. tv2 = v^c4 + let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2 + tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v + let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3 + tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3 + tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2 + tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v + tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u + let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2 + tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5 + let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1 + tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7 + tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1 + tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR) + tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR) + // 17. for i in (c1, c1 - 1, ..., 2): + for (let i = c1; i > _1n; i--) { + let tv5 = i - _2n; // 18. tv5 = i - 2 + tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5 + let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5 + const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1 + tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1 + tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1 + tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1 + tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1) + tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1) + } + // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0. + // When u = 0 and v != 0, u / v = 0 is square and the computed root is + // still 0, so widen only the final flag and keep the full control flow. + return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 }; + }; + if (F.ORDER % _4n === _3n) { + // sqrt_ratio_3mod4(u, v) + const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic + const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z) + sqrtRatio = (u: T, v: T) => { + let tv1 = F.sqr(v); // 1. tv1 = v^2 + const tv2 = F.mul(u, v); // 2. tv2 = u * v + tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2 + let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1 + y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2 + const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2 + const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v + const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u + let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR) + return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2 + }; + } + // No curves uses that + // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8 + return sqrtRatio; +} +/** + * Simplified Shallue-van de Woestijne-Ulas Method + * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}. + * @param Fp - Field implementation. + * @param opts - SWU parameters: + * - `A`: Curve parameter `A`. + * - `B`: Curve parameter `B`. + * - `Z`: Simplified SWU map parameter. + * @returns Deterministic map-to-curve function. + * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error} + * @example + * Map one field element to a Weierstrass curve point with the SWU recipe. + * + * ```ts + * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js'; + * import { Field } from '@noble/curves/abstract/modular.js'; + * const Fp = Field(17n); + * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n }); + * const point = map(5n); + * ``` + */ +export function mapToCurveSimpleSWU( + Fp: TArg>, + opts: { + A: T; + B: T; + Z: T; + } +): (u: T) => { x: T; y: T } { + const F = validateField(Fp as IField) as IField; + const { A, B, Z } = opts; + if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + // RFC 9380 §6.6.2 and Appendix H.2 require: + // 1. Z is non-square in F + // 2. Z != -1 in F + // 3. g(x) - Z is irreducible over F + // 4. g(B / (Z * A)) is square in F + // We can enforce 1, 2, and 4 with the current field API. + // Criterion 3 is not checked here because generic `IField` does not expose + // polynomial-ring / irreducibility operations, and this helper is used for + // both prime and extension fields. + if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z)) + throw new Error('mapToCurveSimpleSWU: invalid opts'); + // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F. + // x = B / (Z * A) + const x = F.mul(B, F.inv(F.mul(Z, A))); + // g(x) = x^3 + A*x + B + const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B); + if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts'); + const sqrtRatio = SWUFpSqrtRatio(F, Z); + if (!F.isOdd) throw new Error('Field does not have .isOdd()'); + // Input: u, an element of F. + // Output: (x, y), a point on E. + return (u: T): { x: T; y: T } => { + // prettier-ignore + let tv1, tv2, tv3, tv4, tv5, tv6, x, y; + tv1 = F.sqr(u); // 1. tv1 = u^2 + tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1 + tv2 = F.sqr(tv1); // 3. tv2 = tv1^2 + tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1 + tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1 + tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3 + tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0) + tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4 + tv2 = F.sqr(tv3); // 9. tv2 = tv3^2 + tv6 = F.sqr(tv4); // 10. tv6 = tv4^2 + tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6 + tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5 + tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3 + tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4 + tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6 + tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5 + x = F.mul(tv1, tv3); // 17. x = tv1 * tv3 + const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6) + y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1 + y = F.mul(y, value); // 20. y = y * y1 + x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square) + y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square) + const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y) + y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1) + const tv4_inv = FpInvertBatch(F, [tv4], true)[0]; + x = F.mul(x, tv4_inv); // 25. x = x / tv4 + return { x, y }; + }; +} + +function getWLengths(Fp: TArg>, Fn: TArg>) { + return { + secretKey: Fn.BYTES, + publicKey: 1 + Fp.BYTES, + publicKeyUncompressed: 1 + 2 * Fp.BYTES, + publicKeyHasPrefix: true, + // Raw compact `(r || s)` signature width; DER and recovered signatures use + // different lengths outside this helper. + signature: 2 * Fn.BYTES, + }; +} + +/** + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * This helper ensures no signature functionality is present. Less code, smaller bundle size. + * @param Point - Weierstrass point constructor. + * @param ecdhOpts - Optional randomness helpers: + * - `randomBytes` (optional): Optional RNG override. + * @returns ECDH helper namespace. + * @example + * Sometimes users only need getPublicKey, getSharedSecret, and secret key handling. + * + * ```ts + * import { ecdh } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * const dh = ecdh(p256.Point); + * const alice = dh.keygen(); + * const shared = dh.getSharedSecret(alice.secretKey, alice.publicKey); + * ``` + */ +export function ecdh( + Point: WeierstrassPointCons, + ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet }> = {} +): ECDH { + const { Fn } = Point; + const randomBytes_ = ecdhOpts.randomBytes === undefined ? wcRandomBytes : ecdhOpts.randomBytes; + // Keep the advertised seed length aligned with mapHashToField(), which keeps a hard 16-byte + // minimum even on toy curves. + const lengths = Object.assign(getWLengths(Point.Fp, Fn), { + seed: Math.max(getMinHashLength(Fn.ORDER), 16), + }); + + function isValidSecretKey(secretKey: TArg) { + try { + const num = Fn.fromBytes(secretKey); + return Fn.isValidNot0(num); + } catch (error) { + return false; + } + } + + function isValidPublicKey(publicKey: TArg, isCompressed?: boolean): boolean { + const { publicKey: comp, publicKeyUncompressed } = lengths; + try { + const l = publicKey.length; + if (isCompressed === true && l !== comp) return false; + if (isCompressed === false && l !== publicKeyUncompressed) return false; + return !!Point.fromBytes(publicKey); + } catch (error) { + return false; + } + } + + /** + * Produces cryptographically secure secret key from random of size + * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible. + */ + function randomSecretKey(seed?: TArg): TRet { + seed = seed === undefined ? randomBytes_(lengths.seed) : seed; + return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet; + } + + /** + * Computes public key for a secret key. Checks for validity of the secret key. + * @param isCompressed - whether to return compact (default), or full key + * @returns Public key, full when isCompressed=false; short when isCompressed=true + */ + function getPublicKey(secretKey: TArg, isCompressed = true): TRet { + return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed); + } + + /** + * Quick and dirty check for item being public key. Does not validate hex, or being on-curve. + */ + function isProbPub(item: TArg): boolean | undefined { + const { secretKey, publicKey, publicKeyUncompressed } = lengths; + const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths; + if (!isBytes(item)) return undefined; + const l = abytes(item, undefined, 'key').length; + const isPub = l === publicKey || l === publicKeyUncompressed; + const isSec = l === secretKey || !!allowedLengths?.includes(l); + // P-521 accepts both 65- and 66-byte secret keys, so overlapping lengths stay ambiguous. + if (isPub && isSec) return undefined; + return isPub; + } + + /** + * ECDH (Elliptic Curve Diffie Hellman). + * Computes encoded shared point from secret key A and public key B. + * Checks: 1) secret key validity 2) shared key is on-curve. + * Does NOT hash the result or expose the SEC 1 x-coordinate-only `z`. + * Returns the encoded shared point on purpose: callers that need `x_P` + * can derive it from the encoded point, but `x_P` alone cannot recover the + * point/parity back. + * This helper only exposes the fully validated public-key path, not cofactor DH. + * @param isCompressed - whether to return compact (default), or full key + * @returns shared point encoding + */ + function getSharedSecret( + secretKeyA: TArg, + publicKeyB: TArg, + isCompressed = true + ): TRet { + if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key'); + if (isProbPub(publicKeyB) === false) throw new Error('second arg must be public key'); + const s = Fn.fromBytes(secretKeyA); + const b = Point.fromBytes(publicKeyB); // checks for being on-curve + return b.multiply(s).toBytes(isCompressed); + } + + const utils = { + isValidSecretKey, + isValidPublicKey, + randomSecretKey, + }; + const keygen = createKeygen(randomSecretKey, getPublicKey); + Object.freeze(utils); + Object.freeze(lengths); + + return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths }); +} + +/** + * Creates ECDSA signing interface for given elliptic curve `Point` and `hash` function. + * + * @param Point - created using {@link weierstrass} function + * @param hash - used for 1) message prehash-ing 2) k generation in `sign`, using hmac_drbg(hash) + * @param ecdsaOpts - rarely needed, see {@link ECDSAOpts}: + * - `lowS`: Default low-S policy. + * - `hmac`: HMAC implementation used by RFC6979 DRBG. + * - `randomBytes`: Optional RNG override. + * - `bits2int`: Optional hash-to-int conversion override. + * - `bits2int_modN`: Optional hash-to-int-mod-n conversion override. + * + * @returns ECDSA helper namespace. + * @example + * Create an ECDSA signer/verifier bundle for one curve implementation. + * + * ```ts + * import { ecdsa } from '@noble/curves/abstract/weierstrass.js'; + * import { p256 } from '@noble/curves/nist.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const p256ecdsa = ecdsa(p256.Point, sha256); + * const { secretKey, publicKey } = p256ecdsa.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256ecdsa.sign(msg, secretKey); + * const isValid = p256ecdsa.verify(sig, msg, publicKey); + * ``` + */ +export function ecdsa( + Point: WeierstrassPointCons, + hash: TArg, + ecdsaOpts: TArg = {} +): ECDSA { + // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes. + const hash_ = hash as CHash; + ahash(hash_); + validateObject( + ecdsaOpts, + {}, + { + hmac: 'function', + lowS: 'boolean', + randomBytes: 'function', + bits2int: 'function', + bits2int_modN: 'function', + } + ); + ecdsaOpts = Object.assign({}, ecdsaOpts); + const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes; + const hmac = + ecdsaOpts.hmac === undefined + ? (key: TArg, msg: TArg) => nobleHmac(hash_, key, msg) + : (ecdsaOpts.hmac as HmacFn); + + const { Fp, Fn } = Point; + const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn; + const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts); + const defaultSigOpts: Required = { + prehash: true, + lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true, + format: 'compact' as ECDSASignatureFormat, + extraEntropy: false, + }; + // SEC 1 4.1.6 public-key recovery tries x = r + jn for j = 0..h. Our recovered-signature + // format only stores one overflow bit, so it can only distinguish q.x = r from q.x = r + n. + // A third lift would have the form q.x = r + 2n. Since valid ECDSA r is in 1..n-1, the + // smallest such lift is 1 + 2n, not 2n. + const hasLargeRecoveryLifts = CURVE_ORDER * _2n + _1n < Fp.ORDER; + + function isBiggerThanHalfOrder(number: bigint) { + const HALF = CURVE_ORDER >> _1n; + return number > HALF; + } + function validateRS(title: string, num: bigint): bigint { + if (!Fn.isValidNot0(num)) + throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); + return num; + } + function assertRecoverableCurve(): void { + // ECDSA recovery only supports curves where the current recovery id can distinguish + // q.x = r and q.x = r + n; larger lifts may need additional `r + n*i` branches. + // SEC 1 4.1.6 recovers candidates via x = r + jn, but this format only encodes j = 0 or 1. + // The next possible candidate is q.x = r + 2n, and its smallest valid value is 1 + 2n. + // To easily get i, we either need to: + // a. increase amount of valid recid values (4, 5...); OR + // b. prohibit recovered signatures for those curves. + if (hasLargeRecoveryLifts) + throw new Error('"recovered" sig type is not supported for cofactor >2 curves'); + } + function validateSigLength(bytes: TArg, format: ECDSASignatureFormat) { + validateSigFormat(format); + const size = lengths.signature!; + const sizer = format === 'compact' ? size : format === 'recovered' ? size + 1 : undefined; + return abytes(bytes, sizer); + } + + /** + * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations. + */ + class Signature implements ECDSASignature { + readonly r: bigint; + readonly s: bigint; + readonly recovery?: number; + + constructor(r: bigint, s: bigint, recovery?: number) { + this.r = validateRS('r', r); // r in [1..N-1]; + this.s = validateRS('s', s); // s in [1..N-1]; + if (recovery != null) { + assertRecoverableCurve(); + if (![0, 1, 2, 3].includes(recovery)) throw new Error('invalid recovery id'); + this.recovery = recovery; + } + Object.freeze(this); + } + + static fromBytes( + bytes: TArg, + format: ECDSASignatureFormat = defaultSigOpts.format + ): Signature { + validateSigLength(bytes, format); + let recid: number | undefined; + if (format === 'der') { + const { r, s } = DER.toSig(abytes(bytes)); + return new Signature(r, s); + } + if (format === 'recovered') { + recid = bytes[0]; + format = 'compact'; + bytes = bytes.subarray(1); + } + const L = lengths.signature! / 2; + const r = bytes.subarray(0, L); + const s = bytes.subarray(L, L * 2); + return new Signature(Fn.fromBytes(r), Fn.fromBytes(s), recid); + } + + static fromHex(hex: string, format?: ECDSASignatureFormat) { + return this.fromBytes(hexToBytes(hex), format); + } + + private assertRecovery(): number { + const { recovery } = this; + if (recovery == null) throw new Error('invalid recovery id: must be present'); + return recovery; + } + + addRecoveryBit(recovery: number): RecoveredSignature { + return new Signature(this.r, this.s, recovery) as RecoveredSignature; + } + + // Unlike the top-level helper below, this method expects a digest that has + // already been hashed to the curve's message representative. + recoverPublicKey(messageHash: TArg): WeierstrassPoint { + const { r, s } = this; + const recovery = this.assertRecovery(); + const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r; + if (!Fp.isValid(radj)) throw new Error('invalid recovery id: sig.r+curve.n != R.x'); + const x = Fp.toBytes(radj); + const R = Point.fromBytes(concatBytes(pprefix((recovery & 1) === 0), x)); + const ir = Fn.inv(radj); // r^-1 + const h = bits2int_modN(abytes(messageHash, undefined, 'msgHash')); // Truncate hash + const u1 = Fn.create(-h * ir); // -hr^-1 + const u2 = Fn.create(s * ir); // sr^-1 + // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1). unsafe is fine: there is no private data. + const Q = Point.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); + if (Q.is0()) throw new Error('invalid recovery: point at infinify'); + Q.assertValidity(); + return Q; + } + + // Signatures should be low-s, to prevent malleability. + hasHighS(): boolean { + return isBiggerThanHalfOrder(this.s); + } + + toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet { + validateSigFormat(format); + if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet; + const { r, s } = this; + const rb = Fn.toBytes(r); + const sb = Fn.toBytes(s); + if (format === 'recovered') { + assertRecoverableCurve(); + return concatBytes(Uint8Array.of(this.assertRecovery()), rb, sb) as TRet; + } + return concatBytes(rb, sb) as TRet; + } + + toHex(format?: ECDSASignatureFormat) { + return bytesToHex(this.toBytes(format)); + } + } + type RecoveredSignature = Signature & { recovery: number }; + Object.freeze(Signature.prototype); + Object.freeze(Signature); + + // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets. + // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int. + // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same. + // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors + const bits2int: (bytes: TArg) => bigint = + ecdsaOpts.bits2int === undefined + ? function bits2int_def(bytes: TArg): bigint { + // Our custom check "just in case", for protection against DoS + if (bytes.length > 8192) throw new Error('input is too large'); + // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m) + // for some cases, since bytes.length * 8 is not actual bitLength. + const num = bytesToNumberBE(bytes); // check for == u8 done here + const delta = bytes.length * 8 - fnBits; // truncate to nBitLength leftmost bits + return delta > 0 ? num >> BigInt(delta) : num; + } + : (ecdsaOpts.bits2int as (bytes: TArg) => bigint); + const bits2int_modN: (bytes: TArg) => bigint = + ecdsaOpts.bits2int_modN === undefined + ? function bits2int_modN_def(bytes: TArg): bigint { + return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here + } + : (ecdsaOpts.bits2int_modN as (bytes: TArg) => bigint); + const ORDER_MASK = bitMask(fnBits); + // Pads output with zero as per spec. + /** Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`. */ + function int2octets(num: bigint): TRet { + aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK); + return Fn.toBytes(num) as TRet; + } + + function validateMsgAndHash(message: TArg, prehash: boolean): TRet { + abytes(message, undefined, 'message'); + return ( + prehash ? abytes(hash_(message), undefined, 'prehashed message') : message + ) as TRet; + } + + /** + * Steps A, D of RFC6979 3.2. + * Creates RFC6979 seed; converts msg/privKey to numbers. + * Used only in sign, not in verify. + * + * Warning: we cannot assume here that message has same amount of bytes as curve order, + * this will be invalid at least for P521. Also it can be bigger for P224 + SHA256. + */ + function prepSig( + message: TArg, + secretKey: TArg, + opts: TArg + ) { + const { lowS, prehash, extraEntropy } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); // RFC6979 3.2 A: h1 = H(m) + // We can't later call bits2octets, since nested bits2int is broken for curves + // with fnBits % 8 !== 0. Because of that, we unwrap it here as int2octets call. + // const bits2octets = (bits) => int2octets(bits2int_modN(bits)) + const h1int = bits2int_modN(message); + const d = Fn.fromBytes(secretKey); // validate secret key, convert to bigint + if (!Fn.isValidNot0(d)) throw new Error('invalid private key'); + const seedArgs: TArg[] = [int2octets(d), int2octets(h1int)]; + // extraEntropy. RFC6979 3.6: additional k' (optional). + if (extraEntropy != null && extraEntropy !== false) { + // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k') + // gen random bytes OR pass as-is + const e = extraEntropy === true ? randomBytes(lengths.secretKey) : extraEntropy; + seedArgs.push(abytes(e, undefined, 'extraEntropy')); // check for being bytes + } + const seed = concatBytes(...seedArgs) as TRet; // Step D of RFC6979 3.2 + const m = h1int; // no need to call bits2int second time here, it is inside truncateHash! + // Converts signature params into point w r/s, checks result for validity. + // To transform k => Signature: + // q = k⋅G + // r = q.x mod n + // s = k^-1(m + rd) mod n + // Can use scalar blinding b^-1(bm + bdr) where b ∈ [1,q−1] according to + // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it: + // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT + function k2sig(kBytes: TArg): Signature | undefined { + // RFC 6979 Section 3.2, step 3: k = bits2int(T) + // Important: all mod() calls here must be done over N + const k = bits2int(kBytes); // Cannot use fields methods, since it is group element + if (!Fn.isValidNot0(k)) return; // Valid scalars (including k) must be in 1..N-1 + const ik = Fn.inv(k); // k^-1 mod n + const q = Point.BASE.multiply(k).toAffine(); // q = k⋅G + const r = Fn.create(q.x); // r = q.x mod n + if (r === _0n) return; + const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n + if (s === _0n) return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n) + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = Fn.neg(s); // if lowS was passed, ensure s is always in the bottom half of N + recovery ^= 1; + } + return new Signature(r, normS, hasLargeRecoveryLifts ? undefined : recovery); + } + return { seed, k2sig }; + } + + /** + * Signs a message or message hash with a secret key. + * With the default `prehash: true`, raw message bytes are hashed internally; + * only `{ prehash: false }` expects a caller-supplied digest. + * + * ``` + * sign(m, d) where + * k = rfc6979_hmac_drbg(m, d) + * (x, y) = G × k + * r = x mod n + * s = (m + dr) / k mod n + * ``` + */ + function sign( + message: TArg, + secretKey: TArg, + opts: TArg = {} + ): TRet { + const { seed, k2sig } = prepSig(message, secretKey, opts); // Steps A, D of RFC6979 3.2. + const drbg = createHmacDrbg(hash_.outputLen, Fn.BYTES, hmac); + const sig = drbg(seed, k2sig); // Steps B, C, D, E, F, G + return sig.toBytes(opts.format); + } + + /** + * Verifies a signature against message and public key. + * Rejects lowS signatures by default: see {@link ECDSAVerifyOpts}. + * Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf: + * + * ``` + * verify(r, s, h, P) where + * u1 = hs^-1 mod n + * u2 = rs^-1 mod n + * R = u1⋅G + u2⋅P + * mod(R.x, n) == r + * ``` + */ + function verify( + signature: TArg, + message: TArg, + publicKey: TArg, + opts: TArg = {} + ): boolean { + const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts); + publicKey = abytes(publicKey, undefined, 'publicKey'); + message = validateMsgAndHash(message, prehash); + if (!isBytes(signature as any)) { + const end = signature instanceof Signature ? ', use sig.toBytes()' : ''; + throw new Error('verify expects Uint8Array signature' + end); + } + validateSigLength(signature, format); // execute this twice because we want loud error + try { + const sig = Signature.fromBytes(signature, format); + const P = Point.fromBytes(publicKey); + if (lowS && sig.hasHighS()) return false; + const { r, s } = sig; + const h = bits2int_modN(message); // mod n, not mod p + const is = Fn.inv(s); // s^-1 mod n + const u1 = Fn.create(h * is); // u1 = hs^-1 mod n + const u2 = Fn.create(r * is); // u2 = rs^-1 mod n + const R = Point.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1⋅G + u2⋅P + if (R.is0()) return false; + const v = Fn.create(R.x); // v = r.x mod n + return v === r; + } catch (e) { + return false; + } + } + + function recoverPublicKey( + signature: TArg, + message: TArg, + opts: TArg = {} + ): TRet { + // Top-level recovery mirrors `sign()` / `verify()`: it hashes raw message + // bytes first unless the caller passes `{ prehash: false }`. + const { prehash } = validateSigOpts(opts, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + return Signature.fromBytes(signature, 'recovered').recoverPublicKey(message).toBytes(); + } + + return Object.freeze({ + keygen, + getPublicKey, + getSharedSecret, + utils, + lengths, + Point, + sign, + verify, + recoverPublicKey, + Signature, + hash: hash_, + }) satisfies Signer; +} diff --git a/node_modules/@noble/curves/src/bls12-381.ts b/node_modules/@noble/curves/src/bls12-381.ts new file mode 100644 index 0000000..457bd46 --- /dev/null +++ b/node_modules/@noble/curves/src/bls12-381.ts @@ -0,0 +1,778 @@ +/** + * bls12-381 is pairing-friendly Barreto-Lynn-Scott elliptic curve construction allowing to: + +* Construct zk-SNARKs at the ~120-bit security, as per [Barbulescu-Duquesne 2017](https://hal.science/hal-01534101/file/main.pdf) +* Efficiently verify N aggregate signatures with 1 pairing and N ec additions: +the Boneh-Lynn-Shacham signature scheme is orders of magnitude more efficient than Schnorr + +BLS can mean 2 different things: + +* Barreto-Lynn-Scott: BLS12, a Pairing Friendly Elliptic Curve +* Boneh-Lynn-Shacham: A Signature Scheme. + +### Summary + +1. BLS Relies on expensive bilinear pairing +2. Secret Keys: 32 bytes +3. Public Keys: 48 OR 96 bytes - big-endian x coordinate of point on G1 OR G2 curve +4. Signatures: 96 OR 48 bytes - big-endian x coordinate of point on G2 OR G1 curve +5. The 12 stands for the Embedding degree. + +Modes of operation: + +* Long signatures: 48-byte keys + 96-byte sigs (G1 keys + G2 sigs). +* Short signatures: 96-byte keys + 48-byte sigs (G2 keys + G1 sigs). + +### Formulas + +- `P = pk x G` - public keys +- `S = pk x H(m)` - signing, uses hash-to-curve on m +- `e(P, H(m)) == e(G, S)` - verification using pairings +- `e(G, S) = e(G, SUM(n)(Si)) = MUL(n)(e(G, Si))` - signature aggregation + +### Curves + +G1 is ordinary elliptic curve. G2 is extension field curve, think "over complex numbers". + +- G1: y² = x³ + 4 +- G2: y² = x³ + 4(u + 1) where u = √−1; r-order subgroup of E'(Fp²), M-type twist + +### Towers + +Pairing G1 + G2 produces element in Fp₁₂, 12-degree polynomial. +Fp₁₂ is usually implemented using tower of lower-degree polynomials for speed. + +- Fp₁₂ = Fp₆² => Fp₂³ +- Fp(u) / (u² - β) where β = -1 +- Fp₂(v) / (v³ - ξ) where ξ = u + 1 +- Fp₆(w) / (w² - γ) where γ = v +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-1-u +- Fp¹²[w] = Fp⁶/w²-v + +### Params + +* Embedding degree (k): 12 +* Seed is sometimes named x or t +* t = -15132376222941642752 +* p = (t-1)² * (t⁴-t²+1)/3 + t +* r = t⁴-t²+1 +* Ate loop size: X + +To verify curve parameters, see +[pairing-friendly-curves spec](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11). +Basic math is done over finite fields over p. +More complicated math is done over polynominal extension fields. + +### Compatibility and notes +1. It is compatible with Algorand, Chia, Dfinity, Ethereum, Filecoin, ZEC. +Filecoin uses little endian byte arrays for secret keys - make sure to reverse byte order. +2. Make sure to correctly select mode: "long signature" or "short signature". +3. Compatible with specs: + RFC 9380, + [cfrg-pairing-friendly-curves-11](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11), + [cfrg-bls-signature-05](https://datatracker.ietf.org/doc/draft-irtf-cfrg-bls-signature/). + + * + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha2.js'; +import { bls, type BlsCurvePairWithSignatures } from './abstract/bls.ts'; +import { Field, type IField } from './abstract/modular.ts'; +import { + abytes, + bitLen, + bitMask, + bytesToHex, + bytesToNumberBE, + concatBytes, + copyBytes, + hexToBytes, + numberToBytesBE, + randomBytes, + type TArg, + type TRet, +} from './utils.ts'; +// Types +import { isogenyMap } from './abstract/hash-to-curve.ts'; +import type { BigintTuple, Fp, Fp12, Fp2, Fp6 } from './abstract/tower.ts'; +import { psiFrobenius, tower12 } from './abstract/tower.ts'; +import { + mapToCurveSimpleSWU, + weierstrass, + type AffinePoint, + type WeierstrassOpts, + type WeierstrassPoint, + type WeierstrassPointCons, +} from './abstract/weierstrass.ts'; + +// Be friendly to bad ECMAScript parsers by not using bigint literals +// prettier-ignore +const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4); + +// To verify math: +// https://tools.ietf.org/html/draft-irtf-cfrg-pairing-friendly-curves-11 + +// The BLS parameter x (seed) for BLS12-381. The stored constant is `|x|`; call +// sites that need the signed parameter apply the minus sign themselves. +// x = -2^63 - 2^62 - 2^60 - 2^57 - 2^48 - 2^16 +const BLS_X = BigInt('0xd201000000010000'); +// t = x (called differently in different places) +// const t = -BLS_X; +const BLS_X_LEN = bitLen(BLS_X); + +// a=0, b=4 +// P is characteristic of field Fp, in which curve calculations are done. +// p = (t-1)² * (t⁴-t²+1)/3 + t +// bls12_381_Fp = (t-1n)**2n * (t**4n - t**2n + 1n) / 3n + t +// r*h is curve order, amount of points on curve, +// where r is order of prime subgroup and h is cofactor. +// r = t⁴-t²+1 +// r = (t**4n - t**2n + 1n) +// cofactor h of G1: (t - 1)²/3, with the signed convention `t = -x` +// cofactorG1 = (t-1n)**2n/3n +// x = 3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507 +// y = 1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569 +const bls12_381_CURVE_G1: WeierstrassOpts = { + p: BigInt( + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab' + ), + n: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'), + h: BigInt('0x396c8c005555e1568c00aaab0000aaab'), + a: _0n, + b: _4n, + Gx: BigInt( + '0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb' + ), + Gy: BigInt( + '0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1' + ), +}; + +// CURVE FIELDS +// r = z⁴ − z² + 1; CURVE.n from other curves +/** + * bls12-381 Fr (Fn) field. + * `fromBytes()` reduces modulo `q` instead of rejecting non-canonical encodings. + */ +export const bls12_381_Fr: TRet> = Field(bls12_381_CURVE_G1.n, { + modFromBytes: true, +}) as TRet>; +const { Fp, Fp2, Fp6, Fp12 } = tower12({ + ORDER: bls12_381_CURVE_G1.p, + X_LEN: BLS_X_LEN, + // Finite extension field over irreducible polynominal. + // Fp(u) / (u² - β) where β = -1 + // Public `Fp2.NONRESIDUE` below is the sextic-tower value `(1, 1) = u + 1`; + // the quadratic non-residue for the base Fp2 construction is still `-1`. + FP2_NONRESIDUE: [_1n, _1n], + Fp2mulByB: ({ c0, c1 }: Fp2) => { + const t0 = Fp.mul(c0, _4n); // 4 * c0 + const t1 = Fp.mul(c1, _4n); // 4 * c1 + // (T0-T1) + (T0+T1)*i + return { c0: Fp.sub(t0, t1), c1: Fp.add(t0, t1) }; + }, + Fp12finalExponentiate: (num: Fp12) => { + const x = BLS_X; + // this^(q⁶) / this + const t0 = Fp12.div(Fp12.frobeniusMap(num, 6), num); + // t0^(q²) * t0 + const t1 = Fp12.mul(Fp12.frobeniusMap(t0, 2), t0); + const t2 = Fp12.conjugate(Fp12._cyclotomicExp(t1, x)); + const t3 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicSquare(t1)), t2); + const t4 = Fp12.conjugate(Fp12._cyclotomicExp(t3, x)); + const t5 = Fp12.conjugate(Fp12._cyclotomicExp(t4, x)); + const t6 = Fp12.mul(Fp12.conjugate(Fp12._cyclotomicExp(t5, x)), Fp12._cyclotomicSquare(t2)); + const t7 = Fp12.conjugate(Fp12._cyclotomicExp(t6, x)); + const t2_t5_pow_q2 = Fp12.frobeniusMap(Fp12.mul(t2, t5), 2); + const t4_t1_pow_q3 = Fp12.frobeniusMap(Fp12.mul(t4, t1), 3); + const t6_t1c_pow_q1 = Fp12.frobeniusMap(Fp12.mul(t6, Fp12.conjugate(t1)), 1); + const t7_t3c_t1 = Fp12.mul(Fp12.mul(t7, Fp12.conjugate(t3)), t1); + // (t2 * t5)^(q²) * (t4 * t1)^(q³) * (t6 * t1.conj)^(q^1) * t7 * t3.conj * t1 + return Fp12.mul(Fp12.mul(Fp12.mul(t2_t5_pow_q2, t4_t1_pow_q3), t6_t1c_pow_q1), t7_t3c_t1); + }, +}); + +// GLV endomorphism Ψ(P), for fast cofactor clearing. `Fp2.NONRESIDUE` here is +// the tower value `u + 1`, so the Frobenius base passed to psiFrobenius is +// `1 / (u + 1)`, and psi2 derives the published `1 / 2^((p - 1) / 3)` constant internally. +let frob: ReturnType | undefined; +const getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.div(Fp2.ONE, Fp2.NONRESIDUE))); +// Eager psiFrobenius setup now dominates `bls12-381.js` import, so defer it to +// first use. After that these locals are rewritten to the direct helper refs. +let G2psi: ReturnType['G2psi'] = (c, P) => { + const fn = getFrob().G2psi; + G2psi = fn; + return fn(c, P); +}; +let G2psi2: ReturnType['G2psi2'] = (c, P) => { + const fn = getFrob().G2psi2; + G2psi2 = fn; + return fn(c, P); +}; + +/** + * Default hash_to_field / hash-to-curve for BLS. + * m: 1 for G1, 2 for G2 + * k: target security level in bits + * hash: any function, e.g. BBS+ uses BLAKE2: see [github](https://github.com/hyperledger/aries-framework-go/issues/2247). + * Field/hash parameters come from [section 8.8.2 of RFC 9380](https://www.rfc-editor.org/rfc/rfc9380#section-8.8.2), + * but the `DST` / `encodeDST` strings below are the BLS-signature-suite override. + */ +const hasher_opts = Object.freeze({ + DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_', + p: Fp.ORDER, + m: 2, + k: 128, + expand: 'xmd', + hash: sha256, +}); + +// a=0, b=4 +// cofactor h of G2, derived with the signed convention `t = -x` +// (t^8 - 4t^7 + 5t^6 - 4t^4 + 6t^3 - 4t^2 - 4t + 13)/9 +// cofactorG2 = (t**8n - 4n*t**7n + 5n*t**6n - 4n*t**4n + 6n*t**3n - 4n*t**2n - 4n*t+13n)/9n +// x = 3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758*u + 352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160 +// y = 927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582*u + 1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905 +const bls12_381_CURVE_G2 = { + p: Fp2.ORDER, + n: bls12_381_CURVE_G1.n, + h: BigInt( + '0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5' + ), + a: Fp2.ZERO, + b: Fp2.fromBigTuple([_4n, _4n]), + Gx: Fp2.fromBigTuple([ + BigInt( + '0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8' + ), + BigInt( + '0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e' + ), + ]), + Gy: Fp2.fromBigTuple([ + BigInt( + '0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801' + ), + BigInt( + '0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be' + ), + ]), +}; + +// Encoding utils +const sortBit = (parts: bigint[], p: bigint) => { + for (const part of parts) { + if (part !== _0n) return Boolean((part * _2n) / p); + } + return false; +}; +const fp2 = { + // Generic tower bytes use `c0 || c1`, but the BLS12-381 G2 point/signature wire encoding uses + // `c1 || c0`, so keep this local wrapper instead of changing generic field serialization. + encode({ c0, c1 }: Fp2): TRet { + const { BYTES: L } = Fp; + return concatBytes(numberToBytesBE(c1, L), numberToBytesBE(c0, L)) as TRet; + }, + decode(bytes: TArg) { + const { BYTES: L } = Fp; + return Fp2.create({ + c0: Fp.create(bytesToNumberBE(bytes.subarray(L))), + c1: Fp.create(bytesToNumberBE(bytes.subarray(0, L))), + }); + }, +}; +const BaseFp = Fp; +type Mask = { compressed: boolean; infinity: boolean; sort: boolean }; +// Keep BLS12-381 point/signature codecs on one control-flow skeleton: the G1/G2 +// and point/signature variants differ only in field packing, subgroup bytes, and +// whether uncompressed form is allowed. Copy-paste decoders were diverging. +const coder = ( + name: 'G1' | 'G2', + Fp: TArg>, + b: T, + encode: TArg<(v: T) => TRet>, + decode: TArg<(bytes: TArg) => T>, + yparts: (y: T) => bigint[] +) => { + const F = Fp as IField; + const enc = encode as (v: T) => TRet; + const dec = decode as (bytes: TArg) => T; + const W = F.BYTES; + return (allowUncompressed: boolean) => ({ + encode(point: WeierstrassPoint, compressed = true): TRet { + if (!compressed && !allowUncompressed) + throw new Error('invalid signature: expected compressed encoding'); + const infinity = point.is0(); + const { x, y } = point.toAffine(); + const bytes = compressed ? enc(x) : concatBytes(enc(x), enc(y)); + let sort; + if (compressed && !infinity) sort = sortBit(yparts(y), BaseFp.ORDER); + return setMask(bytes, { compressed, infinity, sort }) as TRet; + }, + decode(bytes: TArg): AffinePoint { + const raw = allowUncompressed + ? abytes(bytes, undefined, 'point') + : abytes(bytes, W, 'signature'); + const { compressed, infinity, sort, value } = parseMask(raw); + if (!allowUncompressed && !compressed) + throw new Error('invalid signature: expected compressed encoding'); + const len = compressed ? W : 2 * W; + if (value.length !== len) throw new Error(`invalid ${name} point: expected ${len} bytes`); + if (infinity) { + // Infinity canonicality has to be checked on raw bytes before decode() + // reduces coordinates modulo p and turns non-empty payloads into zero. + for (const b of value) { + if (b) throw new Error(`invalid ${name} point: non-canonical zero`); + } + return { x: F.ZERO, y: F.ZERO }; + } + const x = dec(compressed ? value : value.subarray(0, W)); + let y; + if (compressed) { + y = F.sqrt(F.add(F.pow(x, _3n), b)); + if (!y) throw new Error(`invalid ${name} point: compressed`); + if (sortBit(yparts(y), BaseFp.ORDER) !== sort) y = F.neg(y); + } else { + y = dec(value.subarray(W)); + } + // Noble keeps the permissive coordinate reduction path here, but an + // omitted infinity flag must not still decode to ZERO afterwards. + if (!compressed && F.is0(x) && F.is0(y)) + throw new Error(`invalid ${name} point: uncompressed`); + return { x, y }; + }, + }); +}; + +// Internal helper only: it copies before clearing the top flag bits. The +// pairing-friendly-curves draft C.2 step 1 rejects 0x20 / 0x60 / 0xe0 because +// S_bit must be zero for infinity and for all uncompressed encodings. +function validateMask({ compressed, infinity, sort }: Mask) { + if ( + (!compressed && !infinity && sort) || // 0010_0000 = 0x20 + (!compressed && infinity && sort) || // 0110_0000 = 0x60 + (compressed && infinity && sort) // 1110_0000 = 0xe0 + ) + throw new Error('invalid encoding flag'); +} +function parseMask(bytes: TArg) { + // Copy, so we can remove mask data. + // It will be removed also later, when Fp.create will call modulo. + bytes = copyBytes(bytes); + const mask = bytes[0] & 0b1110_0000; + const compressed = !!((mask >> 7) & 1); // compression bit (0b1000_0000) + const infinity = !!((mask >> 6) & 1); // point at infinity bit (0b0100_0000) + const sort = !!((mask >> 5) & 1); // sort bit (0b0010_0000) + validateMask({ compressed, infinity, sort }); + bytes[0] &= 0b0001_1111; // clear mask (zero first 3 bits) + return { compressed, infinity, sort, value: bytes }; +} + +// Internal helper only: mutates a non-empty fresh buffer in place and just +// sets bits. Keep the same invalid-flag guard as parseMask() so encoders cannot +// manufacture states that decoders already reject. +function setMask(bytes: TArg, mask: Partial) { + if (bytes[0] & 0b1110_0000) throw new Error('setMask: non-empty mask'); + validateMask({ compressed: !!mask.compressed, infinity: !!mask.infinity, sort: !!mask.sort }); + if (mask.compressed) bytes[0] |= 0b1000_0000; + if (mask.infinity) bytes[0] |= 0b0100_0000; + if (mask.sort) bytes[0] |= 0b0010_0000; + return bytes; +} + +const g1coder = coder( + 'G1', + Fp, + Fp.create(bls12_381_CURVE_G1.b), + (x: Fp) => numberToBytesBE(x, Fp.BYTES), + (bytes: TArg) => Fp.create(bytesToNumberBE(bytes) & bitMask(Fp.BITS)), + (y: Fp) => [y] +); +const g1 = { point: g1coder(true), sig: g1coder(false) }; +const signatureG1ToBytes = (point: WeierstrassPoint): TRet => { + point.assertValidity(); + return g1.sig.encode(point); +}; +function signatureG1FromBytes(bytes: TArg): WeierstrassPoint { + const Point = bls12_381.G1.Point; + const point = Point.fromAffine(g1.sig.decode(bytes)); + point.assertValidity(); + return point; +} + +const g2coder = coder('G2', Fp2, bls12_381_CURVE_G2.b, fp2.encode, fp2.decode, (y: Fp2) => [ + y.c1, + y.c0, +]); +const g2 = { point: g2coder(true), sig: g2coder(false) }; +const signatureG2ToBytes = (point: WeierstrassPoint): TRet => { + point.assertValidity(); + return g2.sig.encode(point); +}; +function signatureG2FromBytes(bytes: TArg) { + const Point = bls12_381.G2.Point; + const point = Point.fromAffine(g2.sig.decode(bytes)); + point.assertValidity(); + return point; +} + +const signatureCoders = { + ShortSignature: { + fromBytes(bytes: TArg) { + return signatureG1FromBytes(abytes(bytes)); + }, + fromHex(hex: string): WeierstrassPoint { + return signatureG1FromBytes(hexToBytes(hex)); + }, + toBytes(point: WeierstrassPoint) { + return signatureG1ToBytes(point); + }, + // Historical alias: BLS signatures have a single compressed byte format here. + toRawBytes(point: WeierstrassPoint) { + return signatureG1ToBytes(point); + }, + toHex(point: WeierstrassPoint) { + return bytesToHex(signatureG1ToBytes(point)); + }, + }, + LongSignature: { + fromBytes(bytes: TArg): WeierstrassPoint { + return signatureG2FromBytes(abytes(bytes)); + }, + fromHex(hex: string): WeierstrassPoint { + return signatureG2FromBytes(hexToBytes(hex)); + }, + toBytes(point: WeierstrassPoint) { + return signatureG2ToBytes(point); + }, + // Historical alias: BLS signatures have a single compressed byte format here. + toRawBytes(point: WeierstrassPoint) { + return signatureG2ToBytes(point); + }, + toHex(point: WeierstrassPoint) { + return bytesToHex(signatureG2ToBytes(point)); + }, + }, +}; + +const fields = { + Fp, + Fp2, + Fp6, + Fp12, + Fr: bls12_381_Fr, +}; +const G1_Point = weierstrass(bls12_381_CURVE_G1, { + // Public point APIs still accept infinity, even though the Zcash proof + // encoding rules cited above only define nonzero point encodings. + allowInfinityPoint: true, + Fn: bls12_381_Fr, + fromBytes: g1.point.decode, + toBytes: ( + _c: WeierstrassPointCons, + point: WeierstrassPoint, + isComp: boolean + ): TRet => g1.point.encode(point, isComp) as TRet, + // Checks is the point resides in prime-order subgroup. + // point.isTorsionFree() should return true for valid points + // It returns false for shitty points. + // https://eprint.iacr.org/2021/1130.pdf + isTorsionFree: (c, point): boolean => { + // GLV endomorphism ψ(P) + const beta = BigInt( + '0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe' + ); + const phi = new c(Fp.mul(point.X, beta), point.Y, point.Z); + // TODO: unroll + const xP = point.multiplyUnsafe(BLS_X).negate(); // [x]P + const u2P = xP.multiplyUnsafe(BLS_X); // [u2]P + return u2P.equals(phi); + }, + // Clear cofactor of G1 + // https://eprint.iacr.org/2019/403 + clearCofactor: (_c, point) => { + // return this.multiplyUnsafe(CURVE.h); + return point.multiplyUnsafe(BLS_X).add(point); // x*P + P + }, +}); +const G2_Point = weierstrass(bls12_381_CURVE_G2, { + Fp: Fp2, + // Public point APIs still accept infinity, even though the Zcash proof + // encoding rules cited above only define nonzero point encodings. + allowInfinityPoint: true, + Fn: bls12_381_Fr, + fromBytes: g2.point.decode, + toBytes: ( + _c: WeierstrassPointCons, + point: WeierstrassPoint, + isComp: boolean + ): TRet => g2.point.encode(point, isComp) as TRet, + // https://eprint.iacr.org/2021/1130.pdf + // Older version: https://eprint.iacr.org/2019/814.pdf + isTorsionFree: (c, P): boolean => { + return P.multiplyUnsafe(BLS_X).negate().equals(G2psi(c, P)); // ψ(P) == [u](P) + }, + // clear_cofactor_bls12381_g2 from RFC 9380. + // https://eprint.iacr.org/2017/419.pdf + // prettier-ignore + clearCofactor: (c, P) => { + const x = BLS_X; + let t1 = P.multiplyUnsafe(x).negate(); // [-x]P + let t2 = G2psi(c, P); // Ψ(P) + let t3 = P.double(); // 2P + t3 = G2psi2(c, t3); // Ψ²(2P) + t3 = t3.subtract(t2); // Ψ²(2P) - Ψ(P) + t2 = t1.add(t2); // [-x]P + Ψ(P) + t2 = t2.multiplyUnsafe(x).negate(); // [x²]P - [x]Ψ(P) + t3 = t3.add(t2); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + t3 = t3.subtract(t1); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P + const Q = t3.subtract(P); // Ψ²(2P) - Ψ(P) + [x²]P - [x]Ψ(P) + [x]P - 1P + return Q; // [x²-x-1]P + [x-1]Ψ(P) + Ψ²(2P) + }, +}); + +const bls12_hasher_opts = { + mapToG1: mapToG1, + mapToG2: mapToG2, + hasherOpts: hasher_opts, + // RFC 9380 Appendix J defines distinct G1/G2 RO and NU suite IDs, and + // draft-irtf-cfrg-bls-signature-06 §4.2.1 gives separate G1/G2 `_NUL_` DSTs. + // Keep G1 encode-to-curve on the G1 domain instead of inheriting G2's `encodeDST`. + hasherOptsG1: { + ...hasher_opts, + m: 1, + DST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_', + encodeDST: 'BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_', + }, + hasherOptsG2: { ...hasher_opts }, +} as const; + +const bls12_params = { + ateLoopSize: BLS_X, // The BLS parameter x for BLS12-381 + xNegative: true, + twistType: 'multiplicative' as const, + randomBytes: randomBytes, +}; + +/** + * bls12-381 pairing-friendly curve construction. + * Provides both longSignatures and shortSignatures. + * @example + * bls12-381 pairing-friendly curve construction. + * + * ```ts + * const bls = bls12_381.longSignatures; + * const { secretKey, publicKey } = bls.keygen(); + * const msg = bls.hash(new TextEncoder().encode('hello noble')); + * const sig = bls.sign(msg, secretKey); + * const isValid = bls.verify(sig, msg, publicKey); + * ``` + */ +export const bls12_381: BlsCurvePairWithSignatures = bls( + fields, + G1_Point, + G2_Point, + bls12_params, + bls12_hasher_opts, + signatureCoders +); + +// 3-isogeny map from E' to E https://www.rfc-editor.org/rfc/rfc9380#appendix-E.3 +// Coefficients stay in ascending `k_(?,0)`..`k_(?,d)` order; isogenyMap() +// reverses them internally for Horner evaluation. +const isogenyMapG2 = isogenyMap( + Fp2, + [ + // xNum + [ + [ + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6', + ], + [ + '0x0', + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d', + ], + [ + '0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1', + '0x0', + ], + ], + // xDen + [ + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63', + ], + [ + '0xc', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f', + ], + ['0x1', '0x0'], // LAST 1 + ], + // yNum + [ + [ + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + '0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706', + ], + [ + '0x0', + '0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be', + ], + [ + '0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c', + '0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f', + ], + [ + '0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10', + '0x0', + ], + ], + // yDen + [ + [ + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb', + ], + [ + '0x0', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3', + ], + [ + '0x12', + '0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99', + ], + ['0x1', '0x0'], // LAST 1 + ], + ].map((i) => i.map((pair) => Fp2.fromBigTuple(pair.map(BigInt) as BigintTuple))) as [ + Fp2[], + Fp2[], + Fp2[], + Fp2[], + ] +); +// 11-isogeny map from E' to E. Coefficients stay in ascending +// `k_(?,0)`..`k_(?,d)` order; isogenyMap() reverses them for Horner evaluation. +const isogenyMapG1 = isogenyMap( + Fp, + [ + // xNum + [ + '0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7', + '0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb', + '0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0', + '0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861', + '0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9', + '0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983', + '0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84', + '0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e', + '0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317', + '0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e', + '0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b', + '0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229', + ], + // xDen + [ + '0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c', + '0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff', + '0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19', + '0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8', + '0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e', + '0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5', + '0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a', + '0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e', + '0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641', + '0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33', + '0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696', + '0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6', + '0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb', + '0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb', + '0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0', + '0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2', + '0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29', + '0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587', + '0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30', + '0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132', + '0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e', + '0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8', + '0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133', + '0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b', + '0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604', + ], + // yDen + [ + '0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1', + '0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d', + '0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2', + '0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416', + '0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d', + '0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac', + '0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c', + '0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9', + '0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a', + '0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55', + '0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8', + '0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092', + '0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc', + '0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7', + '0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f', + '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [Fp[], Fp[], Fp[], Fp[]] +); + +let G1_SWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined; +let G2_SWU: ((u: Fp2) => { x: Fp2; y: Fp2 }) | undefined; +// SWU setup validates the pre-isogeny curve parameters and builds sqrt-ratio helpers. +// Doing that eagerly adds about 10ms to `bls12-381.js` import here, so keep it lazy; after the +// first map call the cached mapper is reused directly. +const getG1_SWU = () => + G1_SWU || + (G1_SWU = mapToCurveSimpleSWU(Fp, { + A: Fp.create( + BigInt( + '0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d' + ) + ), + B: Fp.create( + BigInt( + '0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0' + ) + ), + Z: Fp.create(BigInt(11)), + })); +const getG2_SWU = () => + G2_SWU || + (G2_SWU = mapToCurveSimpleSWU(Fp2, { + // SWU map for the RFC 9380 §8.8.2 pre-isogeny G2 curve E': + // y² = x³ + 240i * x + 1012 + 1012i + A: Fp2.create({ c0: Fp.create(_0n), c1: Fp.create(BigInt(240)) }), // A' = 240 * I + B: Fp2.create({ c0: Fp.create(BigInt(1012)), c1: Fp.create(BigInt(1012)) }), // B' = 1012 * (1 + I) + Z: Fp2.create({ c0: Fp.create(BigInt(-2)), c1: Fp.create(BigInt(-1)) }), // Z: -(2 + I) + })); + +// Internal hash-to-curve step: G1 uses `m = 1`, so only `scalars[0]` is read, +// and the result is the isogeny image on E before the subgroup clear. +function mapToG1(scalars: bigint[]) { + const { x, y } = getG1_SWU()(Fp.create(scalars[0])); + return isogenyMapG1(x, y); +} +// Internal hash-to-curve step: G2 expects the RFC `m = 2` pair, and the result +// is the isogeny image on E before the subgroup clear. +function mapToG2(scalars: bigint[]) { + const { x, y } = getG2_SWU()(Fp2.fromBigTuple(scalars as BigintTuple)); + return isogenyMapG2(x, y); +} diff --git a/node_modules/@noble/curves/src/bn254.ts b/node_modules/@noble/curves/src/bn254.ts new file mode 100644 index 0000000..4e4590c --- /dev/null +++ b/node_modules/@noble/curves/src/bn254.ts @@ -0,0 +1,280 @@ +/** + * bn254, previously known as alt_bn_128, when it had 128-bit security. + +Barbulescu-Duquesne 2017 shown it's weaker: just about 100 bits, +so the naming has been adjusted to its prime bit count: +https://hal.science/hal-01534101/file/main.pdf. +Compatible with EIP-196 and EIP-197. + +There are huge compatibility issues in the ecosystem: + +1. Different libraries call it in different ways: "bn254", "bn256", "alt_bn128", "bn128". +2. libff has bn128, but it's a different curve with different G2: + https://github.com/scipr-lab/libff/blob/a44f482e18b8ac04d034c193bd9d7df7817ad73f/libff/algebra/curves/bn128/bn128_init.cpp#L166-L169 +3. halo2curves bn256 is also incompatible and returns different outputs + +We don't implement Point methods toHex / toBytes. +To work around this limitation, has to initialize points on their own from BigInts. +Reason it's not implemented is because [there is no standard](https://github.com/privacy-scaling-explorations/halo2curves/issues/109). +Points of divergence: + +- Endianness: LE vs BE (byte-swapped) +- Flags as first hex bits (similar to BLS) vs no-flags +- Imaginary part last in G2 vs first (c0, c1 vs c1, c0) + +The goal of our implementation is to support "Ethereum" variant of the curve, +because it at least has specs: + +- EIP196 (https://eips.ethereum.org/EIPS/eip-196) describes bn254 ECADD and ECMUL opcodes for EVM +- EIP197 (https://eips.ethereum.org/EIPS/eip-197) describes bn254 pairings +- It's hard: EIPs don't have proper tests. EIP-197 returns boolean output instead of Fp12 +- The existing implementations are bad. Some are deprecated: + - https://github.com/paritytech/bn (old version) + - https://github.com/ewasm/ethereum-bn128.rs (uses paritytech/bn) + - https://github.com/zcash-hackworks/bn + - https://github.com/arkworks-rs/curves/blob/master/bn254/src/lib.rs +- Python implementations use different towers and produce different Fp12 outputs: + - https://github.com/ethereum/py_pairing + - https://github.com/ethereum/py_ecc/tree/main/py_ecc/bn128 +- Points are encoded differently in different implementations + +### Params +Seed (X): 4965661367192848881 +Fr: (36x⁴+36x³+18x²+6x+1) +Fp: (36x⁴+36x³+24x²+6x+1) +(E / Fp ): Y² = X³+3 +(Et / Fp²): Y² = X³+3/(u+9) (D-type twist) +Ate loop size: 6x+2 + +### Towers +- Fp²[u] = Fp/u²+1 +- Fp⁶[v] = Fp²/v³-9-u +- Fp¹²[w] = Fp⁶/w²-v + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + blsBasic, + type BlsCurvePair, + type BlsPostPrecomputeFn, + type BlsPostPrecomputePointAddFn, +} from './abstract/bls.ts'; +import { Field, type IField } from './abstract/modular.ts'; +import type { Fp, Fp12, Fp2 } from './abstract/tower.ts'; +import { psiFrobenius, tower12 } from './abstract/tower.ts'; +import { weierstrass, type WeierstrassOpts } from './abstract/weierstrass.ts'; +import { bitLen, type TRet } from './utils.ts'; +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3); +const _6n = /* @__PURE__ */ BigInt(6); + +// Locally documented BN pairing seed. EIP-197 does not name this scalar +// directly; noble stores the positive value and derives any `-x` uses later. +const BN_X = /* @__PURE__ */ BigInt('4965661367192848881'); +// Bit width of the stored seed itself, not the derived Miller-loop scalar `6x+2`. +const BN_X_LEN = /* @__PURE__ */ (() => bitLen(BN_X))(); +// Derived scalar used by the optimized G2 subgroup test required by EIP-197. +const SIX_X_SQUARED = /* @__PURE__ */ (() => _6n * BN_X ** _2n)(); + +const bn254_G1_CURVE: WeierstrassOpts = { + p: BigInt('0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47'), + n: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + // The Ethereum specs define G1 as prime-order but do not spell out the + // cofactor separately; `h = 1` is the implementation-derived value. + h: _1n, + a: _0n, + b: _3n, + Gx: _1n, + Gy: BigInt(2), +}; + +// r == n +// Finite field over r. It's for convenience and is not used in the code below, +// and its canonical `fromBytes()` decoder is stricter than the EIP-196 MUL +// scalar rule that accepts any 256-bit integer. +// These factories are side-effect free; mark them pure so single-export bundles can drop the rest. +/** bn254 scalar field. */ +export const bn254_Fr: TRet> = /* @__PURE__ */ (() => + Field(bn254_G1_CURVE.n) as TRet>)(); + +// `3 / (i + 9)` from EIP-197, stored in noble's internal `(c0, c1) = (b, a)` +// order rather than the spec's `a * i + b` notation. +const Fp2B = /* @__PURE__ */ (() => ({ + c0: BigInt('19485874751759354771024239261021720505790618469301721065564631296452457478373'), + c1: BigInt('266929791119991161246907387137283842545076965332900288569378510910307636690'), +}))(); + +// Bootstrap binding: `Fp12finalExponentiate` needs to reference the finished +// field object while `tower12(...)` is still constructing it. +let Fp12: ReturnType['Fp12']; +const tower = /* @__PURE__ */ (() => { + const res = tower12({ + ORDER: bn254_G1_CURVE.p, + X_LEN: BN_X_LEN, + // Public `Fp2.NONRESIDUE` below is the sextic-tower seed `(9, 1)`, not the + // quadratic relation `i^2 + 1 = 0` from the EIP text. + FP2_NONRESIDUE: [BigInt(9), _1n], + Fp2mulByB: (num: Fp2) => Fp2.mul(num, Fp2B), + Fp12finalExponentiate: (num: Fp12) => { + const powMinusX = (num: Fp12) => Fp12.conjugate(Fp12._cyclotomicExp(num, BN_X)); + const r0 = Fp12.mul(Fp12.conjugate(num), Fp12.inv(num)); + const r = Fp12.mul(Fp12.frobeniusMap(r0, 2), r0); + const y1 = Fp12._cyclotomicSquare(powMinusX(r)); + const y2 = Fp12.mul(Fp12._cyclotomicSquare(y1), y1); + const y4 = powMinusX(y2); + const y6 = powMinusX(Fp12._cyclotomicSquare(y4)); + const y8 = Fp12.mul(Fp12.mul(Fp12.conjugate(y6), y4), Fp12.conjugate(y2)); + const y9 = Fp12.mul(y8, y1); + return Fp12.mul( + Fp12.frobeniusMap(Fp12.mul(Fp12.conjugate(r), y9), 3), + Fp12.mul( + Fp12.frobeniusMap(y8, 2), + Fp12.mul(Fp12.frobeniusMap(y9, 1), Fp12.mul(Fp12.mul(y8, y4), r)) + ) + ); + }, + }); + Fp12 = res.Fp12; + return res; +})(); +const Fp = /* @__PURE__ */ (() => tower.Fp)(); +const Fp2 = /* @__PURE__ */ (() => tower.Fp2)(); + +// END OF CURVE FIELDS +// BN254 uses the same tower seed `(9, 1)` for the Frobenius helper that powers +// the divisive-twist G2 endomorphism. +let frob: ReturnType | undefined; +const getFrob = () => frob || (frob = psiFrobenius(Fp, Fp2, Fp2.NONRESIDUE)); +// Eager psiFrobenius setup now dominates `bn254.js` import, so defer it to +// first use. After that these locals are rewritten to the direct helper refs. +let psi: ReturnType['psi'] = (x, y) => { + const fn = getFrob().psi; + psi = fn; + return fn(x, y); +}; +let G2psi: ReturnType['G2psi'] = (c, P) => { + const fn = getFrob().G2psi; + G2psi = fn; + return fn(c, P); +}; + +export const _postPrecompute: BlsPostPrecomputeFn = ( + Rx: Fp2, + Ry: Fp2, + Rz: Fp2, + Qx: Fp2, + Qy: Fp2, + pointAdd: BlsPostPrecomputePointAddFn +) => { + const q = psi(Qx, Qy); + ({ Rx, Ry, Rz } = pointAdd(Rx, Ry, Rz, q[0], q[1])); + const q2 = psi(q[0], q[1]); + pointAdd(Rx, Ry, Rz, q2[0], Fp2.neg(q2[1])); +}; + +// cofactor: (36 * X^4) + (36 * X^3) + (30 * X^2) + 6*X + 1 +const bn254_G2_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: Fp2.ORDER, + n: bn254_G1_CURVE.n, + // As with G1, the Ethereum specs do not spell out the G2 cofactor + // separately; this literal is the implementation-derived value. + h: BigInt('0x30644e72e131a029b85045b68181585e06ceecda572a2489345f2299c0f9fa8d'), + a: Fp2.ZERO, + b: Fp2B, + Gx: Fp2.fromBigTuple([ + BigInt('10857046999023057135944570762232829481370756359578518086990519993285655852781'), + BigInt('11559732032986387107991004021392285783925812861821192530917403151452391805634'), + ]), + Gy: Fp2.fromBigTuple([ + BigInt('8495653923123431417604973247489272438418190587263600148770280649306958101930'), + BigInt('4082367875863433681332203403145435568316851327593401208105741076214120093531'), + ]), +}))(); + +const fields = /* @__PURE__ */ (() => ({ Fp, Fp2, Fp6: tower.Fp6, Fp12, Fr: bn254_Fr }))(); +const bn254_G1 = /* @__PURE__ */ weierstrass(bn254_G1_CURVE, { + Fp, + Fn: bn254_Fr, + // Ethereum encodes infinity as `(0, 0)`, so the public point API accepts it + // even though it is not an affine curve point, and `fromAffine()` stays lazy: + // adversarial inputs still need `assertValidity()`. + allowInfinityPoint: true, +}); +const bn254_G2 = /* @__PURE__ */ weierstrass(bn254_G2_CURVE, { + Fp: Fp2, + Fn: bn254_Fr, + // Ethereum encodes infinity as `((0, 0), (0, 0))`, so the public point API + // accepts it even though it is not an affine curve point. + allowInfinityPoint: true, + // Optimized BN254 G2 subgroup test used to satisfy the EIP-197 order check. + isTorsionFree: (c, P) => P.multiplyUnsafe(SIX_X_SQUARED).equals(G2psi(c, P)), // [p]P = [6X^2]P +}); +/* +No hashToCurve for now (and signatures): + +- RFC 9380 doesn't mention bn254 and doesn't provide test vectors +- Overall seems like nobody is using BLS signatures on top of bn254 +- Seems like it can utilize SVDW, which is not implemented yet +*/ +// const htfDefaults = Object.freeze({ +// // DST: a domain separation tag defined in section 2.2.5 +// DST: 'BN254G2_XMD:SHA-256_SVDW_RO_', +// encodeDST: 'BN254G2_XMD:SHA-256_SVDW_RO_', +// p: Fp.ORDER, +// m: 2, +// k: 128, +// expand: 'xmd', +// hash: sha256, +// }); +// const hasherOpts = { +// { ...htfDefaults, m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' } +// }; +const bn254_params = /* @__PURE__ */ (() => ({ + // Optimal-ate Miller loop parameter derived from the positive BN seed. + ateLoopSize: BN_X * _6n + _2n, + r: bn254_Fr.ORDER, + xNegative: false, + // EIP-197 writes G2 as `y^2 = x^3 + 3 / (i + 9)`, so the pairing + // configuration uses the divisive twist convention. + twistType: 'divisive' as const, + postPrecompute: _postPrecompute, +}))(); +// const bn254_hasher = { +// hasherOpts: htfDefaults, +// hasherOptsG1: { m: 1, DST: 'BN254G2_XMD:SHA-256_SVDW_RO_' }, +// hasherOptsG2: htfDefaults +// }; +// G2_heff hEff: BigInt('21888242871839275222246405745257275088844257914179612981679871602714643921549'), +// fromBytes: notImplemented, +// toBytes: notImplemented, + +// mapToCurve: notImplemented, +// fromBytes: notImplemented, +// toBytes: notImplemented, +// ShortSignature: { +// fromBytes: notImplemented, +// fromHex: notImplemented, +// toBytes: notImplemented, +// toRawBytes: notImplemented, +// toHex: notImplemented, +// }, + +/** + * bn254 (a.k.a. alt_bn128) pairing-friendly curve. + * Contains G1 / G2 operations and pairings only; the commented-out + * hash-to-curve and signature surface is intentionally not exposed here. + * @example + * Compute a pairing from the two generator points. + * + * ```ts + * const gt = bn254.pairing(bn254.G1.Point.BASE, bn254.G2.Point.BASE); + * ``` + */ +// bn254_hasher +export const bn254: BlsCurvePair = /* @__PURE__ */ blsBasic( + fields, + bn254_G1, + bn254_G2, + bn254_params +); diff --git a/node_modules/@noble/curves/src/ed25519.ts b/node_modules/@noble/curves/src/ed25519.ts new file mode 100644 index 0000000..42cf21a --- /dev/null +++ b/node_modules/@noble/curves/src/ed25519.ts @@ -0,0 +1,705 @@ +/** + * ed25519 Twisted Edwards curve with following addons: + * - X25519 ECDH + * - Ristretto cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes, hexToBytes } from '@noble/hashes/utils.js'; +import { type AffinePoint } from './abstract/curve.ts'; +import { + eddsa, + edwards, + PrimeEdwardsPoint, + type EdDSA, + type EdDSAOpts, + type EdwardsOpts, + type EdwardsPoint, + type EdwardsPointCons, +} from './abstract/edwards.ts'; +import { createFROST, type FROST } from './abstract/frost.ts'; +import { + _DST_scalar, + createHasher, + expand_message_xmd, + type H2CDSTOpts, + type H2CHasher, + type H2CHasherBase, +} from './abstract/hash-to-curve.ts'; +import { + FpInvertBatch, + FpSqrtEven, + isNegativeLE, + mod, + pow2, + type IField, +} from './abstract/modular.ts'; +import { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts'; +import { createOPRF, type OPRF } from './abstract/oprf.ts'; +import { asciiToBytes, bytesToNumberLE, equalBytes, type TArg, type TRet } from './utils.ts'; + +// prettier-ignore +const _0n = /* @__PURE__ */ BigInt(0), _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3); +// prettier-ignore +const _5n = /* @__PURE__ */ BigInt(5), _8n = /* @__PURE__ */ BigInt(8); + +// P = 2n**255n - 19n +const ed25519_CURVE_p = /* @__PURE__ */ BigInt( + '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed' +); +// N = 2n**252n + 27742317777372353535851937790883648493n +// a = Fp.create(BigInt(-1)) +// d = -121665/121666 a.k.a. Fp.neg(121665 * Fp.inv(121666)) +const ed25519_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({ + p: ed25519_CURVE_p, + n: BigInt('0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed'), + h: _8n, + a: BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec'), + d: BigInt('0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3'), + Gx: BigInt('0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a'), + Gy: BigInt('0x6666666666666666666666666666666666666666666666666666666666666658'), +}))(); + +function ed25519_pow_2_252_3(x: bigint) { + // prettier-ignore + const _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80); + const P = ed25519_CURVE_p; + const x2 = (x * x) % P; + const b2 = (x2 * x) % P; // x^3, 11 + const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111 + const b5 = (pow2(b4, _1n, P) * x) % P; // x^31 + const b10 = (pow2(b5, _5n, P) * b5) % P; + const b20 = (pow2(b10, _10n, P) * b10) % P; + const b40 = (pow2(b20, _20n, P) * b20) % P; + const b80 = (pow2(b40, _40n, P) * b40) % P; + const b160 = (pow2(b80, _80n, P) * b80) % P; + const b240 = (pow2(b160, _80n, P) * b80) % P; + const b250 = (pow2(b240, _10n, P) * b10) % P; + const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P; + // ^ This is x^((p-5)/8); multiply by x once more to get x^((p+3)/8). + return { pow_p_5_8, b2 }; +} + +// Mutates and returns the provided 32-byte buffer in place. +function adjustScalarBytes(bytes: TArg): TRet { + // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar, + // set the three least significant bits of the first byte + bytes[0] &= 248; // 0b1111_1000 + // and the most significant bit of the last to zero, + bytes[31] &= 127; // 0b0111_1111 + // set the second most significant bit of the last byte to 1 + bytes[31] |= 64; // 0b0100_0000 + return bytes as TRet; +} + +// √(-1) aka √(a) aka 2^((p-1)/4) +// Fp.sqrt(Fp.neg(1)) +const ED25519_SQRT_M1 = /* @__PURE__ */ BigInt( + '19681161376707505956807079304988542015446066515923890162744021073123829784752' +); +// sqrt(u/v). Returns `{ isValid, value }`; on non-squares `value` is still a +// dummy root-shaped field element so callers can stay constant-time. +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ed25519_CURVE_p; + const v3 = mod(v * v * v, P); // v³ + const v7 = mod(v3 * v3 * v, P); // v⁷ + // (p+3)/8 and (p-5)/8 + const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8; + let x = mod(u * v3 * pow, P); // (uv³)(uv⁷)^(p-5)/8 + const vx2 = mod(v * x * x, P); // vx² + const root1 = x; // First root candidate + const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate + const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root + const useRoot2 = vx2 === mod(-u, P); // If vx² = -u, set x <-- x * 2^((p-1)/4) + const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx² = -u√(-1) + if (useRoot1) x = root1; + if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time + if (isNegativeLE(x, P)) x = mod(-x, P); + return { isValid: useRoot1 || useRoot2, value: x }; +} + +const ed25519_Point = /* @__PURE__ */ edwards(ed25519_CURVE, { uvRatio }); +// Public field alias stays stricter than the RFC 8032 Appendix A sample code: +// `Fp.inv(0)` throws instead of returning `0`. +const Fp = /* @__PURE__ */ (() => ed25519_Point.Fp)(); +const Fn = /* @__PURE__ */ (() => ed25519_Point.Fn)(); + +// RFC 8032 `dom2` helper for ctx/ph variants only. Plain Ed25519 keeps the +// empty-domain path in `ed()` and would be wrong if routed through this helper. +function ed25519_domain( + data: TArg, + ctx: TArg, + phflag: boolean +): TRet { + if (ctx.length > 255) throw new Error('Context is too big'); + return concatBytes( + asciiToBytes('SigEd25519 no Ed25519 collisions'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ) as TRet; +} + +function ed(opts: TArg) { + // Ed25519 keeps ZIP-215 default verification semantics for consensus compatibility. + return eddsa( + ed25519_Point, + sha512, + Object.assign({ adjustScalarBytes, zip215: true }, opts as EdDSAOpts) + ); +} + +/** + * ed25519 curve with EdDSA signatures. + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Generate one Ed25519 keypair, sign a message, and verify it. + * + * ```js + * import { ed25519 } from '@noble/curves/ed25519.js'; + * const { secretKey, publicKey } = ed25519.keygen(); + * // const publicKey = ed25519.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519.sign(msg, secretKey); + * const isValid = ed25519.verify(sig, msg, publicKey); // ZIP215 + * // RFC8032 / FIPS 186-5 + * const isValid2 = ed25519.verify(sig, msg, publicKey, { zip215: false }); + * ``` + */ +export const ed25519: EdDSA = /* @__PURE__ */ ed({}); +/** + * Context version of ed25519 (ctx for domain separation). See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Sign and verify with Ed25519ctx under one explicit context. + * + * ```ts + * const context = new TextEncoder().encode('docs'); + * const { secretKey, publicKey } = ed25519ctx.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ctx.sign(msg, secretKey, { context }); + * const isValid = ed25519ctx.verify(sig, msg, publicKey, { context }); + * ``` + */ +export const ed25519ctx: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain }); +/** + * Prehashed version of ed25519. See {@link ed25519} + * Seeded `keygen(seed)` / `utils.randomSecretKey(seed)` reuse the provided + * 32-byte seed buffer instead of copying it. + * @example + * Use the prehashed Ed25519 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed25519ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed25519ph.sign(msg, secretKey); + * const isValid = ed25519ph.verify(sig, msg, publicKey); + * ``` + */ +export const ed25519ph: EdDSA = /* @__PURE__ */ ed({ domain: ed25519_domain, prehash: sha512 }); +/** + * FROST threshold signatures over ed25519. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed25519 signing. + * + * ```ts + * const alice = ed25519_FROST.Identifier.derive('alice@example.com'); + * const bob = ed25519_FROST.Identifier.derive('bob@example.com'); + * const carol = ed25519_FROST.Identifier.derive('carol@example.com'); + * const deal = ed25519_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ed25519_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-ED25519-SHA512-v1', + Point: ed25519_Point, + validatePoint: (p) => { + p.assertValidity(); + if (!p.isTorsionFree()) throw new Error('bad point: not torsion-free'); + }, + hash: sha512, + // RFC 9591 keeps H2 undecorated here for RFC 8032 compatibility. In createFROST(), + // `H2: ''` becomes an empty DST prefix; the built-in hashToScalar fallback treats + // that the same as omitted DST, even though custom hooks can still observe the empty bag. + H2: '', + }))(); + +/** + * ECDH using curve25519 aka x25519. + * `getSharedSecret()` rejects low-order peer inputs by default, and seeded + * `keygen(seed)` reuses the provided 32-byte seed buffer instead of copying it. + * @example + * Derive one shared secret between two X25519 peers. + * + * ```js + * import { x25519 } from '@noble/curves/ed25519.js'; + * const alice = x25519.keygen(); + * const bob = x25519.keygen(); + * const shared = x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export const x25519: TRet = /* @__PURE__ */ (() => { + const P = ed25519_CURVE_p; + return montgomery({ + P, + type: 'x25519', + powPminus2: (x: bigint): bigint => { + // x^(p-2) aka x^(2^255-21) + const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x); + return mod(pow2(pow_p_5_8, _3n, P) * b2, P); + }, + adjustScalarBytes, + }); +})(); + +// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator) +// RFC 9380 Appendix G.2.2 / Err4730 requires `sgn0(c1) = 0` for the Edwards +// map constant below, so use the even root explicitly. +// 1. c1 = (q + 3) / 8 # Integer arithmetic +const ELL2_C1 = /* @__PURE__ */ (() => (ed25519_CURVE_p + _3n) / _8n)(); +const ELL2_C2 = /* @__PURE__ */ (() => Fp.pow(_2n, ELL2_C1))(); // 2. c2 = 2^c1 +const ELL2_C3 = /* @__PURE__ */ (() => Fp.sqrt(Fp.neg(Fp.ONE)))(); // 3. c3 = sqrt(-1) + +/** + * RFC 9380 method `map_to_curve_elligator2_curve25519`. Experimental name: may be renamed later. + * @private + */ +// prettier-ignore +export function _map_to_curve_elligator2_curve25519(u: bigint): { + xMn: bigint, xMd: bigint, yMn: bigint, yMd: bigint +} { + const ELL2_C4 = (ed25519_CURVE_p - _5n) / _8n; // 4. c4 = (q - 5) / 8 # Integer arithmetic + const ELL2_J = BigInt(486662); + + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1 + // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not + let xd = Fp.add(tv1, Fp.ONE); + let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2) + let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, ELL2_J);// 7. gx1 = J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2 + tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4 + tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3 + tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3 + tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7 + let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8) + y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8) + let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3 + tv2 = Fp.sqr(y11); // 19. tv2 = y11^2 + tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd + let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1 + // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt + let y1 = Fp.cmov(y12, y11, e1); + let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd + let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u + y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2 + let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3 + let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1) + tv2 = Fp.sqr(y21); // 28. tv2 = y21^2 + tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2 + // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt + let y2 = Fp.cmov(y22, y21, e2); + tv2 = Fp.sqr(y1); // 32. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd + let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2 + let e4 = Fp.isOdd!(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4) + return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1) +} + +// sgn0(c1) MUST equal 0 +const ELL2_C1_EDWARDS = /* @__PURE__ */ (() => FpSqrtEven(Fp, Fp.neg(BigInt(486664))))(); +function map_to_curve_elligator2_edwards25519(u: bigint) { + // 1. (xMn, xMd, yMn, yMd) = map_to_curve_elligator2_curve25519(u) + const { xMn, xMd, yMn, yMd } = _map_to_curve_elligator2_curve25519(u); + // map_to_curve_elligator2_curve25519(u) + let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd + xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1 + let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM + let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd + // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d) + let yd = Fp.add(xMn, xMd); + let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd + let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0 + xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e) + xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e) + yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e) + yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e) + const [xd_inv, yd_inv] = FpInvertBatch(Fp, [xd, yd], true); // batch division + // Noble normalizes the RFC rational representation to affine `{ x, y }` + // before returning from the internal helper. + return { x: Fp.mul(xn, xd_inv), y: Fp.mul(yn, yd_inv) }; // 13. return (xn, xd, yn, yd) +} + +/** + * Hashing to ed25519 points / field. RFC 9380 methods. + * Public `mapToCurve()` returns the cofactor-cleared subgroup point; the + * internal map callback below consumes one field element bigint, not `[bigint]`. + * @example + * Hash one message onto the ed25519 curve. + * + * ```ts + * const point = ed25519_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ed25519_hasher: H2CHasher = /* @__PURE__ */ (() => + createHasher( + ed25519_Point, + (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]), + { + DST: 'edwards25519_XMD:SHA-512_ELL2_RO_', + encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_', + p: ed25519_CURVE_p, + m: 1, + k: 128, + expand: 'xmd', + hash: sha512, + } + ))(); + +// √(-1) aka √(a) aka 2^((p-1)/4) +const SQRT_M1 = ED25519_SQRT_M1; +// √(ad - 1) +const SQRT_AD_MINUS_ONE = /* @__PURE__ */ BigInt( + '25063068953384623474111414158702152701244531502492656460079210482610430750235' +); +// 1 / √(a-d) +const INVSQRT_A_MINUS_D = /* @__PURE__ */ BigInt( + '54469307008909316920995813868745141605393597292927456921205312896311721017578' +); +// 1-d² +const ONE_MINUS_D_SQ = /* @__PURE__ */ BigInt( + '1159843021668779879193775521855586647937357759715417654439879720876111806838' +); +// (d-1)² +const D_MINUS_ONE_SQ = /* @__PURE__ */ BigInt( + '40440834346308536858101042469323190826248399146238708352240133220865137265952' +); +// `SQRT_RATIO_M1(1, number)` specialization. Returns `{ isValid, value }`, +// where non-squares get the nonnegative `sqrt(SQRT_M1 / number)` branch. +const invertSqrt = (number: bigint) => uvRatio(_1n, number); + +const MAX_255B = /* @__PURE__ */ BigInt( + '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +); +// RFC 9496 §4.3.4 MAP parser: masks bit 255 and reduces modulo p for element +// derivation. The decode path has the opposite contract and rejects that bit. +const bytes255ToNumberLE = (bytes: TArg) => + Fp.create(bytesToNumberLE(bytes) & MAX_255B); + +/** + * Computes Elligator map for Ristretto255. + * Primary formula source is RFC 9496 §4.3.4 MAP; RFC 9380 Appendix B builds + * `hash_to_ristretto255` on top of this helper. + * Returns an internal Edwards representative, not a public `_RistrettoPoint`. + */ +function calcElligatorRistrettoMap(r0: bigint): EdwardsPoint { + const { d } = ed25519_CURVE; + const P = ed25519_CURVE_p; + const mod = (n: bigint) => Fp.create(n); + const r = mod(SQRT_M1 * r0 * r0); // 1 + const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2 + let c = BigInt(-1); // 3 + const D = mod((c - d * r) * mod(r + d)); // 4 + let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5 + let s_ = mod(s * r0); // 6 + if (!isNegativeLE(s_, P)) s_ = mod(-s_); + if (!Ns_D_is_sq) s = s_; // 7 + if (!Ns_D_is_sq) c = r; // 8 + const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9 + const s2 = s * s; + const W0 = mod((s + s) * D); // 10 + const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11 + const W2 = mod(_1n - s2); // 12 + const W3 = mod(_1n + s2); // 13 + return new ed25519_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +/** + * Wrapper over Edwards Point for ristretto255. + * + * Each ed25519/EdwardsPoint has 8 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Ristretto was created to solve this. + * Ristretto point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +class _RistrettoPoint extends PrimeEdwardsPoint<_RistrettoPoint> { + // Do NOT change syntax: the following gymnastics is done, + // because typescript strips comments, which makes bundlers disable tree-shaking. + // prettier-ignore + static BASE: _RistrettoPoint = + /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.BASE))(); + // prettier-ignore + static ZERO: _RistrettoPoint = + /* @__PURE__ */ (() => new _RistrettoPoint(ed25519_Point.ZERO))(); + // prettier-ignore + static Fp: IField = + /* @__PURE__ */ (() => Fp)(); + // prettier-ignore + static Fn: IField = + /* @__PURE__ */ (() => Fn)(); + + constructor(ep: EdwardsPoint) { + super(ep); + } + + /** + * Create one Ristretto255 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical ristretto255 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical ristretto255 bytes matter. + */ + static fromAffine(ap: AffinePoint): _RistrettoPoint { + return new _RistrettoPoint(ed25519_Point.fromAffine(ap)); + } + + protected assertSame(other: _RistrettoPoint): void { + if (!(other instanceof _RistrettoPoint)) throw new Error('RistrettoPoint expected'); + } + + protected init(ep: EdwardsPoint): _RistrettoPoint { + return new _RistrettoPoint(ep); + } + + static fromBytes(bytes: TArg): _RistrettoPoint { + abytes(bytes, 32); + const { a, d } = ed25519_CURVE; + const P = ed25519_CURVE_p; + const mod = (n: bigint) => Fp.create(n); + const s = bytes255ToNumberLE(bytes); + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 3. Check that s is non-negative, or else abort + if (!equalBytes(Fp.toBytes(s), bytes) || isNegativeLE(s, P)) + throw new Error('invalid ristretto255 encoding 1'); + const s2 = mod(s * s); + const u1 = mod(_1n + a * s2); // 4 (a is -1) + const u2 = mod(_1n - a * s2); // 5 + const u1_2 = mod(u1 * u1); + const u2_2 = mod(u2 * u2); + const v = mod(a * d * u1_2 - u2_2); // 6 + const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7 + const Dx = mod(I * u2); // 8 + const Dy = mod(I * Dx * v); // 9 + let x = mod((s + s) * Dx); // 10 + if (isNegativeLE(x, P)) x = mod(-x); // 10 + const y = mod(u1 * Dy); // 11 + const t = mod(x * y); // 12 + if (!isValid || isNegativeLE(t, P) || y === _0n) + throw new Error('invalid ristretto255 encoding 2'); + return new _RistrettoPoint(new ed25519_Point(x, y, _1n, t)); + } + + /** + * Converts ristretto-encoded string to ristretto point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode). + * @param hex - Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding + */ + static fromHex(hex: string): _RistrettoPoint { + return _RistrettoPoint.fromBytes(hexToBytes(hex)); + } + + /** + * Encodes ristretto point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode). + */ + toBytes(): TRet { + let { X, Y, Z, T } = this.ep; + const P = ed25519_CURVE_p; + const mod = (n: bigint) => Fp.create(n); + const u1 = mod(mod(Z + Y) * mod(Z - Y)); // 1 + const u2 = mod(X * Y); // 2 + // Square root always exists + const u2sq = mod(u2 * u2); + const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3 + const D1 = mod(invsqrt * u1); // 4 + const D2 = mod(invsqrt * u2); // 5 + const zInv = mod(D1 * D2 * T); // 6 + let D: bigint; // 7 + if (isNegativeLE(T * zInv, P)) { + let _x = mod(Y * SQRT_M1); + let _y = mod(X * SQRT_M1); + X = _x; + Y = _y; + D = mod(D1 * INVSQRT_A_MINUS_D); + } else { + D = D2; // 8 + } + if (isNegativeLE(X * zInv, P)) Y = mod(-Y); // 9 + let s = mod((Z - Y) * D); // 10 (check footer's note, no sqrt(-a)) + if (isNegativeLE(s, P)) s = mod(-s); + return Fp.toBytes(s) as TRet; // 11 + } + + /** + * Compares two Ristretto points. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals). + */ + equals(other: _RistrettoPoint): boolean { + this.assertSame(other); + const { X: X1, Y: Y1 } = this.ep; + const { X: X2, Y: Y2 } = other.ep; + const mod = (n: bigint) => Fp.create(n); + // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2) + const one = mod(X1 * Y2) === mod(Y1 * X2); + const two = mod(Y1 * Y2) === mod(X1 * X2); + return one || two; + } + + is0(): boolean { + return this.equals(_RistrettoPoint.ZERO); + } +} +Object.freeze(_RistrettoPoint.BASE); +Object.freeze(_RistrettoPoint.ZERO); +Object.freeze(_RistrettoPoint.prototype); +Object.freeze(_RistrettoPoint); + +/** Prime-order Ristretto255 group bundle. */ +export const ristretto255: { + Point: typeof _RistrettoPoint; +} = /* @__PURE__ */ Object.freeze({ Point: _RistrettoPoint }); + +/** + * Hashing to ristretto255 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 Appendix B, `deriveToCurve()` is the RFC 9496 + * §4.3.4 element-derivation building block, and `hashToScalar()` is a + * library-specific helper for OPRF-style use. + * @example + * Hash one message onto ristretto255. + * + * ```ts + * const point = ristretto255_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ristretto255_hasher: H2CHasherBase = Object.freeze({ + Point: _RistrettoPoint, + /** + * Spec: https://www.rfc-editor.org/rfc/rfc9380.html#name-hashing-to-ristretto255. Caveats: + * * There are no test vectors + * * encodeToCurve / mapToCurve is undefined + * * mapToCurve would be `calcElligatorRistrettoMap(scalars[0])`, not ristretto255_map! + * * hashToScalar is undefined too, so we just use OPRF implementation + * * We cannot re-use 'createHasher', because ristretto255_map is different algorithm/RFC + (os2ip -> bytes255ToNumberLE) + * * mapToCurve == calcElligatorRistrettoMap, hashToCurve == ristretto255_map + * * hashToScalar is undefined in RFC9380 for ristretto, so we use the OPRF + version here. Using `bytes255ToNumblerLE` will create a different result + if we use `bytes255ToNumberLE` as os2ip + * * current version is closest to spec. + */ + hashToCurve(msg: TArg, options?: TArg): _RistrettoPoint { + // == 'hash_to_ristretto255' + // Preserve explicit empty/invalid DST overrides so expand_message_xmd() can reject them. + const DST = options?.DST === undefined ? 'ristretto255_XMD:SHA-512_R255MAP_RO_' : options.DST; + const xmd = expand_message_xmd(msg, DST, 64, sha512); + // NOTE: RFC 9380 incorrectly calls this function `ristretto255_map`. + // In RFC 9496, `map` was the per-point function inside the construction. + // That also led to confusion that `ristretto255_map` is `mapToCurve`. + // It is not: it is the older hash-to-curve construction. + return ristretto255_hasher.deriveToCurve!(xmd); + }, + hashToScalar(msg: TArg, options: TArg = { DST: _DST_scalar }) { + const xmd = expand_message_xmd(msg, options.DST, 64, sha512); + return Fn.create(bytesToNumberLE(xmd)); + }, + /** + * HashToCurve-like construction based on RFC 9496 (Element Derivation). + * Converts 64 uniform random bytes into a curve point. + * + * WARNING: This represents an older hash-to-curve construction from before + * RFC 9380 was finalized. + * It was later reused as a component in the newer + * `hash_to_ristretto255` function defined in RFC 9380. + */ + deriveToCurve(bytes: TArg): _RistrettoPoint { + // https://www.rfc-editor.org/rfc/rfc9496.html#name-element-derivation + abytes(bytes, 64); + const r1 = bytes255ToNumberLE(bytes.subarray(0, 32)); + const R1 = calcElligatorRistrettoMap(r1); + const r2 = bytes255ToNumberLE(bytes.subarray(32, 64)); + const R2 = calcElligatorRistrettoMap(r2); + return new _RistrettoPoint(R1.add(R2)); + }, +}); + +/** + * ristretto255 OPRF/VOPRF/POPRF bundle, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over ristretto255. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = ristretto255_oprf.oprf.generateKeyPair(); + * const blind = ristretto255_oprf.oprf.blind(input); + * const evaluated = ristretto255_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = ristretto255_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const ristretto255_oprf: TRet = /* @__PURE__ */ (() => + createOPRF({ + name: 'ristretto255-SHA512', + Point: _RistrettoPoint, + hash: sha512, + hashToGroup: ristretto255_hasher.hashToCurve, + hashToScalar: ristretto255_hasher.hashToScalar, + }))(); +/** + * FROST threshold signatures over ristretto255. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ristretto255 signing. + * + * ```ts + * const alice = ristretto255_FROST.Identifier.derive('alice@example.com'); + * const bob = ristretto255_FROST.Identifier.derive('bob@example.com'); + * const carol = ristretto255_FROST.Identifier.derive('carol@example.com'); + * const deal = ristretto255_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ristretto255_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-RISTRETTO255-SHA512-v1', + Point: _RistrettoPoint, + validatePoint: (p) => { + // Prime-order wrappers are torsion-free at the abstract-group level. + p.assertValidity(); + }, + hash: sha512, + }))(); + +/** + * Weird / bogus points, useful for debugging. + * All 8 ed25519 points of 8-torsion subgroup can be generated from the point + * T = `26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05`. + * The subgroup generated by `T` is `{ O, T, 2T, 3T, 4T, 5T, 6T, 7T }`; the + * array below is that set, not the powers in that exact index order. + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED25519_TORSION_SUBGROUP, ed25519 } from '@noble/curves/ed25519.js'; + * const point = ed25519.Point.fromHex(ED25519_TORSION_SUBGROUP[1]); + * ``` + */ +export const ED25519_TORSION_SUBGROUP: readonly string[] = /* @__PURE__ */ Object.freeze([ + '0100000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', + '0000000000000000000000000000000000000000000000000000000000000080', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', + 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', + '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', + '0000000000000000000000000000000000000000000000000000000000000000', + 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', +]); diff --git a/node_modules/@noble/curves/src/ed448.ts b/node_modules/@noble/curves/src/ed448.ts new file mode 100644 index 0000000..9580dc1 --- /dev/null +++ b/node_modules/@noble/curves/src/ed448.ts @@ -0,0 +1,695 @@ +/** + * Edwards448 (also called Goldilocks) curve with following addons: + * - X448 ECDH + * - Decaf cofactor elimination + * - Elligator hash-to-group / point indistinguishability + * Conforms to RFC 8032 https://www.rfc-editor.org/rfc/rfc8032.html#section-5.2 + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { shake256 } from '@noble/hashes/sha3.js'; +import { concatBytes, hexToBytes, createHasher as wrapConstructor } from '@noble/hashes/utils.js'; +import type { AffinePoint } from './abstract/curve.ts'; +import { + eddsa, + edwards, + PrimeEdwardsPoint, + type EdDSA, + type EdDSAOpts, + type EdwardsOpts, + type EdwardsPoint, + type EdwardsPointCons, +} from './abstract/edwards.ts'; +import { createFROST, type FROST } from './abstract/frost.ts'; +import { + _DST_scalar, + createHasher, + expand_message_xof, + type H2CDSTOpts, + type H2CHasher, + type H2CHasherBase, +} from './abstract/hash-to-curve.ts'; +import { Field, FpInvertBatch, isNegativeLE, mod, pow2, type IField } from './abstract/modular.ts'; +import { montgomery, type MontgomeryECDH } from './abstract/montgomery.ts'; +import { createOPRF, type OPRF } from './abstract/oprf.ts'; +import { + abytes, + asciiToBytes, + bytesToNumberLE, + equalBytes, + type TArg, + type TRet, +} from './utils.ts'; + +// edwards448 curve +// a = 1n +// d = Fp.neg(39081n) +// Finite field 2n**448n - 2n**224n - 1n +// Subgroup order +// 2n**446n - 13818066809895115352007386748515426880336692474882178609894547503885n +const ed448_CURVE_p = /* @__PURE__ */ BigInt( + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffff' +); +const ed448_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({ + p: ed448_CURVE_p, + n: BigInt( + '0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffff7cca23e9c44edb49aed63690216cc2728dc58f552378c292ab5844f3' + ), + h: BigInt(4), + a: BigInt(1), + d: BigInt( + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffff6756' + ), + Gx: BigInt( + '0x4f1970c66bed0ded221d15a622bf36da9e146570470f1767ea6de324a3d3a46412ae1af72ab66511433b80e18b00938e2626a82bc70cc05e' + ), + Gy: BigInt( + '0x693f46716eb6bc248876203756c9c7624bea73736ca3984087789c1e05a0c2d73ad3ff1ce67c39c4fdbd132c4ed7c8ad9808795bf230fa14' + ), +}))(); + +// This is not RFC 8032 edwards448 / Goldilocks (`ed448` below, d = -39081). +// It is NIST SP 800-186 §3.2.3.3 E448, the Curve448-isomorphic Edwards model +// also described in draft-ietf-lwig-curve-representations-23 Appendix M, with +// d = 39082/39081 and Gy = 3/2. +// RFC 7748's literal Edwards point / birational map are wrong here: the literal +// point is the wrong-sign (Gx, -Gy) order-2*n variant. Keep the corrected +// prime-order (Gx, Gy) base so Point.BASE stays a subgroup generator, which is +// what noble's generic Edwards API expects. +const E448_CURVE: EdwardsOpts = /* @__PURE__ */ (() => + Object.assign({}, ed448_CURVE, { + d: BigInt( + '0xd78b4bdc7f0daf19f24f38c29373a2ccad46157242a50f37809b1da3412a12e79ccc9c81264cfe9ad080997058fb61c4243cc32dbaa156b9' + ), + Gx: BigInt( + '0x79a70b2b70400553ae7c9df416c792c61128751ac92969240c25a07d728bdc93e21f7787ed6972249de732f38496cd11698713093e9c04fc' + ), + Gy: BigInt( + '0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff80000000000000000000000000000000000000000000000000000001' + ), + }))(); + +const shake256_114 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 114 })); +const shake256_64 = /* @__PURE__ */ wrapConstructor(() => shake256.create({ dkLen: 64 })); + +// prettier-ignore +const _1n = /* @__PURE__ */ BigInt(1), _2n = /* @__PURE__ */ BigInt(2), _3n = /* @__PURE__ */ BigInt(3), _4n = /* @__PURE__ */ BigInt(4), _11n = /* @__PURE__ */ BigInt(11); +// prettier-ignore +const _22n = /* @__PURE__ */ BigInt(22), _44n = /* @__PURE__ */ BigInt(44), _88n = /* @__PURE__ */ BigInt(88), _223n = /* @__PURE__ */ BigInt(223); + +// powPminus3div4 calculates z = x^k mod p, where k = (p-3)/4. +// Used for efficient square root calculation. +// ((P-3)/4).toString(2) would produce bits [223x 1, 0, 222x 1] +function ed448_pow_Pminus3div4(x: bigint): bigint { + const P = ed448_CURVE_p; + const b2 = (x * x * x) % P; + const b3 = (b2 * b2 * x) % P; + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b222 = (pow2(b220, _2n, P) * b2) % P; + const b223 = (pow2(b222, _1n, P) * x) % P; + return (pow2(b223, _223n, P) * b222) % P; +} + +// Mutates and returns the provided buffer in place. The final `bytes[56] = 0` +// write is the Ed448 path; for 56-byte X448 inputs it is an out-of-bounds no-op. +function adjustScalarBytes(bytes: TArg): TRet { + // Section 5: Likewise, for X448, set the two least significant bits of the first byte to 0, + bytes[0] &= 252; // 0b11111100 + // and the most significant bit of the last byte to 1. + bytes[55] |= 128; // 0b10000000 + // NOTE: is NOOP for 56 bytes scalars (X25519/X448) + bytes[56] = 0; // Byte outside of group (456 buts vs 448 bits) + return bytes as TRet; +} + +// Constant-time Ed448 decode helper for RFC 8032 §5.2.3 steps 2-3. Unlike +// `SQRT_RATIO_M1`, the returned `value` only has the documented meaning when +// `isValid` is true. +function uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } { + const P = ed448_CURVE_p; + // https://www.rfc-editor.org/rfc/rfc8032#section-5.2.3 + // To compute the square root of (u/v), the first step is to compute the + // candidate root x = (u/v)^((p+1)/4). This can be done using the + // following trick, to use a single modular powering for both the + // inversion of v and the square root: + // x = (u/v)^((p+1)/4) = u³v(u⁵v³)^((p-3)/4) (mod p) + const u2v = mod(u * u * v, P); // u²v + const u3v = mod(u2v * u, P); // u³v + const u5v3 = mod(u3v * u2v * v, P); // u⁵v³ + const root = ed448_pow_Pminus3div4(u5v3); + const x = mod(u3v * root, P); + // Verify that root is exists + const x2 = mod(x * x, P); // x² + // If vx² = u, the recovered x-coordinate is x. Otherwise, no + // square root exists, and the decoding fails. + return { isValid: mod(x2 * v, P) === u, value: x }; +} + +// Finite field 2n**448n - 2n**224n - 1n +// RFC 8032 encodes Ed448 field/scalar elements in 57 bytes even though field +// values fit in 448 bits and scalars in 446 bits. Noble models that with a +// 456-bit storage width so the final-octet x-sign bit (bit 455) still fits in +// the shared little-endian container. +const Fp = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 456, isLE: true }))(); +// Same 57-byte container shape as `Fp`; canonical scalar encodings still have +// the top ten bits clear per RFC 8032. +const Fn = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 456, isLE: true }))(); +// Generic 56-byte field shape used by decaf448 and raw X448 u-coordinates. +// Plain `Field` decoding stays canonical here, so callers that want RFC 7748's +// modulo-p acceptance must reduce externally. +const Fp448 = /* @__PURE__ */ (() => Field(ed448_CURVE_p, { BITS: 448, isLE: true }))(); +// Strict 56-byte scalar parser matching RFC 9496's recommended canonical form. +const Fn448 = /* @__PURE__ */ (() => Field(ed448_CURVE.n, { BITS: 448, isLE: true }))(); + +// SHAKE256(dom4(phflag,context)||x, 114) +// RFC 8032 `dom4` prefix. Empty contexts are valid; the accepted length range +// is 0..255 octets inclusive. +function dom4(data: TArg, ctx: TArg, phflag: boolean): TRet { + if (ctx.length > 255) throw new Error('context must be smaller than 255, got: ' + ctx.length); + return concatBytes( + asciiToBytes('SigEd448'), + new Uint8Array([phflag ? 1 : 0, ctx.length]), + ctx, + data + ) as TRet; +} +const ed448_Point = /* @__PURE__ */ edwards(ed448_CURVE, { Fp, Fn, uvRatio }); + +// Shared internal factory for both `ed448` and `ed448ph`; callers are only +// expected to override narrow family options such as prehashing. +function ed4(opts: TArg) { + return eddsa( + ed448_Point, + shake256_114, + Object.assign({ adjustScalarBytes, domain: dom4 }, opts as EdDSAOpts) + ); +} + +/** + * ed448 EdDSA curve and methods. + * @example + * Generate one Ed448 keypair, sign a message, and verify it. + * + * ```js + * import { ed448 } from '@noble/curves/ed448.js'; + * const { secretKey, publicKey } = ed448.keygen(); + * // const publicKey = ed448.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448.sign(msg, secretKey); + * const isValid = ed448.verify(sig, msg, publicKey); + * ``` + */ +export const ed448: EdDSA = /* @__PURE__ */ ed4({}); + +// There is no ed448ctx, since ed448 supports ctx by default +/** + * Prehashed version of ed448. See {@link ed448} + * @example + * Use the prehashed Ed448 variant for one message. + * + * ```ts + * const { secretKey, publicKey } = ed448ph.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = ed448ph.sign(msg, secretKey); + * const isValid = ed448ph.verify(sig, msg, publicKey); + * ``` + */ +export const ed448ph: EdDSA = /* @__PURE__ */ ed4({ prehash: shake256_64 }); +/** + * E448 here is NIST SP 800-186 §3.2.3.3 E448, the Edwards representation of + * Curve448, not RFC 8032 edwards448 / Goldilocks. + * Goldilocks is the separate 4-isogenous curve exposed as `ed448`. + * We keep the corrected prime-order base here; RFC 7748's literal Edwards + * point / map are wrong for this curve model, and the literal point is the + * wrong-sign order-2*n variant. + * @param X - Projective X coordinate. + * @param Y - Projective Y coordinate. + * @param Z - Projective Z coordinate. + * @param T - Projective T coordinate. + * @example + * Multiply the E448 base point. + * + * ```ts + * const point = E448.BASE.multiply(2n); + * ``` + */ +export const E448: EdwardsPointCons = /* @__PURE__ */ edwards(E448_CURVE); + +/** + * ECDH using curve448 aka x448. + * The wrapper aborts on all-zero shared secrets by default, and seeded + * `keygen(seed)` reuses the provided 56-byte seed buffer instead of copying it. + * + * @example + * Derive one shared secret between two X448 peers. + * + * ```js + * import { x448 } from '@noble/curves/ed448.js'; + * const alice = x448.keygen(); + * const bob = x448.keygen(); + * const shared = x448.getSharedSecret(alice.secretKey, bob.publicKey); + * ``` + */ +export const x448: TRet = /* @__PURE__ */ (() => { + const P = ed448_CURVE_p; + return montgomery({ + P, + type: 'x448', + powPminus2: (x: bigint): bigint => { + const Pminus3div4 = ed448_pow_Pminus3div4(x); + const Pminus3 = pow2(Pminus3div4, _2n, P); + return mod(Pminus3 * x, P); // Pminus3 * x = Pminus2 + }, + adjustScalarBytes, + }); +})(); + +// Hash To Curve Elligator2 Map +// 1. c1 = (q - 3) / 4 # Integer arithmetic +const ELL2_C1 = /* @__PURE__ */ (() => (ed448_CURVE_p - BigInt(3)) / BigInt(4))(); +const ELL2_J = /* @__PURE__ */ BigInt(156326); + +// Returns RFC 9380 Appendix G.2.3 rational Montgomery numerators/denominators +// `{ xn, xd, yn, yd }`, not an affine point. +function map_to_curve_elligator2_curve448(u: bigint) { + let tv1 = Fp.sqr(u); // 1. tv1 = u^2 + let e1 = Fp.eql(tv1, Fp.ONE); // 2. e1 = tv1 == 1 + tv1 = Fp.cmov(tv1, Fp.ZERO, e1); // 3. tv1 = CMOV(tv1, 0, e1) # If Z * u^2 == -1, set tv1 = 0 + let xd = Fp.sub(Fp.ONE, tv1); // 4. xd = 1 - tv1 + let x1n = Fp.neg(ELL2_J); // 5. x1n = -J + let tv2 = Fp.sqr(xd); // 6. tv2 = xd^2 + let gxd = Fp.mul(tv2, xd); // 7. gxd = tv2 * xd # gxd = xd^3 + let gx1 = Fp.mul(tv1, Fp.neg(ELL2_J)); // 8. gx1 = -J * tv1 # x1n + J * xd + gx1 = Fp.mul(gx1, x1n); // 9. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd + gx1 = Fp.add(gx1, tv2); // 10. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2 + gx1 = Fp.mul(gx1, x1n); // 11. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2 + let tv3 = Fp.sqr(gxd); // 12. tv3 = gxd^2 + tv2 = Fp.mul(gx1, gxd); // 13. tv2 = gx1 * gxd # gx1 * gxd + tv3 = Fp.mul(tv3, tv2); // 14. tv3 = tv3 * tv2 # gx1 * gxd^3 + let y1 = Fp.pow(tv3, ELL2_C1); // 15. y1 = tv3^c1 # (gx1 * gxd^3)^((p - 3) / 4) + y1 = Fp.mul(y1, tv2); // 16. y1 = y1 * tv2 # gx1 * gxd * (gx1 * gxd^3)^((p - 3) / 4) + // 17. x2n = -tv1 * x1n # x2 = x2n / xd = -1 * u^2 * x1n / xd + let x2n = Fp.mul(x1n, Fp.neg(tv1)); + let y2 = Fp.mul(y1, u); // 18. y2 = y1 * u + y2 = Fp.cmov(y2, Fp.ZERO, e1); // 19. y2 = CMOV(y2, 0, e1) + tv2 = Fp.sqr(y1); // 20. tv2 = y1^2 + tv2 = Fp.mul(tv2, gxd); // 21. tv2 = tv2 * gxd + let e2 = Fp.eql(tv2, gx1); // 22. e2 = tv2 == gx1 + let xn = Fp.cmov(x2n, x1n, e2); // 23. xn = CMOV(x2n, x1n, e2) # If e2, x = x1, else x = x2 + let y = Fp.cmov(y2, y1, e2); // 24. y = CMOV(y2, y1, e2) # If e2, y = y1, else y = y2 + let e3 = Fp.isOdd(y); // 25. e3 = sgn0(y) == 1 # Fix sign of y + y = Fp.cmov(y, Fp.neg(y), e2 !== e3); // 26. y = CMOV(y, -y, e2 XOR e3) + return { xn, xd, yn: y, yd: Fp.ONE }; // 27. return (xn, xd, y, 1) +} + +// Returns affine `{ x, y }` after inverting the Appendix G.2.4 denominators. +function map_to_curve_elligator2_edwards448(u: bigint) { + // 1. (xn, xd, yn, yd) = map_to_curve_elligator2_curve448(u) + let { xn, xd, yn, yd } = map_to_curve_elligator2_curve448(u); + let xn2 = Fp.sqr(xn); // 2. xn2 = xn^2 + let xd2 = Fp.sqr(xd); // 3. xd2 = xd^2 + let xd4 = Fp.sqr(xd2); // 4. xd4 = xd2^2 + let yn2 = Fp.sqr(yn); // 5. yn2 = yn^2 + let yd2 = Fp.sqr(yd); // 6. yd2 = yd^2 + let xEn = Fp.sub(xn2, xd2); // 7. xEn = xn2 - xd2 + let tv2 = Fp.sub(xEn, xd2); // 8. tv2 = xEn - xd2 + xEn = Fp.mul(xEn, xd2); // 9. xEn = xEn * xd2 + xEn = Fp.mul(xEn, yd); // 10. xEn = xEn * yd + xEn = Fp.mul(xEn, yn); // 11. xEn = xEn * yn + xEn = Fp.mul(xEn, _4n); // 12. xEn = xEn * 4 + tv2 = Fp.mul(tv2, xn2); // 13. tv2 = tv2 * xn2 + tv2 = Fp.mul(tv2, yd2); // 14. tv2 = tv2 * yd2 + let tv3 = Fp.mul(yn2, _4n); // 15. tv3 = 4 * yn2 + let tv1 = Fp.add(tv3, yd2); // 16. tv1 = tv3 + yd2 + tv1 = Fp.mul(tv1, xd4); // 17. tv1 = tv1 * xd4 + let xEd = Fp.add(tv1, tv2); // 18. xEd = tv1 + tv2 + tv2 = Fp.mul(tv2, xn); // 19. tv2 = tv2 * xn + let tv4 = Fp.mul(xn, xd4); // 20. tv4 = xn * xd4 + let yEn = Fp.sub(tv3, yd2); // 21. yEn = tv3 - yd2 + yEn = Fp.mul(yEn, tv4); // 22. yEn = yEn * tv4 + yEn = Fp.sub(yEn, tv2); // 23. yEn = yEn - tv2 + tv1 = Fp.add(xn2, xd2); // 24. tv1 = xn2 + xd2 + tv1 = Fp.mul(tv1, xd2); // 25. tv1 = tv1 * xd2 + tv1 = Fp.mul(tv1, xd); // 26. tv1 = tv1 * xd + tv1 = Fp.mul(tv1, yn2); // 27. tv1 = tv1 * yn2 + tv1 = Fp.mul(tv1, BigInt(-2)); // 28. tv1 = -2 * tv1 + let yEd = Fp.add(tv2, tv1); // 29. yEd = tv2 + tv1 + tv4 = Fp.mul(tv4, yd2); // 30. tv4 = tv4 * yd2 + yEd = Fp.add(yEd, tv4); // 31. yEd = yEd + tv4 + tv1 = Fp.mul(xEd, yEd); // 32. tv1 = xEd * yEd + let e = Fp.eql(tv1, Fp.ZERO); // 33. e = tv1 == 0 + xEn = Fp.cmov(xEn, Fp.ZERO, e); // 34. xEn = CMOV(xEn, 0, e) + xEd = Fp.cmov(xEd, Fp.ONE, e); // 35. xEd = CMOV(xEd, 1, e) + yEn = Fp.cmov(yEn, Fp.ONE, e); // 36. yEn = CMOV(yEn, 1, e) + yEd = Fp.cmov(yEd, Fp.ONE, e); // 37. yEd = CMOV(yEd, 1, e) + + const inv = FpInvertBatch(Fp, [xEd, yEd], true); // batch division + return { x: Fp.mul(xEn, inv[0]), y: Fp.mul(yEn, inv[1]) }; // 38. return (xEn, xEd, yEn, yEd) +} + +/** + * Hashing / encoding to ed448 points / field. RFC 9380 methods. + * Public `mapToCurve()` consumes one field element bigint for `m = 1`, and RFC + * Appendix J vectors use the special `QUUX-V01-*` test DST overrides rather + * than the default suite IDs below. + * @example + * Hash one message onto the ed448 curve. + * + * ```ts + * const point = ed448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const ed448_hasher: H2CHasher = /* @__PURE__ */ (() => + createHasher(ed448_Point, (scalars: bigint[]) => map_to_curve_elligator2_edwards448(scalars[0]), { + DST: 'edwards448_XOF:SHAKE256_ELL2_RO_', + encodeDST: 'edwards448_XOF:SHAKE256_ELL2_NU_', + p: ed448_CURVE_p, + m: 1, + k: 224, + expand: 'xof', + hash: shake256, + }))(); +/** + * FROST threshold signatures over ed448. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 ed448 signing. + * + * ```ts + * const alice = ed448_FROST.Identifier.derive('alice@example.com'); + * const bob = ed448_FROST.Identifier.derive('bob@example.com'); + * const carol = ed448_FROST.Identifier.derive('carol@example.com'); + * const deal = ed448_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const ed448_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-ED448-SHAKE256-v1', + Point: ed448_Point, + validatePoint: (p) => { + p.assertValidity(); + if (!p.isTorsionFree()) throw new Error('bad point: not torsion-free'); + }, + // Group: edwards448 [RFC8032], where Ne = 57 and Ns = 57. + // Fn is 57 bytes, Fp is 57 bytes too + Fn, + hash: shake256_114, + H2: 'SigEd448\0\0', + }))(); + +// 1-d +const ONE_MINUS_D = /* @__PURE__ */ BigInt('39082'); +// 1-2d +const ONE_MINUS_TWO_D = /* @__PURE__ */ BigInt('78163'); +// √(-d) +const SQRT_MINUS_D = /* @__PURE__ */ BigInt( + '98944233647732219769177004876929019128417576295529901074099889598043702116001257856802131563896515373927712232092845883226922417596214' +); +// 1 / √(-d) +const INVSQRT_MINUS_D = /* @__PURE__ */ BigInt( + '315019913931389607337177038330951043522456072897266928557328499619017160722351061360252776265186336876723201881398623946864393857820716' +); +// RFC 9496 `SQRT_RATIO_M1` must return `CT_ABS(s)`, i.e. the nonnegative root. +// Keep this Decaf-local: RFC 9496 decode/encode/map formulas depend on that +// canonical representative, while ordinary Ed448 decoding still uses `uvRatio()` +// plus the public sign bit from RFC 8032. +const sqrtRatioM1 = (u: bigint, v: bigint) => { + const P = ed448_CURVE_p; + const { isValid, value } = uvRatio(u, v); + return { isValid, value: isNegativeLE(value, P) ? Fp448.create(-value) : value }; +}; +const invertSqrt = (number: bigint) => sqrtRatioM1(_1n, number); + +/** + * Elligator map for hash-to-curve of decaf448. + * Primary formula source is RFC 9496 §5.3.4. Step 1 intentionally reduces the + * input modulo `p`, and the return value is the internal Edwards + * representation, not a public decaf encoding. + */ +function calcElligatorDecafMap(r0: bigint): EdwardsPoint { + const { d, p: P } = ed448_CURVE; + const mod = (n: bigint) => Fp448.create(n); + + const r = mod(-(r0 * r0)); // 1 + const u0 = mod(d * (r - _1n)); // 2 + const u1 = mod((u0 + _1n) * (u0 - r)); // 3 + + const { isValid: was_square, value: v } = sqrtRatioM1(ONE_MINUS_TWO_D, mod((r + _1n) * u1)); // 4 + + let v_prime = v; // 5 + if (!was_square) v_prime = mod(r0 * v); + + let sgn = _1n; // 6 + if (!was_square) sgn = mod(-_1n); + + const s = mod(v_prime * (r + _1n)); // 7 + let s_abs = s; + if (isNegativeLE(s, P)) s_abs = mod(-s); + + const s2 = s * s; + const W0 = mod(s_abs * _2n); // 8 + const W1 = mod(s2 + _1n); // 9 + const W2 = mod(s2 - _1n); // 10 + const W3 = mod(v_prime * s * (r - _1n) * ONE_MINUS_TWO_D + sgn); // 11 + return new ed448_Point(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2)); +} + +// Keep the Decaf448 base representative literal here: deriving it with +// `new _DecafPoint(ed448_Point.BASE).multiplyUnsafe(2)` forces eager WNAF precomputes and +// adds about 100ms to `ed448.js` import time. +const DECAF_BASE_X = /* @__PURE__ */ BigInt( + '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa955555555555555555555555555555555555555555555555555555555' +); +const DECAF_BASE_Y = /* @__PURE__ */ BigInt( + '0xae05e9634ad7048db359d6205086c2b0036ed7a035884dd7b7e36d728ad8c4b80d6565833a2a3098bbbcb2bed1cda06bdaeafbcdea9386ed' +); +const DECAF_BASE_T = /* @__PURE__ */ BigInt( + '0x696d84643374bace9d70983a12aa9d461da74d2d5c35e8d97ba72c3aba4450a5d29274229bd22c1d5e3a6474ee4ffb0e7a9e200a28eee402' +); + +/** + * Each ed448/EdwardsPoint has 4 different equivalent points. This can be + * a source of bugs for protocols like ring signatures. Decaf was created to solve this. + * Decaf point operates in X:Y:Z:T extended coordinates like EdwardsPoint, + * but it should work in its own namespace: do not combine those two. + * See [RFC9496](https://www.rfc-editor.org/rfc/rfc9496). + */ +class _DecafPoint extends PrimeEdwardsPoint<_DecafPoint> { + // The following gymnastics is done because typescript strips comments otherwise + // prettier-ignore + static BASE: _DecafPoint = + /* @__PURE__ */ (() => new _DecafPoint(new ed448_Point(DECAF_BASE_X, DECAF_BASE_Y, _1n, DECAF_BASE_T)))(); + // prettier-ignore + static ZERO: _DecafPoint = + /* @__PURE__ */ (() => new _DecafPoint(ed448_Point.ZERO))(); + // prettier-ignore + static Fp: IField = + /* @__PURE__ */ (() => Fp448)(); + // prettier-ignore + static Fn: IField = + /* @__PURE__ */ (() => Fn448)(); + + constructor(ep: EdwardsPoint) { + super(ep); + } + + /** + * Create one Decaf448 point from affine Edwards coordinates. + * This wraps the internal Edwards representative directly and is not a + * canonical decaf448 decoding path. + * Use `toBytes()` / `fromBytes()` if canonical decaf448 bytes matter. + */ + static fromAffine(ap: AffinePoint): _DecafPoint { + return new _DecafPoint(ed448_Point.fromAffine(ap)); + } + + protected assertSame(other: _DecafPoint): void { + if (!(other instanceof _DecafPoint)) throw new Error('DecafPoint expected'); + } + + protected init(ep: EdwardsPoint): _DecafPoint { + return new _DecafPoint(ep); + } + + static fromBytes(bytes: TArg): _DecafPoint { + abytes(bytes, 56); + const { d, p: P } = ed448_CURVE; + const mod = (n: bigint) => Fp448.create(n); + const s = Fp448.fromBytes(bytes); + + // 1. Check that s_bytes is the canonical encoding of a field element, or else abort. + // 2. Check that s is non-negative, or else abort + if (!equalBytes(Fn448.toBytes(s), bytes) || isNegativeLE(s, P)) + throw new Error('invalid decaf448 encoding 1'); + + const s2 = mod(s * s); // 1 + const u1 = mod(_1n + s2); // 2 + const u1sq = mod(u1 * u1); + const u2 = mod(u1sq - _4n * d * s2); // 3 + + const { isValid, value: invsqrt } = invertSqrt(mod(u2 * u1sq)); // 4 + + let u3 = mod((s + s) * invsqrt * u1 * SQRT_MINUS_D); // 5 + if (isNegativeLE(u3, P)) u3 = mod(-u3); + + const x = mod(u3 * invsqrt * u2 * INVSQRT_MINUS_D); // 6 + const y = mod((_1n - s2) * invsqrt * u1); // 7 + const t = mod(x * y); // 8 + + if (!isValid) throw new Error('invalid decaf448 encoding 2'); + return new _DecafPoint(new ed448_Point(x, y, _1n, t)); + } + + /** + * Converts decaf-encoded string to decaf point. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-decode-2). + * @param hex - Decaf-encoded 56 bytes. Not every 56-byte string is valid decaf encoding + */ + static fromHex(hex: string): _DecafPoint { + return _DecafPoint.fromBytes(hexToBytes(hex)); + } + + /** + * Encodes decaf point to Uint8Array. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-encode-2). + */ + toBytes(): TRet { + const { X, Z, T } = this.ep; + const P = ed448_CURVE.p; + const mod = (n: bigint) => Fp448.create(n); + const u1 = mod(mod(X + T) * mod(X - T)); // 1 + const x2 = mod(X * X); + const { value: invsqrt } = invertSqrt(mod(u1 * ONE_MINUS_D * x2)); // 2 + let ratio = mod(invsqrt * u1 * SQRT_MINUS_D); // 3 + if (isNegativeLE(ratio, P)) ratio = mod(-ratio); + const u2 = mod(INVSQRT_MINUS_D * ratio * Z - T); // 4 + let s = mod(ONE_MINUS_D * invsqrt * X * u2); // 5 + if (isNegativeLE(s, P)) s = mod(-s); + return Fn448.toBytes(s) as TRet; + } + + /** + * Compare one point to another. + * Described in [RFC9496](https://www.rfc-editor.org/rfc/rfc9496#name-equals-2). + */ + equals(other: _DecafPoint): boolean { + this.assertSame(other); + const { X: X1, Y: Y1 } = this.ep; + const { X: X2, Y: Y2 } = other.ep; + // (x1 * y2 == y1 * x2) + return Fp448.create(X1 * Y2) === Fp448.create(Y1 * X2); + } + + is0(): boolean { + return this.equals(_DecafPoint.ZERO); + } +} +Object.freeze(_DecafPoint.BASE); +Object.freeze(_DecafPoint.ZERO); +Object.freeze(_DecafPoint.prototype); +Object.freeze(_DecafPoint); + +/** Prime-order Decaf448 group bundle. */ +export const decaf448: { + Point: typeof _DecafPoint; +} = /* @__PURE__ */ Object.freeze({ Point: _DecafPoint }); + +/** + * Hashing to decaf448 points / field. RFC 9380 methods. + * `hashToCurve()` is RFC 9380 `hash_to_decaf448`, `deriveToCurve()` is RFC + * 9496 element derivation, and `hashToScalar()` is a library helper layered on + * top of RFC 9496 scalar reduction. + * @example + * Hash one message onto decaf448. + * + * ```ts + * const point = decaf448_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const decaf448_hasher: H2CHasherBase = Object.freeze({ + Point: _DecafPoint, + hashToCurve(msg: TArg, options?: TArg): _DecafPoint { + // Preserve explicit empty/invalid DST overrides so expand_message_xof() can reject them. + const DST = options?.DST === undefined ? 'decaf448_XOF:SHAKE256_D448MAP_RO_' : options.DST; + return decaf448_hasher.deriveToCurve!(expand_message_xof(msg, DST, 112, 224, shake256)); + }, + /** + * Warning: has big modulo bias of 2^-64. + * RFC is invalid. RFC says "use 64-byte xof", while for 2^-112 bias + * it must use 84-byte xof (56+56/2), not 64. + */ + hashToScalar(msg: TArg, options: TArg = { DST: _DST_scalar }): bigint { + // Can't use `Fn448.fromBytes()`. 64-byte input => 56-byte field element + const xof = expand_message_xof(msg, options.DST, 64, 256, shake256); + return Fn448.create(bytesToNumberLE(xof)); + }, + /** + * HashToCurve-like construction based on RFC 9496 (Element Derivation). + * Converts 112 uniform random bytes into a curve point. + * + * WARNING: This represents an older hash-to-curve construction from before + * RFC 9380 was finalized. + * It was later reused as a component in the newer + * `hash_to_decaf448` function defined in RFC 9380. + */ + deriveToCurve(bytes: TArg): _DecafPoint { + abytes(bytes, 112); + const skipValidation = true; + // Note: Similar to the field element decoding described in + // [RFC7748], and unlike the field element decoding described in + // Section 5.3.1, non-canonical values are accepted. + const r1 = Fp448.create(Fp448.fromBytes(bytes.subarray(0, 56), skipValidation)); + const R1 = calcElligatorDecafMap(r1); + const r2 = Fp448.create(Fp448.fromBytes(bytes.subarray(56, 112), skipValidation)); + const R2 = calcElligatorDecafMap(r2); + return new _DecafPoint(R1.add(R2)); + }, +}); + +/** + * decaf448 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over decaf448. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = decaf448_oprf.oprf.generateKeyPair(); + * const blind = decaf448_oprf.oprf.blind(input); + * const evaluated = decaf448_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = decaf448_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const decaf448_oprf: TRet = /* @__PURE__ */ (() => + createOPRF({ + name: 'decaf448-SHAKE256', + Point: _DecafPoint, + hash: (msg: TArg) => shake256(msg, { dkLen: 64 }), + hashToGroup: decaf448_hasher.hashToCurve, + hashToScalar: decaf448_hasher.hashToScalar, + }))(); + +/** + * Weird / bogus points, useful for debugging. + * Unlike ed25519, there is no ed448 generator point which can produce full T subgroup. + * Instead, the torsion subgroup here is cyclic of order 4, generated by + * `(1, 0)`, and the array below lists that subgroup set (Klein four-group). + * @example + * Decode one known torsion point for debugging. + * + * ```ts + * import { ED448_TORSION_SUBGROUP, ed448 } from '@noble/curves/ed448.js'; + * const point = ed448.Point.fromHex(ED448_TORSION_SUBGROUP[1]); + * ``` + */ +export const ED448_TORSION_SUBGROUP: readonly string[] = /* @__PURE__ */ Object.freeze([ + '010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + 'fefffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffff00', + '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', + '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080', +]); diff --git a/node_modules/@noble/curves/src/index.ts b/node_modules/@noble/curves/src/index.ts new file mode 100644 index 0000000..201a00a --- /dev/null +++ b/node_modules/@noble/curves/src/index.ts @@ -0,0 +1,37 @@ +/** + * Audited & minimal JS implementation of elliptic curve cryptography. + * @module + * @example +```js +import { secp256k1, schnorr } from '@noble/curves/secp256k1.js'; +import { ed25519, ed25519ph, ed25519ctx, x25519, ristretto255 } from '@noble/curves/ed25519.js'; +import { ed448, ed448ph, x448, decaf448 } from '@noble/curves/ed448.js'; +import { p256, p384, p521 } from '@noble/curves/nist.js'; +import { bls12_381 } from '@noble/curves/bls12-381.js'; +import { bn254 } from '@noble/curves/bn254.js'; +import { + jubjub, + babyjubjub, + brainpoolP256r1, + brainpoolP384r1, + brainpoolP512r1, +} from '@noble/curves/misc.js'; +import * as webcrypto from '@noble/curves/webcrypto.js'; + +// hash-to-curve +import { secp256k1_hasher } from '@noble/curves/secp256k1.js'; +import { p256_hasher, p384_hasher, p521_hasher } from '@noble/curves/nist.js'; +import { ristretto255_hasher } from '@noble/curves/ed25519.js'; +import { decaf448_hasher } from '@noble/curves/ed448.js'; + +// OPRFs +import { p256_oprf, p384_oprf, p521_oprf } from '@noble/curves/nist.js'; +import { ristretto255_oprf } from '@noble/curves/ed25519.js'; +import { decaf448_oprf } from '@noble/curves/ed448.js'; + +// utils +import { bytesToHex, hexToBytes, concatBytes } from '@noble/curves/abstract/utils.js'; +import { Field } from '@noble/curves/abstract/modular.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/node_modules/@noble/curves/src/misc.ts b/node_modules/@noble/curves/src/misc.ts new file mode 100644 index 0000000..e9abde2 --- /dev/null +++ b/node_modules/@noble/curves/src/misc.ts @@ -0,0 +1,259 @@ +/** + * Miscellaneous, rarely used curves. + * jubjub, babyjubjub, pallas, vesta. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { blake512 } from '@noble/hashes/blake1.js'; +import { blake2s } from '@noble/hashes/blake2.js'; +import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes } from '@noble/hashes/utils.js'; +import { + eddsa, + edwards, + type EdDSA, + type EdwardsOpts, + type EdwardsPoint, +} from './abstract/edwards.ts'; +import { ecdsa, weierstrass, type ECDSA, type WeierstrassOpts } from './abstract/weierstrass.ts'; +import { asciiToBytes, type TArg } from './utils.ts'; + +// Jubjub curves have 𝔽p over scalar fields of other curves. They are friendly to ZK proofs. + +// Zcash Protocol Specification "Jubjub" parameters: +// q = BLS12-381 Fr, r, h = 8, a = -1, d = -10240/10241. +// Gx/Gy keep the canonical Jubjub base point used by Zcash implementations. +const jubjub_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({ + p: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001'), + n: BigInt('0xe7db4ea6533afa906673b0101343b00a6682093ccc81082d0970e5ed6f72cb7'), + h: BigInt(8), + a: BigInt('0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000000'), + d: BigInt('0x2a9318e74bfa2b48f5fd9207e6bd7fd4292d7f6d37579d2601065fd6d6343eb1'), + Gx: BigInt('0x11dafe5d23e1218086a365b99fbf3d3be72f6afd7d1f72623e6b071492d1122b'), + Gy: BigInt('0x1d523cf1ddab1a1793132e78c866c0c33e26ba5cc220fed7cc3f870e59d292aa'), +}))(); +/** + * Generic EdDSA-over-Jubjub convenience wrapper with `sha512`. + * This is not the Zcash RedJubjub / Sapling signature scheme. + * @example + * Generate one Jubjub keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = jubjub.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = jubjub.sign(msg, secretKey); + * const isValid = jubjub.verify(sig, msg, publicKey); + * ``` + */ +export const jubjub: EdDSA = /* @__PURE__ */ (() => eddsa(edwards(jubjub_CURVE), sha512))(); + +// BabyJubJub over bn254 Fr. EIP-2494 explicitly defines both the full-group generator G and the +// prime-order subgroup base point B = 8*G. +// noble's Edwards abstraction expects Point.BASE / curve.n to describe the prime-order subgroup, so +// use the EIP base point B here. +// Historical noble incorrectly used the EIP generator G as Point.BASE, which mismatched the +// abstraction and leaked the wrong order into consumers. +// Historical noble used G instead: +// Gx = 995203441582195749578291179787384436505546430278305826713579947235728471134 +// Gy = 5472060717959818805561601436314318772137091100104008585924551046643952123905 +const babyjubjub_CURVE: EdwardsOpts = /* @__PURE__ */ (() => ({ + p: BigInt('0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001'), + n: BigInt('0x060c89ce5c263405370a08b6d0302b0bab3eedb83920ee0a677297dc392126f1'), + h: BigInt(8), + a: BigInt('168700'), + d: BigInt('168696'), + Gx: BigInt('0xbb77a6ad63e739b4eacb2e09d6277c12ab8d8010534e0b62893f3f6bb957051'), + Gy: BigInt('0x25797203f7a0b24925572e1cd16bf9edfce0051fb9e133774b3c257a872d7d8b'), +}))(); +/** + * Curve over scalar field of bn254. babyjubjub Fp = bn254 n + * This is a working generic EdDSA-over-BabyJubJub wrapper that uses `blake512` for the 64-byte + * secret expansion required by the shared EdDSA helper. + * It is not the BabyJubJub stack used by iden3/circomlib, `babyjubjub-rs`, or + * `@zk-kit/eddsa-poseidon`: those pair the subgroup base B/B8 with Blake-style secret expansion + * plus dedicated Poseidon / MiMC / Pedersen transcript hashing. This wrapper stays generic and is + * not meant as an interoperability target for those BabyJubJub signing stacks. + * @example + * Access the BabyJubJub base point and round-trip it through the point codec. + * + * ```ts + * import { babyjubjub } from '@noble/curves/misc.js'; + * const base = babyjubjub.Point.BASE; + * const encoded = base.toBytes(); + * const decoded = babyjubjub.Point.fromBytes(encoded); + * ``` + */ +export const babyjubjub: EdDSA = /* @__PURE__ */ (() => + eddsa(edwards(babyjubjub_CURVE), blake512))(); + +// Sapling URS randomness beacon from the Zcash protocol. This stays as the 64-byte ASCII +// lowercase-hex string used for the first Blake2s block, not 32 raw bytes. +const jubjub_gh_first_block = /* @__PURE__ */ asciiToBytes( + '096b36a5804bfacef1691e173c366a47ff5ba84a44f26ddd7e8d9f79d5b42df0' +); + +/** + * @param tag - Hash input. + * @param personalization - BLAKE2 personalization bytes. + * @returns Prime-order Jubjub point. + * @throws If the digest does not decode to a Jubjub point, or if the + * cofactor-cleared point has small order. {@link Error} + * @example + * Hash a tag into a prime-order Jubjub point. + * + * ```ts + * import { jubjub_groupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const tag = Uint8Array.of(2); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_groupHash(tag, personalization); + * ``` + */ +export function jubjub_groupHash( + tag: TArg, + personalization: TArg +): EdwardsPoint { + const h = blake2s.create({ personalization, dkLen: 32 }); + h.update(jubjub_gh_first_block); + h.update(tag); + // NOTE: returns EdwardsPoint, in case it will be multiplied later + let p = jubjub.Point.fromBytes(h.digest()); + // NOTE: cannot replace with isSmallOrder, returns Point*8 + p = p.multiply(jubjub_CURVE.h); + if (p.equals(jubjub.Point.ZERO)) throw new Error('Point has small order'); + return p; +} + +/** + * No secret data is leaked here at all. + * It operates over public data. + * @param m - Message prefix. + * @param personalization - 8-byte BLAKE2 personalization bytes. + * @returns First non-zero group hash. + * @throws If the personalization is invalid, or if no non-zero Jubjub group + * hash can be found. {@link Error} + * @example + * Derive the first non-zero Jubjub group hash for one personalization tag. + * + * ```ts + * import { jubjub_findGroupHash } from '@noble/curves/misc.js'; + * import { asciiToBytes } from '@noble/curves/utils.js'; + * const msg = Uint8Array.of(); + * const personalization = asciiToBytes('Zcash_G_'); + * const point = jubjub_findGroupHash(msg, personalization); + * ``` + */ +export function jubjub_findGroupHash( + m: TArg, + personalization: TArg +): EdwardsPoint { + // Validate BLAKE2s personalization once up front; otherwise the retry loop swallows the real + // input error and turns it into a misleading "tag overflow". + abytes(personalization, 8, 'personalization'); + const tag = concatBytes(m, Uint8Array.of(0)); + const hashes = []; + for (let i = 0; i < 256; i++) { + tag[tag.length - 1] = i; + try { + hashes.push(jubjub_groupHash(tag, personalization)); + } catch (e) {} + } + if (!hashes.length) throw new Error('findGroupHash tag overflow'); + return hashes[0]; +} + +const brainpoolP256r1_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt('0xa9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e5377'), + a: BigInt('0x7d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9'), + b: BigInt('0x26dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b6'), + n: BigInt('0xa9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7'), + Gx: BigInt('0x8bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262'), + Gy: BigInt('0x547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f046997'), + h: BigInt(1), +}))(); +/** + * Brainpool P256r1 with sha256, from RFC 5639. + * @example + * Generate one Brainpool P256r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP256r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP256r1.sign(msg, secretKey); + * const isValid = brainpoolP256r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP256r1: ECDSA = /* @__PURE__ */ (() => + ecdsa(weierstrass(brainpoolP256r1_CURVE), sha256))(); + +const brainpoolP384r1_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt( + '0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b412b1da197fb71123acd3a729901d1a71874700133107ec53' + ), + a: BigInt( + '0x7bc382c63d8c150c3c72080ace05afa0c2bea28e4fb22787139165efba91f90f8aa5814a503ad4eb04a8c7dd22ce2826' + ), + b: BigInt( + '0x04a8c7dd22ce28268b39b55416f0447c2fb77de107dcd2a62e880ea53eeb62d57cb4390295dbc9943ab78696fa504c11' + ), + n: BigInt( + '0x8cb91e82a3386d280f5d6f7e50e641df152f7109ed5456b31f166e6cac0425a7cf3ab6af6b7fc3103b883202e9046565' + ), + Gx: BigInt( + '0x1d1c64f068cf45ffa2a63a81b7c13f6b8847a3e77ef14fe3db7fcafe0cbd10e8e826e03436d646aaef87b2e247d4af1e' + ), + Gy: BigInt( + '0x8abe1d7520f9c2a45cb1eb8e95cfd55262b70b29feec5864e19c054ff99129280e4646217791811142820341263c5315' + ), + h: BigInt(1), +}))(); +/** + * Brainpool P384r1 with sha384, from RFC 5639. + * @example + * Generate one Brainpool P384r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP384r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP384r1.sign(msg, secretKey); + * const isValid = brainpoolP384r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP384r1: ECDSA = /* @__PURE__ */ (() => + ecdsa(weierstrass(brainpoolP384r1_CURVE), sha384))(); + +const brainpoolP512r1_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt( + '0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca703308717d4d9b009bc66842aecda12ae6a380e62881ff2f2d82c68528aa6056583a48f3' + ), + a: BigInt( + '0x7830a3318b603b89e2327145ac234cc594cbdd8d3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94ca' + ), + b: BigInt( + '0x3df91610a83441caea9863bc2ded5d5aa8253aa10a2ef1c98b9ac8b57f1117a72bf2c7b9e7c1ac4d77fc94cadc083e67984050b75ebae5dd2809bd638016f723' + ), + n: BigInt( + '0xaadd9db8dbe9c48b3fd4e6ae33c9fc07cb308db3b3c9d20ed6639cca70330870553e5c414ca92619418661197fac10471db1d381085ddaddb58796829ca90069' + ), + Gx: BigInt( + '0x81aee4bdd82ed9645a21322e9c4c6a9385ed9f70b5d916c1b43b62eef4d0098eff3b1f78e2d0d48d50d1687b93b97d5f7c6d5047406a5e688b352209bcb9f822' + ), + Gy: BigInt( + '0x7dde385d566332ecc0eabfa9cf7822fdf209f70024a57b1aa000c55b881f8111b2dcde494a5f485e5bca4bd88a2763aed1ca2b2fa8f0540678cd1e0f3ad80892' + ), + h: BigInt(1), +}))(); +/** + * Brainpool P512r1 with sha512, from RFC 5639. + * @example + * Generate one Brainpool P512r1 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = brainpoolP512r1.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = brainpoolP512r1.sign(msg, secretKey); + * const isValid = brainpoolP512r1.verify(sig, msg, publicKey); + * ``` + */ +export const brainpoolP512r1: ECDSA = /* @__PURE__ */ (() => + ecdsa(weierstrass(brainpoolP512r1_CURVE), sha512))(); diff --git a/node_modules/@noble/curves/src/nist.ts b/node_modules/@noble/curves/src/nist.ts new file mode 100644 index 0000000..ffec01d --- /dev/null +++ b/node_modules/@noble/curves/src/nist.ts @@ -0,0 +1,327 @@ +/** + * Internal module for NIST P256, P384, P521 curves. + * Do not use for now. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256, sha384, sha512 } from '@noble/hashes/sha2.js'; +import { createFROST, type FROST } from './abstract/frost.ts'; +import { createHasher, type H2CHasher } from './abstract/hash-to-curve.ts'; +import { createOPRF, type OPRF } from './abstract/oprf.ts'; +import { + ecdsa, + mapToCurveSimpleSWU, + weierstrass, + type ECDSA, + type WeierstrassOpts, + type WeierstrassPointCons, +} from './abstract/weierstrass.ts'; +import { type TRet } from './utils.ts'; + +// p = 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n - 1n +// a = Fp256.create(BigInt('-3')); +const p256_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'), + n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'), + h: BigInt(1), + a: BigInt('0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc'), + b: BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b'), + Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'), + Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'), +}))(); + +// p = 2n**384n - 2n**128n - 2n**96n + 2n**32n - 1n +const p384_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt( + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff' + ), + n: BigInt( + '0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973' + ), + h: BigInt(1), + a: BigInt( + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc' + ), + b: BigInt( + '0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef' + ), + Gx: BigInt( + '0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7' + ), + Gy: BigInt( + '0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f' + ), +}))(); + +// p = 2n**521n - 1n +const p521_CURVE: WeierstrassOpts = /* @__PURE__ */ (() => ({ + p: BigInt( + '0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff' + ), + n: BigInt( + '0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409' + ), + h: BigInt(1), + a: BigInt( + '0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc' + ), + b: BigInt( + '0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00' + ), + Gx: BigInt( + '0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66' + ), + Gy: BigInt( + '0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650' + ), +}))(); + +type SwuOpts = { + A: bigint; + B: bigint; + Z: bigint; +}; + +function createSWU(Point: WeierstrassPointCons, opts: SwuOpts) { + let map: ((u: bigint) => { x: bigint; y: bigint }) | undefined; + // RFC 9380's NIST suites here all use m = 1, so createHasher passes one field element per map. + // Building the SWU sqrt-ratio helper eagerly adds noticeable `nist.js` import cost, so defer it + // to first use; after that the cached mapper is reused directly. + return (scalars: bigint[]) => (map || (map = mapToCurveSimpleSWU(Point.Fp, opts)))(scalars[0]); +} + +// NIST P256 +const p256_Point = /* @__PURE__ */ weierstrass(p256_CURVE); +/** + * NIST P256 (aka secp256r1, prime256v1) curve, ECDSA and ECDH methods. + * Hashes inputs with sha256 by default. + * + * @example + * Generate one P-256 keypair, sign a message, and verify it. + * + * ```js + * import { p256 } from '@noble/curves/nist.js'; + * const { secretKey, publicKey } = p256.keygen(); + * // const publicKey = p256.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p256.sign(msg, secretKey); + * const isValid = p256.verify(sig, msg, publicKey); + * // const sigKeccak = p256.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export const p256: ECDSA = /* @__PURE__ */ ecdsa(p256_Point, sha256); +/** + * Hashing / encoding to p256 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-256 curve. + * + * ```ts + * const point = p256_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p256_hasher: H2CHasher> = /* @__PURE__ */ (() => { + return createHasher( + p256_Point, + createSWU(p256_Point, { + A: p256_CURVE.a, + B: p256_CURVE.b, + Z: p256_Point.Fp.create(BigInt('-10')), + }), + { + DST: 'P256_XMD:SHA-256_SSWU_RO_', + encodeDST: 'P256_XMD:SHA-256_SSWU_NU_', + p: p256_CURVE.p, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ); +})(); +/** + * p256 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-256. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p256_oprf.oprf.generateKeyPair(); + * const blind = p256_oprf.oprf.blind(input); + * const evaluated = p256_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p256_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p256_oprf: TRet = /* @__PURE__ */ (() => + createOPRF({ + name: 'P256-SHA256', + Point: p256_Point, + hash: sha256, + hashToGroup: p256_hasher.hashToCurve, + hashToScalar: p256_hasher.hashToScalar, + }))(); +/** + * FROST threshold signatures over p256. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 p256 signing. + * + * ```ts + * const alice = p256_FROST.Identifier.derive('alice@example.com'); + * const bob = p256_FROST.Identifier.derive('bob@example.com'); + * const carol = p256_FROST.Identifier.derive('carol@example.com'); + * const deal = p256_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const p256_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-P256-SHA256-v1', + Point: p256_Point, + hashToScalar: p256_hasher.hashToScalar, + hash: sha256, + }))(); + +// NIST P384 +const p384_Point = /* @__PURE__ */ weierstrass(p384_CURVE); +/** + * NIST P384 (aka secp384r1) curve, ECDSA and ECDH methods. Hashes inputs with sha384 by default. + * @example + * Generate one P-384 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p384.sign(msg, secretKey); + * const isValid = p384.verify(sig, msg, publicKey); + * ``` + */ +export const p384: ECDSA = /* @__PURE__ */ ecdsa(p384_Point, sha384); +/** + * Hashing / encoding to p384 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-384 curve. + * + * ```ts + * const point = p384_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p384_hasher: H2CHasher> = /* @__PURE__ */ (() => { + return createHasher( + p384_Point, + createSWU(p384_Point, { + A: p384_CURVE.a, + B: p384_CURVE.b, + Z: p384_Point.Fp.create(BigInt('-12')), + }), + { + DST: 'P384_XMD:SHA-384_SSWU_RO_', + encodeDST: 'P384_XMD:SHA-384_SSWU_NU_', + p: p384_CURVE.p, + m: 1, + k: 192, + expand: 'xmd', + hash: sha384, + } + ); +})(); +/** + * p384 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-384. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p384_oprf.oprf.generateKeyPair(); + * const blind = p384_oprf.oprf.blind(input); + * const evaluated = p384_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p384_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p384_oprf: TRet = /* @__PURE__ */ (() => + createOPRF({ + name: 'P384-SHA384', + Point: p384_Point, + hash: sha384, + hashToGroup: p384_hasher.hashToCurve, + hashToScalar: p384_hasher.hashToScalar, + }))(); + +// NIST P521 +// RFC 7518 fixes the canonical JWK/JOSE width at 66 bytes: +// - Section 3.4 says ECDSA octet strings must not omit leading zero octets +// - Sections 6.2.1.2/6.2.1.3 say P-521 coordinates "x"/"y" must be 66 octets +// - Section 6.2.2.1 says private scalar "d" must be ceil(log2(n)/8) octets, i.e. 66 for P-521 +// NIST FIPS 186-5 Appendix A.3.3 also routes deterministic ECDSA private keys through Appendix +// B.2.3, whose Integer-to-Octet-String output has explicit fixed length L; for P-521 that is the +// same 66-byte order width. +// RFC 6979 matches that width too: private key x is an integer, while `int2octets(x)` uses +// rlen = 8 * ceil(qlen/8); for P-521, qlen = 521 so the canonical octet width is 66 bytes. +// Wycheproof ECDH stores private values as integers, not fixed-width scalar bytes, so it does not +// require a dedicated 65-byte parser path; the repo tests now normalize those integer fixtures to +// the canonical 66-byte width before use. There is no good standards or oracle reason to accept +// exactly 65 bytes here: the coherent choices are canonical 66 only, or a broader integer-style +// parser across many widths. Since this field parser is fixed-width, keep it canonical and use the +// default exact-66-byte scalar field path. +const p521_Point = /* @__PURE__ */ weierstrass(p521_CURVE); +/** + * NIST P521 (aka secp521r1) curve, ECDSA and ECDH methods. Hashes inputs with sha512 by default. + * Deterministic `keygen(seed)` expects 99 seed bytes here because the generic scalar-derivation + * helper uses `getMinHashLength(n)`, not the 66-byte canonical secret-key width. + * @example + * Generate one P-521 keypair, sign a message, and verify it. + * + * ```ts + * const { secretKey, publicKey } = p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = p521.sign(msg, secretKey); + * const isValid = p521.verify(sig, msg, publicKey); + * ``` + */ +export const p521: ECDSA = /* @__PURE__ */ ecdsa(p521_Point, sha512); +/** + * Hashing / encoding to p521 points / field. RFC 9380 methods. + * @example + * Hash one message onto the P-521 curve. + * + * ```ts + * const point = p521_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const p521_hasher: H2CHasher> = /* @__PURE__ */ (() => { + return createHasher( + p521_Point, + createSWU(p521_Point, { + A: p521_CURVE.a, + B: p521_CURVE.b, + Z: p521_Point.Fp.create(BigInt('-4')), + }), + { + DST: 'P521_XMD:SHA-512_SSWU_RO_', + encodeDST: 'P521_XMD:SHA-512_SSWU_NU_', + p: p521_CURVE.p, + m: 1, + k: 256, + expand: 'xmd', + hash: sha512, + } + ); +})(); +/** + * p521 OPRF, defined in RFC 9497. + * @example + * Run one blind/evaluate/finalize OPRF round over P-521. + * + * ```ts + * const input = new TextEncoder().encode('hello noble'); + * const keys = p521_oprf.oprf.generateKeyPair(); + * const blind = p521_oprf.oprf.blind(input); + * const evaluated = p521_oprf.oprf.blindEvaluate(keys.secretKey, blind.blinded); + * const output = p521_oprf.oprf.finalize(input, blind.blind, evaluated); + * ``` + */ +export const p521_oprf: TRet = /* @__PURE__ */ (() => + createOPRF({ + name: 'P521-SHA512', + Point: p521_Point, + hash: sha512, + hashToGroup: p521_hasher.hashToCurve, + hashToScalar: p521_hasher.hashToScalar, // produces L=98 just like in RFC + }))(); diff --git a/node_modules/@noble/curves/src/secp256k1.ts b/node_modules/@noble/curves/src/secp256k1.ts new file mode 100644 index 0000000..4380a27 --- /dev/null +++ b/node_modules/@noble/curves/src/secp256k1.ts @@ -0,0 +1,570 @@ +/** + * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf). + * + * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism ψ, + * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored). + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { sha256 } from '@noble/hashes/sha2.js'; +import { randomBytes } from '@noble/hashes/utils.js'; +import { createKeygen, type CurveLengths } from './abstract/curve.ts'; +import { + createFROST, + type FROST, + type FrostPublic, + type FrostSecret, + type Nonces, +} from './abstract/frost.ts'; +import { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts'; +import { Field, mapHashToField, pow2 } from './abstract/modular.ts'; +import { + type ECDSA, + ecdsa, + type EndomorphismOpts, + mapToCurveSimpleSWU, + type WeierstrassPoint as PointType, + weierstrass, + type WeierstrassOpts, + type WeierstrassPointCons, +} from './abstract/weierstrass.ts'; +import { + abytes, + asciiToBytes, + bytesToNumberBE, + concatBytes, + type TArg, + type TRet, +} from './utils.ts'; + +// Seems like generator was produced from some seed: +// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x` +// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n +const secp256k1_CURVE: WeierstrassOpts = { + p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'), + n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'), + h: BigInt(1), + a: BigInt(0), + b: BigInt(7), + Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'), + Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'), +}; + +const secp256k1_ENDO: EndomorphismOpts = { + beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'), + basises: [ + [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')], + [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')], + ], +}; + +const _0n = /* @__PURE__ */ BigInt(0); +const _2n = /* @__PURE__ */ BigInt(2); + +/** + * √n = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit. + * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00] + */ +function sqrtMod(y: bigint): bigint { + const P = secp256k1_CURVE.p; + // prettier-ignore + const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + // prettier-ignore + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = (y * y * y) % P; // x^3, 11 + const b3 = (b2 * b2 * y) % P; // x^7 + const b6 = (pow2(b3, _3n, P) * b3) % P; + const b9 = (pow2(b6, _3n, P) * b3) % P; + const b11 = (pow2(b9, _2n, P) * b2) % P; + const b22 = (pow2(b11, _11n, P) * b11) % P; + const b44 = (pow2(b22, _22n, P) * b22) % P; + const b88 = (pow2(b44, _44n, P) * b44) % P; + const b176 = (pow2(b88, _88n, P) * b88) % P; + const b220 = (pow2(b176, _44n, P) * b44) % P; + const b223 = (pow2(b220, _3n, P) * b3) % P; + const t1 = (pow2(b223, _23n, P) * b22) % P; + const t2 = (pow2(t1, _6n, P) * b2) % P; + const root = pow2(t2, _2n, P); + if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root'); + return root; +} + +const Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod }); +const Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, { + Fp: Fpk1, + endo: secp256k1_ENDO, +}); + +/** + * secp256k1 curve: ECDSA and ECDH methods. + * + * Uses sha256 to hash messages. To use a different hash, + * pass `{ prehash: false }` to sign / verify. + * + * @example + * Generate one secp256k1 keypair, sign a message, and verify it. + * + * ```js + * import { secp256k1 } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = secp256k1.keygen(); + * // const publicKey = secp256k1.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = secp256k1.sign(msg, secretKey); + * const isValid = secp256k1.verify(sig, msg, publicKey); + * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false }); + * ``` + */ +export const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256); + +// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code. +// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki +/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */ +const TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {}; +// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII. +function taggedHash(tag: string, ...messages: TArg): TRet { + let tagP = TAGGED_HASH_PREFIXES[tag]; + if (tagP === undefined) { + const tagH = sha256(asciiToBytes(tag)); + tagP = concatBytes(tagH, tagH); + TAGGED_HASH_PREFIXES[tag] = tagP; + } + return sha256(concatBytes(tagP, ...messages)) as TRet; +} + +// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03 +const pointToBytes = (point: TArg>): TRet => + point.toBytes(true).slice(1) as TRet; +const hasEven = (y: bigint) => y % _2n === _0n; + +// Calculate point, scalar and bytes +function schnorrGetExtPubKey(priv: TArg) { + const { Fn, BASE } = Pointk1; + const d_ = Fn.fromBytes(priv); + const p = BASE.multiply(d_); // P = d'⋅G; 0 < d' < n check is done inside + const scalar = hasEven(p.y) ? d_ : Fn.neg(d_); + return { scalar, bytes: pointToBytes(p) }; +} +/** + * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point. + * @returns valid point checked for being on-curve + */ +function lift_x(x: bigint): PointType { + const Fp = Fpk1; + if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x ≥ p'); + const xx = Fp.create(x * x); + const c = Fp.create(xx * x + BigInt(7)); // Let c = x³ + 7 mod p. + let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt(). + // Return the unique point P such that x(P) = x and + // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise. + if (!hasEven(y)) y = Fp.neg(y); + const p = Pointk1.fromAffine({ x, y }); + p.assertValidity(); + return p; +} +// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only +// parses big-endian bytes and does not enforce the fixed-width contract itself. +const num = bytesToNumberBE; +/** Create tagged hash, convert it to bigint, reduce modulo-n. */ +function challenge(...args: TArg): bigint { + return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args))); +} + +/** Schnorr public key is just `x` coordinate of Point as per BIP340. */ +function schnorrGetPublicKey(secretKey: TArg): TRet { + return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'≥n. Ret bytes(d'⋅G) +} + +/** + * Creates Schnorr signature as per BIP340. Verifies itself before returning anything. + * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not + * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden + * deterministic signing against side-channel and fault-injection attacks. + */ +function schnorrSign( + message: TArg, + secretKey: TArg, + auxRand: TArg = randomBytes(32) +): TRet { + const { Fn, BASE } = Pointk1; + const m = abytes(message, undefined, 'message'); + const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder + const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array + // Let t be the byte-wise xor of bytes(d) and hash/aux(a). + const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a))); + const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m) + // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand) + // here: that helper parses canonical secret keys and rejects rand >= n instead + // of reducing the nonce hash modulo the group order. + const k_ = Fn.create(num(rand)); + // BIP-340: "Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'⋅G." + if (k_ === 0n) throw new Error('sign failed: k is zero'); + const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction. + const k = hasEven(p.y) ? k_ : Fn.neg(k_); + const rx = pointToBytes(p); + const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n. + const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n). + sig.set(rx, 0); + sig.set(Fn.toBytes(Fn.create(k + e * d)), 32); + // If Verify(bytes(P), m, sig) (see below) returns failure, abort + if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced'); + return sig as TRet; +} + +/** + * Verifies Schnorr signature. + * Will swallow errors & return false except for initial type validation of arguments. + */ +function schnorrVerify( + signature: TArg, + message: TArg, + publicKey: TArg +): boolean { + const { Fp, Fn, BASE } = Pointk1; + const sig = abytes(signature, 64, 'signature'); + const m = abytes(message, undefined, 'message'); + const pub = abytes(publicKey, 32, 'publicKey'); + try { + const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails + const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r ≥ p. + if (!Fp.isValidNot0(r)) return false; + const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s ≥ n. + // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches + // s = 0 only with negligible probability (k + e*d ≡ 0 mod n), so treat zero-s inputs as + // crafted edge cases and fail closed instead of carrying that extra verification surface. + if (!Fn.isValidNot0(s)) return false; + + // int(challenge(bytes(r) || bytes(P) || m)) % n + const e = challenge(Fn.toBytes(r), pointToBytes(P), m); + // R = s⋅G - e⋅P, where -eP == (n-e)P + const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e))); + const { x, y } = R.toAffine(); + // Fail if is_infinite(R) / not has_even_y(R) / x(R) ≠ r. + if (R.is0() || !hasEven(y) || x !== r) return false; + return true; + } catch (error) { + return false; + } +} + +export const __TEST: { lift_x: typeof lift_x } = /* @__PURE__ */ Object.freeze({ lift_x }); + +/** Schnorr-specific secp256k1 API from BIP340. */ +export type SecpSchnorr = { + /** + * Generate one Schnorr secret/public keypair. + * @param seed - Optional seed for deterministic testing or custom randomness. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet }; + /** + * Derive the x-only public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns X-only public key bytes. + */ + getPublicKey: typeof schnorrGetPublicKey; + /** + * Create one BIP340 Schnorr signature. + * @param message - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @param auxRand - Optional auxiliary randomness. + * @returns Compact Schnorr signature bytes. + */ + sign: typeof schnorrSign; + /** + * Verify one BIP340 Schnorr signature. + * @param signature - Compact signature bytes. + * @param message - Signed message bytes. + * @param publicKey - X-only public key bytes. + * @returns `true` when the signature is valid. + */ + verify: typeof schnorrVerify; + /** Underlying secp256k1 point constructor. */ + Point: WeierstrassPointCons; + /** Helper utilities for Schnorr-specific key handling and tagged hashing. */ + utils: { + /** Generate one Schnorr secret key. */ + randomSecretKey: (seed?: TArg) => TRet; + /** Convert one point into its x-only BIP340 byte encoding. */ + pointToBytes: (point: TArg>) => TRet; + /** Lift one x coordinate into the unique even-Y point. */ + lift_x: typeof lift_x; + /** Compute a BIP340 tagged hash. */ + taggedHash: typeof taggedHash; + }; + /** Public byte lengths for keys, signatures, and seeds. */ + lengths: CurveLengths; +}; +/** + * Schnorr signatures over secp256k1. + * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}. + * @example + * Generate one BIP340 Schnorr keypair, sign a message, and verify it. + * + * ```js + * import { schnorr } from '@noble/curves/secp256k1.js'; + * const { secretKey, publicKey } = schnorr.keygen(); + * // const publicKey = schnorr.getPublicKey(secretKey); + * const msg = new TextEncoder().encode('hello'); + * const sig = schnorr.sign(msg, secretKey); + * const isValid = schnorr.verify(sig, msg, publicKey); + * ``` + */ +export const schnorr: SecpSchnorr = /* @__PURE__ */ (() => { + const size = 32; + const seedLength = 48; + const randomSecretKey = (seed?: TArg): TRet => { + seed = seed === undefined ? randomBytes(seedLength) : seed; + return mapHashToField(seed, secp256k1_CURVE.n); + }; + return Object.freeze({ + keygen: createKeygen(randomSecretKey, schnorrGetPublicKey), + getPublicKey: schnorrGetPublicKey, + sign: schnorrSign, + verify: schnorrVerify, + Point: Pointk1, + utils: Object.freeze({ + randomSecretKey, + taggedHash, + lift_x, + pointToBytes, + }), + lengths: Object.freeze({ + secretKey: size, + publicKey: size, + publicKeyHasPrefix: false, + signature: size * 2, + seed: seedLength, + }), + }); +})(); + +// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order. +// The final `1` in each denominator array is the explicit monic leading term. +const isoMap = /* @__PURE__ */ (() => + isogenyMap( + Fpk1, + [ + // xNum + [ + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7', + '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581', + '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262', + '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c', + ], + // xDen + [ + '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b', + '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + // yNum + [ + '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c', + '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3', + '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931', + '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84', + ], + // yDen + [ + '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b', + '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573', + '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f', + '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1 + ], + ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]] + ))(); +// RFC 9380 §8.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below. +let mapSWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined; +const getMapSWU = () => + mapSWU || + (mapSWU = mapToCurveSimpleSWU(Fpk1, { + // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so + // defer it to first use; after that the cached mapper is reused directly. + A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'), + B: BigInt('1771'), + Z: Fpk1.create(BigInt('-11')), + })); + +/** + * Hashing / encoding to secp256k1 points / field. RFC 9380 methods. + * @example + * Hash one message onto secp256k1. + * + * ```ts + * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble')); + * ``` + */ +export const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() => + createHasher( + Pointk1, + (scalars: bigint[]) => { + const { x, y } = getMapSWU()(Fpk1.create(scalars[0])); + return isoMap(x, y); + }, + { + DST: 'secp256k1_XMD:SHA-256_SSWU_RO_', + encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_', + p: Fpk1.ORDER, + m: 1, + k: 128, + expand: 'xmd', + hash: sha256, + } + ))(); +/** + * FROST threshold signatures over secp256k1. RFC 9591. + * @example + * Create one trusted-dealer package for 2-of-3 secp256k1 signing. + * + * ```ts + * const alice = secp256k1_FROST.Identifier.derive('alice@example.com'); + * const bob = secp256k1_FROST.Identifier.derive('bob@example.com'); + * const carol = secp256k1_FROST.Identifier.derive('carol@example.com'); + * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const secp256k1_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-secp256k1-SHA256-v1', + Point: Pointk1, + hashToScalar: secp256k1_hasher.hashToScalar, + hash: sha256, + }))(); + +// Taproot utils +// `undefined` means "disable TapTweak entirely"; callers that want the BIP-341/BIP-386 empty +// merkle root must pass `new Uint8Array(0)` explicitly. +function tweak(point: PointType, merkleRoot?: TArg): bigint { + if (merkleRoot === undefined) return _0n; + const x = pointToBytes(point); + const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot)); + // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: "if t >= SECP256K1_ORDER: + // raise ValueError". TapTweak must reject overflow instead of reducing modulo n. + if (!Pointk1.Fn.isValid(t)) throw new Error('invalid TapTweak hash'); + return t; +} +function frostPubToEvenY(pub: TArg): TRet { + const VK = Pointk1.fromBytes(pub.commitments[0]); + // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning. + if (hasEven(VK.y)) return pub as TRet; + return { + signers: { min: pub.signers.min, max: pub.signers.max }, + commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()), + verifyingShares: Object.fromEntries( + Object.entries(pub.verifyingShares).map(([k, v]) => [ + k, + Pointk1.fromBytes(v).negate().toBytes(), + ]) + ), + } as TRet; +} +function frostSecretToEvenY(s: TArg, pub: TArg): TRet { + const VK = Pointk1.fromBytes(pub.commitments[0]); + // Keep aliasing on the already-even path so wrapper callers can preserve package identity. + if (hasEven(VK.y)) return s as TRet; + const Fn = Pointk1.Fn; + return { + ...s, + signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))), + } as TRet; +} +function frostNoncesToEvenY(PK: PointType, nonces: TArg): TRet { + if (hasEven(PK.y)) return nonces as TRet; + const Fn = Pointk1.Fn; + return { + binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))), + hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))), + } as TRet; +} + +function frostTweakSecret( + s: TArg, + pub: TArg, + merkleRoot?: TArg +): TRet { + const Fn = Pointk1.Fn; + const keyPackage = frostSecretToEvenY(s, pub); + const evenPub = frostPubToEvenY(pub); + const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot); + const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t)); + return { + identifier: keyPackage.identifier, + signingShare, + } as TRet; +} + +function frostTweakPublic( + pub: TArg, + merkleRoot?: TArg +): TRet { + const PKPackage = frostPubToEvenY(pub); + const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot); + const tp = Pointk1.BASE.multiply(t); + const commitments = PKPackage.commitments.map((c, i) => + (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes() + ); + const verifyingShares: Record = {}; + for (const k in PKPackage.verifyingShares) { + verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes(); + } + return { + signers: { min: PKPackage.signers.min, max: PKPackage.signers.max }, + commitments, + verifyingShares, + } as TRet; +} + +/** + * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591. + * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while + * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves. + * @example + * Create one trusted-dealer package for Taproot-compatible FROST signing. + * + * ```ts + * const alice = schnorr_FROST.Identifier.derive('alice@example.com'); + * const bob = schnorr_FROST.Identifier.derive('bob@example.com'); + * const carol = schnorr_FROST.Identifier.derive('carol@example.com'); + * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]); + * ``` + */ +export const schnorr_FROST: TRet = /* @__PURE__ */ (() => + createFROST({ + name: 'FROST-secp256k1-SHA256-TR-v1', + Point: Pointk1, + hashToScalar: secp256k1_hasher.hashToScalar, + hash: sha256, + // Taproot related hacks + parsePublicKey(publicKey) { + // External Taproot keys are x-only, but local key packages still use compressed points. + if (publicKey.length === 32) return lift_x(bytesToNumberBE(publicKey)); + if (publicKey.length === 33) return Pointk1.fromBytes(publicKey); + throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`); + }, + adjustScalar(n: bigint) { + const PK = Pointk1.BASE.multiply(n); + return hasEven(PK.y) ? n : Pointk1.Fn.neg(n); + }, + adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()), + challenge(R, PK, msg) { + return challenge(pointToBytes(R), pointToBytes(PK), msg); + }, + adjustNonces: frostNoncesToEvenY, + adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare), + adjustPublic: frostPubToEvenY, + adjustSecret: frostSecretToEvenY, + adjustTx: { + // Compat with official implementation + encode: (tx) => tx.subarray(1) as TRet, + decode: (tx) => concatBytes(Uint8Array.of(0x02), tx) as TRet, + }, + adjustDKG: (k) => { + // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the + // empty Taproot merkle root, while dealer-generated keys stay untweaked. + const merkleRoot = new Uint8Array(0); + return { + public: frostTweakPublic(k.public, merkleRoot), + secret: frostTweakSecret(k.secret, k.public, merkleRoot), + }; + }, + }))(); diff --git a/node_modules/@noble/curves/src/utils.ts b/node_modules/@noble/curves/src/utils.ts new file mode 100644 index 0000000..beec9db --- /dev/null +++ b/node_modules/@noble/curves/src/utils.ts @@ -0,0 +1,808 @@ +/** + * Hex, bytes and number utilities. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { + 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'; +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array + ? BigInt64Array + : T extends BigUint64Array + ? BigUint64Array + : T extends Float32Array + ? Float32Array + : T extends Float64Array + ? Float64Array + : T extends Int16Array + ? Int16Array + : T extends Int32Array + ? Int32Array + : T extends Int8Array + ? Int8Array + : T extends Uint16Array + ? Uint16Array + : T extends Uint32Array + ? Uint32Array + : T extends Uint8ClampedArray + ? Uint8ClampedArray + : T extends Uint8Array + ? Uint8Array + : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array + ? ReturnType + : T extends BigUint64Array + ? ReturnType + : T extends Float32Array + ? ReturnType + : T extends Float64Array + ? ReturnType + : T extends Int16Array + ? ReturnType + : T extends Int32Array + ? ReturnType + : T extends Int8Array + ? ReturnType + : T extends Uint16Array + ? ReturnType + : T extends Uint32Array + ? ReturnType + : T extends Uint8ClampedArray + ? ReturnType + : T extends Uint8Array + ? ReturnType + : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = + | T + | ([TypedArg] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TRet }) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; + } + : T extends [infer A, ...infer R] + ? [TArg, ...{ [K in keyof R]: TArg }] + : T extends readonly [infer A, ...infer R] + ? readonly [TArg, ...{ [K in keyof R]: TArg }] + : T extends (infer A)[] + ? TArg[] + : T extends readonly (infer A)[] + ? readonly TArg[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TArg } + : T + : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown + ? T & + ([TypedRet] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TArg }) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; + } + : T extends [infer A, ...infer R] + ? [TRet, ...{ [K in keyof R]: TRet }] + : T extends readonly [infer A, ...infer R] + ? readonly [TRet, ...{ [K in keyof R]: TRet }] + : T extends (infer A)[] + ? TRet[] + : T extends readonly (infer A)[] + ? readonly TRet[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TRet } + : T + : TypedRet) + : never; +/** + * Validates that a value is a byte array. + * @param value - Value to validate. + * @param length - Optional exact byte length. + * @param title - Optional field name. + * @returns Original byte array. + * @example + * Reject non-byte input before passing data into curve code. + * + * ```ts + * abytes(new Uint8Array(1)); + * ``` + */ +export const abytes = >(value: T, length?: number, title?: string): T => + abytes_(value, length, title) as T; +/** + * Validates that a value is a non-negative safe integer. + * @param n - Value to validate. + * @param title - Optional field name. + * @example + * Validate a numeric length before allocating buffers. + * + * ```ts + * anumber(1); + * ``` + */ +export const anumber: typeof anumber_ = anumber_; +/** + * Encodes bytes as lowercase hex. + * @param bytes - Bytes to encode. + * @returns Lowercase hex string. + * @example + * Serialize bytes as hex for logging or fixtures. + * + * ```ts + * bytesToHex(Uint8Array.of(1, 2, 3)); + * ``` + */ +export const bytesToHex: typeof bytesToHex_ = bytesToHex_; +/** + * Concatenates byte arrays. + * @param arrays - Byte arrays to join. + * @returns Concatenated bytes. + * @example + * Join domain-separated chunks into one buffer. + * + * ```ts + * concatBytes(Uint8Array.of(1), Uint8Array.of(2)); + * ``` + */ +export const concatBytes = (...arrays: TArg): TRet => + concatBytes_(...arrays) as TRet; +/** + * Decodes lowercase or uppercase hex into bytes. + * @param hex - Hex string to decode. + * @returns Decoded bytes. + * @example + * Parse fixture hex into bytes before hashing. + * + * ```ts + * hexToBytes('0102'); + * ``` + */ +export const hexToBytes = (hex: string): TRet => hexToBytes_(hex) as TRet; +/** + * Checks whether a value is a Uint8Array. + * @param a - Value to inspect. + * @returns `true` when `a` is a Uint8Array. + * @example + * Branch on byte input before decoding it. + * + * ```ts + * isBytes(new Uint8Array(1)); + * ``` + */ +export const isBytes: typeof isBytes_ = isBytes_; +/** + * Reads random bytes from the platform CSPRNG. + * @param bytesLength - Number of random bytes to read. + * @returns Fresh random bytes. + * @example + * Generate a random seed for a keypair. + * + * ```ts + * randomBytes(2); + * ``` + */ +export const randomBytes = (bytesLength?: number): TRet => + randomBytes_(bytesLength) as TRet; +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); + +/** Callable hash interface with metadata and optional extendable output support. */ +export type CHash = { + /** + * Hash one message. + * @param message - Message bytes to hash. + * @returns Digest bytes. + */ + (message: TArg): TRet; + /** Hash block length in bytes. */ + blockLen: number; + /** Default output length in bytes. */ + outputLen: number; + /** Whether `.create()` can be used as an XOF stream. */ + canXOF: boolean; + /** + * Create one stateful hash or XOF instance, for example SHAKE with a custom output length. + * @param opts - Optional extendable-output configuration: + * - `dkLen` (optional): Optional output length for XOF-style hashes. + * @returns Hash instance. + */ + create(opts?: { dkLen?: number }): any; +}; +/** Plain callable hash interface. */ +export type FHash = (message: TArg) => TRet; +/** HMAC callback signature. */ +export type HmacFn = (key: TArg, message: TArg) => TRet; +/** + * Validates that a flag is boolean. + * @param value - Value to validate. + * @param title - Optional field name. + * @returns Original value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Reject non-boolean option flags early. + * + * ```ts + * abool(true); + * ``` + */ +export function abool(value: boolean, title: string = ''): boolean { + if (typeof value !== 'boolean') { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + 'expected boolean, got type=' + typeof value); + } + return value; +} + +/** + * Validates that a value is a non-negative bigint or safe integer. + * @param n - Value to validate. + * @returns The same validated value. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate one integer-like value before serializing it. + * + * ```ts + * abignumber(1n); + * ``` + */ +export function abignumber(n: T): T { + if (typeof n === 'bigint') { + if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n); + } else anumber(n); + return n; +} + +/** + * Validates that a value is a safe integer. + * @param value - Integer to validate. + * @param title - Optional field name. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a window size before scalar arithmetic uses it. + * + * ```ts + * asafenumber(1); + * ``` + */ +export function asafenumber(value: number, title: string = ''): void { + if (typeof value !== 'number') { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + 'expected number, got type=' + typeof value); + } + if (!Number.isSafeInteger(value)) { + const prefix = title && `"${title}" `; + throw new RangeError(prefix + 'expected safe integer, got ' + value); + } +} + +/** + * Encodes a bigint into even-length big-endian hex. + * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still + * gets one leading zero nibble so the result always represents whole bytes. + * @param num - Number to encode. + * @returns Big-endian hex string. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Encode a scalar into hex without a `0x` prefix. + * + * ```ts + * numberToHexUnpadded(255n); + * ``` + */ +export function numberToHexUnpadded(num: number | bigint): string { + const hex = abignumber(num).toString(16); + return hex.length & 1 ? '0' + hex : hex; +} + +/** + * Parses a big-endian hex string into bigint. + * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the + * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error. + * @param hex - Hex string without `0x`. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parse a scalar from fixture hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex); + return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian +} + +// BE: Big Endian, LE: Little Endian +/** + * Parses big-endian bytes into bigint. + * @param bytes - Bytes in big-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in network byte order. + * + * ```ts + * bytesToNumberBE(Uint8Array.of(1, 0)); + * ``` + */ +export function bytesToNumberBE(bytes: TArg): bigint { + return hexToNumber(bytesToHex_(bytes)); +} +/** + * Parses little-endian bytes into bigint. + * @param bytes - Bytes in little-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in little-endian form. + * + * ```ts + * bytesToNumberLE(Uint8Array.of(1, 0)); + * ``` + */ +export function bytesToNumberLE(bytes: TArg): bigint { + return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse())); +} + +/** + * Encodes a bigint into fixed-length big-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. Must be greater than zero. + * @returns Big-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar into a 32-byte field element. + * + * ```ts + * numberToBytesBE(255n, 2); + * ``` + */ +export function numberToBytesBE(n: number | bigint, len: number): TRet { + anumber_(len); + if (len === 0) throw new RangeError('zero length'); + n = abignumber(n); + const hex = n.toString(16); + // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error. + if (hex.length > len * 2) throw new RangeError('number too large'); + return hexToBytes_(hex.padStart(len * 2, '0')) as TRet; +} +/** + * Encodes a bigint into fixed-length little-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Little-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar for little-endian protocols. + * + * ```ts + * numberToBytesLE(255n, 2); + * ``` + */ +export function numberToBytesLE(n: number | bigint, len: number): TRet { + return numberToBytesBE(n, len).reverse() as TRet; +} +// Unpadded, rarely used +/** + * Encodes a bigint into variable-length big-endian bytes. + * @param n - Number to encode. + * @returns Variable-length big-endian bytes. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a bigint without fixed-width padding. + * + * ```ts + * numberToVarBytesBE(255n); + * ``` + */ +export function numberToVarBytesBE(n: number | bigint): TRet { + return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet; +} + +// Compares 2 u8a-s in kinda constant time +/** + * Compares two byte arrays in constant-ish time. + * @param a - Left byte array. + * @param b - Right byte array. + * @returns `true` when bytes match. + * @example + * Compare two encoded points without early exit. + * + * ```ts + * equalBytes(Uint8Array.of(1), Uint8Array.of(1)); + * ``` + */ +export function equalBytes(a: TArg, b: TArg): boolean { + a = abytes(a); + b = abytes(b); + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; + return diff === 0; +} + +/** + * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer, + * and Buffer#slice creates mutable copy. Never use Buffers! + * @param bytes - Bytes to copy. + * @returns Detached copy. + * @example + * Make an isolated copy before mutating serialized bytes. + * + * ```ts + * copyBytes(Uint8Array.of(1, 2, 3)); + * ``` + */ +export function copyBytes(bytes: TArg): TRet { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)) as TRet; +} + +/** + * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols + * Should be safe to use for things expected to be ASCII. + * Returns exact same result as `TextEncoder` for ASCII or throws. + * @param ascii - ASCII input text. + * @returns Encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode an ASCII domain-separation tag. + * + * ```ts + * asciiToBytes('ABC'); + * ``` + */ +export function asciiToBytes(ascii: string): TRet { + if (typeof ascii !== 'string') throw new TypeError('ascii string expected, got ' + typeof ascii); + return Uint8Array.from(ascii, (c, i) => { + const charCode = c.charCodeAt(0); + if (c.length !== 1 || charCode > 127) { + throw new RangeError( + `string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}` + ); + } + return charCode; + }) as TRet; +} + +// Historical name: this accepts non-negative bigints, including zero. +const isPosBig = (n: bigint) => typeof n === 'bigint' && _0n <= n; + +/** + * Checks whether a bigint lies inside a half-open range. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * @returns `true` when the value is inside the range. + * @example + * Check whether a candidate scalar fits the field order. + * + * ```ts + * inRange(2n, 1n, 3n); + * ``` + */ +export function inRange(n: bigint, min: bigint, max: bigint): boolean { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} + +/** + * Asserts `min <= n < max`. NOTE: upper bound is exclusive. + * @param title - Value label for error messages. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * Wrong-type inputs are not separated from out-of-range values here: they still flow through the + * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Assert that a bigint stays within one half-open range. + * + * ```ts + * aInRange('x', 2n, 1n, 256n); + * ``` + */ +export function aInRange(title: string, n: bigint, min: bigint, max: bigint): void { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n); +} + +// Bit operations + +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + * TODO: merge with nLength in modular + * @param n - Value to inspect. + * @returns Bit length. + * @throws If the value is negative. {@link Error} + * @example + * Measure the bit length of a scalar before serialization. + * + * ```ts + * bitLen(8n); + * ``` + */ +export function bitLen(n: bigint): number { + // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a + // contract bug and must not silently collapse to zero bits. + if (n < _0n) throw new Error('expected non-negative bigint, got ' + n); + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1); + return len; +} + +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw + * bigint shift semantics; because the mask is built as `1n << pos`, + * they currently collapse to `0n` and make the helper a no-op. + * @returns Bit as bigint. + * @example + * Gets single bit at position. + * + * ```ts + * bitGet(5n, 0); + * ``` + */ +export function bitGet(n: bigint, pos: number): bigint { + return (n >> BigInt(pos)) & _1n; +} + +/** + * Sets single bit at position. + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics, + * so they currently behave like left shifts. + * @param value - Whether the bit should be set. + * @returns Updated bigint. + * @example + * Sets single bit at position. + * + * ```ts + * bitSet(0n, 1, true); + * ``` + */ +export function bitSet(n: bigint, pos: number, value: boolean): bigint { + const mask = _1n << BigInt(pos); + // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched. + return value ? n | mask : n & ~mask; +} + +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift + * semantics and therefore produce `-1n`. + * @returns Bitmask value. + * @example + * Calculate mask for N bits. + * + * ```ts + * bitMask(4); + * ``` + */ +export const bitMask = (n: number): bigint => (_1n << BigInt(n)) - _1n; + +// DRBG + +type Pred = (v: TArg) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0` + * is not rejected here and would make the internal generate loop non-progressing. + * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length. + * @param hmacFn - HMAC implementation. + * @returns Function that will call DRBG until the predicate returns anything + * other than `undefined`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Build a deterministic nonce generator for RFC6979-style signing. + * + * ```ts + * import { createHmacDrbg } from '@noble/curves/utils.js'; + * import { hmac } from '@noble/hashes/hmac.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg)); + * const seed = new Uint8Array(32); + * drbg(seed, (bytes) => bytes); + * ``` + */ +export function createHmacDrbg( + hashLen: number, + qByteLen: number, + hmacFn: TArg +): TRet<(seed: Uint8Array, predicate: Pred) => T> { + anumber_(hashLen, 'hashLen'); + anumber_(qByteLen, 'qByteLen'); + if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function'); + // creates Uint8Array + const u8n = (len: number): TRet => new Uint8Array(len) as TRet; + const NULL = Uint8Array.of(); + const byte0 = Uint8Array.of(0x00); + const byte1 = Uint8Array.of(0x01); + const _maxDrbgIters = 1000; + + // Step B, Step C: set hashLen to 8*ceil(hlen/8). + // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures. + let v: Uint8Array = u8n(hashLen); + // Steps B and C of RFC6979 3.2. + let k: Uint8Array = u8n(hashLen); + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + // hmac(k)(v, ...values) + const h = (...msgs: TArg) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs)); + const reseed = (seed: TArg = NULL) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) return; + k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= _maxDrbgIters) throw new Error('drbg: tried max amount of iterations'); + let len = 0; + const out: Uint8Array[] = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed: TArg, pred: TArg>): T => { + reset(); + reseed(seed); // Steps D-G + let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate. + // Falsy values like 0 are valid outputs. + while ((res = (pred as Pred)(gen())) === undefined) reseed(); + reset(); + return res; + }; + return genUntil as TRet<(seed: Uint8Array, predicate: Pred) => T>; +} + +/** + * Validates declared required and optional field types on a plain object. + * Extra keys are intentionally ignored because many callers validate only the subset they use from + * richer option bags or runtime objects. + * @param object - Object to validate. + * @param fields - Required field types. + * @param optFields - Optional field types. + * @throws On wrong argument types. {@link TypeError} + * @example + * Check user options before building a curve helper. + * + * ```ts + * validateObject({ flag: true }, { flag: 'boolean' }); + * ``` + */ +export function validateObject( + object: Record, + fields: Record = {}, + optFields: Record = {} +): void { + if (Object.prototype.toString.call(object) !== '[object Object]') + throw new TypeError('expected valid options object'); + type Item = keyof typeof object; + function checkField(fieldName: Item, expectedType: string, isOpt: boolean) { + // Config/data fields must be explicit own properties, but runtime objects such as Field + // instances intentionally satisfy required method slots via their shared prototype. + if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName)) + throw new TypeError(`param "${fieldName}" is invalid: expected own property`); + const val = object[fieldName]; + if (isOpt && val === undefined) return; + const current = typeof val; + if (current !== expectedType || val === null) + throw new TypeError( + `param "${fieldName}" is invalid: expected ${expectedType}, got ${current}` + ); + } + const iter = (f: typeof fields, isOpt: boolean) => + Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)); + iter(fields, false); + iter(optFields, true); +} + +/** + * Throws not implemented error. + * @returns Never returns. + * @throws If the unfinished code path is reached. {@link Error} + * @example + * Surface the placeholder error from an unfinished code path. + * + * ```ts + * try { + * notImplemented(); + * } catch {} + * ``` + */ +export const notImplemented = (): never => { + throw new Error('not implemented'); +}; + +/** Generic keygen/getPublicKey interface shared by curve helpers. */ +export interface CryptoKeys { + /** Public byte lengths for keys and optional seeds. */ + lengths: { seed?: number; public?: number; secret?: number }; + /** + * Generate one secret/public keypair. + * @param seed - Optional seed bytes for deterministic key generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array }; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: Uint8Array) => Uint8Array; +} + +/** Generic interface for signatures. Has keygen, sign and verify. */ +export interface Signer extends CryptoKeys { + // Interfaces are fun. We cannot just add new fields without copying old ones. + /** Public byte lengths for keys, signatures, and optional signing randomness. */ + lengths: { + seed?: number; + public?: number; + secret?: number; + signRand?: number; + signature?: number; + }; + /** + * Sign one message. + * @param msg - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @returns Signature bytes. + */ + sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array; + /** + * Verify one signature. + * @param sig - Signature bytes. + * @param msg - Signed message bytes. + * @param publicKey - Public key bytes. + * @returns `true` when the signature is valid. + */ + verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean; +} diff --git a/node_modules/@noble/curves/src/webcrypto.ts b/node_modules/@noble/curves/src/webcrypto.ts new file mode 100644 index 0000000..b30755c --- /dev/null +++ b/node_modules/@noble/curves/src/webcrypto.ts @@ -0,0 +1,632 @@ +/** + * Friendly wrapper over elliptic curves from built-in WebCrypto. Experimental: API may change. + +# WebCrypto issues + +## No way to get public keys + +- Export of raw secret key is prohibited by spec: + - https://w3c.github.io/webcrypto/#ecdsa-operations-export-key + -> "If format is "raw":" -> "If the [[type]] internal slot of key is not "public", + then throw an InvalidAccessError." +- Import of raw secret keys is prohibited by spec: + - https://w3c.github.io/webcrypto/#ecdsa-operations-import-key + -> "If format is "raw":" -> "If usages contains a value which is not "verify" + then throw a SyntaxError." +- SPKI (Simple public-key infrastructure) is public-key-only +- PKCS8 is secret-key-only +- No way to get public key from secret key, but we convert to JWK and then + create it manually, since a JWK secret key includes both private and public + parts. +- Noble supports generating keys for both sign, verify & getSharedSecret, + but JWK key includes usage, which forces us to patch it (non-JWK is ok) +- We have import/export for 'raw', but it doesn't work in Firefox / Safari + +## Point encoding + +- Raw export of public points returns uncompressed points, + but this is implementation specific and not much we can do there. +- `getSharedSecret` differs for p256, p384, p521: + Noble returns 33-byte output (y-parity + x coordinate), + while in WebCrypto returns 32-byte output (x coordinate). + This is intentional: noble keeps the full encoded shared point, and x-only + callers can slice it down themselves. +- `getSharedSecret` identical for X25519, X448 + +## Availability + +Node.js additionally supports ed448. +There seems no reasonable way to check for availability, other than actually calling methods. + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { TArg, TRet } from './utils.ts'; + +/** Raw type */ +const TYPE_RAW = 'raw'; +const TYPE_JWK = 'jwk'; +const TYPE_SPKI = 'spki'; +const TYPE_PKCS = 'pkcs8'; +/** Key serialization formats supported by the WebCrypto wrappers. */ +export type WebCryptoFormat = + | typeof TYPE_RAW + | typeof TYPE_JWK + | typeof TYPE_SPKI + | typeof TYPE_PKCS; +/** WebCrypto keys can be in raw, jwk, pkcs8/spki formats. Raw is internal and fragile. */ +export type WebCryptoOpts = { + /** Preferred secret-key serialization format. */ + formatSec?: WebCryptoFormat; + /** Preferred public-key serialization format. */ + formatPub?: WebCryptoFormat; +}; +// default formats +const dfsec = TYPE_PKCS; +const dfpub = TYPE_SPKI; + +function getSubtle(): any { + const s: any = globalThis?.crypto?.subtle; + if (typeof s === 'object' && s != null) return s; + throw new Error('crypto.subtle must be defined'); +} + +function createKeygenA( + randomSecretKey: any, + getPublicKey: any +): TRet<(seed?: Uint8Array) => Promise<{ secretKey: Uint8Array; publicKey: Uint8Array }>> { + // Runtime accepts an accidental `keygen(seed)` argument for parity with other wrappers, but the + // seed is intentionally ignored because WebCrypto keygen here always goes through fresh keygen. + return async function keygenA(_seed?: TArg) { + const secretKey = (await randomSecretKey()) as TRet; + return { secretKey, publicKey: (await getPublicKey(secretKey)) as TRet }; + }; +} + +// Internal helper only: strict hex parser for the local hardcoded PKCS8 header constants. +function hexToBytesLocal(hex: string): TRet { + const pairs = hex.match(/[0-9a-f]{2}/gi); + if (!pairs || pairs.length * 2 !== hex.length) throw new Error('invalid hex'); + return Uint8Array.from(pairs, (b) => Number.parseInt(b, 16)) as TRet; +} + +export const __TEST: { hexToBytesLocal: typeof hexToBytesLocal } = /* @__PURE__ */ Object.freeze({ + hexToBytesLocal, +}); + +// Trying to do generics here creates hell on conversion and usage +type JsonWebKey = { + crv?: string; + d?: string; + kty?: string; + x?: string; + y?: string; + [key: string]: unknown; +}; +type Key = JsonWebKey | Uint8Array; +type CryptoKey = Awaited>; +type KeyUsage = 'deriveBits' | 'deriveKey' | 'sign' | 'verify'; +type Algo = string | { name: string; namedCurve: string }; +type SigAlgo = string | { name: string; hash?: { name: string } }; + +type KeyUtils = { + import(key: TArg, format?: WebCryptoFormat): Promise; + export(key: CryptoKey, format?: WebCryptoFormat): TRet>; + convert( + key: TArg, + inFormat?: WebCryptoFormat, + outFormat?: WebCryptoFormat + ): TRet>; +}; + +function assertType(type: 'private' | 'public', key: any) { + // Callers are expected to pass a non-null key-like object; `null` / `undefined` still fail first + // via property access before reaching the explicit wrapper error. + if (key.type !== type) throw new Error(`invalid key type, expected ${type}`); +} + +function createKeyUtils(algo: Algo, derive: boolean, keyLen: number, pkcs8header: string) { + const secUsage: KeyUsage[] = derive ? ['deriveBits'] : ['sign']; + const pubUsage: KeyUsage[] = derive ? [] : ['verify']; + // Return Uint8Array instead of ArrayBuffer + const arrBufToU8 = (res: TArg, format: WebCryptoFormat): TRet => + (format === TYPE_JWK + ? (res as JsonWebKey) + : new Uint8Array(res as unknown as ArrayBuffer)) as TRet; + const pub: KeyUtils = { + async import(key: TArg, format: WebCryptoFormat): Promise { + // For sign/verify wrappers we pass caller-provided JWK metadata through unchanged and let + // WebCrypto enforce mismatched `key_ops` / extractability instead of normalizing it here. + const keyi: CryptoKey = await getSubtle().importKey(format, key, algo, true, pubUsage); + assertType('public', keyi); + return keyi; + }, + async export(key: CryptoKey, format: WebCryptoFormat): Promise> { + assertType('public', key); + const keyi = await getSubtle().exportKey(format, key); + return arrBufToU8(keyi, format); + }, + async convert( + key: TArg, + inFormat: WebCryptoFormat, + outFormat: WebCryptoFormat + ): Promise> { + return pub.export(await pub.import(key, inFormat), outFormat); + }, + }; + const priv: KeyUtils = { + async import(key: TArg, format: WebCryptoFormat): Promise { + const crypto = getSubtle(); + let keyi: CryptoKey; + if (format === TYPE_RAW) { + // Chrome, node, bun, deno: works + // Safari, Firefox: Data provided to an operation does not meet requirements + // This is the best one can do. JWK can't be used: it contains public key component inside. + const k = key as Uint8Array; + const head = hexToBytesLocal(pkcs8header); + const all = new Uint8Array(head.length + k.length); + all.set(head, 0); + all.set(k, head.length); + + keyi = await crypto.importKey(TYPE_PKCS, all, algo, true, secUsage); + } else { + // Sign/verify wrappers keep caller JWK metadata as-is and assume the supplied `key_ops` + // already match the requested operation. ECDH is different: noble treats the same key + // material as usable for both sign and derive, so JWK imported through the derive path + // must rewrite `key_ops` or WebCrypto refuses otherwise-correct keys exported by keygen. + if (derive && format === TYPE_JWK) key = { ...key, key_ops: secUsage }; + keyi = await crypto.importKey(format, key, algo, true, secUsage); + } + assertType('private', keyi); + return keyi; + }, + async export(key: CryptoKey, format: WebCryptoFormat): Promise> { + const crypto = getSubtle(); + assertType('private', key); + if (format === TYPE_RAW) { + // scure-base base64urlnopad could have been used, but we can't add more deps. + // pkcs8 would be even more fragile + const jwk = await crypto.exportKey(TYPE_JWK, key); + const base64 = jwk.d.replace(/-/g, '+').replace(/_/g, '/'); // base64url + const pad = base64.length % 4 ? '='.repeat(4 - (base64.length % 4)) : ''; // add padding + const binary = atob(base64 + pad); + // This is not ASCII, and not text: this is only semi-safe with atob output + const raw = Uint8Array.from(binary, (c) => c.charCodeAt(0)); + // Pad key to key len because Bun strips leading zero for P-521 only + const res = new Uint8Array(keyLen); + res.set(raw, keyLen - raw.length); + return res as TRet; + } + const keyi = await crypto.exportKey(format, key); + return arrBufToU8(keyi, format); + }, + async convert( + key: TArg, + inFormat: WebCryptoFormat, + outFormat: WebCryptoFormat + ): Promise> { + return priv.export(await priv.import(key, inFormat), outFormat); + }, + }; + async function getPublicKey( + secretKey: TArg, + opts: TArg = {} + ): Promise> { + const fsec = opts.formatSec ?? dfsec; + const fpub = opts.formatPub ?? dfpub; + // Export to jwk, remove private scalar and then convert to format + const jwk = ( + fsec === TYPE_JWK ? { ...secretKey } : await priv.convert(secretKey, fsec, TYPE_JWK) + ) as JsonWebKey; + delete jwk.d; + jwk.key_ops = pubUsage; + if (fpub === TYPE_JWK) return jwk as TRet; + return pub.convert(jwk, TYPE_JWK, fpub); + } + async function randomSecretKey(format: WebCryptoFormat = dfsec): Promise> { + const keyPair = await getSubtle().generateKey(algo, true, secUsage); + return priv.export(keyPair.privateKey, format); + } + // Key generation could be slow, so we cache result once. + let supported: boolean | undefined; + return { + pub: pub as KeyUtils, + priv: priv as KeyUtils, + async isSupported(): Promise { + if (supported !== undefined) return supported; + try { + const crypto = getSubtle(); + const key = await crypto.generateKey(algo, true, secUsage); + // Deno is broken and generates key for unsupported curves, but then fails on export + await priv.export(key.privateKey, TYPE_JWK); + // Bun fails on derive for x25519, but not x448 + if (derive) { + await crypto.deriveBits( + { name: typeof algo === 'string' ? algo : algo.name, public: key.publicKey }, + key.privateKey, + 8 + ); + } + return (supported = true); + } catch (e) { + return (supported = false); + } + }, + getPublicKey, + keygen: createKeygenA(randomSecretKey, getPublicKey), + utils: Object.freeze({ + randomSecretKey, + // Runtime expects both formats explicitly here; omitted formats just flow into + // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`). + convertPublicKey: pub.convert as KeyUtils['convert'], + // Runtime expects both formats explicitly here; omitted formats just flow into + // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`). + convertSecretKey: priv.convert as KeyUtils['convert'], + }), + }; +} + +function createSigner( + keys: ReturnType, + algo: SigAlgo +): TRet { + return { + // Historical param name: wrappers pass message bytes here, while WebCrypto performs the + // algorithm-specific hashing itself for ECDSA. We also return provider signatures verbatim: + // this wrapper is intentionally "raw WebCrypto", so it does not parse scalars or normalize + // high-S ECDSA outputs into software noble's low-S convention. + async sign( + msgHash: TArg, + secretKey: TArg, + opts: TArg = {} + ): Promise> { + const key = await keys.priv.import(secretKey, opts.formatSec ?? dfsec); + const sig = await getSubtle().sign(algo, key, msgHash); + return new Uint8Array(sig) as TRet; + }, + async verify( + signature: TArg, + msgHash: TArg, + publicKey: TArg, + opts: TArg = {} + ): Promise { + const key = await keys.pub.import(publicKey, opts.formatPub ?? dfpub); + return await getSubtle().verify(algo, key, signature, msgHash); + }, + }; +} + +function createECDH( + keys: ReturnType, + algo: Algo, + keyLen: number +): TRet { + return { + // Runtime accepts the alternate key formats supported by `keys.import(...)`; the public type is + // still narrower than that accepted surface. + async getSharedSecret( + secretKeyA: TArg, + publicKeyB: TArg, + opts: TArg = {} + ): Promise> { + // if (_isCompressed !== true) throw new Error('WebCrypto only supports compressed keys'); + const secKey = await keys.priv.import( + secretKeyA, + opts.formatSec === undefined ? dfsec : opts.formatSec + ); + const pubKey = await keys.pub.import( + publicKeyB, + opts.formatPub === undefined ? dfpub : opts.formatPub + ); + const shared = await getSubtle().deriveBits( + { name: typeof algo === 'string' ? algo : algo.name, public: pubKey }, + secKey, + 8 * keyLen + ); + return new Uint8Array(shared) as TRet; + }, + }; +} + +type WebCryptoBaseCurve = { + name: string; + isSupported(): Promise; + keygen(): TRet>; + getPublicKey(secretKey: TArg, opts?: TArg): TRet>; + utils: { + randomSecretKey: (format?: WebCryptoFormat) => TRet>; + convertSecretKey: ( + key: TArg, + inFormat?: WebCryptoFormat, + outFormat?: WebCryptoFormat + ) => TRet>; + convertPublicKey: ( + key: TArg, + inFormat?: WebCryptoFormat, + outFormat?: WebCryptoFormat + ) => TRet>; + }; +}; + +// Specific per-curve methods - no reason to export them; we can't "add" a new curve +/** WebCrypto signing interface shared by ECDSA and EdDSA helpers. */ +export type WebCryptoSigner = { + /** + * Sign one message with a WebCrypto-backed private key. + * @param message - Message bytes to sign. + * @param secretKey - Secret key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns Signature bytes. + */ + sign( + message: TArg, + secretKey: TArg, + opts?: TArg + ): TRet>; + /** + * Verify one signature with a WebCrypto-backed public key. + * @param signature - Signature bytes. + * @param message - Signed message bytes. + * @param publicKey - Public key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns `true` when the signature is valid. + */ + verify( + signature: TArg, + message: TArg, + publicKey: TArg, + opts?: TArg + ): Promise; +}; +/** WebCrypto ECDH interface for shared-secret derivation. */ +export type WebCryptoECDH = { + /** + * Derive one shared secret from a local secret key and peer public key. + * Short-Weierstrass wrappers return the raw x-coordinate here, not noble's parity-prefixed + * shared-point encoding. Runtime also accepts alternate key formats through `opts`, even though + * this public type is still narrowed to byte arrays. + * @param secA - Local secret key in one supported format. + * @param pubB - Peer public key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns Shared secret bytes. + */ + getSharedSecret( + secA: TArg, + pubB: TArg, + opts?: TArg + ): TRet>; +}; +/** WebCrypto ECDSA interface with keygen, signing, and ECDH helpers. */ +export type WebCryptoECDSA = WebCryptoBaseCurve & WebCryptoSigner & WebCryptoECDH; +/** WebCrypto EdDSA interface with keygen and signing helpers. */ +export type WebCryptoEdDSA = WebCryptoBaseCurve & WebCryptoSigner; +/** WebCrypto Montgomery interface with keygen and ECDH helpers. */ +export type WebCryptoMontgomery = WebCryptoBaseCurve & WebCryptoECDH; + +function wrapECDSA( + curve: 'P-256' | 'P-384' | 'P-521', + hash: string, + keyLen: number, + pkcs8header: string +): TRet { + const ECDH_ALGO = { name: 'ECDH', namedCurve: curve }; + const keys = createKeyUtils({ name: 'ECDSA', namedCurve: curve }, false, keyLen, pkcs8header); + const keysEcdh = createKeyUtils(ECDH_ALGO, true, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + // Support probing comes from the sign-side wrapper only; ECDH availability is not checked + // independently here even though the public wrapper also exposes `getSharedSecret(...)`. + isSupported: keys.isSupported, + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createSigner(keys, { name: 'ECDSA', hash: { name: hash } }), + ...createECDH(keysEcdh, ECDH_ALGO, keyLen), + utils: Object.freeze({ + ...keys.utils, + async convertSecretKey( + key: TArg, + inFormat?: WebCryptoFormat, + outFormat?: WebCryptoFormat + ): Promise> { + const jwk = inFormat === TYPE_JWK ? (key as JsonWebKey) : undefined; + // `wrapECDSA(...)` exposes the same key material for both sign and derive, so an ECDH-flavored + // JWK secret key from `getSharedSecret(...)` should still round-trip through `utils`. + if ( + Array.isArray(jwk?.key_ops) && + jwk.key_ops.length === 1 && + jwk.key_ops[0] === 'deriveBits' + ) + return keysEcdh.utils.convertSecretKey(key, inFormat, outFormat); + return keys.utils.convertSecretKey(key, inFormat, outFormat); + }, + }), + }); +} + +function wrapEdDSA( + curve: 'Ed25519' | 'Ed448', + keyLen: number, + pkcs8header: string +): TRet { + const keys = createKeyUtils(curve, false, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + isSupported: keys.isSupported, + // This wrapper intentionally re-exports the generic WebCrypto key-conversion/signing behavior + // without adding extra JWK-metadata or extractability guardrails of its own. + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createSigner(keys, { name: curve }), + utils: keys.utils, + }); +} + +function wrapMontgomery( + curve: 'X25519' | 'X448', + keyLen: number, + pkcs8header: string +): TRet { + const keys = createKeyUtils(curve, true, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + isSupported: keys.isSupported, + // This wrapper intentionally re-exports the generic ECDH key-format behavior without widening + // the narrow public `Uint8Array` key types. + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createECDH(keys, curve, keyLen), + utils: keys.utils, + }); +} + +/** + * Friendly wrapper over built-in WebCrypto NIST P-256 (secp256r1). + * Inherits the generic WebCrypto ECDSA caveats: `isSupported()` only probes the sign-side API, and + * the conversion/signing helpers keep the shared `createKeyUtils(...)` / `createSigner(...)` quirks, + * including raw WebCrypto ECDSA signatures without low-S normalization. + * @example + * Check support, then sign and verify once with WebCrypto P-256. + * + * ```ts + * if (await p256.isSupported()) { + * const { secretKey, publicKey } = await p256.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p256.sign(msg, secretKey); + * const isValid = await p256.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p256: TRet = /* @__PURE__ */ wrapECDSA( + 'P-256', + 'SHA-256', + 32, + '3041020100301306072a8648ce3d020106082a8648ce3d030107042730250201010420' +); + +/** + * Friendly wrapper over built-in WebCrypto NIST P-384 (secp384r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-384. + * + * ```ts + * if (await p384.isSupported()) { + * const { secretKey, publicKey } = await p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p384.sign(msg, secretKey); + * const isValid = await p384.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p384: TRet = /* @__PURE__ */ wrapECDSA( + 'P-384', + 'SHA-384', + 48, + '304e020100301006072a8648ce3d020106052b81040022043730350201010430' +); + +/** + * Friendly wrapper over built-in WebCrypto NIST P-521 (secp521r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-521. + * + * ```ts + * if (await p521.isSupported()) { + * const { secretKey, publicKey } = await p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p521.sign(msg, secretKey); + * const isValid = await p521.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p521: TRet = /* @__PURE__ */ wrapECDSA( + 'P-521', + 'SHA-512', + 66, + '3060020100301006072a8648ce3d020106052b81040023044930470201010442' +); + +/** + * Friendly wrapper over built-in WebCrypto ed25519. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed25519. + * + * ```ts + * if (await ed25519.isSupported()) { + * const { secretKey, publicKey } = await ed25519.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed25519.sign(msg, secretKey); + * const isValid = await ed25519.verify(sig, msg, publicKey); + * } + * ``` + */ +export const ed25519: TRet = /* @__PURE__ */ wrapEdDSA( + 'Ed25519', + 32, + '302e020100300506032b657004220420' +); + +/** + * Friendly wrapper over built-in WebCrypto ed448. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed448. + * + * ```ts + * if (await ed448.isSupported()) { + * const { secretKey, publicKey } = await ed448.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed448.sign(msg, secretKey); + * const isValid = await ed448.verify(sig, msg, publicKey); + * } + * ``` + */ +export const ed448: TRet = /* @__PURE__ */ wrapEdDSA( + 'Ed448', + 57, + '3047020100300506032b6571043b0439' +); + +/** + * Friendly wrapper over built-in WebCrypto x25519 (ECDH over Curve25519). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X25519. + * + * ```ts + * if (await x25519.isSupported()) { + * const alice = await x25519.keygen(); + * const bob = await x25519.keygen(); + * const shared = await x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export const x25519: TRet = /* @__PURE__ */ wrapMontgomery( + 'X25519', + 32, + '302e020100300506032b656e04220420' +); + +/** + * Friendly wrapper over built-in WebCrypto x448 (ECDH over Curve448). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X448. + * + * ```ts + * if (await x448.isSupported()) { + * const alice = await x448.keygen(); + * const bob = await x448.keygen(); + * const shared = await x448.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export const x448: TRet = /* @__PURE__ */ wrapMontgomery( + 'X448', + 56, + '3046020100300506032b656f043a0438' +); diff --git a/node_modules/@noble/curves/utils.d.ts b/node_modules/@noble/curves/utils.d.ts new file mode 100644 index 0000000..078e8d9 --- /dev/null +++ b/node_modules/@noble/curves/utils.d.ts @@ -0,0 +1,536 @@ +/** + * Hex, bytes and number utilities. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { anumber as anumber_, bytesToHex as bytesToHex_, isBytes as isBytes_ } from '@noble/hashes/utils.js'; +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +/** + * Validates that a value is a byte array. + * @param value - Value to validate. + * @param length - Optional exact byte length. + * @param title - Optional field name. + * @returns Original byte array. + * @example + * Reject non-byte input before passing data into curve code. + * + * ```ts + * abytes(new Uint8Array(1)); + * ``` + */ +export declare const abytes: >(value: T, length?: number, title?: string) => T; +/** + * Validates that a value is a non-negative safe integer. + * @param n - Value to validate. + * @param title - Optional field name. + * @example + * Validate a numeric length before allocating buffers. + * + * ```ts + * anumber(1); + * ``` + */ +export declare const anumber: typeof anumber_; +/** + * Encodes bytes as lowercase hex. + * @param bytes - Bytes to encode. + * @returns Lowercase hex string. + * @example + * Serialize bytes as hex for logging or fixtures. + * + * ```ts + * bytesToHex(Uint8Array.of(1, 2, 3)); + * ``` + */ +export declare const bytesToHex: typeof bytesToHex_; +/** + * Concatenates byte arrays. + * @param arrays - Byte arrays to join. + * @returns Concatenated bytes. + * @example + * Join domain-separated chunks into one buffer. + * + * ```ts + * concatBytes(Uint8Array.of(1), Uint8Array.of(2)); + * ``` + */ +export declare const concatBytes: (...arrays: TArg) => TRet; +/** + * Decodes lowercase or uppercase hex into bytes. + * @param hex - Hex string to decode. + * @returns Decoded bytes. + * @example + * Parse fixture hex into bytes before hashing. + * + * ```ts + * hexToBytes('0102'); + * ``` + */ +export declare const hexToBytes: (hex: string) => TRet; +/** + * Checks whether a value is a Uint8Array. + * @param a - Value to inspect. + * @returns `true` when `a` is a Uint8Array. + * @example + * Branch on byte input before decoding it. + * + * ```ts + * isBytes(new Uint8Array(1)); + * ``` + */ +export declare const isBytes: typeof isBytes_; +/** + * Reads random bytes from the platform CSPRNG. + * @param bytesLength - Number of random bytes to read. + * @returns Fresh random bytes. + * @example + * Generate a random seed for a keypair. + * + * ```ts + * randomBytes(2); + * ``` + */ +export declare const randomBytes: (bytesLength?: number) => TRet; +/** Callable hash interface with metadata and optional extendable output support. */ +export type CHash = { + /** + * Hash one message. + * @param message - Message bytes to hash. + * @returns Digest bytes. + */ + (message: TArg): TRet; + /** Hash block length in bytes. */ + blockLen: number; + /** Default output length in bytes. */ + outputLen: number; + /** Whether `.create()` can be used as an XOF stream. */ + canXOF: boolean; + /** + * Create one stateful hash or XOF instance, for example SHAKE with a custom output length. + * @param opts - Optional extendable-output configuration: + * - `dkLen` (optional): Optional output length for XOF-style hashes. + * @returns Hash instance. + */ + create(opts?: { + dkLen?: number; + }): any; +}; +/** Plain callable hash interface. */ +export type FHash = (message: TArg) => TRet; +/** HMAC callback signature. */ +export type HmacFn = (key: TArg, message: TArg) => TRet; +/** + * Validates that a flag is boolean. + * @param value - Value to validate. + * @param title - Optional field name. + * @returns Original value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Reject non-boolean option flags early. + * + * ```ts + * abool(true); + * ``` + */ +export declare function abool(value: boolean, title?: string): boolean; +/** + * Validates that a value is a non-negative bigint or safe integer. + * @param n - Value to validate. + * @returns The same validated value. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate one integer-like value before serializing it. + * + * ```ts + * abignumber(1n); + * ``` + */ +export declare function abignumber(n: T): T; +/** + * Validates that a value is a safe integer. + * @param value - Integer to validate. + * @param title - Optional field name. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a window size before scalar arithmetic uses it. + * + * ```ts + * asafenumber(1); + * ``` + */ +export declare function asafenumber(value: number, title?: string): void; +/** + * Encodes a bigint into even-length big-endian hex. + * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still + * gets one leading zero nibble so the result always represents whole bytes. + * @param num - Number to encode. + * @returns Big-endian hex string. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Encode a scalar into hex without a `0x` prefix. + * + * ```ts + * numberToHexUnpadded(255n); + * ``` + */ +export declare function numberToHexUnpadded(num: number | bigint): string; +/** + * Parses a big-endian hex string into bigint. + * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the + * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error. + * @param hex - Hex string without `0x`. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parse a scalar from fixture hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export declare function hexToNumber(hex: string): bigint; +/** + * Parses big-endian bytes into bigint. + * @param bytes - Bytes in big-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in network byte order. + * + * ```ts + * bytesToNumberBE(Uint8Array.of(1, 0)); + * ``` + */ +export declare function bytesToNumberBE(bytes: TArg): bigint; +/** + * Parses little-endian bytes into bigint. + * @param bytes - Bytes in little-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in little-endian form. + * + * ```ts + * bytesToNumberLE(Uint8Array.of(1, 0)); + * ``` + */ +export declare function bytesToNumberLE(bytes: TArg): bigint; +/** + * Encodes a bigint into fixed-length big-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. Must be greater than zero. + * @returns Big-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar into a 32-byte field element. + * + * ```ts + * numberToBytesBE(255n, 2); + * ``` + */ +export declare function numberToBytesBE(n: number | bigint, len: number): TRet; +/** + * Encodes a bigint into fixed-length little-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Little-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar for little-endian protocols. + * + * ```ts + * numberToBytesLE(255n, 2); + * ``` + */ +export declare function numberToBytesLE(n: number | bigint, len: number): TRet; +/** + * Encodes a bigint into variable-length big-endian bytes. + * @param n - Number to encode. + * @returns Variable-length big-endian bytes. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a bigint without fixed-width padding. + * + * ```ts + * numberToVarBytesBE(255n); + * ``` + */ +export declare function numberToVarBytesBE(n: number | bigint): TRet; +/** + * Compares two byte arrays in constant-ish time. + * @param a - Left byte array. + * @param b - Right byte array. + * @returns `true` when bytes match. + * @example + * Compare two encoded points without early exit. + * + * ```ts + * equalBytes(Uint8Array.of(1), Uint8Array.of(1)); + * ``` + */ +export declare function equalBytes(a: TArg, b: TArg): boolean; +/** + * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer, + * and Buffer#slice creates mutable copy. Never use Buffers! + * @param bytes - Bytes to copy. + * @returns Detached copy. + * @example + * Make an isolated copy before mutating serialized bytes. + * + * ```ts + * copyBytes(Uint8Array.of(1, 2, 3)); + * ``` + */ +export declare function copyBytes(bytes: TArg): TRet; +/** + * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols + * Should be safe to use for things expected to be ASCII. + * Returns exact same result as `TextEncoder` for ASCII or throws. + * @param ascii - ASCII input text. + * @returns Encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode an ASCII domain-separation tag. + * + * ```ts + * asciiToBytes('ABC'); + * ``` + */ +export declare function asciiToBytes(ascii: string): TRet; +/** + * Checks whether a bigint lies inside a half-open range. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * @returns `true` when the value is inside the range. + * @example + * Check whether a candidate scalar fits the field order. + * + * ```ts + * inRange(2n, 1n, 3n); + * ``` + */ +export declare function inRange(n: bigint, min: bigint, max: bigint): boolean; +/** + * Asserts `min <= n < max`. NOTE: upper bound is exclusive. + * @param title - Value label for error messages. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * Wrong-type inputs are not separated from out-of-range values here: they still flow through the + * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Assert that a bigint stays within one half-open range. + * + * ```ts + * aInRange('x', 2n, 1n, 256n); + * ``` + */ +export declare function aInRange(title: string, n: bigint, min: bigint, max: bigint): void; +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + * TODO: merge with nLength in modular + * @param n - Value to inspect. + * @returns Bit length. + * @throws If the value is negative. {@link Error} + * @example + * Measure the bit length of a scalar before serialization. + * + * ```ts + * bitLen(8n); + * ``` + */ +export declare function bitLen(n: bigint): number; +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw + * bigint shift semantics; because the mask is built as `1n << pos`, + * they currently collapse to `0n` and make the helper a no-op. + * @returns Bit as bigint. + * @example + * Gets single bit at position. + * + * ```ts + * bitGet(5n, 0); + * ``` + */ +export declare function bitGet(n: bigint, pos: number): bigint; +/** + * Sets single bit at position. + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics, + * so they currently behave like left shifts. + * @param value - Whether the bit should be set. + * @returns Updated bigint. + * @example + * Sets single bit at position. + * + * ```ts + * bitSet(0n, 1, true); + * ``` + */ +export declare function bitSet(n: bigint, pos: number, value: boolean): bigint; +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift + * semantics and therefore produce `-1n`. + * @returns Bitmask value. + * @example + * Calculate mask for N bits. + * + * ```ts + * bitMask(4); + * ``` + */ +export declare const bitMask: (n: number) => bigint; +type Pred = (v: TArg) => T | undefined; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0` + * is not rejected here and would make the internal generate loop non-progressing. + * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length. + * @param hmacFn - HMAC implementation. + * @returns Function that will call DRBG until the predicate returns anything + * other than `undefined`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Build a deterministic nonce generator for RFC6979-style signing. + * + * ```ts + * import { createHmacDrbg } from '@noble/curves/utils.js'; + * import { hmac } from '@noble/hashes/hmac.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg)); + * const seed = new Uint8Array(32); + * drbg(seed, (bytes) => bytes); + * ``` + */ +export declare function createHmacDrbg(hashLen: number, qByteLen: number, hmacFn: TArg): TRet<(seed: Uint8Array, predicate: Pred) => T>; +/** + * Validates declared required and optional field types on a plain object. + * Extra keys are intentionally ignored because many callers validate only the subset they use from + * richer option bags or runtime objects. + * @param object - Object to validate. + * @param fields - Required field types. + * @param optFields - Optional field types. + * @throws On wrong argument types. {@link TypeError} + * @example + * Check user options before building a curve helper. + * + * ```ts + * validateObject({ flag: true }, { flag: 'boolean' }); + * ``` + */ +export declare function validateObject(object: Record, fields?: Record, optFields?: Record): void; +/** + * Throws not implemented error. + * @returns Never returns. + * @throws If the unfinished code path is reached. {@link Error} + * @example + * Surface the placeholder error from an unfinished code path. + * + * ```ts + * try { + * notImplemented(); + * } catch {} + * ``` + */ +export declare const notImplemented: () => never; +/** Generic keygen/getPublicKey interface shared by curve helpers. */ +export interface CryptoKeys { + /** Public byte lengths for keys and optional seeds. */ + lengths: { + seed?: number; + public?: number; + secret?: number; + }; + /** + * Generate one secret/public keypair. + * @param seed - Optional seed bytes for deterministic key generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: Uint8Array) => { + secretKey: Uint8Array; + publicKey: Uint8Array; + }; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: Uint8Array) => Uint8Array; +} +/** Generic interface for signatures. Has keygen, sign and verify. */ +export interface Signer extends CryptoKeys { + /** Public byte lengths for keys, signatures, and optional signing randomness. */ + lengths: { + seed?: number; + public?: number; + secret?: number; + signRand?: number; + signature?: number; + }; + /** + * Sign one message. + * @param msg - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @returns Signature bytes. + */ + sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array; + /** + * Verify one signature. + * @param sig - Signature bytes. + * @param msg - Signed message bytes. + * @param publicKey - Public key bytes. + * @returns `true` when the signature is valid. + */ + verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean; +} +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/utils.d.ts.map b/node_modules/@noble/curves/utils.d.ts.map new file mode 100644 index 0000000..9881ab6 --- /dev/null +++ b/node_modules/@noble/curves/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EAEL,OAAO,IAAI,QAAQ,EACnB,UAAU,IAAI,WAAW,EAGzB,OAAO,IAAI,QAAQ,EAEpB,MAAM,wBAAwB,CAAC;AAChC;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,QAAQ,CAAC,CAAC,IAAI,CAAC,SAAS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QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7D;;;;OAIG;IACH,MAAM,EAAE,CAAC,IAAI,CAAC,EAAE,UAAU,KAAK;QAAE,SAAS,EAAE,UAAU,CAAC;QAAC,SAAS,EAAE,UAAU,CAAA;KAAE,CAAC;IAChF;;;;OAIG;IACH,YAAY,EAAE,CAAC,SAAS,EAAE,UAAU,KAAK,UAAU,CAAC;CACrD;AAED,qEAAqE;AACrE,MAAM,WAAW,MAAO,SAAQ,UAAU;IAExC,iFAAiF;IACjF,OAAO,EAAE;QACP,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,CAAC;IACF;;;;;OAKG;IACH,IAAI,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,KAAK,UAAU,CAAC;IAC7D;;;;;;OAMG;IACH,MAAM,EAAE,CAAC,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,KAAK,OAAO,CAAC;CAC9E"} \ No newline at end of file diff --git a/node_modules/@noble/curves/utils.js b/node_modules/@noble/curves/utils.js new file mode 100644 index 0000000..87cf2f7 --- /dev/null +++ b/node_modules/@noble/curves/utils.js @@ -0,0 +1,598 @@ +/** + * Hex, bytes and number utilities. + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import { 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'; +/** + * Validates that a value is a byte array. + * @param value - Value to validate. + * @param length - Optional exact byte length. + * @param title - Optional field name. + * @returns Original byte array. + * @example + * Reject non-byte input before passing data into curve code. + * + * ```ts + * abytes(new Uint8Array(1)); + * ``` + */ +export const abytes = (value, length, title) => abytes_(value, length, title); +/** + * Validates that a value is a non-negative safe integer. + * @param n - Value to validate. + * @param title - Optional field name. + * @example + * Validate a numeric length before allocating buffers. + * + * ```ts + * anumber(1); + * ``` + */ +export const anumber = anumber_; +/** + * Encodes bytes as lowercase hex. + * @param bytes - Bytes to encode. + * @returns Lowercase hex string. + * @example + * Serialize bytes as hex for logging or fixtures. + * + * ```ts + * bytesToHex(Uint8Array.of(1, 2, 3)); + * ``` + */ +export const bytesToHex = bytesToHex_; +/** + * Concatenates byte arrays. + * @param arrays - Byte arrays to join. + * @returns Concatenated bytes. + * @example + * Join domain-separated chunks into one buffer. + * + * ```ts + * concatBytes(Uint8Array.of(1), Uint8Array.of(2)); + * ``` + */ +export const concatBytes = (...arrays) => concatBytes_(...arrays); +/** + * Decodes lowercase or uppercase hex into bytes. + * @param hex - Hex string to decode. + * @returns Decoded bytes. + * @example + * Parse fixture hex into bytes before hashing. + * + * ```ts + * hexToBytes('0102'); + * ``` + */ +export const hexToBytes = (hex) => hexToBytes_(hex); +/** + * Checks whether a value is a Uint8Array. + * @param a - Value to inspect. + * @returns `true` when `a` is a Uint8Array. + * @example + * Branch on byte input before decoding it. + * + * ```ts + * isBytes(new Uint8Array(1)); + * ``` + */ +export const isBytes = isBytes_; +/** + * Reads random bytes from the platform CSPRNG. + * @param bytesLength - Number of random bytes to read. + * @returns Fresh random bytes. + * @example + * Generate a random seed for a keypair. + * + * ```ts + * randomBytes(2); + * ``` + */ +export const randomBytes = (bytesLength) => randomBytes_(bytesLength); +const _0n = /* @__PURE__ */ BigInt(0); +const _1n = /* @__PURE__ */ BigInt(1); +/** + * Validates that a flag is boolean. + * @param value - Value to validate. + * @param title - Optional field name. + * @returns Original value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Reject non-boolean option flags early. + * + * ```ts + * abool(true); + * ``` + */ +export function abool(value, title = '') { + if (typeof value !== 'boolean') { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + 'expected boolean, got type=' + typeof value); + } + return value; +} +/** + * Validates that a value is a non-negative bigint or safe integer. + * @param n - Value to validate. + * @returns The same validated value. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate one integer-like value before serializing it. + * + * ```ts + * abignumber(1n); + * ``` + */ +export function abignumber(n) { + if (typeof n === 'bigint') { + if (!isPosBig(n)) + throw new RangeError('positive bigint expected, got ' + n); + } + else + anumber(n); + return n; +} +/** + * Validates that a value is a safe integer. + * @param value - Integer to validate. + * @param title - Optional field name. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a window size before scalar arithmetic uses it. + * + * ```ts + * asafenumber(1); + * ``` + */ +export function asafenumber(value, title = '') { + if (typeof value !== 'number') { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + 'expected number, got type=' + typeof value); + } + if (!Number.isSafeInteger(value)) { + const prefix = title && `"${title}" `; + throw new RangeError(prefix + 'expected safe integer, got ' + value); + } +} +/** + * Encodes a bigint into even-length big-endian hex. + * The historical "unpadded" name only means "no fixed-width field padding"; odd-length hex still + * gets one leading zero nibble so the result always represents whole bytes. + * @param num - Number to encode. + * @returns Big-endian hex string. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Encode a scalar into hex without a `0x` prefix. + * + * ```ts + * numberToHexUnpadded(255n); + * ``` + */ +export function numberToHexUnpadded(num) { + const hex = abignumber(num).toString(16); + return hex.length & 1 ? '0' + hex : hex; +} +/** + * Parses a big-endian hex string into bigint. + * Accepts odd-length hex through the native `BigInt('0x' + hex)` parser and currently surfaces the + * same native `SyntaxError` for malformed hex instead of wrapping it in a library-specific error. + * @param hex - Hex string without `0x`. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Parse a scalar from fixture hex. + * + * ```ts + * hexToNumber('ff'); + * ``` + */ +export function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new TypeError('hex string expected, got ' + typeof hex); + return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian +} +// BE: Big Endian, LE: Little Endian +/** + * Parses big-endian bytes into bigint. + * @param bytes - Bytes in big-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in network byte order. + * + * ```ts + * bytesToNumberBE(Uint8Array.of(1, 0)); + * ``` + */ +export function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex_(bytes)); +} +/** + * Parses little-endian bytes into bigint. + * @param bytes - Bytes in little-endian order. + * @returns Parsed bigint value. + * @throws On wrong argument types. {@link TypeError} + * @example + * Read a scalar encoded in little-endian form. + * + * ```ts + * bytesToNumberLE(Uint8Array.of(1, 0)); + * ``` + */ +export function bytesToNumberLE(bytes) { + return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse())); +} +/** + * Encodes a bigint into fixed-length big-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. Must be greater than zero. + * @returns Big-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar into a 32-byte field element. + * + * ```ts + * numberToBytesBE(255n, 2); + * ``` + */ +export function numberToBytesBE(n, len) { + anumber_(len); + if (len === 0) + throw new RangeError('zero length'); + n = abignumber(n); + const hex = n.toString(16); + // Detect overflow before hex parsing so oversized values don't leak the shared odd-hex error. + if (hex.length > len * 2) + throw new RangeError('number too large'); + return hexToBytes_(hex.padStart(len * 2, '0')); +} +/** + * Encodes a bigint into fixed-length little-endian bytes. + * @param n - Number to encode. + * @param len - Output length in bytes. + * @returns Little-endian byte array. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a scalar for little-endian protocols. + * + * ```ts + * numberToBytesLE(255n, 2); + * ``` + */ +export function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +// Unpadded, rarely used +/** + * Encodes a bigint into variable-length big-endian bytes. + * @param n - Number to encode. + * @returns Variable-length big-endian bytes. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Serialize a bigint without fixed-width padding. + * + * ```ts + * numberToVarBytesBE(255n); + * ``` + */ +export function numberToVarBytesBE(n) { + return hexToBytes_(numberToHexUnpadded(abignumber(n))); +} +// Compares 2 u8a-s in kinda constant time +/** + * Compares two byte arrays in constant-ish time. + * @param a - Left byte array. + * @param b - Right byte array. + * @returns `true` when bytes match. + * @example + * Compare two encoded points without early exit. + * + * ```ts + * equalBytes(Uint8Array.of(1), Uint8Array.of(1)); + * ``` + */ +export function equalBytes(a, b) { + a = abytes(a); + b = abytes(b); + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * Copies Uint8Array. We can't use u8a.slice(), because u8a can be Buffer, + * and Buffer#slice creates mutable copy. Never use Buffers! + * @param bytes - Bytes to copy. + * @returns Detached copy. + * @example + * Make an isolated copy before mutating serialized bytes. + * + * ```ts + * copyBytes(Uint8Array.of(1, 2, 3)); + * ``` + */ +export function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)); +} +/** + * Decodes 7-bit ASCII string to Uint8Array, throws on non-ascii symbols + * Should be safe to use for things expected to be ASCII. + * Returns exact same result as `TextEncoder` for ASCII or throws. + * @param ascii - ASCII input text. + * @returns Encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode an ASCII domain-separation tag. + * + * ```ts + * asciiToBytes('ABC'); + * ``` + */ +export function asciiToBytes(ascii) { + if (typeof ascii !== 'string') + throw new TypeError('ascii string expected, got ' + typeof ascii); + return Uint8Array.from(ascii, (c, i) => { + const charCode = c.charCodeAt(0); + if (c.length !== 1 || charCode > 127) { + throw new RangeError(`string contains non-ASCII character "${ascii[i]}" with code ${charCode} at position ${i}`); + } + return charCode; + }); +} +// Historical name: this accepts non-negative bigints, including zero. +const isPosBig = (n) => typeof n === 'bigint' && _0n <= n; +/** + * Checks whether a bigint lies inside a half-open range. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * @returns `true` when the value is inside the range. + * @example + * Check whether a candidate scalar fits the field order. + * + * ```ts + * inRange(2n, 1n, 3n); + * ``` + */ +export function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +/** + * Asserts `min <= n < max`. NOTE: upper bound is exclusive. + * @param title - Value label for error messages. + * @param n - Candidate value. + * @param min - Inclusive lower bound. + * @param max - Exclusive upper bound. + * Wrong-type inputs are not separated from out-of-range values here: they still flow through the + * shared `RangeError` path because this is only a throwing wrapper around `inRange(...)`. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Assert that a bigint stays within one half-open range. + * + * ```ts + * aInRange('x', 2n, 1n, 256n); + * ``` + */ +export function aInRange(title, n, min, max) { + // Why min <= n < max and not a (min < n < max) OR b (min <= n <= max)? + // consider P=256n, min=0n, max=P + // - a for min=0 would require -1: `inRange('x', x, -1n, P)` + // - b would commonly require subtraction: `inRange('x', x, 0n, P - 1n)` + // - our way is the cleanest: `inRange('x', x, 0n, P) + if (!inRange(n, min, max)) + throw new RangeError('expected valid ' + title + ': ' + min + ' <= n < ' + max + ', got ' + n); +} +// Bit operations +/** + * Calculates amount of bits in a bigint. + * Same as `n.toString(2).length` + * TODO: merge with nLength in modular + * @param n - Value to inspect. + * @returns Bit length. + * @throws If the value is negative. {@link Error} + * @example + * Measure the bit length of a scalar before serialization. + * + * ```ts + * bitLen(8n); + * ``` + */ +export function bitLen(n) { + // Size callers in this repo only use non-negative orders / scalars, so negative inputs are a + // contract bug and must not silently collapse to zero bits. + if (n < _0n) + throw new Error('expected non-negative bigint, got ' + n); + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +/** + * Gets single bit at position. + * NOTE: first bit position is 0 (same as arrays) + * Same as `!!+Array.from(n.toString(2)).reverse()[pos]` + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw + * bigint shift semantics; because the mask is built as `1n << pos`, + * they currently collapse to `0n` and make the helper a no-op. + * @returns Bit as bigint. + * @example + * Gets single bit at position. + * + * ```ts + * bitGet(5n, 0); + * ``` + */ +export function bitGet(n, pos) { + return (n >> BigInt(pos)) & _1n; +} +/** + * Sets single bit at position. + * @param n - Source value. + * @param pos - Bit position. Negative positions are passed through to raw bigint shift semantics, + * so they currently behave like left shifts. + * @param value - Whether the bit should be set. + * @returns Updated bigint. + * @example + * Sets single bit at position. + * + * ```ts + * bitSet(0n, 1, true); + * ``` + */ +export function bitSet(n, pos, value) { + const mask = _1n << BigInt(pos); + // Clearing needs AND-not here; OR with zero leaves an already-set bit untouched. + return value ? n | mask : n & ~mask; +} +/** + * Calculate mask for N bits. Not using ** operator with bigints because of old engines. + * Same as BigInt(`0b${Array(i).fill('1').join('')}`) + * @param n - Number of bits. Negative widths are currently passed through to raw bigint shift + * semantics and therefore produce `-1n`. + * @returns Bitmask value. + * @example + * Calculate mask for N bits. + * + * ```ts + * bitMask(4); + * ``` + */ +export const bitMask = (n) => (_1n << BigInt(n)) - _1n; +/** + * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs. + * @param hashLen - Hash output size in bytes. Callers are expected to pass a positive length; `0` + * is not rejected here and would make the internal generate loop non-progressing. + * @param qByteLen - Requested output size in bytes. Callers are expected to pass a positive length. + * @param hmacFn - HMAC implementation. + * @returns Function that will call DRBG until the predicate returns anything + * other than `undefined`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Build a deterministic nonce generator for RFC6979-style signing. + * + * ```ts + * import { createHmacDrbg } from '@noble/curves/utils.js'; + * import { hmac } from '@noble/hashes/hmac.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg)); + * const seed = new Uint8Array(32); + * drbg(seed, (bytes) => bytes); + * ``` + */ +export function createHmacDrbg(hashLen, qByteLen, hmacFn) { + anumber_(hashLen, 'hashLen'); + anumber_(qByteLen, 'qByteLen'); + if (typeof hmacFn !== 'function') + throw new TypeError('hmacFn must be a function'); + // creates Uint8Array + const u8n = (len) => new Uint8Array(len); + const NULL = Uint8Array.of(); + const byte0 = Uint8Array.of(0x00); + const byte1 = Uint8Array.of(0x01); + const _maxDrbgIters = 1000; + // Step B, Step C: set hashLen to 8*ceil(hlen/8). + // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 signatures. + let v = u8n(hashLen); + // Steps B and C of RFC6979 3.2. + let k = u8n(hashLen); + let i = 0; // Iterations counter, will throw when over 1000 + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + // hmac(k)(v, ...values) + const h = (...msgs) => hmacFn(k, concatBytes(v, ...msgs)); + const reseed = (seed = NULL) => { + // HMAC-DRBG reseed() function. Steps D-G + k = h(byte0, seed); // k = hmac(k || v || 0x00 || seed) + v = h(); // v = hmac(k || v) + if (seed.length === 0) + return; + k = h(byte1, seed); // k = hmac(k || v || 0x01 || seed) + v = h(); // v = hmac(k || v) + }; + const gen = () => { + // HMAC-DRBG generate() function + if (i++ >= _maxDrbgIters) + throw new Error('drbg: tried max amount of iterations'); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); // Steps D-G + let res = undefined; // Step H: grind until the predicate accepts a candidate. + // Falsy values like 0 are valid outputs. + while ((res = pred(gen())) === undefined) + reseed(); + reset(); + return res; + }; + return genUntil; +} +/** + * Validates declared required and optional field types on a plain object. + * Extra keys are intentionally ignored because many callers validate only the subset they use from + * richer option bags or runtime objects. + * @param object - Object to validate. + * @param fields - Required field types. + * @param optFields - Optional field types. + * @throws On wrong argument types. {@link TypeError} + * @example + * Check user options before building a curve helper. + * + * ```ts + * validateObject({ flag: true }, { flag: 'boolean' }); + * ``` + */ +export function validateObject(object, fields = {}, optFields = {}) { + if (Object.prototype.toString.call(object) !== '[object Object]') + throw new TypeError('expected valid options object'); + function checkField(fieldName, expectedType, isOpt) { + // Config/data fields must be explicit own properties, but runtime objects such as Field + // instances intentionally satisfy required method slots via their shared prototype. + if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName)) + throw new TypeError(`param "${fieldName}" is invalid: expected own property`); + const val = object[fieldName]; + if (isOpt && val === undefined) + return; + const current = typeof val; + if (current !== expectedType || val === null) + throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); + } + const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)); + iter(fields, false); + iter(optFields, true); +} +/** + * Throws not implemented error. + * @returns Never returns. + * @throws If the unfinished code path is reached. {@link Error} + * @example + * Surface the placeholder error from an unfinished code path. + * + * ```ts + * try { + * notImplemented(); + * } catch {} + * ``` + */ +export const notImplemented = () => { + throw new Error('not implemented'); +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/utils.js.map b/node_modules/@noble/curves/utils.js.map new file mode 100644 index 0000000..fbb5eae --- /dev/null +++ b/node_modules/@noble/curves/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,sEAAsE;AACtE,OAAO,EACL,MAAM,IAAI,OAAO,EACjB,OAAO,IAAI,QAAQ,EACnB,UAAU,IAAI,WAAW,EACzB,WAAW,IAAI,YAAY,EAC3B,UAAU,IAAI,WAAW,EACzB,OAAO,IAAI,QAAQ,EACnB,WAAW,IAAI,YAAY,GAC5B,MAAM,wBAAwB,CAAC;AA0GhC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CAA6B,KAAQ,EAAE,MAAe,EAAE,KAAc,EAAK,EAAE,CACjG,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAM,CAAC;AACrC;;;;;;;;;;GAUG;AACH,MA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CAC5E,CAAC;IACN,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,CAAgB,EAAE,KAAc,EAAE,EAAE,CAChD,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;IACjE,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACpB,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;AACxB,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,GAAU,EAAE;IACxC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;AACrC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/webcrypto.d.ts b/node_modules/@noble/curves/webcrypto.d.ts new file mode 100644 index 0000000..42d926c --- /dev/null +++ b/node_modules/@noble/curves/webcrypto.d.ts @@ -0,0 +1,241 @@ +/** + * Friendly wrapper over elliptic curves from built-in WebCrypto. Experimental: API may change. + +# WebCrypto issues + +## No way to get public keys + +- Export of raw secret key is prohibited by spec: + - https://w3c.github.io/webcrypto/#ecdsa-operations-export-key + -> "If format is "raw":" -> "If the [[type]] internal slot of key is not "public", + then throw an InvalidAccessError." +- Import of raw secret keys is prohibited by spec: + - https://w3c.github.io/webcrypto/#ecdsa-operations-import-key + -> "If format is "raw":" -> "If usages contains a value which is not "verify" + then throw a SyntaxError." +- SPKI (Simple public-key infrastructure) is public-key-only +- PKCS8 is secret-key-only +- No way to get public key from secret key, but we convert to JWK and then + create it manually, since a JWK secret key includes both private and public + parts. +- Noble supports generating keys for both sign, verify & getSharedSecret, + but JWK key includes usage, which forces us to patch it (non-JWK is ok) +- We have import/export for 'raw', but it doesn't work in Firefox / Safari + +## Point encoding + +- Raw export of public points returns uncompressed points, + but this is implementation specific and not much we can do there. +- `getSharedSecret` differs for p256, p384, p521: + Noble returns 33-byte output (y-parity + x coordinate), + while in WebCrypto returns 32-byte output (x coordinate). + This is intentional: noble keeps the full encoded shared point, and x-only + callers can slice it down themselves. +- `getSharedSecret` identical for X25519, X448 + +## Availability + +Node.js additionally supports ed448. +There seems no reasonable way to check for availability, other than actually calling methods. + + * @module + */ +/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +import type { TArg, TRet } from './utils.ts'; +/** Raw type */ +declare const TYPE_RAW = "raw"; +declare const TYPE_JWK = "jwk"; +declare const TYPE_SPKI = "spki"; +declare const TYPE_PKCS = "pkcs8"; +/** Key serialization formats supported by the WebCrypto wrappers. */ +export type WebCryptoFormat = typeof TYPE_RAW | typeof TYPE_JWK | typeof TYPE_SPKI | typeof TYPE_PKCS; +/** WebCrypto keys can be in raw, jwk, pkcs8/spki formats. Raw is internal and fragile. */ +export type WebCryptoOpts = { + /** Preferred secret-key serialization format. */ + formatSec?: WebCryptoFormat; + /** Preferred public-key serialization format. */ + formatPub?: WebCryptoFormat; +}; +declare function hexToBytesLocal(hex: string): TRet; +export declare const __TEST: { + hexToBytesLocal: typeof hexToBytesLocal; +}; +type JsonWebKey = { + crv?: string; + d?: string; + kty?: string; + x?: string; + y?: string; + [key: string]: unknown; +}; +type Key = JsonWebKey | Uint8Array; +type WebCryptoBaseCurve = { + name: string; + isSupported(): Promise; + keygen(): TRet>; + getPublicKey(secretKey: TArg, opts?: TArg): TRet>; + utils: { + randomSecretKey: (format?: WebCryptoFormat) => TRet>; + convertSecretKey: (key: TArg, inFormat?: WebCryptoFormat, outFormat?: WebCryptoFormat) => TRet>; + convertPublicKey: (key: TArg, inFormat?: WebCryptoFormat, outFormat?: WebCryptoFormat) => TRet>; + }; +}; +/** WebCrypto signing interface shared by ECDSA and EdDSA helpers. */ +export type WebCryptoSigner = { + /** + * Sign one message with a WebCrypto-backed private key. + * @param message - Message bytes to sign. + * @param secretKey - Secret key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns Signature bytes. + */ + sign(message: TArg, secretKey: TArg, opts?: TArg): TRet>; + /** + * Verify one signature with a WebCrypto-backed public key. + * @param signature - Signature bytes. + * @param message - Signed message bytes. + * @param publicKey - Public key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns `true` when the signature is valid. + */ + verify(signature: TArg, message: TArg, publicKey: TArg, opts?: TArg): Promise; +}; +/** WebCrypto ECDH interface for shared-secret derivation. */ +export type WebCryptoECDH = { + /** + * Derive one shared secret from a local secret key and peer public key. + * Short-Weierstrass wrappers return the raw x-coordinate here, not noble's parity-prefixed + * shared-point encoding. Runtime also accepts alternate key formats through `opts`, even though + * this public type is still narrowed to byte arrays. + * @param secA - Local secret key in one supported format. + * @param pubB - Peer public key in one supported format. + * @param opts - Optional key-format overrides. See {@link WebCryptoOpts}. + * @returns Shared secret bytes. + */ + getSharedSecret(secA: TArg, pubB: TArg, opts?: TArg): TRet>; +}; +/** WebCrypto ECDSA interface with keygen, signing, and ECDH helpers. */ +export type WebCryptoECDSA = WebCryptoBaseCurve & WebCryptoSigner & WebCryptoECDH; +/** WebCrypto EdDSA interface with keygen and signing helpers. */ +export type WebCryptoEdDSA = WebCryptoBaseCurve & WebCryptoSigner; +/** WebCrypto Montgomery interface with keygen and ECDH helpers. */ +export type WebCryptoMontgomery = WebCryptoBaseCurve & WebCryptoECDH; +/** + * Friendly wrapper over built-in WebCrypto NIST P-256 (secp256r1). + * Inherits the generic WebCrypto ECDSA caveats: `isSupported()` only probes the sign-side API, and + * the conversion/signing helpers keep the shared `createKeyUtils(...)` / `createSigner(...)` quirks, + * including raw WebCrypto ECDSA signatures without low-S normalization. + * @example + * Check support, then sign and verify once with WebCrypto P-256. + * + * ```ts + * if (await p256.isSupported()) { + * const { secretKey, publicKey } = await p256.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p256.sign(msg, secretKey); + * const isValid = await p256.verify(sig, msg, publicKey); + * } + * ``` + */ +export declare const p256: TRet; +/** + * Friendly wrapper over built-in WebCrypto NIST P-384 (secp384r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-384. + * + * ```ts + * if (await p384.isSupported()) { + * const { secretKey, publicKey } = await p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p384.sign(msg, secretKey); + * const isValid = await p384.verify(sig, msg, publicKey); + * } + * ``` + */ +export declare const p384: TRet; +/** + * Friendly wrapper over built-in WebCrypto NIST P-521 (secp521r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-521. + * + * ```ts + * if (await p521.isSupported()) { + * const { secretKey, publicKey } = await p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p521.sign(msg, secretKey); + * const isValid = await p521.verify(sig, msg, publicKey); + * } + * ``` + */ +export declare const p521: TRet; +/** + * Friendly wrapper over built-in WebCrypto ed25519. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed25519. + * + * ```ts + * if (await ed25519.isSupported()) { + * const { secretKey, publicKey } = await ed25519.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed25519.sign(msg, secretKey); + * const isValid = await ed25519.verify(sig, msg, publicKey); + * } + * ``` + */ +export declare const ed25519: TRet; +/** + * Friendly wrapper over built-in WebCrypto ed448. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed448. + * + * ```ts + * if (await ed448.isSupported()) { + * const { secretKey, publicKey } = await ed448.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed448.sign(msg, secretKey); + * const isValid = await ed448.verify(sig, msg, publicKey); + * } + * ``` + */ +export declare const ed448: TRet; +/** + * Friendly wrapper over built-in WebCrypto x25519 (ECDH over Curve25519). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X25519. + * + * ```ts + * if (await x25519.isSupported()) { + * const alice = await x25519.keygen(); + * const bob = await x25519.keygen(); + * const shared = await x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export declare const x25519: TRet; +/** + * Friendly wrapper over built-in WebCrypto x448 (ECDH over Curve448). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X448. + * + * ```ts + * if (await x448.isSupported()) { + * const alice = await x448.keygen(); + * const bob = await x448.keygen(); + * const shared = await x448.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export declare const x448: TRet; +export {}; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/curves/webcrypto.d.ts.map b/node_modules/@noble/curves/webcrypto.d.ts.map new file mode 100644 index 0000000..d71670e --- /dev/null +++ b/node_modules/@noble/curves/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,sEAAsE;AACtE,OAAO,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7C,eAAe;AACf,QAAA,MAAM,QAAQ,QAAQ,CAAC;AACvB,QAAA,MAAM,QAAQ,QAAQ,CAAC;AACvB,QAAA,MAAM,SAAS,SAAS,CAAC;AACzB,QAAA,MAAM,SAAS,UAAU,CAAC;AAC1B,qEAAqE;AACrE,MAAM,MAAM,eAAe,GACvB,OAAO,QAAQ,GACf,OAAO,QAAQ,GACf,OAAO,SAAS,GAChB,OAAO,SAAS,CAAC;AACrB,0FAA0F;AAC1F,MAAM,MAAM,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,GAAG,kBAAkB,GAAG,aAAa,CAAC;AA8ErE;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,cAAc,CAKrC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,cAAc,CAKrC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,cAAc,CAKrC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,cAAc,CAIxC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,cAAc,CAItC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,mBAAmB,CAI5C,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,mBAAmB,CAI1C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/curves/webcrypto.js b/node_modules/@noble/curves/webcrypto.js new file mode 100644 index 0000000..41ef43a --- /dev/null +++ b/node_modules/@noble/curves/webcrypto.js @@ -0,0 +1,363 @@ +/** Raw type */ +const TYPE_RAW = 'raw'; +const TYPE_JWK = 'jwk'; +const TYPE_SPKI = 'spki'; +const TYPE_PKCS = 'pkcs8'; +// default formats +const dfsec = TYPE_PKCS; +const dfpub = TYPE_SPKI; +function getSubtle() { + const s = globalThis?.crypto?.subtle; + if (typeof s === 'object' && s != null) + return s; + throw new Error('crypto.subtle must be defined'); +} +function createKeygenA(randomSecretKey, getPublicKey) { + // Runtime accepts an accidental `keygen(seed)` argument for parity with other wrappers, but the + // seed is intentionally ignored because WebCrypto keygen here always goes through fresh keygen. + return async function keygenA(_seed) { + const secretKey = (await randomSecretKey()); + return { secretKey, publicKey: (await getPublicKey(secretKey)) }; + }; +} +// Internal helper only: strict hex parser for the local hardcoded PKCS8 header constants. +function hexToBytesLocal(hex) { + const pairs = hex.match(/[0-9a-f]{2}/gi); + if (!pairs || pairs.length * 2 !== hex.length) + throw new Error('invalid hex'); + return Uint8Array.from(pairs, (b) => Number.parseInt(b, 16)); +} +export const __TEST = /* @__PURE__ */ Object.freeze({ + hexToBytesLocal, +}); +function assertType(type, key) { + // Callers are expected to pass a non-null key-like object; `null` / `undefined` still fail first + // via property access before reaching the explicit wrapper error. + if (key.type !== type) + throw new Error(`invalid key type, expected ${type}`); +} +function createKeyUtils(algo, derive, keyLen, pkcs8header) { + const secUsage = derive ? ['deriveBits'] : ['sign']; + const pubUsage = derive ? [] : ['verify']; + // Return Uint8Array instead of ArrayBuffer + const arrBufToU8 = (res, format) => (format === TYPE_JWK + ? res + : new Uint8Array(res)); + const pub = { + async import(key, format) { + // For sign/verify wrappers we pass caller-provided JWK metadata through unchanged and let + // WebCrypto enforce mismatched `key_ops` / extractability instead of normalizing it here. + const keyi = await getSubtle().importKey(format, key, algo, true, pubUsage); + assertType('public', keyi); + return keyi; + }, + async export(key, format) { + assertType('public', key); + const keyi = await getSubtle().exportKey(format, key); + return arrBufToU8(keyi, format); + }, + async convert(key, inFormat, outFormat) { + return pub.export(await pub.import(key, inFormat), outFormat); + }, + }; + const priv = { + async import(key, format) { + const crypto = getSubtle(); + let keyi; + if (format === TYPE_RAW) { + // Chrome, node, bun, deno: works + // Safari, Firefox: Data provided to an operation does not meet requirements + // This is the best one can do. JWK can't be used: it contains public key component inside. + const k = key; + const head = hexToBytesLocal(pkcs8header); + const all = new Uint8Array(head.length + k.length); + all.set(head, 0); + all.set(k, head.length); + keyi = await crypto.importKey(TYPE_PKCS, all, algo, true, secUsage); + } + else { + // Sign/verify wrappers keep caller JWK metadata as-is and assume the supplied `key_ops` + // already match the requested operation. ECDH is different: noble treats the same key + // material as usable for both sign and derive, so JWK imported through the derive path + // must rewrite `key_ops` or WebCrypto refuses otherwise-correct keys exported by keygen. + if (derive && format === TYPE_JWK) + key = { ...key, key_ops: secUsage }; + keyi = await crypto.importKey(format, key, algo, true, secUsage); + } + assertType('private', keyi); + return keyi; + }, + async export(key, format) { + const crypto = getSubtle(); + assertType('private', key); + if (format === TYPE_RAW) { + // scure-base base64urlnopad could have been used, but we can't add more deps. + // pkcs8 would be even more fragile + const jwk = await crypto.exportKey(TYPE_JWK, key); + const base64 = jwk.d.replace(/-/g, '+').replace(/_/g, '/'); // base64url + const pad = base64.length % 4 ? '='.repeat(4 - (base64.length % 4)) : ''; // add padding + const binary = atob(base64 + pad); + // This is not ASCII, and not text: this is only semi-safe with atob output + const raw = Uint8Array.from(binary, (c) => c.charCodeAt(0)); + // Pad key to key len because Bun strips leading zero for P-521 only + const res = new Uint8Array(keyLen); + res.set(raw, keyLen - raw.length); + return res; + } + const keyi = await crypto.exportKey(format, key); + return arrBufToU8(keyi, format); + }, + async convert(key, inFormat, outFormat) { + return priv.export(await priv.import(key, inFormat), outFormat); + }, + }; + async function getPublicKey(secretKey, opts = {}) { + const fsec = opts.formatSec ?? dfsec; + const fpub = opts.formatPub ?? dfpub; + // Export to jwk, remove private scalar and then convert to format + const jwk = (fsec === TYPE_JWK ? { ...secretKey } : await priv.convert(secretKey, fsec, TYPE_JWK)); + delete jwk.d; + jwk.key_ops = pubUsage; + if (fpub === TYPE_JWK) + return jwk; + return pub.convert(jwk, TYPE_JWK, fpub); + } + async function randomSecretKey(format = dfsec) { + const keyPair = await getSubtle().generateKey(algo, true, secUsage); + return priv.export(keyPair.privateKey, format); + } + // Key generation could be slow, so we cache result once. + let supported; + return { + pub: pub, + priv: priv, + async isSupported() { + if (supported !== undefined) + return supported; + try { + const crypto = getSubtle(); + const key = await crypto.generateKey(algo, true, secUsage); + // Deno is broken and generates key for unsupported curves, but then fails on export + await priv.export(key.privateKey, TYPE_JWK); + // Bun fails on derive for x25519, but not x448 + if (derive) { + await crypto.deriveBits({ name: typeof algo === 'string' ? algo : algo.name, public: key.publicKey }, key.privateKey, 8); + } + return (supported = true); + } + catch (e) { + return (supported = false); + } + }, + getPublicKey, + keygen: createKeygenA(randomSecretKey, getPublicKey), + utils: Object.freeze({ + randomSecretKey, + // Runtime expects both formats explicitly here; omitted formats just flow into + // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`). + convertPublicKey: pub.convert, + // Runtime expects both formats explicitly here; omitted formats just flow into + // `subtle.importKey(...)`, and JWK conversion also assumes extractable keys (`ext !== false`). + convertSecretKey: priv.convert, + }), + }; +} +function createSigner(keys, algo) { + return { + // Historical param name: wrappers pass message bytes here, while WebCrypto performs the + // algorithm-specific hashing itself for ECDSA. We also return provider signatures verbatim: + // this wrapper is intentionally "raw WebCrypto", so it does not parse scalars or normalize + // high-S ECDSA outputs into software noble's low-S convention. + async sign(msgHash, secretKey, opts = {}) { + const key = await keys.priv.import(secretKey, opts.formatSec ?? dfsec); + const sig = await getSubtle().sign(algo, key, msgHash); + return new Uint8Array(sig); + }, + async verify(signature, msgHash, publicKey, opts = {}) { + const key = await keys.pub.import(publicKey, opts.formatPub ?? dfpub); + return await getSubtle().verify(algo, key, signature, msgHash); + }, + }; +} +function createECDH(keys, algo, keyLen) { + return { + // Runtime accepts the alternate key formats supported by `keys.import(...)`; the public type is + // still narrower than that accepted surface. + async getSharedSecret(secretKeyA, publicKeyB, opts = {}) { + // if (_isCompressed !== true) throw new Error('WebCrypto only supports compressed keys'); + const secKey = await keys.priv.import(secretKeyA, opts.formatSec === undefined ? dfsec : opts.formatSec); + const pubKey = await keys.pub.import(publicKeyB, opts.formatPub === undefined ? dfpub : opts.formatPub); + const shared = await getSubtle().deriveBits({ name: typeof algo === 'string' ? algo : algo.name, public: pubKey }, secKey, 8 * keyLen); + return new Uint8Array(shared); + }, + }; +} +function wrapECDSA(curve, hash, keyLen, pkcs8header) { + const ECDH_ALGO = { name: 'ECDH', namedCurve: curve }; + const keys = createKeyUtils({ name: 'ECDSA', namedCurve: curve }, false, keyLen, pkcs8header); + const keysEcdh = createKeyUtils(ECDH_ALGO, true, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + // Support probing comes from the sign-side wrapper only; ECDH availability is not checked + // independently here even though the public wrapper also exposes `getSharedSecret(...)`. + isSupported: keys.isSupported, + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createSigner(keys, { name: 'ECDSA', hash: { name: hash } }), + ...createECDH(keysEcdh, ECDH_ALGO, keyLen), + utils: Object.freeze({ + ...keys.utils, + async convertSecretKey(key, inFormat, outFormat) { + const jwk = inFormat === TYPE_JWK ? key : undefined; + // `wrapECDSA(...)` exposes the same key material for both sign and derive, so an ECDH-flavored + // JWK secret key from `getSharedSecret(...)` should still round-trip through `utils`. + if (Array.isArray(jwk?.key_ops) && + jwk.key_ops.length === 1 && + jwk.key_ops[0] === 'deriveBits') + return keysEcdh.utils.convertSecretKey(key, inFormat, outFormat); + return keys.utils.convertSecretKey(key, inFormat, outFormat); + }, + }), + }); +} +function wrapEdDSA(curve, keyLen, pkcs8header) { + const keys = createKeyUtils(curve, false, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + isSupported: keys.isSupported, + // This wrapper intentionally re-exports the generic WebCrypto key-conversion/signing behavior + // without adding extra JWK-metadata or extractability guardrails of its own. + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createSigner(keys, { name: curve }), + utils: keys.utils, + }); +} +function wrapMontgomery(curve, keyLen, pkcs8header) { + const keys = createKeyUtils(curve, true, keyLen, pkcs8header); + return Object.freeze({ + name: curve, + isSupported: keys.isSupported, + // This wrapper intentionally re-exports the generic ECDH key-format behavior without widening + // the narrow public `Uint8Array` key types. + getPublicKey: keys.getPublicKey, + keygen: createKeygenA(keys.utils.randomSecretKey, keys.getPublicKey), + ...createECDH(keys, curve, keyLen), + utils: keys.utils, + }); +} +/** + * Friendly wrapper over built-in WebCrypto NIST P-256 (secp256r1). + * Inherits the generic WebCrypto ECDSA caveats: `isSupported()` only probes the sign-side API, and + * the conversion/signing helpers keep the shared `createKeyUtils(...)` / `createSigner(...)` quirks, + * including raw WebCrypto ECDSA signatures without low-S normalization. + * @example + * Check support, then sign and verify once with WebCrypto P-256. + * + * ```ts + * if (await p256.isSupported()) { + * const { secretKey, publicKey } = await p256.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p256.sign(msg, secretKey); + * const isValid = await p256.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p256 = /* @__PURE__ */ wrapECDSA('P-256', 'SHA-256', 32, '3041020100301306072a8648ce3d020106082a8648ce3d030107042730250201010420'); +/** + * Friendly wrapper over built-in WebCrypto NIST P-384 (secp384r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-384. + * + * ```ts + * if (await p384.isSupported()) { + * const { secretKey, publicKey } = await p384.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p384.sign(msg, secretKey); + * const isValid = await p384.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p384 = /* @__PURE__ */ wrapECDSA('P-384', 'SHA-384', 48, '304e020100301006072a8648ce3d020106052b81040022043730350201010430'); +/** + * Friendly wrapper over built-in WebCrypto NIST P-521 (secp521r1). + * Inherits the generic WebCrypto ECDSA caveats around support probing and key/signing conversion. + * @example + * Check support, then sign and verify once with WebCrypto P-521. + * + * ```ts + * if (await p521.isSupported()) { + * const { secretKey, publicKey } = await p521.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await p521.sign(msg, secretKey); + * const isValid = await p521.verify(sig, msg, publicKey); + * } + * ``` + */ +export const p521 = /* @__PURE__ */ wrapECDSA('P-521', 'SHA-512', 66, '3060020100301006072a8648ce3d020106052b81040023044930470201010442'); +/** + * Friendly wrapper over built-in WebCrypto ed25519. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed25519. + * + * ```ts + * if (await ed25519.isSupported()) { + * const { secretKey, publicKey } = await ed25519.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed25519.sign(msg, secretKey); + * const isValid = await ed25519.verify(sig, msg, publicKey); + * } + * ``` + */ +export const ed25519 = /* @__PURE__ */ wrapEdDSA('Ed25519', 32, '302e020100300506032b657004220420'); +/** + * Friendly wrapper over built-in WebCrypto ed448. + * Inherits the generic WebCrypto EdDSA caveats around JWK conversion metadata and extractability. + * @example + * Check support, then sign and verify once with WebCrypto Ed448. + * + * ```ts + * if (await ed448.isSupported()) { + * const { secretKey, publicKey } = await ed448.keygen(); + * const msg = new TextEncoder().encode('hello noble'); + * const sig = await ed448.sign(msg, secretKey); + * const isValid = await ed448.verify(sig, msg, publicKey); + * } + * ``` + */ +export const ed448 = /* @__PURE__ */ wrapEdDSA('Ed448', 57, '3047020100300506032b6571043b0439'); +/** + * Friendly wrapper over built-in WebCrypto x25519 (ECDH over Curve25519). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X25519. + * + * ```ts + * if (await x25519.isSupported()) { + * const alice = await x25519.keygen(); + * const bob = await x25519.keygen(); + * const shared = await x25519.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export const x25519 = /* @__PURE__ */ wrapMontgomery('X25519', 32, '302e020100300506032b656e04220420'); +/** + * Friendly wrapper over built-in WebCrypto x448 (ECDH over Curve448). + * Inherits the generic WebCrypto Montgomery caveat that runtime accepts more key formats than the + * narrow public `Uint8Array` argument types suggest. + * @example + * Check support, then derive one shared secret with WebCrypto X448. + * + * ```ts + * if (await x448.isSupported()) { + * const alice = await x448.keygen(); + * const bob = await x448.keygen(); + * const shared = await x448.getSharedSecret(alice.secretKey, bob.publicKey); + * } + * ``` + */ +export const x448 = /* @__PURE__ */ wrapMontgomery('X448', 56, '3046020100300506032b656f043a0438'); +//# sourceMappingURL=webcrypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/curves/webcrypto.js.map b/node_modules/@noble/curves/webcrypto.js.map new file mode 100644 index 0000000..5b4d753 --- /dev/null +++ b/node_modules/@noble/curves/webcrypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AA6CA,eAAe;AACf,MAAM,QAAQ,GAAG,KAAK,CAAC;AACvB,MAAM,QAAQ,GAAG,KAAK,CAAC;AACvB,MAAM,SAAS,GAAG,MAAM,CAAC;AACzB,MAAM,SAAS,GAAG,OAAO,CAAC;AAc1B,kBAAkB;AAClB,MAAM,KAAK,GAAG,SAAS,CAAC;AACxB,MAAM,KAAK,GAAG,SAAS,CAAC;AAExB,SAAS,SAAS;IAChB,MAAM,CAAC,GAAQ,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC;IAC1C,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,IAAI,IAAI;QAAE,OAAO,CAAC,CAAC;IACjD,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;AACnD,CAAC;AAED,SAAS,aAAa,CACpB,eAAoB,EACpB,YAAiB;IAEjB,gGAAgG;IAChG,gGAAgG;IAChG,OAAO,KAAK,UAAU,OAAO,CAAC,KAAwB;QACpD,MAAM,SAAS,GAAG,CAAC,MAAM,eAAe,EAAE,CAAqB,CAAC;QAChE,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,CAAC,MAAM,YAAY,CAAC,SAAS,CAAC,CAAqB,EAAE,CAAC;IACvF,CAAC,CAAC;AACJ,CAAC;AAED,0FAA0F;AAC1F,SAAS,eAAe,CAAC,GAAW;IAClC,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;IACzC,IAAI,CAAC,KAAK,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,KAAK,GAAG,CAAC,MAAM;QAAE,MAAM,IAAI,KAAK,CA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MAAM,CAAC,MAAM,KAAK,GAAyB,eAAe,CAAC,SAAS,CAClE,OAAO,EACP,EAAE,EACF,kCAAkC,CACnC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,MAAM,GAA8B,eAAe,CAAC,cAAc,CAC7E,QAAQ,EACR,EAAE,EACF,kCAAkC,CACnC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,IAAI,GAA8B,eAAe,CAAC,cAAc,CAC3E,MAAM,EACN,EAAE,EACF,kCAAkC,CACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/LICENSE b/node_modules/@noble/hashes/LICENSE new file mode 100644 index 0000000..9297a04 --- /dev/null +++ b/node_modules/@noble/hashes/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/hashes/README.md b/node_modules/@noble/hashes/README.md new file mode 100644 index 0000000..7cb8034 --- /dev/null +++ b/node_modules/@noble/hashes/README.md @@ -0,0 +1,563 @@ +# noble-hashes + +Audited & minimal JS implementation of hash functions, MACs and KDFs. + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🏎 Fast: hand-optimized for caveats of JS engines +- 🔍 Reliable: chained / sliding window / DoS / ACVP tests and fuzzing +- 🔁 No unrolled loops: makes it easier to verify and reduces source code size up to 5x +- 🦘 Includes SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF, Scrypt, Argon2 +- 🥈 Optional, friendly wrapper over native WebCrypto +- 🪶 22KB (gzipped) for everything, 2.4KB for single-hash build + +Use [awasm-noble](https://github.com/paulmillr/awasm-noble) if you need an even faster (WASM) alternative. +Check out [Upgrading](#upgrading) for information about upgrading from previous versions. +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-hashes/discussions) for questions and support. + +The library's initial development was funded by [Ethereum Foundation](https://ethereum.org/). + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out the homepage](https://paulmillr.com/noble/) + for reading resources, documentation, and apps built with noble + +## Usage + +> `npm install @noble/hashes` + +> `deno add jsr:@noble/hashes` + +We support all major platforms and runtimes. +For React Native, you may need a [polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file [noble-hashes.js](https://github.com/paulmillr/noble-hashes/releases) is also available. + +```js +// import * from '@noble/hashes'; // Error: use sub-imports, to ensure small app size +import { sha256 as noble_sha256 } from '@noble/hashes/sha2.js'; +const hash = noble_sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); + +// Available modules +import { sha256, sha384, sha512, sha224, sha512_224, sha512_256 } from '@noble/hashes/sha2.js'; +import { + sha3_256, sha3_512, + keccak_256, keccak_512, + shake128, shake256, +} from '@noble/hashes/sha3.js'; +import { + cshake256, turboshake256, kmac256, tuplehash256, + kt128, kt256, keccakprg, +} from '@noble/hashes/sha3-addons.js'; +import { blake3 } from '@noble/hashes/blake3.js'; +import { blake2b, blake2s } from '@noble/hashes/blake2.js'; +import { blake256, blake512 } from '@noble/hashes/blake1.js'; +import { sha1, md5, ripemd160 } from '@noble/hashes/legacy.js'; +import { hmac } from '@noble/hashes/hmac.js'; +import { hkdf } from '@noble/hashes/hkdf.js'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js'; +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js'; +import * as webcrypto from '@noble/hashes/webcrypto.js'; +// const { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } = webcrypto; +import * as utils from '@noble/hashes/utils.js'; +const { bytesToHex, concatBytes, equalBytes, hexToBytes } = utils; +``` + +- [sha2: sha256, sha384, sha512](#sha2-sha256-sha384-sha512-and-others) +- [sha3: FIPS, SHAKE, Keccak](#sha3-fips-shake-keccak) +- [sha3-addons: cSHAKE, KMAC, KT128, TurboSHAKE](#sha3-addons-cshake-kmac-kt128-turboshake) +- [blake1, blake2, blake3](#blake1-blake2-blake3) +- [legacy: sha1, md5, ripemd160](#legacy-sha1-md5-ripemd160) +- MACs: [hmac](#hmac) | [kmac](#sha3-addons-cshake-kmac-kt128-turboshake) | [blake3 key mode](#blake1-blake2-blake3) +- KDFs: [hkdf](#hkdf) | [pbkdf2](#pbkdf2) | [scrypt](#scrypt) | [argon2](#argon2) +- [webcrypto: friendly wrapper](#webcrypto-friendly-wrapper) +- [utils](#utils) +- [Security](#security) | [Speed](#speed) | [Contributing & testing](#contributing--testing) | [License](#license) + +### Implementations + +Hash functions: + +- `sha256()`: receive & return `Uint8Array` +- `sha256.create().update(a).update(b).digest()`: support partial updates +- `blake3.create({ context: 'e', dkLen: 32 })`: can have options +- support little-endian architecture; also experimentally big-endian +- can hash up to 4GB per chunk, with any amount of chunks + +#### sha2: sha256, sha384, sha512 and others + +```typescript +import { sha224, sha256, sha384, sha512, sha512_224, sha512_256 } from '@noble/hashes/sha2.js'; +const res = sha256(Uint8Array.from([0xbc])); // basic +for (let hash of [sha256, sha384, sha512, sha224, sha512_224, sha512_256]) { + const arr = Uint8Array.from([0x10, 0x20, 0x30]); + const a = hash(arr); + const b = hash.create().update(arr).digest(); +} +``` + +Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and +[the paper on truncated SHA512/256](https://eprint.iacr.org/2010/548.pdf). + +#### sha3: FIPS, SHAKE, Keccak + +```typescript +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256, +} from '@noble/hashes/sha3.js'; +for (let hash of [ + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, +]) { + const arr = Uint8Array.from([0x10, 0x20, 0x30]); + const a = hash(arr); + const b = hash.create().update(arr).digest(); +} +const shka = shake128(Uint8Array.from([0x10]), { dkLen: 512 }); +const shkb = shake256(Uint8Array.from([0x30]), { dkLen: 512 }); +``` + +Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf), +[Website](https://keccak.team/keccak.html). + +Check out [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub) + +#### sha3-addons: cSHAKE, KMAC, K12, TurboSHAKE + +```typescript +import { + cshake128, cshake256, kt128, kt256, + keccakprg, kmac128, kmac256, + parallelhash256, tuplehash256, + turboshake128, turboshake256, +} from '@noble/hashes/sha3-addons.js'; +const data = Uint8Array.from([0x10, 0x20, 0x30]); +const personalization = new TextEncoder().encode('def'); +const ec1 = cshake128(data, { personalization }); +const ec2 = cshake256(data, { personalization }); +const et1 = turboshake128(data); +const et2 = turboshake256(data, { D: 0x05 }); +// tuplehash(['ab', 'c']) !== tuplehash(['a', 'bc']) !== tuplehash([data]) +const et3 = tuplehash256([new TextEncoder().encode('ab'), new TextEncoder().encode('c')]); +// Not parallel in JS (similar to blake3 / kt128), added for compat +const ep1 = parallelhash256(data, { blockLen: 8 }); +const kk = Uint8Array.from([0xca]); +const ek10 = kmac128(kk, data); +const ek11 = kmac256(kk, data); +const ek12 = kt128(data); // kangarootwelve 128-bit +const ek13 = kt256(data); // kangarootwelve 256-bit +// pseudo-random generator, first argument is capacity. XKCP recommends 254 bits capacity for 128-bit security strength. +// * with a capacity of 254 bits. +const p = keccakprg(254); +p.addEntropy(Uint8Array.from([1, 2, 3])); +const rand1b = p.randomBytes(32); +``` + +- cSHAKE, KMAC, TupleHash, ParallelHash + XOF are available, matching + [NIST SP 800-185](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf) +- Reduced-round Keccak KT128 (KangarooTwelve 🦘, K12) and TurboSHAKE are available, matching + [RFC 9861](https://datatracker.ietf.org/doc/rfc9861/). +- [KeccakPRG](https://keccak.team/files/CSF-0.1.pdf): pseudo-random generator based on Keccak + +#### blake1, blake2, blake3 + +```typescript +import { blake224, blake256, blake384, blake512 } from '@noble/hashes/blake1.js'; +import { blake2b, blake2s } from '@noble/hashes/blake2.js'; +import { blake3 } from '@noble/hashes/blake3.js'; + +for (let hash of [blake224, blake256, blake384, blake512, blake2b, blake2s, blake3]) { + const arr = Uint8Array.from([0x10, 0x20, 0x30]); + const a = hash(arr); + const b = hash.create().update(arr).digest(); +} + +// blake2 advanced usage +const ab = Uint8Array.from([0x01]); +const txt = new TextEncoder(); +blake2s(ab); +blake2s(ab, { key: new Uint8Array(32) }); +blake2s(ab, { personalization: txt.encode('pers1234') }); +blake2s(ab, { salt: txt.encode('salt1234') }); +blake2b(ab); +blake2b(ab, { key: new Uint8Array(64) }); +blake2b(ab, { personalization: txt.encode('pers1234pers1234') }); +blake2b(ab, { salt: txt.encode('salt1234salt1234') }); + +// blake3 advanced usage +blake3(ab); +blake3(ab, { dkLen: 256 }); +blake3(ab, { key: new Uint8Array(32) }); +blake3(ab, { context: txt.encode('application-name') }); +``` + +- Blake1 is legacy hash, one of SHA3 proposals. It is rarely used anywhere. See [pdf](https://www.aumasson.jp/blake/blake.pdf). +- Blake2 is popular fast hash. blake2b focuses on 64-bit platforms while blake2s is for 8-bit to 32-bit ones. See [RFC 7693](https://datatracker.ietf.org/doc/html/rfc7693), [Website](https://www.blake2.net) +- Blake3 is faster, reduced-round blake2. See [Website & specs](https://blake3.io) + +#### legacy: sha1, md5, ripemd160 + +SHA1 (RFC 3174), MD5 (RFC 1321) and RIPEMD160 (RFC 2286) legacy, weak hash functions. +Don't use them in a new protocol. What "weak" means: + +- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160. +- No practical pre-image attacks (only theoretical, 2^123.4) +- HMAC seems kinda ok: https://datatracker.ietf.org/doc/html/rfc6151 + +```typescript +import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js'; +for (let hash of [md5, ripemd160, sha1]) { + const arr = Uint8Array.from([0x10, 0x20, 0x30]); + const a = hash(arr); + const b = hash.create().update(arr).digest(); +} +``` + +#### hmac + +```typescript +import { hmac } from '@noble/hashes/hmac.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +const key = new Uint8Array(32).fill(1); +const msg = new Uint8Array(32).fill(2); +const mac1 = hmac(sha256, key, msg); +const mac2 = hmac.create(sha256, key).update(msg).digest(); +``` + +Conforms to [RFC 2104](https://datatracker.ietf.org/doc/html/rfc2104). + +#### hkdf + +```typescript +import { hkdf } from '@noble/hashes/hkdf.js'; +import { randomBytes } from '@noble/hashes/utils.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = new TextEncoder().encode('application-key'); +const hk1 = hkdf(sha256, inputKey, salt, info, 32); + +// == same as +import { extract, expand } from '@noble/hashes/hkdf.js'; +const prk = extract(sha256, inputKey, salt); +const hk2 = expand(sha256, prk, info, 32); +``` + +Conforms to [RFC 5869](https://datatracker.ietf.org/doc/html/rfc5869). + +#### pbkdf2 + +```typescript +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +const pbkey1 = pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 }); +const pbkey2 = await pbkdf2Async(sha256, 'password', 'salt', { c: 524288, dkLen: 32 }); +const pbkey3 = await pbkdf2Async(sha256, Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + c: 524288, + dkLen: 32, +}); +``` + +Conforms to [RFC 2898](https://datatracker.ietf.org/doc/html/rfc2898). + +#### scrypt + +```typescript +import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js'; +const scr1 = scrypt('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr2 = await scryptAsync('password', 'salt', { N: 2 ** 16, r: 8, p: 1, dkLen: 32 }); +const scr3 = await scryptAsync(Uint8Array.from([1, 2, 3]), Uint8Array.from([4, 5, 6]), { + N: 2 ** 17, + r: 8, + p: 1, + dkLen: 32, + onProgress(percentage) { + console.log('progress', percentage); + }, + maxmem: 2 ** 32 + 128 * 8 * 1, // N * r * p * 128 + (128*r*p) +}); +``` + +Conforms to [RFC 7914](https://datatracker.ietf.org/doc/html/rfc7914), +[Website](https://www.tarsnap.com/scrypt.html) + +- `N, r, p` are work factors. It is common to only adjust N, while keeping `r: 8, p: 1`. + See [the blog post](https://blog.filippo.io/the-scrypt-parameters/). + JS doesn't support parallelization, making increasing `p` meaningless. +- `dkLen` is the length of output bytes e.g. `32` or `64` +- `onProgress` can be used with async version of the function to report progress to a user. +- `maxmem` prevents DoS and is limited to `1GB + 1KB` (`2**30 + 2**10`), but can be adjusted using formula: `N * r * p * 128 + (128 * r * p)` + +Time it takes to derive Scrypt key under different values of N (2\*\*N) on Apple M4 (mobile phones can be 1x-4x slower): + +| N pow | Time | RAM | +| ----- | ---- | ----- | +| 16 | 0.1s | 64MB | +| 17 | 0.2s | 128MB | +| 18 | 0.4s | 256MB | +| 19 | 0.8s | 512MB | +| 20 | 1.5s | 1GB | +| 21 | 3.1s | 2GB | +| 22 | 6.2s | 4GB | +| 23 | 13s | 8GB | +| 24 | 27s | 16GB | + +> [!NOTE] +> We support N larger than `2**20` where available, however, +> not all JS engines support >= 2GB ArrayBuffer-s. +> When using such N, you'll need to manually adjust `maxmem`, using formula above. +> Other JS implementations don't support large N-s. + +#### argon2 + +```ts +import { argon2d, argon2i, argon2id } from '@noble/hashes/argon2.js'; +const arg1 = argon2id('password', 'saltsalt', { t: 2, m: 65536, p: 1, maxmem: 2 ** 32 - 1 }); +``` + +Argon2 [RFC 9106](https://datatracker.ietf.org/doc/html/rfc9106) implementation. + +> [!WARNING] +> Argon2 can't be fast in JS, because there is no fast Uint64Array. +> It is suggested to use [Scrypt](#scrypt) instead. +> Being 5x slower than native code means brute-forcing attackers have bigger advantage. + +#### webcrypto: friendly wrapper + +```js +import { sha256, sha384, sha512, hmac, hkdf, pbkdf2 } from '@noble/hashes/webcrypto.js'; +import { randomBytes } from '@noble/hashes/utils.js'; +const whash = await sha256(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); + +const key = new Uint8Array(32).fill(1); +const msg = new Uint8Array(32).fill(2); +const wmac = await hmac(sha256, key, msg); + +const inputKey = randomBytes(32); +const salt = randomBytes(32); +const info = new TextEncoder().encode('application-key'); +const hk1 = await hkdf(sha256, inputKey, salt, info, 32); + +const pbkey1 = await pbkdf2(sha256, 'password', 'salt', { c: 524288, dkLen: 32 }); +``` + +Sometimes people want to use built-in `crypto.subtle` instead of pure JS implementation. +However, it has terrible API. + +We simplify access to built-ins with API which mirrors noble-hashes. +The overhead is minimal - just 30+ lines of code, which verify input correctness. + +> [!NOTE] +> Webcrypto methods are always async. + +#### utils + +```typescript +import { bytesToHex as toHex, randomBytes } from '@noble/hashes/utils.js'; +console.log(toHex(randomBytes(32))); +``` + +- `bytesToHex` will convert `Uint8Array` to a hex string +- `randomBytes(bytes)` will produce cryptographically secure random `Uint8Array` of length `bytes` + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/noble-hashes/compare/2.2.0..main) +- at version 1.0.0, in Jan 2022, independently, by [Cure53](https://cure53.de) + - PDFs: [website](https://cure53.de/pentest-report_hashing-libs.pdf), [in-repo](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - Scope: everything, besides `blake3`, `sha3-addons`, `sha1` and `argon2`, which have not been audited + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +It is tested against property-based, cross-library and Wycheproof vectors, +and is being fuzzed in [the separate repo](https://github.com/paulmillr/fuzzing). + +If you see anything unusual: investigate and report. + +### Constant-timeness + +We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time" +extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance +in a scripting language. Which means _any other JS library can't have +constant-timeness_. Even statically typed Rust, a language without GC, +[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security) +for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones. +Use low-level libraries & languages. + +### Memory dumping + +The library shares state buffers between hash +function calls. The buffers are zeroed-out after each call. However, if an attacker +can read application memory, you are doomed in any case: + +- At some point, input will be a string and strings are immutable in JS: + there is no way to overwrite them with zeros. For example: deriving + key from `scrypt(password, salt)` where password and salt are strings +- Input from a file will stay in file buffers +- Input / output will be re-used multiple times in application which means it could stay in memory +- `await anything()` will always write all internal variables (including numbers) + to memory. With async functions / Promises there are no guarantees when the code + chunk would be executed. Which means attacker can have plenty of time to read data from memory +- There is no way to guarantee anything about zeroing sensitive data without + complex tests-suite which will dump process memory and verify that there is + no sensitive data left. For JS it means testing all browsers (incl. mobile), + which is complex. And of course it will be useless without using the same + test-suite in the actual application that consumes the library + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there are 0 dependencies; and a few dev dependencies: + +- jsbt contains helpers for building, benchmarking & testing secure JS apps. It is developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +### Randomness + +We rely on the built-in +[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), +which is considered a cryptographically secure PRNG. + +Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy. + +### Quantum computers + +Cryptographically relevant quantum computer, if built, will allow to +utilize Grover's algorithm to break hashes in 2^n/2 operations, instead of 2^n. + +This means SHA256 should be replaced with SHA512, SHA3-256 with SHA3-512, SHAKE128 with SHAKE256 etc. + +Australian ASD prohibits SHA256 and similar hashes [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography). + +## Upgrading + +Supported node.js versions: + +- v2: v20.19+ (ESM-only) +- v1: v14.21+ (ESM & CJS) + +v2.0 changelog: + +- The package is now ESM-only. ESM can finally be loaded from common.js on node v20.19+ +- `.js` extension must be used for all modules + - Old: `@noble/hashes/sha3` + - New: `@noble/hashes/sha3.js` + - This simplifies working in browsers natively without transpilers +- Only allow Uint8Array as hash inputs, prohibit `string` + - Strict validation checks improve security + - To replicate previous behavior, use `utils.utf8ToBytes` +- Rename / remove some modules for consistency. Previously, sha384 resided in sha512, which was weird + - `sha256`, `sha512` => `sha2.js` (consistent with `sha3.js`) + - `blake2b`, `blake2s` => `blake2.js` (consistent with `blake3.js`, `blake1.js`) + - `ripemd160`, `sha1`, `md5` => `legacy.js` (all low-security hashes are there) + - `_assert` => `utils.js` + - `crypto` internal module got removed: use built-in WebCrypto instead +- Improve typescript types & option autocomplete +- Bump compilation target from es2020 to es2022 + +## Contributing & testing + +`test/misc` directory contains implementations of loop unrolling and md5. + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run bench` will run benchmarks +- `npm run build:release` will build single file +- There is **additional** 20-min DoS test `npm run test:dos` and 2-hour multicore test `npm run test:slow`. + See [our approach to testing](./test/README.md) + +Some hashes are outside of scope of the library: +- [Pedersen in micro-zk-proofs](https://github.com/paulmillr/micro-zk-proofs/blob/1ed5ce1253583b2e540eef7f3477fb52bf5344ff/src/pedersen.ts) +- [Poseidon in noble-curves](https://github.com/paulmillr/noble-curves/blob/3d124dd3ecec8b6634cc0b2ba1c183aded5304f9/src/abstract/poseidon.ts) +- [Poly1305 & GHash in noble-ciphers](https://github.com/paulmillr/noble-ciphers) + +See [paulmillr.com/noble](https://paulmillr.com/noble/) for useful resources, articles, documentation and demos related to the library. + +## Speed + +```sh +npm run bench +``` + +Benchmarks measured on Apple M4. If you need truly exemplar performance, switch to [awasm-noble](https://github.com/paulmillr/awasm-noble). + +``` +# 32B +sha256 x 2,016,129 ops/sec @ 496ns/op +sha512 x 740,740 ops/sec @ 1μs/op +sha3_256 x 287,686 ops/sec @ 3μs/op +sha3_512 x 288,267 ops/sec @ 3μs/op +k12 x 476,190 ops/sec @ 2μs/op +blake2b x 410,340 ops/sec @ 2μs/op +blake2s x 942,507 ops/sec @ 1μs/op +blake3 x 1,006,036 ops/sec @ 994ns/op +ripemd160 x 1,410,437 ops/sec @ 709ns/op +md5 x 1,663,893 ops/sec @ 601ns/op +sha1 x 1,589,825 ops/sec @ 629ns/op + +# 1MB +sha256 x 331 ops/sec @ 3ms/op +sha512 x 128 ops/sec @ 7ms/op +sha3_256 x 39 ops/sec @ 25ms/op +sha3_512 x 21 ops/sec @ 46ms/op +kt128 x 91 ops/sec @ 10ms/op +kt256 x 75 ops/sec @ 13ms/op +turboshake128 x 93 ops/sec @ 10ms/op +blake256 x 57 ops/sec @ 17ms/op +blake2b x 61 ops/sec @ 16ms/op +blake2s x 78 ops/sec @ 12ms/op +blake3 x 95 ops/sec @ 10ms/op +ripemd160 x 177 ops/sec @ 5ms/op +md5 x 250 ops/sec @ 3ms/op +sha1 x 416 ops/sec @ 2ms/op + +# MAC +hmac(sha256) x 599,880 ops/sec @ 1μs/op +hmac(sha512) x 197,122 ops/sec @ 5μs/op +kmac256 x 87,981 ops/sec @ 11μs/op +blake3(key) x 796,812 ops/sec @ 1μs/op + +# KDF +hkdf(sha256) x 259,942 ops/sec @ 3μs/op +blake3(context) x 424,808 ops/sec @ 2μs/op +pbkdf2(sha256, c: 2 ** 18) x 5 ops/sec @ 197ms/op +pbkdf2(sha512, c: 2 ** 18) x 1 ops/sec @ 630ms/op +scrypt(n: 2 ** 18, r: 8, p: 1) x 2 ops/sec @ 400ms/op +argon2id(t: 1, m: 256MB) 2881ms +``` + +The library could be 3x faster by utilizing loop unrolling. It isn't used because +unrolling a) would increase bundle size b) make lib un-readable c) current perf is "fast enough" +for most use-cases. + +## License + +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/hashes/_blake.d.ts b/node_modules/@noble/hashes/_blake.d.ts new file mode 100644 index 0000000..e509cf5 --- /dev/null +++ b/node_modules/@noble/hashes/_blake.d.ts @@ -0,0 +1,21 @@ +/** + * Internal helpers for blake hash. + * @module + */ +import { type TRet } from './utils.ts'; +/** + * Internal blake permutation table. + * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also + * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows + * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants. + */ +export declare const BSIGMA: TRet; +export type Num4 = { + a: number; + b: number; + c: number; + d: number; +}; +export declare function G1s(a: number, b: number, c: number, d: number, x: number): Num4; +export declare function G2s(a: number, b: number, c: number, d: number, x: number): Num4; +//# sourceMappingURL=_blake.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_blake.d.ts.map b/node_modules/@noble/hashes/_blake.d.ts.map new file mode 100644 index 0000000..c7de007 --- /dev/null +++ b/node_modules/@noble/hashes/_blake.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake.d.ts","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAQ,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AAEH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,UAAU,CAkBlC,CAAC;AAGH,MAAM,MAAM,IAAI,GAAG;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,CAAC;CAAE,CAAC;AAKnE,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E;AAKD,wBAAgB,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,IAAI,CAM/E"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_blake.js b/node_modules/@noble/hashes/_blake.js new file mode 100644 index 0000000..23a11c6 --- /dev/null +++ b/node_modules/@noble/hashes/_blake.js @@ -0,0 +1,52 @@ +/** + * Internal helpers for blake hash. + * @module + */ +import { rotr } from "./utils.js"; +/** + * Internal blake permutation table. + * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also + * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows + * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants. + */ +// prettier-ignore +export const BSIGMA = /* @__PURE__ */ Uint8Array.from([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + // Blake1, unused in others + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, +]); +// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair. +// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed +// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path. +export function G1s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} +// 32-bit / BLAKE2s second half of G. +// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed +// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path. +export function G2s(a, b, c, d, x) { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} +//# sourceMappingURL=_blake.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_blake.js.map b/node_modules/@noble/hashes/_blake.js.map new file mode 100644 index 0000000..1869f1b --- /dev/null +++ b/node_modules/@noble/hashes/_blake.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_blake.js","sourceRoot":"","sources":["src/_blake.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAa,MAAM,YAAY,CAAC;AAE7C;;;;;GAKG;AACH,kBAAkB;AAClB,MAAM,CAAC,MAAM,MAAM,GAAqB,eAAe,CAAC,UAAU,CAAC,IAAI,CAAC;IACtE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;IACpD,EAAE,EAAE,EAAE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CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChB,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;IACnB,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC;AACxB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_md.d.ts b/node_modules/@noble/hashes/_md.d.ts new file mode 100644 index 0000000..44b0272 --- /dev/null +++ b/node_modules/@noble/hashes/_md.d.ts @@ -0,0 +1,99 @@ +/** + * Internal Merkle-Damgard hash utils. + * @module + */ +import { type Hash, type TArg, type TRet } from './utils.ts'; +/** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export declare function Chi(a: number, b: number, c: number): number; +/** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export declare function Maj(a: number, b: number, c: number): number; +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ +export declare abstract class HashMD> implements Hash { + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF = false; + readonly padOffset: number; + readonly isLE: boolean; + protected buffer: Uint8Array; + protected view: DataView; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean); + update(data: TArg): this; + digestInto(out: TArg): void; + digest(): TRet; + _cloneInto(to?: T): T; + clone(): T; +} +/** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ +/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ +export declare const SHA256_IV: TRet; +/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must + * treat it as read-only because constructors copy words from it by index. */ +export declare const SHA224_IV: TRet; +/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth + * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only + * because constructors copy halves from it by index. */ +export declare const SHA384_IV: TRet; +/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first + * eight prime numbers. Exported as a shared table; callers must treat it as read-only because + * constructors copy halves from it by index. */ +export declare const SHA512_IV: TRet; +//# sourceMappingURL=_md.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_md.d.ts.map b/node_modules/@noble/hashes/_md.d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;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;gBAEhB,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO;IAQjF,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IA0BpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAkCvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;IAS1B,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,CAAC;IAarB,KAAK,IAAI,CAAC;CAGX;AAED;;;GAGG;AAEH;;uEAEuE;AACvE,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;6EAC6E;AAC7E,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAEtC,CAAC;AAEH;;;wDAGwD;AACxD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC;AAEH;;;gDAGgD;AAChD,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,WAAW,CAGtC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_md.js b/node_modules/@noble/hashes/_md.js new file mode 100644 index 0000000..0fda375 --- /dev/null +++ b/node_modules/@noble/hashes/_md.js @@ -0,0 +1,202 @@ +/** + * Internal Merkle-Damgard hash utils. + * @module + */ +import { abytes, aexists, aoutput, clean, createView, } from "./utils.js"; +/** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Chi(a, b, c) { + return (a & b) ^ (~a & c); +} +/** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Maj(a, b, c) { + return (a & b) ^ (a & c) ^ (b & c); +} +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ +export class HashMD { + blockLen; + outputLen; + canXOF = false; + padOffset; + isLE; + // For partial updates less than block size + buffer; + view; + finished = false; + length = 0; + pos = 0; + destroyed = false; + constructor(blockLen, outputLen, padOffset, isLE) { + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + clean(this.buffer.subarray(pos)); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from + // the padding fill above, and JS will overflow before user input can make that half non-zero. + // So we only need to write the low 64 bits here. + view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT + if (len % 4) + throw new Error('_sha2: outputLen must be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return + // fresh bytes to the caller. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to ||= new this.constructor(); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and + // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it. + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + clone() { + return this._cloneInto(); + } +} +/** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ +/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ +export const SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]); +/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must + * treat it as read-only because constructors copy words from it by index. */ +export const SHA224_IV = /* @__PURE__ */ Uint32Array.from([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, +]); +/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth + * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only + * because constructors copy halves from it by index. */ +export const SHA384_IV = /* @__PURE__ */ Uint32Array.from([ + 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4, +]); +/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first + * eight prime numbers. Exported as a shared table; callers must treat it as read-only because + * constructors copy halves from it by index. */ +export const SHA512_IV = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, +]); +//# sourceMappingURL=_md.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_md.js.map b/node_modules/@noble/hashes/_md.js.map new file mode 100644 index 0000000..9f2e86c --- /dev/null +++ b/node_modules/@noble/hashes/_md.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_md.js","sourceRoot":"","sources":["src/_md.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,MAAM,EACN,OAAO,EACP,OAAO,EACP,KAAK,EACL,UAAU,GAIX,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS;IACjD,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5B,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,GAAG,CAAC,CAAS,EAAE,CAAS,EAAE,CAAS;IACjD,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AACrC,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,OAAgB,MAAM;IASjB,QAAQ,CAAS;IACjB,SAAS,CAAS;IAClB,MAAM,GAAG,KAAK,CAAC;IACf,SAAS,CAAS;IAClB,IAAI,CAAU;IAEvB,2CAA2C;IACjC,MAAM,CAAa;IACnB,IAAI,CAAW;IACf,QAAQ,GAAG,KAAK,CAAC;IACjB,MAAM,GAAG,CAAC,CAAC;IACX,GAAG,GAAG,CAAC,CAAC;IACR,SAAS,GAAG,KAAK,CAAC;IAE5B,YAAY,QAAgB,EAAE,SAAiB,EAAE,SAAiB,EAAE,IAAa;QAC/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IAAI,CAAC;IAC3E,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;IAC9F,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC/F,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.d.ts b/node_modules/@noble/hashes/_u64.d.ts new file mode 100644 index 0000000..306b1c5 --- /dev/null +++ b/node_modules/@noble/hashes/_u64.d.ts @@ -0,0 +1,63 @@ +/** + * Internal helpers for u64. + * BigUint64Array is too slow as per 2026, so we implement it using + * Uint32Array. + * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588} + * @module + */ +import type { TRet } from './utils.ts'; +declare function fromBig(n: bigint, le?: boolean): { + h: number; + l: number; +}; +declare function split(lst: bigint[], le?: boolean): TRet; +declare const toBig: (h: number, l: number) => bigint; +declare const shrSH: (h: number, _l: number, s: number) => number; +declare const shrSL: (h: number, l: number, s: number) => number; +declare const rotrSH: (h: number, l: number, s: number) => number; +declare const rotrSL: (h: number, l: number, s: number) => number; +declare const rotrBH: (h: number, l: number, s: number) => number; +declare const rotrBL: (h: number, l: number, s: number) => number; +declare const rotr32H: (_h: number, l: number) => number; +declare const rotr32L: (h: number, _l: number) => number; +declare const rotlSH: (h: number, l: number, s: number) => number; +declare const rotlSL: (h: number, l: number, s: number) => number; +declare const rotlBH: (h: number, l: number, s: number) => number; +declare const rotlBL: (h: number, l: number, s: number) => number; +declare function add(Ah: number, Al: number, Bh: number, Bl: number): { + h: number; + l: number; +}; +declare const add3L: (Al: number, Bl: number, Cl: number) => number; +declare const add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; +declare const add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; +declare const add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; +declare const add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +declare const add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; +export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig }; +declare const u64: { + fromBig: typeof fromBig; + split: typeof split; + toBig: (h: number, l: number) => bigint; + shrSH: (h: number, _l: number, s: number) => number; + shrSL: (h: number, l: number, s: number) => number; + rotrSH: (h: number, l: number, s: number) => number; + rotrSL: (h: number, l: number, s: number) => number; + rotrBH: (h: number, l: number, s: number) => number; + rotrBL: (h: number, l: number, s: number) => number; + rotr32H: (_h: number, l: number) => number; + rotr32L: (h: number, _l: number) => number; + rotlSH: (h: number, l: number, s: number) => number; + rotlSL: (h: number, l: number, s: number) => number; + rotlBH: (h: number, l: number, s: number) => number; + rotlBL: (h: number, l: number, s: number) => number; + add: typeof add; + add3L: (Al: number, Bl: number, Cl: number) => number; + add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; + add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; + add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; + add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; + add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; +}; +export default u64; +//# sourceMappingURL=_u64.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.d.ts.map b/node_modules/@noble/hashes/_u64.d.ts.map new file mode 100644 index 0000000..6fa63a4 --- /dev/null +++ b/node_modules/@noble/hashes/_u64.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.d.ts","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAOvC,iBAAS,OAAO,CACd,CAAC,EAAE,MAAM,EACT,EAAE,UAA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EAAE,EAAE,MAAM,KAAK,MAAM,CAAC;CAOrpC,CAAC;AAEF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.js b/node_modules/@noble/hashes/_u64.js new file mode 100644 index 0000000..e66551e --- /dev/null +++ b/node_modules/@noble/hashes/_u64.js @@ -0,0 +1,84 @@ +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); +// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high +// }` to match little-endian word order rather than the property names. +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array +// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`. +function split(lst, le = false) { + const len = lst.length; + let Ah = new Uint32Array(len); + let Al = new Uint32Array(len); + for (let i = 0; i < len; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS +// bitwise results back to uint32 first, and little-endian callers must swap. +const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`. +const shrSH = (h, _l, s) => h >>> s; +// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`. +const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s)); +// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half. +const rotr32H = (_h, l) => l; +// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half. +const rotr32L = (h, _l) => h; +// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`. +const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s)); +// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`. +const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s)); +// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s)); +// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s)); +// Add two split 64-bit words and return the split `{ h, l }` sum. +// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out +// of the low sum and instead use division. +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`. +const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`. +const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`. +const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`. +const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`. +const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`. +const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; +// prettier-ignore +export { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig }; +// Canonical grouped namespace for callers that prefer one object. +// Named exports stay for direct imports. +// prettier-ignore +const u64 = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// Default export mirrors named `u64` for compatibility with object-style imports. +export default u64; +//# sourceMappingURL=_u64.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/_u64.js.map b/node_modules/@noble/hashes/_u64.js.map new file mode 100644 index 0000000..538e533 --- /dev/null +++ b/node_modules/@noble/hashes/_u64.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_u64.js","sourceRoot":"","sources":["src/_u64.ts"],"names":[],"mappings":"AASA,MAAM,UAAU,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAC;AACvD,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AAExC,iGAAiG;AACjG,uEAAuE;AACvE,SAAS,OAAO,CACd,CAAS,EACT,EAAE,GAAG,KAA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AC,EAAE,KAAK,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC;AACjE,oGAAoG;AACpG,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAE,EAAU,EAAU,EAAE,CAChG,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAEvD,kBAAkB;AAClB,OAAO,EACL,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EACrK,CAAC;AACF,kEAAkE;AAClE,yCAAyC;AACzC,kBAAkB;AAClB,MAAM,GAAG,GAAkpC;IACzpC,OAAO,EAAE,KAAK,EAAE,KAAK;IACrB,KAAK,EAAE,KAAK;IACZ,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,OAAO,EAAE,OAAO;IAChB,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM;IAC9B,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK;CAC9C,CAAC;AACF,kFAAkF;AAClF,eAAe,GAAG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.d.ts b/node_modules/@noble/hashes/argon2.d.ts new file mode 100644 index 0000000..541fdac --- /dev/null +++ b/node_modules/@noble/hashes/argon2.d.ts @@ -0,0 +1,112 @@ +import { type KDFInput, type TArg, type TRet } from './utils.ts'; +/** Argon2 cost, output, and optional secret/personalization inputs. */ +export type ArgonOpts = { + /** Time cost measured in iterations. */ + t: number; + /** Memory cost in kibibytes. */ + m: number; + /** Parallelization parameter. */ + p: number; + /** Argon2 version number. Defaults to `0x13`. */ + version?: number; + /** Optional secret key mixed into initialization. */ + key?: KDFInput; + /** Optional personalization string or bytes. */ + personalization?: KDFInput; + /** Desired output length in bytes. RFC 9106 §3.1 requires `T` in the 4..(2^32 - 1) range. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variants. */ + asyncTick?: number; + /** Maximum temporary memory budget in bytes. */ + maxmem?: number; + /** + * Optional progress callback invoked during long-running derivations. + * param progress - completion fraction in the `0..1` range + */ + onProgress?: (progress: number) => void; +}; +/** + * Argon2d GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d. + * ```ts + * argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2d: (password: TArg, salt: TArg, opts: TArg) => TRet; +/** + * Argon2i side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i. + * ```ts + * argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2i: (password: TArg, salt: TArg, opts: TArg) => TRet; +/** + * Argon2id, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id. + * ```ts + * argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2id: (password: TArg, salt: TArg, opts: TArg) => TRet; +/** + * Argon2d async GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d asynchronously. + * ```ts + * await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2dAsync: (password: TArg, salt: TArg, opts: TArg) => Promise>; +/** + * Argon2i async side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i asynchronously. + * ```ts + * await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2iAsync: (password: TArg, salt: TArg, opts: TArg) => Promise>; +/** + * Argon2id async, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id asynchronously. + * ```ts + * await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare const argon2idAsync: (password: TArg, salt: TArg, opts: TArg) => Promise>; +//# sourceMappingURL=argon2.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.d.ts.map b/node_modules/@noble/hashes/argon2.d.ts.map new file mode 100644 index 0000000..6d0f0d8 --- /dev/null +++ b/node_modules/@noble/hashes/argon2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.d.ts","sourceRoot":"","sources":["src/argon2.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,KACpB,IAAI,CAAC,UAAU,CAA8C,CAAC;AA2EjE;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAmD,CAAC;AAC/E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,YAAY,GACvB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAkD,CAAC;AAC9E;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,aAAa,GACxB,UAAU,IAAI,CAAC,QAAQ,CAAC,EACxB,MAAM,IAAI,CAAC,QAAQ,CAAC,EACpB,MAAM,IAAI,CAAC,SAAS,CAAC,KACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAmD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.js b/node_modules/@noble/hashes/argon2.js new file mode 100644 index 0000000..b2fcd1f --- /dev/null +++ b/node_modules/@noble/hashes/argon2.js @@ -0,0 +1,517 @@ +/** + * Argon2 KDF from RFC 9106. Can be used to create a key from password and salt. + * We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness: + * * argon uses uint64, but JS doesn't have fast uint64array + * * uint64 multiplication is 1/3 of time + * * `P` function would be very nice with u64, because most of value will be in registers, + * hovewer with u32 it will require 32 registers, which is too much. + * * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down + * @module + */ +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from "./_u64.js"; +import { blake2b } from "./blake2.js"; +import { anumber, clean, kdfInputToBytes, nextTick, swap32IfBE, swap8IfBE, u32, u8, } from "./utils.js"; +// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the +// spec-bound part here; the object keys are internal labels. +const AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 }; +// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob. +const ARGON2_SYNC_POINTS = 4; +// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted +// optional fields by emitting empty bytes. +const abytesOrZero = (buf, errorTitle = '') => { + if (buf === undefined) + return Uint8Array.of(); + return kdfInputToBytes(buf, errorTitle); +}; +// Unsigned `u32 * u32 = { h, l }`, returned as split 64-bit halves. +function mul(a, b) { + // Split into 16-bit limbs so each partial product stays exact under `Math.imul`. + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const carry = (ll >>> 16) + (hl & 0xffff) + lh; + const high = (hh + (hl >>> 16) + (carry >>> 16)) | 0; + const low = (carry << 16) | (ll & 0xffff); + return { h: high, l: low }; +} +function mul2(a, b) { + // Double the split 64-bit product; carry from `l` is folded back into `h` via `l >>> 31`. + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} +// BlaMka permutation for Argon2 +// `A + B + 2 * trunc(A) * trunc(B)`, where `trunc(...)` means the low 32-bit halves. +function blamka(Ah, Al, Bh, Bl) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} +// Temporary block buffer. +// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's +// 8x8 matrix of 16-byte registers. +const A2_BUF = new Uint32Array(256); +// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s. +function G(a, b, c, d) { + let Al = A2_BUF[2 * a], Ah = A2_BUF[2 * a + 1]; // prettier-ignore + let Bl = A2_BUF[2 * b], Bh = A2_BUF[2 * b + 1]; // prettier-ignore + let Cl = A2_BUF[2 * c], Ch = A2_BUF[2 * c + 1]; // prettier-ignore + let Dl = A2_BUF[2 * d], Dh = A2_BUF[2 * d + 1]; // prettier-ignore + // RFC 9106 Figure 19 GB rotates by 32, 24, 16, and 63 bits after each XOR step. + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + ((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah)); + ((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh)); + ((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch)); + ((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh)); +} +// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves. +// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word +// indices inside eight 16-byte inputs, not copied word values. +// prettier-ignore +function P(v00, v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15) { + // RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix. + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} +function block(x, xPos, yPos, outPos, needXor) { + for (let i = 0; i < 256; i++) + A2_BUF[i] = x[xPos + i] ^ x[yPos + i]; + // rows (8 consecutive 16-register groups) + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P(i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15); + } + // columns (8 strided 16-register groups) + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P(i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113); + } + // RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y). + if (needXor) + for (let i = 0; i < 256; i++) + x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else + for (let i = 0; i < 256; i++) + x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + clean(A2_BUF); +} +// Variable-Length Hash Function H' +// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`. +function Hp(A, dkLen) { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + // Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x. + T[0] = swap8IfBE(dkLen); + // Fast path + if (dkLen <= 64) + return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only + // `V_{r+1}` is emitted in full at the remaining length. + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) { + const Vh = blake2b.create({}).update(V); + Vh.digestInto(V); + Vh.destroy(); + out.set(V.subarray(0, 32), pos); + } + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + clean(V, T); + // H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes. + return out; +} +// Used only inside process block! +function indexAlpha(r, s, laneLen, segmentLen, index, randL, sameLane = false) { + // RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`. + let area; + if (r === 0) { + if (s === 0) + area = index - 1; + else if (sameLane) + area = s * segmentLen + index - 1; + else + area = s * segmentLen + (index == 0 ? -1 : 0); + } + else if (sameLane) + area = laneLen - segmentLen + index - 1; + else + area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + // RFC 9106 Figure 13: `mul(randL, randL).h` is `floor(J_1^2 / 2^32)`, and the outer high-half + // multiply computes `floor(|W| * x / 2^32)` without floating-point math. + const rel = area - 1 - mul(area, mul(randL, randL).h).h; + return (startPos + rel) % laneLen; +} +// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value. +const maxUint32 = Math.pow(2, 32); +// Validate safe JS integers in `[0, 2^32 - 1]`. +function isU32(num) { + return Number.isSafeInteger(num) && num >= 0 && num < maxUint32; +} +function argon2Opts(opts) { + const merged = { + version: 0x13, + dkLen: 32, + maxmem: maxUint32 - 1, + asyncTick: 10, + }; + // Unknown keys are copied through unchanged here and later ignored unless + // destructuring consumes them. + for (let [k, v] of Object.entries(opts)) + if (v !== undefined) + merged[k] = v; + const { dkLen, p, m, t, version, onProgress, asyncTick } = merged; + // RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1. + if (!isU32(dkLen) || dkLen < 4) + throw new Error('"dkLen" must be 4..'); + if (!isU32(p) || p < 1 || p >= Math.pow(2, 24)) + throw new Error('"p" must be 1..2^24'); + if (!isU32(m)) + throw new Error('"m" must be 0..2^32'); + if (!isU32(t) || t < 1) + throw new Error('"t" (iterations) must be 1..2^32'); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('"progressCb" must be a function'); + anumber(asyncTick, 'asyncTick'); + /* + Memory size m MUST be an integer number of kibibytes from 8*p + to 2^(32)-1. The actual number of blocks is m', which is m + rounded down to the nearest multiple of 4*p. + */ + if (!isU32(m) || m < 8 * p) + throw new Error('"m" (memory) must be at least 8*p bytes'); + // Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`. + if (version !== 0x10 && version !== 0x13) + throw new Error('"version" must be 0x10 or 0x13, got ' + version); + return merged; +} +function argon2Init(password, salt, type, opts) { + password = kdfInputToBytes(password, 'password'); + salt = kdfInputToBytes(salt, 'salt'); + if (!isU32(password.length)) + throw new Error('"password" must be less of length 1..4Gb'); + // RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password + // hashing; this library intentionally takes the stricter common >=8-byte salt path. + if (!isU32(salt.length) || salt.length < 8) + throw new Error('"salt" must be of length 8..4Gb'); + if (!Object.values(AT).includes(type)) + throw new Error('"type" was invalid'); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = argon2Opts(opts); + // Validation + key = abytesOrZero(key, 'key'); + personalization = abytesOrZero(personalization, 'personalization'); + // H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) || + // LE32(v) || LE32(y) || LE32(length(P)) || P || + // LE32(length(S)) || S || LE32(length(K)) || K || + // LE32(length(X)) || X) + const h = blake2b.create(); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (let item of [p, dkLen, m, t, version, type]) { + // RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before exposing bytes. + BUF[0] = swap8IfBE(item); + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes + h.update(BUF8).update(i); + } + // Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append + // `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks. + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation. + const memUsed = mP * 1024; + if (!isU32(maxmem)) + throw new Error('"maxmem" expected <2**32, got ' + maxmem); + if (memUsed > maxmem) + throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem); + const B = new Uint32Array(memUsed / 4); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = swap8IfBE(l); + H0[16] = swap8IfBE(0); + B.set(swap32IfBE(u32(Hp(H0, 1024))), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = swap8IfBE(1); + B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256); + } + let perBlock = () => { }; + if (onProgress) { + // The first segment of the first pass skips two preinitialized blocks per lane. + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + clean(BUF, H0); + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick }; +} +function argon2Output(B, p, laneLen, dkLen) { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) + B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + // RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words + // back to spec byte order before `Hp(...)` reinterprets them as bytes. + const res = Hp(swap32IfBE(B_final), dkLen); + // Wipe both the xor scratch and the full working matrix once final digest bytes exist. + // JS cleanup is still only best-effort, but this local buffer is no longer needed here. + clean(B, B_final); + return res; +} +function processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor) { + if (offset % laneLen) + prev = offset - 1; + let randL, randH; + if (dataIndependent) { + let i128 = index % 128; + // RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so regenerate + // it whenever the segment index crosses a multiple of 128. + if (i128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * i128]; + randH = address[2 * i128 + 1]; + } + else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // Address-block path selects `J1` / `J2`, then maps them to the reference + // lane/block per RFC 9106 §3.4. + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} +function argon2(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init(password, salt, type, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + // RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy + // `0x10` keeps the older overwrite behavior used by the v16 test vectors. + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + // RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only + // in pass 0, slices 0 and 1; Argon2i uses it in every segment. + const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + } + } + } + } + clean(address); + return argon2Output(B, p, laneLen, dkLen); +} +/** + * Argon2d GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d. + * ```ts + * argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2d = (password, salt, opts) => argon2(AT.Argond2d, password, salt, opts); +/** + * Argon2i side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i. + * ```ts + * argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2i = (password, salt, opts) => argon2(AT.Argon2i, password, salt, opts); +/** + * Argon2id, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id. + * ```ts + * argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2id = (password, salt, opts) => argon2(AT.Argon2id, password, salt, opts); +async function argon2Async(type, password, salt, opts) { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } = argon2Init(password, salt, type, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + let ts = Date.now(); + for (let r = 0; r < t; r++) { + // RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy + // `0x10` keeps the older overwrite behavior used by the v16 test vectors. + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + // RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only + // in pass 0, slices 0 and 1; Argon2i uses it in every segment. + const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock(B, address, l, r, s, index, laneLen, segmentLen, lanes, offset, prev, dataIndependent, needXor); + // Date.now() is not monotonic. If the clock goes backwards, + // still yield control. + const diff = Date.now() - ts; + if (!(diff >= 0 && diff < asyncTick)) { + await nextTick(); + ts += diff; + } + } + } + } + } + clean(address); + return argon2Output(B, p, laneLen, dkLen); +} +/** + * Argon2d async GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d asynchronously. + * ```ts + * await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2dAsync = (password, salt, opts) => argon2Async(AT.Argond2d, password, salt, opts); +/** + * Argon2i async side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i asynchronously. + * ```ts + * await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2iAsync = (password, salt, opts) => argon2Async(AT.Argon2i, password, salt, opts); +/** + * Argon2id async, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id asynchronously. + * ```ts + * await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2idAsync = (password, salt, opts) => argon2Async(AT.Argon2id, password, salt, opts); +//# sourceMappingURL=argon2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/argon2.js.map b/node_modules/@noble/hashes/argon2.js.map new file mode 100644 index 0000000..d98e07e --- /dev/null +++ b/node_modules/@noble/hashes/argon2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"argon2.js","sourceRoot":"","sources":["src/argon2.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAC3F,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,OAAO,EACP,KAAK,EACL,eAAe,EACf,QAAQ,EACR,UAAU,EACV,SAAS,EACT,GAAG,EACH,EAAE,GAIH,MAAM,YAAY,CAAC;AAEpB,6FAA6F;AAC7F,6DAA6D;AAC7D,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,EAAW,CAAC;AAG7D,oGAAoG;AACpG,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,6DAA6D;AAC7D,2CAA2C;AAC3C,MAAM,YAAY,GAAG,CAAC,GAAoB,EAAE,UAAU,GAAG,EAAE,EAAoB,EAAE;IAC/E,IAAI,GAAG,KAAK,SAAS;QAAE,OAAO,UAAU,CAAC,EAAE,EAAE,CAAC;IAC9C,OAAO,eAAe,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;AAC1C,CAAC,CAAC;AAEF,oEAAoE;AACpE,SAAS,GAAG,CAAC,CAAS,EAAE,CAAS;IAC/B,iFAAiF;IACjF,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,CAAC,GAAG,MAAM,CAAC;IACtB,MAAM,EAAE,GAAG,CAAC,KAAK,EAAE,CAAC;IACpB,MAAM,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC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AM,CAAC,MAAM,YAAY,GAAG,CAC1B,QAAwB,EACxB,IAAoB,EACpB,IAAqB,EACM,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;AAC9E;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAC3B,QAAwB,EACxB,IAAoB,EACpB,IAAqB,EACM,EAAE,CAAC,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake1.d.ts b/node_modules/@noble/hashes/blake1.d.ts new file mode 100644 index 0000000..11d8782 --- /dev/null +++ b/node_modules/@noble/hashes/blake1.d.ts @@ -0,0 +1,156 @@ +import { type CHash, type Hash, type TArg, type TRet } from './utils.ts'; +/** Blake1 options. Basically just `salt`. */ +export type BlakeOpts = { + /** Optional salt mixed into initialization. */ + salt?: Uint8Array; +}; +declare abstract class BLAKE1> implements Hash { + readonly canXOF = false; + protected finished: boolean; + protected length: number; + protected pos: number; + protected destroyed: boolean; + protected buffer: Uint8Array; + protected view: DataView; + protected salt: Uint32Array; + abstract compress(view: DataView, offset: number, withLength?: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + readonly blockLen: number; + readonly outputLen: number; + private lengthFlag; + private counterLen; + protected constants: Uint32Array; + constructor(blockLen: number, outputLen: number, lengthFlag: number, counterLen: number, saltLen: number, constants: Uint32Array, opts?: BlakeOpts); + update(data: TArg): this; + destroy(): void; + _cloneInto(to?: T): T; + clone(): T; + digestInto(out: TArg): void; + digest(): TRet; +} +declare class BLAKE1_32B extends BLAKE1 { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + destroy(): void; + compress(view: DataView, offset: number, withLength?: boolean): void; +} +declare class BLAKE1_64B extends BLAKE1 { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts?: BlakeOpts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + destroy(): void; + compress(view: DataView, offset: number, withLength?: boolean): void; +} +/** Internal blake1-224 hash class. */ +export declare class _BLAKE224 extends BLAKE1_32B { + constructor(opts?: BlakeOpts); +} +/** Internal blake1-256 hash class. */ +export declare class _BLAKE256 extends BLAKE1_32B { + constructor(opts?: BlakeOpts); +} +/** Internal blake1-384 hash class. */ +export declare class _BLAKE384 extends BLAKE1_64B { + constructor(opts?: BlakeOpts); +} +/** Internal blake1-512 hash class. */ +export declare class _BLAKE512 extends BLAKE1_64B { + constructor(opts?: BlakeOpts); +} +/** + * Blake1-224 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-224. + * ```ts + * blake224(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake224: TRet>; +/** + * Blake1-256 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-256. + * ```ts + * blake256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake256: TRet>; +/** + * Blake1-384 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-384. + * ```ts + * blake384(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake384: TRet>; +/** + * Blake1-512 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-512. + * ```ts + * blake512(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake512: TRet>; +export {}; +//# sourceMappingURL=blake1.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake1.d.ts.map b/node_modules/@noble/hashes/blake1.d.ts.map new file mode 100644 index 0000000..16d351e --- /dev/null +++ b/node_modules/@noble/hashes/blake1.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake1.d.ts","sourceRoot":"","sources":["src/blake1.ts"],"names":[],"mappings":"AA4BA,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB,6CAA6C;AAC7C,MAAM,MAAM,SAAS,GAAG;IACtB,+CAA+C;IAC/C,IAAI,CAAC,EAAE,UAAU,CAAC;CACnB,CAAC;AAOF,uBAAe,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IAC3D,QAAQ,CAAC,MAAM,SAAS;IACxB,SAAS,CAAC,QAAQ,UAAS;IAC3B,SAAS,CAAC,MAAM,SAAK;IACrB,SAAS,CAAC,GAAG,SAAK;IAClB,SAAS,CAAC,SAAS,UAAS;IAE5B,SAAS,CAAC,MAAM,EAAE,UAAU,CAAC;IAC7B,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC;IACzB,SAAS,CAAC,IAAI,EAAE,WAAW,CAAC;IA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C,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC;AACF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC;AACF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,SAAS,CAAC,CAEtD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake1.js b/node_modules/@noble/hashes/blake1.js new file mode 100644 index 0000000..01ff8e0 --- /dev/null +++ b/node_modules/@noble/hashes/blake1.js @@ -0,0 +1,560 @@ +/** + * Blake1 legacy hash function, one of SHA3 proposals. + * Rarely used. Check out blake2 or blake3 instead. + * {@link https://www.aumasson.jp/blake/blake.pdf} + * + * In the best case, there are 0 allocations. + * + * Differences from blake2: + * + * - BE instead of LE + * - Paddings, similar to MD5, RIPEMD, SHA1, SHA2, but: + * - length flag is located before actual length + * - padding block is compressed differently (no lengths) + * Instead of msg[sigma[k]], we have `msg[sigma[k]] ^ constants[sigma[k-1]]` + * (-1 for g1, g2 without -1) + * - Salt is XOR-ed into constants instead of state + * - Salt is XOR-ed with output in `compress` + * - Additional rows (+64 bytes) in SIGMA for new rounds + * - Different round count: + * - 14 / 10 rounds in blake256 / blake2s + * - 16 / 12 rounds in blake512 / blake2b + * - blake512: G1b: rotr 24 -> 25, G2b: rotr 63 -> 11 + * @module + */ +import { BSIGMA, G1s, G2s } from "./_blake.js"; +import { SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js"; +import * as u64 from "./_u64.js"; +// prettier-ignore +import { abytes, aexists, aoutput, clean, createHasher, createView } from "./utils.js"; +// Shared unsalted sentinel, sized for the 64-bit path and reused by the 32-bit path via prefix. +const EMPTY_SALT = /* @__PURE__ */ new Uint32Array(8); +// Base destroy logic only clears salt-derived state; the partial message buffer and length/position +// bookkeeping remain until the instance or backing buffer is reused. +class BLAKE1 { + canXOF = false; + finished = false; + length = 0; + pos = 0; + destroyed = false; + // For partial updates less than block size + buffer; + view; + salt; + blockLen; + outputLen; + lengthFlag; + counterLen; + constants; + constructor(blockLen, outputLen, lengthFlag, counterLen, saltLen, constants, opts = {}) { + const { salt } = opts; + this.blockLen = blockLen; + this.outputLen = outputLen; + this.lengthFlag = lengthFlag; + this.counterLen = counterLen; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + if (salt !== undefined) { + let slt = salt; + abytes(slt, 4 * saltLen, 'salt'); + // if (slt.length !== 4 * saltLen) throw new Error('wrong salt length'); + const salt32 = (this.salt = new Uint32Array(saltLen)); + const sv = createView(slt); + this.constants = constants.slice(); + for (let i = 0, offset = 0; i < salt32.length; i++, offset += 4) { + salt32[i] = sv.getUint32(offset, false); + this.constants[i] ^= salt32[i]; + } + } + else { + this.salt = EMPTY_SALT; + this.constants = constants; + } + } + update(data) { + aexists(this); + abytes(data); + // From _md, but update length before each compress + const { view, buffer, blockLen } = this; + const len = data.length; + let dataView; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + if (!dataView) + dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) { + this.length += blockLen; + this.compress(dataView, pos); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.length += blockLen; + this.compress(view, 0, true); + this.pos = 0; + } + } + return this; + } + destroy() { + this.destroyed = true; + if (this.salt !== EMPTY_SALT) { + clean(this.salt, this.constants); + } + } + _cloneInto(to) { + to ||= new this.constructor(); + to.set(...this.get()); + const { buffer, length, finished, destroyed, constants, salt, pos } = this; + to.buffer.set(buffer); + // Clone salt-derived arrays by value so destroying the clone cannot wipe the source instance. + to.constants = constants.slice(); + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + to.salt = salt.slice(); + return to; + } + clone() { + return this._cloneInto(); + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + const { buffer, blockLen, counterLen, lengthFlag, view } = this; + clean(buffer.subarray(this.pos)); // clean buf + const counter = BigInt((this.length + this.pos) * 8); + const counterPos = blockLen - counterLen - 1; + buffer[this.pos] |= 0b1000_0000; // End block flag + this.length += this.pos; // add unwritten length + // Not enough in buffer for length: write what we have. + if (this.pos > counterPos) { + this.compress(view, 0); + clean(buffer); + this.pos = 0; + } + // Difference with md: here we have lengthFlag! + buffer[counterPos] |= lengthFlag; // Length flag + // We always set 8 byte length flag. Because length will overflow significantly sooner. + view.setBigUint64(blockLen - 8, counter, false); + // Blake1 omits the counter from the extra all-padding block; only the block that still carries + // message bytes mixes in the final bit length. + this.compress(view, 0, this.pos !== 0); + // Write output + clean(buffer); + const v = createView(out); + const state = this.get(); + for (let i = 0; i < this.outputLen / 4; ++i) + v.setUint32(i * 4, state[i]); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Return a copy so callers do not alias the instance scratch buffer used during finalization. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } +} +// Blake1-512 / Blake1-384 constant table `C512`. +// Stored as sixteen 64-bit constants split into `[high32, low32]` halves so +// the Blake1-64 path can reuse one layout for both `v8..v15` initialization +// and the permuted constant lookups. +const B64C = /* @__PURE__ */ Uint32Array.from([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, +]); +// Blake1-256 / Blake1-224 constant table `C256`, derived as the first half of `C512`. +const B32C = /* @__PURE__ */ B64C.slice(0, 16); +// Blake1-256 IV cloned from SHA-256. +const B256_IV = /* @__PURE__ */ SHA256_IV.slice(); +// Blake1-224 IV cloned from SHA-224. +const B224_IV = /* @__PURE__ */ SHA224_IV.slice(); +// Blake1-384 IV cloned from the SHA-384 high-then-low 32-bit halves. +const B384_IV = /* @__PURE__ */ SHA384_IV.slice(); +// Blake1-512 IV cloned from the SHA-512 high-then-low 32-bit halves. +const B512_IV = /* @__PURE__ */ SHA512_IV.slice(); +// Precompute the odd/even companion constants used by all 14 Blake1-32 rounds. +// Each pair stores `u[sigma[2i + 1]]` then `u[sigma[2i]]`, matching the `G1s` / `G2s` xor order. +function generateTBL256() { + const TBL = []; + for (let i = 0, j = 0; i < 14; i++, j += 16) { + for (let offset = 1; offset < 16; offset += 2) { + TBL.push(B32C[BSIGMA[j + offset]]); + TBL.push(B32C[BSIGMA[j + offset - 1]]); + } + } + return new Uint32Array(TBL); +} +// Full 14-round companion-constant table for Blake1-32. +const TBL256 = /* @__PURE__ */ generateTBL256(); +// Shared synchronous message-word scratch for the 32-bit Blake1 path. +const BLAKE256_W = /* @__PURE__ */ new Uint32Array(16); +class BLAKE1_32B extends BLAKE1 { + v0; + v1; + v2; + v3; + v4; + v5; + v6; + v7; + constructor(outputLen, IV, lengthFlag, opts = {}) { + super(64, outputLen, lengthFlag, 8, 4, B32C, opts); + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + destroy() { + super.destroy(); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } + compress(view, offset, withLength = true) { + for (let i = 0; i < 16; i++, offset += 4) + BLAKE256_W[i] = view.getUint32(offset, false); + // Cannot reuse blake2s compress: Blake1 mixes each message word with the companion constants + // precomputed in `TBL256`, rather than using the raw schedule words directly. + let v00 = this.v0 | 0; + let v01 = this.v1 | 0; + let v02 = this.v2 | 0; + let v03 = this.v3 | 0; + let v04 = this.v4 | 0; + let v05 = this.v5 | 0; + let v06 = this.v6 | 0; + let v07 = this.v7 | 0; + let v08 = this.constants[0] | 0; + let v09 = this.constants[1] | 0; + let v10 = this.constants[2] | 0; + let v11 = this.constants[3] | 0; + // Blake1-32 injects the 64-bit bit counter as `[t0, t0, t1, t1]` across `v12..v15`; the + // final all-padding block passes `withLength = false`, leaving these lanes as raw constants. + const { h, l } = u64.fromBig(BigInt(withLength ? this.length * 8 : 0)); + let v12 = (this.constants[4] ^ l) >>> 0; + let v13 = (this.constants[5] ^ l) >>> 0; + let v14 = (this.constants[6] ^ h) >>> 0; + let v15 = (this.constants[7] ^ h) >>> 0; + // prettier-ignore + for (let i = 0, k = 0, j = 0; i < 14; i++) { + ({ a: v00, b: v04, c: v08, d: v12 } = G1s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v04, c: v08, d: v12 } = G2s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v05, c: v09, d: v13 } = G1s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v05, c: v09, d: v13 } = G2s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v06, c: v10, d: v14 } = G1s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v06, c: v10, d: v14 } = G2s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v07, c: v11, d: v15 } = G1s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v07, c: v11, d: v15 } = G2s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v05, c: v10, d: v15 } = G1s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v05, c: v10, d: v15 } = G2s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v06, c: v11, d: v12 } = G1s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v06, c: v11, d: v12 } = G2s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v07, c: v08, d: v13 } = G1s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v07, c: v08, d: v13 } = G2s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v04, c: v09, d: v14 } = G1s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v04, c: v09, d: v14 } = G2s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + } + this.v0 = (this.v0 ^ v00 ^ v08 ^ this.salt[0]) >>> 0; + this.v1 = (this.v1 ^ v01 ^ v09 ^ this.salt[1]) >>> 0; + this.v2 = (this.v2 ^ v02 ^ v10 ^ this.salt[2]) >>> 0; + this.v3 = (this.v3 ^ v03 ^ v11 ^ this.salt[3]) >>> 0; + this.v4 = (this.v4 ^ v04 ^ v12 ^ this.salt[0]) >>> 0; + this.v5 = (this.v5 ^ v05 ^ v13 ^ this.salt[1]) >>> 0; + this.v6 = (this.v6 ^ v06 ^ v14 ^ this.salt[2]) >>> 0; + this.v7 = (this.v7 ^ v07 ^ v15 ^ this.salt[3]) >>> 0; + clean(BLAKE256_W); + } +} +// Shared Blake1-64 work vector storing 16 working words as adjacent high/low 32-bit halves. +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// Shared synchronous message-word scratch for the 64-bit Blake1 path. +const BLAKE512_W = /* @__PURE__ */ new Uint32Array(32); +// Precompute the high/low companion constants used by all 16 Blake1-64 rounds. +// Each quartet stores `u[sigma[2i + 1]]` high/low halves, then `u[sigma[2i]]` high/low halves. +function generateTBL512() { + const TBL = []; + for (let r = 0, k = 0; r < 16; r++, k += 16) { + for (let offset = 1; offset < 16; offset += 2) { + TBL.push(B64C[BSIGMA[k + offset] * 2 + 0]); + TBL.push(B64C[BSIGMA[k + offset] * 2 + 1]); + TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 0]); + TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 1]); + } + } + return new Uint32Array(TBL); +} +// Full 16-round companion-constant table as high/low halves. +const TBL512 = /* @__PURE__ */ generateTBL512(); +// Blake1-64 first half-round with rotations `32` and `25`; `k` is the half-call schedule index. +function G1b(a, b, c, d, msg, k) { + const Xpos = 2 * BSIGMA[k]; + const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore + let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore + let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore + let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore + let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh) >>> 0; + Al = (ll | 0) >>> 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 25) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 25), Bl: u64.rotrSL(Bh, Bl, 25) }); + ((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah)); + ((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh)); + ((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch)); + ((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh)); +} +// Blake1-64 second half-round with rotations `16` and `11`; `k` is the half-call schedule index. +function G2b(a, b, c, d, msg, k) { + const Xpos = 2 * BSIGMA[k]; + const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore + let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore + let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore + let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore + let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 11) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 11), Bl: u64.rotrSL(Bh, Bl, 11) }); + ((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah)); + ((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh)); + ((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch)); + ((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh)); +} +// Legacy field names keep the local `l/h` spelling, but array/state order stays `[high, low]` to +// match the IV tables and `BBUF` layout. +class BLAKE1_64B extends BLAKE1 { + v0l; + v0h; + v1l; + v1h; + v2l; + v2h; + v3l; + v3h; + v4l; + v4h; + v5l; + v5h; + v6l; + v6h; + v7l; + v7h; + constructor(outputLen, IV, lengthFlag, opts = {}) { + super(128, outputLen, lengthFlag, 16, 8, B64C, opts); + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + destroy() { + super.destroy(); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + compress(view, offset, withLength = true) { + for (let i = 0; i < 32; i++, offset += 4) + BLAKE512_W[i] = view.getUint32(offset, false); + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(this.constants.subarray(0, 16), 16); + if (withLength) { + // Blake1-64 injects the 64-bit bit counter into `v12` and `v13`; the final all-padding + // block passes `withLength = false`, leaving the trailing constant lanes untouched. + const { h, l } = u64.fromBig(BigInt(this.length * 8)); + BBUF[24] = (BBUF[24] ^ h) >>> 0; + BBUF[25] = (BBUF[25] ^ l) >>> 0; + BBUF[26] = (BBUF[26] ^ h) >>> 0; + BBUF[27] = (BBUF[27] ^ l) >>> 0; + } + for (let i = 0, k = 0; i < 16; i++) { + G1b(0, 4, 8, 12, BLAKE512_W, k++); + G2b(0, 4, 8, 12, BLAKE512_W, k++); + G1b(1, 5, 9, 13, BLAKE512_W, k++); + G2b(1, 5, 9, 13, BLAKE512_W, k++); + G1b(2, 6, 10, 14, BLAKE512_W, k++); + G2b(2, 6, 10, 14, BLAKE512_W, k++); + G1b(3, 7, 11, 15, BLAKE512_W, k++); + G2b(3, 7, 11, 15, BLAKE512_W, k++); + G1b(0, 5, 10, 15, BLAKE512_W, k++); + G2b(0, 5, 10, 15, BLAKE512_W, k++); + G1b(1, 6, 11, 12, BLAKE512_W, k++); + G2b(1, 6, 11, 12, BLAKE512_W, k++); + G1b(2, 7, 8, 13, BLAKE512_W, k++); + G2b(2, 7, 8, 13, BLAKE512_W, k++); + G1b(3, 4, 9, 14, BLAKE512_W, k++); + G2b(3, 4, 9, 14, BLAKE512_W, k++); + } + this.v0l ^= BBUF[0] ^ BBUF[16] ^ this.salt[0]; + this.v0h ^= BBUF[1] ^ BBUF[17] ^ this.salt[1]; + this.v1l ^= BBUF[2] ^ BBUF[18] ^ this.salt[2]; + this.v1h ^= BBUF[3] ^ BBUF[19] ^ this.salt[3]; + this.v2l ^= BBUF[4] ^ BBUF[20] ^ this.salt[4]; + this.v2h ^= BBUF[5] ^ BBUF[21] ^ this.salt[5]; + this.v3l ^= BBUF[6] ^ BBUF[22] ^ this.salt[6]; + this.v3h ^= BBUF[7] ^ BBUF[23] ^ this.salt[7]; + this.v4l ^= BBUF[8] ^ BBUF[24] ^ this.salt[0]; + this.v4h ^= BBUF[9] ^ BBUF[25] ^ this.salt[1]; + this.v5l ^= BBUF[10] ^ BBUF[26] ^ this.salt[2]; + this.v5h ^= BBUF[11] ^ BBUF[27] ^ this.salt[3]; + this.v6l ^= BBUF[12] ^ BBUF[28] ^ this.salt[4]; + this.v6h ^= BBUF[13] ^ BBUF[29] ^ this.salt[5]; + this.v7l ^= BBUF[14] ^ BBUF[30] ^ this.salt[6]; + this.v7h ^= BBUF[15] ^ BBUF[31] ^ this.salt[7]; + clean(BBUF, BLAKE512_W); + } +} +/** Internal blake1-224 hash class. */ +export class _BLAKE224 extends BLAKE1_32B { + constructor(opts = {}) { + super(28, B224_IV, 0b0000_0000, opts); + } +} +/** Internal blake1-256 hash class. */ +export class _BLAKE256 extends BLAKE1_32B { + constructor(opts = {}) { + super(32, B256_IV, 0b0000_0001, opts); + } +} +/** Internal blake1-384 hash class. */ +export class _BLAKE384 extends BLAKE1_64B { + constructor(opts = {}) { + super(48, B384_IV, 0b0000_0000, opts); + } +} +/** Internal blake1-512 hash class. */ +export class _BLAKE512 extends BLAKE1_64B { + constructor(opts = {}) { + super(64, B512_IV, 0b0000_0001, opts); + } +} +/** + * Blake1-224 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-224. + * ```ts + * blake224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake224 = /* @__PURE__ */ createHasher((opts) => new _BLAKE224(opts)); +/** + * Blake1-256 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-256. + * ```ts + * blake256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake256 = /* @__PURE__ */ createHasher((opts) => new _BLAKE256(opts)); +/** + * Blake1-384 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-384. + * ```ts + * blake384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake384 = /* @__PURE__ */ createHasher((opts) => new _BLAKE384(opts)); +/** + * Blake1-512 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-512. + * ```ts + * blake512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake512 = /* @__PURE__ */ createHasher((opts) => new _BLAKE512(opts)); +//# sourceMappingURL=blake1.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake1.js.map b/node_modules/@noble/hashes/blake1.js.map new file mode 100644 index 0000000..496638d --- /dev/null +++ b/node_modules/@noble/hashes/blake1.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake1.js","sourceRoot":"","sources":["src/blake1.ts"],"names":[],"mappings":"AAAA;;;;;;;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CACF;AACD,sCAAsC;AACtC,MAAM,OAAO,SAAU,SAAQ,UAAU;IACvC,YAAY,OAAkB,EAAE;QAC9B,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;CACF;AACD,sCAAsC;AACtC,MAAM,OAAO,SAAU,SAAQ,UAAU;IACvC,YAAY,OAAkB,EAAE;QAC9B,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;IACxC,CAAC;CACF;AACD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAsC,eAAe,CAAC,YAAY,CACrF,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAC9B,CAAC;AACF;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAsC,eAAe,CAAC,YAAY,CACrF,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAC9B,CAAC;AACF;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAsC,eAAe,CAAC,YAAY,CACrF,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAC9B,CAAC;AACF;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAsC,eAAe,CAAC,YAAY,CACrF,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,SAAS,CAAC,IAAI,CAAC,CAC9B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2.d.ts b/node_modules/@noble/hashes/blake2.d.ts new file mode 100644 index 0000000..ff66cdb --- /dev/null +++ b/node_modules/@noble/hashes/blake2.d.ts @@ -0,0 +1,184 @@ +import { type CHash, type Hash, type TArg, type TRet } from './utils.ts'; +/** + * Blake hash options. + * `dkLen` is output length. `key` is used in MAC mode. `salt` is used in + * KDF mode. + */ +export type Blake2Opts = { + /** Desired digest length in bytes. RFC 7693 uses 1..64 for blake2b and 1..32 for blake2s. */ + dkLen?: number; + /** Optional MAC key. */ + key?: Uint8Array; + /** Optional salt mixed into initialization. */ + salt?: Uint8Array; + /** Optional personalization bytes. */ + personalization?: Uint8Array; +}; +/** Internal base class for BLAKE2. */ +export declare abstract class _BLAKE2> implements Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected finished: boolean; + protected destroyed: boolean; + protected length: number; + protected pos: number; + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF: boolean; + constructor(blockLen: number, outputLen: number); + update(data: TArg): this; + digestInto(out: TArg): void; + digest(): TRet; + _cloneInto(to?: T): T; + clone(): T; +} +/** Internal blake2b hash class with state stored as LE u32 low/high halves. */ +export declare class _BLAKE2b extends _BLAKE2<_BLAKE2b> { + private v0l; + private v0h; + private v1l; + private v1h; + private v2l; + private v2h; + private v3l; + private v3h; + private v4l; + private v4h; + private v5l; + private v5h; + private v6l; + private v6h; + private v7l; + private v7h; + constructor(opts?: Blake2Opts); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(v0l: number, v0h: number, v1l: number, v1h: number, v2l: number, v2h: number, v3l: number, v3h: number, v4l: number, v4h: number, v5l: number, v5h: number, v6l: number, v6h: number, v7l: number, v7h: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present, + * must be 16 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2b. + * ```ts + * blake2b(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake2b: TRet>; +/** Internal type, 16 numbers. */ +export type _Num16 = { + v0: number; + v1: number; + v2: number; + v3: number; + v4: number; + v5: number; + v6: number; + v7: number; + v8: number; + v9: number; + v10: number; + v11: number; + v12: number; + v13: number; + v14: number; + v15: number; +}; +/** + * BLAKE2-compress core method. + * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15` + * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves. + * @param s - flattened sigma schedule bytes + * @param offset - starting word offset inside `msg`, not a byte offset + * @param msg - message words + * @param rounds - round count to execute + * @param v0 - state word 0 + * @param v1 - state word 1 + * @param v2 - state word 2 + * @param v3 - state word 3 + * @param v4 - state word 4 + * @param v5 - state word 5 + * @param v6 - state word 6 + * @param v7 - state word 7 + * @param v8 - state word 8 + * @param v9 - state word 9 + * @param v10 - state word 10 + * @param v11 - state word 11 + * @param v12 - state word 12 + * @param v13 - state word 13 + * @param v14 - state word 14 + * @param v15 - state word 15 + * @returns Updated compression state words. + * @example + * Run the BLAKE2 compression core on zeroed state and message words. + * ```ts + * import { compress } from '@noble/hashes/blake2.js'; + * const state = compress( + * new Uint8Array(16), + * 0, + * new Uint32Array(16), + * 1, + * 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 0, 0, 0 + * ); + * state.v0; + * ``` + */ +export declare function compress(s: TArg, offset: number, msg: TArg, rounds: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number): _Num16; +/** Internal blake2s hash class. */ +export declare class _BLAKE2s extends _BLAKE2<_BLAKE2s> { + private v0; + private v1; + private v2; + private v3; + private v4; + private v5; + private v6; + private v7; + constructor(opts?: Blake2Opts); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number): void; + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void; + destroy(): void; +} +/** + * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present, + * must be 8 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2s. + * ```ts + * blake2s(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const blake2s: TRet>; +//# sourceMappingURL=blake2.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2.d.ts.map b/node_modules/@noble/hashes/blake2.d.ts.map new file mode 100644 index 0000000..947c111 --- /dev/null +++ b/node_modules/@noble/hashes/blake2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2.d.ts","sourceRoot":"","sources":["src/blake2.ts"],"names":[],"mappings":"AASA,OAAO,EAKL,KAAK,KAAK,EACV,KAAK,IAAI,EACT,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,6FAA6F;IAC7F,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,wBAAwB;IACxB,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,+CAA+C;IAC/C,IAAI,CAAC,EAAE,UAAU,CAAC;IAClB,sCAAsC;IACtC,eAAe,CAAC,EAAE,UAAU,CAAC;CAC9B,CAAC;AAiFF,sCAAsC;AACtC,8BAAsB,OAAO,CAAC,CAAC,SAAS,OAAO,CAAC,CAAC,CAAC,CAAE,YAAW,IAAI,CAAC,CAAC,CAAC;IACpE,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IACpF,SAAS,CAAC,QAAQ,CAAC,GAAG,IAAI,MAAM,EAAE;IAClC,SAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,IAAI,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CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;IAC3B,OAAO,CAAC,EAAE,CAAiB;gBAEf,IAAI,GAAE,UAAe;IAgCjC,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAKjF,SAAS,CAAC,GAAG,CACX,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAC7F,IAAI;IAUP,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI;IAoB3E,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,UAAU,CAAC,CAErD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2.js b/node_modules/@noble/hashes/blake2.js new file mode 100644 index 0000000..7c80cef --- /dev/null +++ b/node_modules/@noble/hashes/blake2.js @@ -0,0 +1,501 @@ +/** + * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions. + * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster. + * @module + */ +import { BSIGMA, G1s, G2s } from "./_blake.js"; +import { SHA256_IV } from "./_md.js"; +import * as u64 from "./_u64.js"; +// prettier-ignore +import { abytes, aexists, anumber, aoutput, clean, createHasher, swap32IfBE, swap8IfBE, u32 } from "./utils.js"; +// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves +// for the BLAKE2b u64 helpers below. +const B2B_IV = /* @__PURE__ */ Uint32Array.from([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19, +]); +// Shared synchronous BLAKE2b work vector as LE u32 low/high halves. +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs. +function G1b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + ((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah)); + ((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh)); + ((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch)); + ((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh)); +} +// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset. +function G2b(a, b, c, d, msg, x) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + ((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah)); + ((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh)); + ((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch)); + ((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh)); +} +function checkBlake2Opts(outputLen, opts = {}, keyLen, saltLen, persLen) { + anumber(keyLen); + // RFC 7693 §2.1 requires digest length nn in 1..keyLen. + if (outputLen <= 0 || outputLen > keyLen) + throw new Error('outputLen bigger than keyLen'); + const { key, salt, personalization } = opts; + // This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty. + if (key !== undefined && (key.length < 1 || key.length > keyLen)) + throw new Error('"key" expected to be undefined or of length=1..' + keyLen); + if (salt !== undefined) + abytes(salt, saltLen, 'salt'); + if (personalization !== undefined) + abytes(personalization, persLen, 'personalization'); +} +/** Internal base class for BLAKE2. */ +export class _BLAKE2 { + buffer; + buffer32; + finished = false; + destroyed = false; + length = 0; + pos = 0; + blockLen; + outputLen; + canXOF = false; + constructor(blockLen, outputLen) { + anumber(blockLen); + anumber(outputLen); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.buffer = new Uint8Array(blockLen); + this.buffer32 = u32(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len;) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + swap32IfBE(buffer32); + this.compress(buffer32, 0, false); + swap32IfBE(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // Zero-copy only for full, 4-byte-aligned, non-final blocks. + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + swap32IfBE(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + swap32IfBE(data32); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + clean(this.buffer.subarray(pos)); + swap32IfBE(buffer32); + this.compress(buffer32, 0, true); + swap32IfBE(buffer32); + // Reject unaligned views explicitly instead of hiding them behind a full scratch copy. + if (out.byteOffset & 3) + throw new RangeError('"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset); + const state = this.get(); + const out32 = u32(out); + const full = Math.floor(this.outputLen / 4); + for (let i = 0; i < full; i++) + out32[i] = swap8IfBE(state[i]); + const tail = this.outputLen % 4; + if (!tail) + return; + const off = full * 4; + const word = state[full]; + for (let i = 0; i < tail; i++) + out[off + i] = word >>> (8 * i); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Return a copy so callers do not alias the instance scratch buffer used during finalization. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + // Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state. + to ||= new this.constructor({ dkLen: outputLen }); + to.set(...this.get()); + to.buffer.set(buffer); + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // @ts-ignore + to.outputLen = outputLen; + return to; + } + clone() { + return this._cloneInto(); + } +} +/** Internal blake2b hash class with state stored as LE u32 low/high halves. */ +export class _BLAKE2b extends _BLAKE2 { + // Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves. + v0l = B2B_IV[0] | 0; + v0h = B2B_IV[1] | 0; + v1l = B2B_IV[2] | 0; + v1h = B2B_IV[3] | 0; + v2l = B2B_IV[4] | 0; + v2h = B2B_IV[5] | 0; + v3l = B2B_IV[6] | 0; + v3h = B2B_IV[7] | 0; + v4l = B2B_IV[8] | 0; + v4h = B2B_IV[9] | 0; + v5l = B2B_IV[10] | 0; + v5h = B2B_IV[11] | 0; + v6l = B2B_IV[12] | 0; + v6h = B2B_IV[13] | 0; + v7l = B2B_IV[14] | 0; + v7h = B2B_IV[15] | 0; + constructor(opts = {}) { + const olen = opts.dkLen === undefined ? 64 : opts.dkLen; + super(128, olen); + checkBlake2Opts(olen, opts, 64, 16, 16); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`; + // the high 32 bits stay at `IV[0]`. + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + const slt = u32(salt); + this.v4l ^= swap8IfBE(slt[0]); + this.v4h ^= swap8IfBE(slt[1]); + this.v5l ^= swap8IfBE(slt[2]); + this.v5h ^= swap8IfBE(slt[3]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + const pers = u32(personalization); + this.v6l ^= swap8IfBE(pers[0]); + this.v6h ^= swap8IfBE(pers[1]); + this.v7l ^= swap8IfBE(pers[2]); + this.v7h ^= swap8IfBE(pers[3]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + } + } + // prettier-ignore + get() { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + compress(msg, offset, isLast) { + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(B2B_IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = BSIGMA; + // SIGMA selects 64-bit message words; multiply by 2 because `msg` stores + // each word as [low32, high32]. + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + clean(BBUF); + } + destroy() { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present, + * must be 16 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2b. + * ```ts + * blake2b(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake2b = /* @__PURE__ */ createHasher((opts) => new _BLAKE2b(opts)); +/** + * BLAKE2-compress core method. + * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15` + * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves. + * @param s - flattened sigma schedule bytes + * @param offset - starting word offset inside `msg`, not a byte offset + * @param msg - message words + * @param rounds - round count to execute + * @param v0 - state word 0 + * @param v1 - state word 1 + * @param v2 - state word 2 + * @param v3 - state word 3 + * @param v4 - state word 4 + * @param v5 - state word 5 + * @param v6 - state word 6 + * @param v7 - state word 7 + * @param v8 - state word 8 + * @param v9 - state word 9 + * @param v10 - state word 10 + * @param v11 - state word 11 + * @param v12 - state word 12 + * @param v13 - state word 13 + * @param v14 - state word 14 + * @param v15 - state word 15 + * @returns Updated compression state words. + * @example + * Run the BLAKE2 compression core on zeroed state and message words. + * ```ts + * import { compress } from '@noble/hashes/blake2.js'; + * const state = compress( + * new Uint8Array(16), + * 0, + * new Uint32Array(16), + * 1, + * 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 0, 0, 0 + * ); + * state.v0; + * ``` + */ +// prettier-ignore +export function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} +// Blake2s reuses the SHA-256 IV words as-is. +const B2S_IV = /* @__PURE__ */ SHA256_IV.slice(); +/** Internal blake2s hash class. */ +export class _BLAKE2s extends _BLAKE2 { + // Internal state, same as SHA-256 + v0 = B2S_IV[0] | 0; + v1 = B2S_IV[1] | 0; + v2 = B2S_IV[2] | 0; + v3 = B2S_IV[3] | 0; + v4 = B2S_IV[4] | 0; + v5 = B2S_IV[5] | 0; + v6 = B2S_IV[6] | 0; + v7 = B2S_IV[7] | 0; + constructor(opts = {}) { + const olen = opts.dkLen === undefined ? 32 : opts.dkLen; + super(64, olen); + checkBlake2Opts(olen, opts, 32, 8, 8); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since + // BLAKE2s stores each state word as one `u32`. + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + const slt = u32(salt); + this.v4 ^= swap8IfBE(slt[0]); + this.v5 ^= swap8IfBE(slt[1]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + const pers = u32(personalization); + this.v6 ^= swap8IfBE(pers[0]); + this.v7 ^= swap8IfBE(pers[1]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + } + } + get() { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + set(v0, v1, v2, v3, v4, v5, v6, v7) { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + compress(msg, offset, isLast) { + const { h, l } = u64.fromBig(BigInt(this.length)); + // Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into + // v12/v13, and invert v14 on the final block. + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(BSIGMA, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7]); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy() { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** + * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present, + * must be 8 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2s. + * ```ts + * blake2s(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake2s = /* @__PURE__ */ createHasher((opts) => new _BLAKE2s(opts)); +//# sourceMappingURL=blake2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake2.js.map b/node_modules/@noble/hashes/blake2.js.map new file mode 100644 index 0000000..2f8733f --- /dev/null +++ b/node_modules/@noble/hashes/blake2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake2.js","sourceRoot":"","sources":["src/blake2.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,kBAAkB;AAClB,OA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CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACnC,CAAC;CACF;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,OAAO,GAAsC,eAAe,CAAC,YAAY,CACpF,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,QAAQ,CAAC,IAAI,CAAC,CAC7B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.d.ts b/node_modules/@noble/hashes/blake3.d.ts new file mode 100644 index 0000000..1fd4cc7 --- /dev/null +++ b/node_modules/@noble/hashes/blake3.d.ts @@ -0,0 +1,68 @@ +import { _BLAKE2 } from './blake2.ts'; +import { type CHashXOF, type HashXOF, type TArg, type TRet } from './utils.ts'; +/** + * Ensure to use EITHER `key` OR `context`, not both. + * + * * `key`: 32-byte MAC key. + * * `context`: caller-encoded KDF context bytes. If your protocol defines a + * string context, encode it before passing it here. + * A good default format for the original context string is + * "[application] [commit timestamp] [purpose]". + */ +export type Blake3Opts = { + /** Desired digest length in bytes. The BLAKE3 spec allows 0..2^64-1 bytes of output. */ + dkLen?: number; + /** Optional 32-byte MAC key. */ + key?: Uint8Array; + /** Optional KDF context bytes. */ + context?: Uint8Array; +}; +/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */ +export declare class _BLAKE3 extends _BLAKE2<_BLAKE3> implements HashXOF<_BLAKE3> { + readonly canXOF = true; + private chunkPos; + private chunksDone; + private flags; + private IV; + private state; + private stack; + private posOut; + private bufferOut32; + private bufferOut; + private chunkOut; + private enableXOF; + constructor(opts?: Blake3Opts, flags?: number); + protected get(): []; + protected set(): void; + private b2Compress; + protected compress(buf: Uint32Array, bufPos?: number, isLast?: boolean): void; + _cloneInto(to?: _BLAKE3): _BLAKE3; + destroy(): void; + private b2CompressOut; + protected finish(): void; + private writeInto; + xofInto(out: TArg): TRet; + xof(bytes: number): TRet; + digestInto(out: TArg): void; + digest(): TRet; +} +/** + * BLAKE3 hash function. Can be used as MAC and KDF. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, or KDF configuration. `key` must be + * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be + * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}. + * @returns Digest bytes. + * @example + * Hash, MAC, or derive key material with BLAKE3. + * ```ts + * import { blake3 } from '@noble/hashes/blake3.js'; + * import { utf8ToBytes } from '@noble/hashes/utils.js'; + * const data = new Uint8Array(32); + * const hash = blake3(data); + * const mac = blake3(data, { key: new Uint8Array(32) }); + * const kdf = blake3(data, { context: utf8ToBytes('application name') }); + * ``` + */ +export declare const blake3: TRet>; +//# sourceMappingURL=blake3.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.d.ts.map b/node_modules/@noble/hashes/blake3.d.ts.map new file mode 100644 index 0000000..94e019e --- /dev/null +++ b/node_modules/@noble/hashes/blake3.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.d.ts","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,OAAO,EAAY,MAAM,aAAa,CAAC;AAEhD,OAAO,EAML,KAAK,QAAQ,EACb,KAAK,OAAO,EACZ,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AA4BpB;;;;;;;;GAQG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,wFAAwF;IACxF,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gCAAgC;IAChC,GAAG,CAAC,EAAE,UAAU,CAAC;IACjB,kCAAkC;IAClC,OAAO,CAAC,EAAE,UAAU,CAAC;CACtB,CAAC;AAEF,iFAAiF;AACjF,qBAAa,OAAQ,SAAQ,OAAO,CAAC,OAAO,CAAE,YAAW,OAAO,CAAC,OAAO,CAAC;IACvE,QAAQ,CAAC,MAAM,QAAQ;IACvB,OAAO,CAAC,QAAQ,CAAK;IAGrB,OAAO,CAAC,UAAU,CAAK;IACvB,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,EAAE,CAAc;IACxB,OAAO,CAAC,KAAK,CAAc;IAC3B,OAAO,CAAC,KAAK,CAAqB;IAElC,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,SAAS,CAAa;IAG9B,OAAO,CAAC,QAAQ,CAAK;IACrB,OAAO,CAAC,SAAS,CAAQ;gBAEb,IAAI,GAAE,UAAe,EAAE,KAAK,SAAI;IA6B5C,SAAS,CAAC,GAAG,IAAI,EAAE;IAGnB,SAAS,CAAC,GAAG,IAAI,IAAI;IAGrB,OAAO,CAAC,UAAU;IAmBlB,SAAS,CAAC,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,MAAM,GAAE,MAAU,EAAE,MAAM,GAAE,OAAe,GAAG,IAAI;IAkCvF,UAAU,CAAC,EAAE,CAAC,EAAE,OAAO,GAAG,OAAO;IAiBjC,OAAO,IAAI,IAAI;IAQf,OAAO,CAAC,aAAa;IA+BrB,SAAS,CAAC,MAAM,IAAI,IAAI;IAsBxB,OAAO,CAAC,SAAS;IAcjB,OAAO,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,UAAU,CAAC;IAIhD,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IAIpC,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAQvC,MAAM,IAAI,IAAI,CAAC,UAAU,CAAC;CAK3B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,UAAU,CAAC,CAEtD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.js b/node_modules/@noble/hashes/blake3.js new file mode 100644 index 0000000..a5718c2 --- /dev/null +++ b/node_modules/@noble/hashes/blake3.js @@ -0,0 +1,284 @@ +/** + * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF. + * + * It is advertised as "the fastest cryptographic hash". However, it isn't true in JS. + * Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%: + * + * * There is only 30% reduction in number of rounds from blake2s + * * Speed-up comes from tree structure, which is parallelized using SIMD & threading. + * These features are not present in JS, so we only get overhead from trees. + * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs. + * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm + * @module + */ +import { SHA256_IV } from "./_md.js"; +import { fromBig } from "./_u64.js"; +import { _BLAKE2, compress } from "./blake2.js"; +// prettier-ignore +import { abytes, aexists, anumber, aoutput, clean, copyBytes, createHasher, swap32IfBE, u32, u8 } from "./utils.js"; +// Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree +// flags (`CHUNK_*`, `PARENT`, `ROOT`). +const B3_Flags = { + CHUNK_START: 0b1, + CHUNK_END: 0b10, + PARENT: 0b100, + ROOT: 0b1000, + KEYED_HASH: 0b10000, + DERIVE_KEY_CONTEXT: 0b100000, + DERIVE_KEY_MATERIAL: 0b1000000, +}; +// Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis. +const B3_IV = /* @__PURE__ */ SHA256_IV.slice(); +// Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly +// permuting the identity row. +const B3_SIGMA = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) + res.push(...v); + return Uint8Array.from(res); +})(); +/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */ +export class _BLAKE3 extends _BLAKE2 { + canXOF = true; + chunkPos = 0; // Position of current block in chunk + // How many chunks we already have; exact while this stays within + // JS's safe-integer range. + chunksDone = 0; + flags = 0 | 0; + IV; + state; + stack = []; + // Output + posOut = 0; + bufferOut32 = new Uint32Array(16); + bufferOut; + // Index of output chunk; exact while this stays within JS's + // safe-integer range. + chunkOut = 0; + enableXOF = true; + constructor(opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen); + const { key, context } = opts; + const hasContext = context !== undefined; + if (key !== undefined) { + if (hasContext) + throw new Error('Only "key" or "context" can be specified at same time'); + abytes(key, 32, 'key'); + const k = copyBytes(key); + this.IV = u32(k); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.KEYED_HASH; + } + else if (hasContext) { + abytes(context, undefined, 'context'); + const ctx = context; + const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT) + .update(ctx) + .digest(); + this.IV = u32(contextKey); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL; + } + else { + this.IV = B3_IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and + // copies it directly in _cloneInto(). + get() { + return []; + } + set() { } + // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1, + // block length, and flags, then keep only the first 8 output words. + b2Compress(counter, flags, buf, bufPos = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + compress(buf, bufPos = 0, isLast = false) { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) + flags |= B3_Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) + flags |= B3_Flags.CHUNK_END; + if (!isLast) + this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // Chunks are used as a binary tree where the current stack is the path. + // Zero means the current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) + break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to) { + to = super._cloneInto(to); + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + // Clone each CV stack entry by value so extending or destroying the clone + // cannot alias the source tree state. + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy() { + this.destroyed = true; + clean(this.state, this.buffer32, this.IV, this.bufferOut32); + clean(...this.stack); + } + // Root/XOF compression: rerun the same ROOT inputs with incrementing output + // counter `t` and materialize all 16 output words. + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + swap32IfBE(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + swap32IfBE(buffer32); + swap32IfBE(out32); + this.posOut = 0; + } + finish() { + if (this.finished) + return; + this.finished = true; + // Padding + clean(this.buffer.subarray(this.pos)); + // Process last chunk + let flags = this.flags | B3_Flags.ROOT; + if (this.stack.length) { + // Finalize the current chunk first, then rerun the last parent + // compression as ROOT with t = 0 and b = 64. + flags |= B3_Flags.PARENT; + swap32IfBE(this.buffer32); + this.compress(this.buffer32, 0, true); + swap32IfBE(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } + else { + flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error('digest() was already called'); + this.enableXOF = false; + // `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest. + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out; + } +} +/** + * BLAKE3 hash function. Can be used as MAC and KDF. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, or KDF configuration. `key` must be + * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be + * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}. + * @returns Digest bytes. + * @example + * Hash, MAC, or derive key material with BLAKE3. + * ```ts + * import { blake3 } from '@noble/hashes/blake3.js'; + * import { utf8ToBytes } from '@noble/hashes/utils.js'; + * const data = new Uint8Array(32); + * const hash = blake3(data); + * const mac = blake3(data, { key: new Uint8Array(32) }); + * const kdf = blake3(data, { context: utf8ToBytes('application name') }); + * ``` + */ +export const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts)); +//# sourceMappingURL=blake3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/blake3.js.map b/node_modules/@noble/hashes/blake3.js.map new file mode 100644 index 0000000..40965f6 --- /dev/null +++ b/node_modules/@noble/hashes/blake3.js.map @@ -0,0 +1 @@ +{"version":3,"file":"blake3.js","sourceRoot":"","sources":["src/blake3.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACrC,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAChD,kBAAkB;AAClB,OAAO,E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AC,SAAS,GAAG,KAAK,CAAC;QACvB,8FAA8F;QAC9F,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;QAChD,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IACD,MAAM;QACJ,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QACrB,OAAO,GAAuB,CAAC;IACjC,CAAC;CACF;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,CAAC,MAAM,MAAM,GAAwC,eAAe,CAAC,YAAY,CACrF,CAAC,IAAI,GAAG,EAAE,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,IAAI,CAAC,CACjC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.d.ts b/node_modules/@noble/hashes/eskdf.d.ts new file mode 100644 index 0000000..7ff4281 --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.d.ts @@ -0,0 +1,92 @@ +import { type TRet } from './utils.ts'; +/** + * Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering RFC 7914 + * @param salt - unique salt string, UTF-8 encoded before entering RFC 7914 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte scrypt key used by ESKDF. + * ```ts + * scrypt('password123', 'user@example.com'); + * ``` + */ +export declare function scrypt(password: string, salt: string): TRet; +/** + * PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte PBKDF2 key used by ESKDF. + * ```ts + * pbkdf2('password123', 'user@example.com'); + * ``` + */ +export declare function pbkdf2(password: string, salt: string): TRet; +/** + * Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)` + * flow unless you specifically need the raw main seed. + * Derives the main seed by xor'ing two branches: + * the scrypt branch uses a `0x01` separator byte on username/password, + * and the PBKDF2 branch uses `0x02`. + * Username and password strings are encoded by the underlying KDFs after the + * local separator bytes are appended. + * @param username - account identifier used as public salt + * @param password - user password string + * @returns Main 32-byte seed for the account. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive the main ESKDF seed from username and password. + * ```ts + * deriveMainSeed('example-user', 'example-password'); + * ``` + */ +export declare function deriveMainSeed(username: string, password: string): TRet; +type AccountID = number | string; +type OptsLength = { + keyLength: number; +}; +type OptsMod = { + modulus: bigint; +}; +type KeyOpts = undefined | OptsLength | OptsMod; +/** Not using classes because constructor cannot be async. */ +export interface ESKDF { + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric account identifier, or a string id for + * `password\d{0,3}`, `ssh`, `tor`, or `file` + * @param options - Optional child-key shaping parameters. See {@link KeyOpts}. + * @returns Derived child key bytes. + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => TRet; + /** Deletes the main seed from the ESKDF instance. */ + expire: () => void; + /** + * Human-readable fingerprint: first 6 bytes of + * `deriveChildKey('fingerprint', 0)`, formatted as uppercase + * colon-separated hex. + */ + fingerprint: string; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @returns Frozen API that derives child keys and exposes the account fingerprint. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive account-specific child keys from the main ESKDF seed. + * ```ts + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * const fingerprint = kdf.fingerprint; + * kdf.expire(); + * ``` + */ +export declare function eskdf(username: string, password: string): Promise>; +export {}; +//# sourceMappingURL=eskdf.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.d.ts.map b/node_modules/@noble/hashes/eskdf.d.ts.map new file mode 100644 index 0000000..d0a7953 --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.d.ts","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":"AAQA,OAAO,EAQL,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAYpB;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAEvE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAEvE;AAkBD;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAanF;AAED,KAAK,SAAS,GAAG,MAAM,GAAG,MAAM,CAAC;AAkCjC,KAAK,UAAU,GAAG;IAAE,SAAS,EAAE,MAAM,CAAA;CAAE,CAAC;AACxC,KAAK,OAAO,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC;AACnC,KAAK,OAAO,GAAG,SAAS,GAAG,UAAU,GAAG,OAAO,CAAC;AA6ChD,6DAA6D;AAC7D,MAAM,WAAW,KAAK;IACpB;;;;;;;;;OASG;IACH,cAAc,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;IAChG,qDAAqD;IACrD,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;CACrB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CA+BpF"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.js b/node_modules/@noble/hashes/eskdf.js new file mode 100644 index 0000000..5ea541d --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.js @@ -0,0 +1,218 @@ +/** + * Experimental KDF for AES. + * @module + */ +import { hkdf } from "./hkdf.js"; +import { pbkdf2 as _pbkdf2 } from "./pbkdf2.js"; +import { scrypt as _scrypt } from "./scrypt.js"; +import { sha256 } from "./sha2.js"; +import { abytes, bytesToHex, clean, createView, hexToBytes, kdfInputToBytes, } from "./utils.js"; +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. +// Fixed ESKDF scrypt work factor: interactive-latency target with about 512 MiB RAM per derivation. +const SCRYPT_FACTOR = /* @__PURE__ */ (() => 2 ** 19)(); +// Fixed ESKDF PBKDF2 work factor: CPU-only companion branch in the same rough +// interactive-latency range. +const PBKDF2_FACTOR = /* @__PURE__ */ (() => 2 ** 17)(); +/** + * Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering RFC 7914 + * @param salt - unique salt string, UTF-8 encoded before entering RFC 7914 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte scrypt key used by ESKDF. + * ```ts + * scrypt('password123', 'user@example.com'); + * ``` + */ +export function scrypt(password, salt) { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} +/** + * PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte PBKDF2 key used by ESKDF. + * ```ts + * pbkdf2('password123', 'user@example.com'); + * ``` + */ +export function pbkdf2(password, salt) { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} +// Combines two 32-byte byte arrays into a fresh 32-byte result without aliasing either input. +function xor32(a, b) { + abytes(a, 32); + abytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr; +} +// All local string length checks are in JS UTF-16 code units, not UTF-8 bytes. +function strHasLength(str, min, max) { + return typeof str === 'string' && str.length >= min && str.length <= max; +} +/** + * Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)` + * flow unless you specifically need the raw main seed. + * Derives the main seed by xor'ing two branches: + * the scrypt branch uses a `0x01` separator byte on username/password, + * and the PBKDF2 branch uses `0x02`. + * Username and password strings are encoded by the underlying KDFs after the + * local separator bytes are appended. + * @param username - account identifier used as public salt + * @param password - user password string + * @returns Main 32-byte seed for the account. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive the main ESKDF seed from username and password. + * ```ts + * deriveMainSeed('example-user', 'example-password'); + * ``` + */ +export function deriveMainSeed(username, password) { + if (!strHasLength(username, 8, 255)) + throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) + throw new Error('invalid password'); + // Keep the protocol separators as the literal bytes 0x01 / 0x02 even after minification. + // Embedding them as non-printable characters directly can be awkward across + // JS tooling and environments. + const codes = { _1: 1, _2: 2 }; + const sep = { s: String.fromCharCode(codes._1), p: String.fromCharCode(codes._2) }; + const scr = scrypt(password + sep.s, username + sep.s); + const pbk = pbkdf2(password + sep.p, username + sep.p); + const res = xor32(scr, pbk); + clean(scr, pbk); + return res; +} +/** + * Converts protocol & accountId pair to HKDF params: + * `info` is UTF-8 protocol bytes, numeric ids become 4-byte BE `salt`, + * and string ids become UTF-8 `salt` bytes. + */ +function getSaltInfo(protocol, accountId = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + // Exact-match only: substring matches like `assh` / `mentor` must not widen the public whitelist. + const allowsStr = /^(password\d{0,3}|ssh|tor|file)$/.test(protocol); + let salt; // Assigned below: either 4-byte BE account bytes or UTF-8 account bytes. + if (typeof accountId === 'string') { + if (!allowsStr) + throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be string of length 1..255'); + salt = kdfInputToBytes(accountId); + } + else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > Math.pow(2, 32) - 1) + throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } + else { + throw new Error('accountId must be a number' + (allowsStr ? ' or string' : '')); + } + const info = kdfInputToBytes(protocol); + return { salt, info }; +} +// Local modulus-size helper, not a general bigint-byte-length primitive: +// `<= 128n` is rejected by ESKDF policy. +function countBytes(num) { + if (typeof num !== 'bigint' || num <= BigInt(128)) + throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it per the FIPS 186-5 Appendix A.3.1 / + * A.4.1 extra-bits guidance. + */ +function getKeyLength(options) { + if (!options || typeof options !== 'object') + return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) + throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) + throw new Error('must have either keyLength or modulus option'); + // FIPS 186-5 Appendix A.3.1 / A.4.1 calls for at least 64 extra bits. + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) + throw new Error('invalid keyLength'); + return l; +} +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Adapts FIPS 186-5 Appendix A.4.1: `getKeyLength()` already requested the + * extra 64-bit margin, and this step maps the result into `1..modulus-1`. + */ +function modReduceKey(key, modulus) { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) + throw new Error('expected positive number'); // Guard against bad values + // Strip the extra 64-bit margin that `getKeyLength()` requested + // for bias reduction. + const len = key.length - 8; + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) + throw new Error('invalid length of result key'); + return bytes; +} +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @returns Frozen API that derives child keys and exposes the account fingerprint. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive account-specific child keys from the main ESKDF seed. + * ```ts + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * const fingerprint = kdf.fingerprint; + * kdf.expire(); + * ``` + */ +export async function eskdf(username, password) { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed = deriveMainSeed(username, password); + function deriveCK(protocol, accountId = 0, options) { + // Reject expired instances before deriving any HKDF inputs from the closure-held seed. + abytes(seed, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + // Validate option shape and coarse length bounds; + // `hkdf()` still rejects non-integer lengths. + const keyLength = getKeyLength(options); + const key = hkdf(sha256, seed, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + // Overwrite the closure-held seed before dropping the reference. + if (seed) + seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} +//# sourceMappingURL=eskdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/eskdf.js.map b/node_modules/@noble/hashes/eskdf.js.map new file mode 100644 index 0000000..49209e5 --- /dev/null +++ b/node_modules/@noble/hashes/eskdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eskdf.js","sourceRoot":"","sources":["src/eskdf.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EACL,MAAM,EACN,UAAU,EACV,KAAK,EACL,UAAU,EACV,UAAU,EACV,eAAe,GAGhB,MAAM,YAAY,CAAC;AAEpB,wDAAwD;AACxD,gFAAgF;AAChF,sEAAsE;AAEtE,oGAAoG;AACpG,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AACxD,8EAA8E;AAC9E,6BAA6B;AAC7B,MAAM,aAAa,GAAG,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AAExD;;;;;;;;;;GAUG;AACH,MAAM,UAAU,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAAO,OAAO,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,MAAM,CAAC,QAAgB,EAAE,IAAY;IACnD,OAA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CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;SAC/D,IAAI,CAAC,GAAG,CAAC,CAAC;IACb,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.d.ts b/node_modules/@noble/hashes/hkdf.d.ts new file mode 100644 index 0000000..0ace1fe --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.d.ts @@ -0,0 +1,64 @@ +import { type CHash, type TArg, type TRet } from './utils.ts'; +/** + * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK` + * Arguments position differs from spec (IKM is first one, since it is not optional) + * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @returns Pseudorandom key derived from input keying material. + * @example + * Run the HKDF extract step. + * ```ts + * import { extract } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export declare function extract(hash: TArg, ikm: TArg, salt?: TArg): TRet; +/** + * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM` + * @param hash - hash function that would be used (e.g. sha256) + * @param prk - a pseudorandom key of at least HashLen octets + * (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material with the requested length. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * Run the HKDF expand step. + * ```ts + * import { expand } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16); + * ``` + */ +export declare function expand(hash: TArg, prk: TArg, info?: TArg, length?: number): TRet; +/** + * HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material derived from the input key. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export declare const hkdf: (hash: TArg, ikm: TArg, salt: TArg, info: TArg, length: number) => TRet; +//# sourceMappingURL=hkdf.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.d.ts.map b/node_modules/@noble/hashes/hkdf.d.ts.map new file mode 100644 index 0000000..9b6a97f --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.d.ts","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":"AAMA,OAAO,EAA0B,KAAK,KAAK,EAAS,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAE7F;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,OAAO,CACrB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,GACtB,IAAI,CAAC,UAAU,CAAC,CAOlB;AAQD;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,MAAM,CACpB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,IAAI,CAAC,EAAE,IAAI,CAAC,UAAU,CAAC,EACvB,MAAM,GAAE,MAAW,GAClB,IAAI,CAAC,UAAU,CAAC,CAiClB;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,eAAO,MAAM,IAAI,GACf,MAAM,IAAI,CAAC,KAAK,CAAC,EACjB,KAAK,IAAI,CAAC,UAAU,CAAC,EACrB,MAAM,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,MAAM,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,QAAQ,MAAM,KACb,IAAI,CAAC,UAAU,CAAyD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.js b/node_modules/@noble/hashes/hkdf.js new file mode 100644 index 0000000..ccb0130 --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.js @@ -0,0 +1,120 @@ +/** + * HKDF (RFC 5869): extract + expand in one step. + * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}. + * @module + */ +import { hmac } from "./hmac.js"; +import { abytes, ahash, anumber, clean } from "./utils.js"; +/** + * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK` + * Arguments position differs from spec (IKM is first one, since it is not optional) + * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @returns Pseudorandom key derived from input keying material. + * @example + * Run the HKDF extract step. + * ```ts + * import { extract } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export function extract(hash, ikm, salt) { + ahash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) + salt = new Uint8Array(hash.outputLen); + return hmac(hash, salt, ikm); +} +// Shared mutable scratch byte for the RFC 5869 block counter `N`. +// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning. +const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); +// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input. +const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); +/** + * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM` + * @param hash - hash function that would be used (e.g. sha256) + * @param prk - a pseudorandom key of at least HashLen octets + * (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material with the requested length. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * Run the HKDF expand step. + * ```ts + * import { expand } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16); + * ``` + */ +export function expand(hash, prk, info, length = 32) { + ahash(hash); + anumber(length, 'length'); + abytes(prk, undefined, 'prk'); + const olen = hash.outputLen; + // RFC 5869 §2.3: PRK is "a pseudorandom key of at least HashLen octets". + if (prk.length < olen) + throw new Error('"prk" must be at least HashLen octets'); + // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM. + if (length > 255 * olen) + throw new Error('Length must be <= 255*HashLen'); + const blocks = Math.ceil(length / olen); + if (info === undefined) + info = EMPTY_BUFFER; + else + abytes(info, undefined, 'info'); + // first L(ength) octets of T + const okm = new Uint8Array(blocks * olen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, olen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + clean(T, HKDF_COUNTER); + return okm.slice(0, length); +} +/** + * HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material derived from the input key. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); +//# sourceMappingURL=hkdf.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hkdf.js.map b/node_modules/@noble/hashes/hkdf.js.map new file mode 100644 index 0000000..1a783f4 --- /dev/null +++ b/node_modules/@noble/hashes/hkdf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hkdf.js","sourceRoot":"","sources":["src/hkdf.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAA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IAAiB,EACjB,GAAqB,EACrB,IAAkC,EAClC,IAAkC,EAClC,MAAc,EACI,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.d.ts b/node_modules/@noble/hashes/hmac.d.ts new file mode 100644 index 0000000..7ec669d --- /dev/null +++ b/node_modules/@noble/hashes/hmac.d.ts @@ -0,0 +1,47 @@ +/** + * HMAC: RFC2104 message authentication code. + * @module + */ +import { type CHash, type Hash, type TArg, type TRet } from './utils.ts'; +/** + * Internal class for HMAC. + * Accepts any byte key, although RFC 2104 §3 recommends keys at least + * `HashLen` bytes long. + */ +export declare class _HMAC> implements Hash<_HMAC> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + canXOF: boolean; + private finished; + private destroyed; + constructor(hash: TArg, key: TArg); + update(buf: TArg): this; + digestInto(out: TArg): void; + digest(): TRet; + _cloneInto(to?: _HMAC): _HMAC; + clone(): _HMAC; + destroy(): void; +} +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - authentication key bytes + * @param message - message bytes to authenticate + * @returns Authentication tag bytes. + * @example + * Compute an RFC 2104 HMAC. + * ```ts + * import { hmac } from '@noble/hashes/hmac.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +type HmacFn = { + (hash: TArg, key: TArg, message: TArg): TRet; + create(hash: TArg, key: TArg): TRet<_HMAC>; +}; +export declare const hmac: TRet; +export {}; +//# sourceMappingURL=hmac.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.d.ts.map b/node_modules/@noble/hashes/hmac.d.ts.map new file mode 100644 index 0000000..07fe4ab --- /dev/null +++ b/node_modules/@noble/hashes/hmac.d.ts.map @@ -0,0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,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC;CACpE,CAAC;AACF,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,MAAM,CAS1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.js b/node_modules/@noble/hashes/hmac.js new file mode 100644 index 0000000..fd066ea --- /dev/null +++ b/node_modules/@noble/hashes/hmac.js @@ -0,0 +1,93 @@ +/** + * HMAC: RFC2104 message authentication code. + * @module + */ +import { abytes, aexists, ahash, aoutput, clean, } from "./utils.js"; +/** + * Internal class for HMAC. + * Accepts any byte key, although RFC 2104 §3 recommends keys at least + * `HashLen` bytes long. + */ +export class _HMAC { + oHash; + iHash; + blockLen; + outputLen; + canXOF = false; + finished = false; + destroyed = false; + constructor(hash, key) { + ahash(hash); + abytes(key, undefined, 'key'); + this.iHash = hash.create(); + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of the first block) of the outer hash here, + // we can re-use it between multiple calls via clone. + this.oHash = hash.create(); + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) + pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before + // overwriting that same prefix with the final tag, leaving any oversized tail untouched. + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + // Create new instance without calling constructor since the key + // is already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} +export const hmac = /* @__PURE__ */ (() => { + const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest()); + hmac_.create = (hash, key) => new _HMAC(hash, key); + return hmac_; +})(); +//# sourceMappingURL=hmac.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/hmac.js.map b/node_modules/@noble/hashes/hmac.js.map new file mode 100644 index 0000000..4f3ed1a --- /dev/null +++ b/node_modules/@noble/hashes/hmac.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hmac.js","sourceRoot":"","sources":["src/hmac.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EACL,MAAM,EACN,OAAO,EACP,KAAK,EACL,OAAO,EACP,KAAK,GAKN,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,MAAM,OAAO,KAAK;IAChB,KAAK,CAAI;IACT,KAAK,CAAI;IACT,QAAQ,CAAS;IACjB,SAAS,CAAS;IAClB,MAAM,GAAG,KAAK,CAAC;IACP,QAAQ,GAAG,KAAK,CAAC;IACjB,SAAS,GAAG,KAAK,CAAC;IAE1B,YAAY,IAAiB,EAAE,GAAqB;QAClD,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,MAAM,CAAC,GAAG,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC;QAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,EAAO,CAAC;QAChC,IAAI,OAAO,IAAI,C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AAE,CAAC,KAAK,CAAC,CAAC;QACtC,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACtC,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;IACvB,CAAC;CACF;AAoBD,MAAM,CAAC,MAAM,IAAI,GAAiB,eAAe,CAAC,CAAC,GAAG,EAAE;IACtD,MAAM,KAAK,GAAG,CAAC,CACb,IAAiB,EACjB,GAAqB,EACrB,OAAyB,EACP,EAAE,CAAC,IAAI,KAAK,CAAM,IAAI,EAAE,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAiB,CAAC;IAC3F,KAAK,CAAC,MAAM,GAAG,CAAC,IAAiB,EAAE,GAAqB,EAAoB,EAAE,CAC5E,IAAI,KAAK,CAAM,IAAI,EAAE,GAAG,CAAqB,CAAC;IAChD,OAAO,KAAK,CAAC;AACf,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.d.ts b/node_modules/@noble/hashes/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/node_modules/@noble/hashes/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.d.ts.map b/node_modules/@noble/hashes/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/hashes/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.js b/node_modules/@noble/hashes/index.js new file mode 100644 index 0000000..5bcf959 --- /dev/null +++ b/node_modules/@noble/hashes/index.js @@ -0,0 +1,35 @@ +/** + * Audited & minimal JS implementation of hash functions, MACs, and KDFs. + * Check out individual modules. + * @module + * @example +```js +import { + sha256, sha384, sha512, sha224, sha512_224, sha512_256 +} from '@noble/hashes/sha2.js'; +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3.js'; +import { + cshake128, cshake256, + turboshake128, turboshake256, + kt128, kt256, + kmac128, kmac256, + tuplehash256, parallelhash256, + keccakprg +} from '@noble/hashes/sha3-addons.js'; +import { blake3 } from '@noble/hashes/blake3.js'; +import { blake2b, blake2s } from '@noble/hashes/blake2.js'; +import { hmac } from '@noble/hashes/hmac.js'; +import { hkdf } from '@noble/hashes/hkdf.js'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js'; +import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js'; +import * as utils from '@noble/hashes/utils.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/index.js.map b/node_modules/@noble/hashes/index.js.map new file mode 100644 index 0000000..9ad47d2 --- /dev/null +++ b/node_modules/@noble/hashes/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/legacy.d.ts b/node_modules/@noble/hashes/legacy.d.ts new file mode 100644 index 0000000..1f9fd43 --- /dev/null +++ b/node_modules/@noble/hashes/legacy.d.ts @@ -0,0 +1,102 @@ +/** + +SHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions. +RFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors, +not the base RIPEMD-160 compression spec. +Don't use them in a new protocol. What "weak" means: + +- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160. +- No practical pre-image attacks (only theoretical, 2^123.4) +- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151 + * @module + */ +import { HashMD } from './_md.ts'; +import { type CHash, type TRet } from './utils.ts'; +/** Internal SHA1 legacy hash class. */ +export declare class _SHA1 extends HashMD<_SHA1> { + private A; + private B; + private C; + private D; + private E; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA1. + * ```ts + * sha1(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha1: TRet; +/** Internal MD5 legacy hash class. */ +export declare class _MD5 extends HashMD<_MD5> { + private A; + private B; + private C; + private D; + constructor(); + protected get(): [number, number, number, number]; + protected set(A: number, B: number, C: number, D: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * MD5 (RFC 1321) legacy hash function. It was cryptographically broken. + * MD5 architecture is similar to SHA1, with some differences: + * - Reduced output length: 16 bytes (128 bit) instead of 20 + * - 64 rounds, instead of 80 + * - Little-endian: could be faster, but will require more code + * - Non-linear index selection: huge speed-up for unroll + * - Per round constants: more memory accesses, additional speed-up for unroll + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with MD5. + * ```ts + * md5(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const md5: TRet; +/** + * Internal RIPEMD-160 legacy hash class. + * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification. + */ +export declare class _RIPEMD160 extends HashMD<_RIPEMD160> { + private h0; + private h1; + private h2; + private h3; + private h4; + constructor(); + protected get(): [number, number, number, number, number]; + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** + * RIPEMD-160 - a legacy hash function from 1990s. + * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point + * at the base RIPEMD-160 references. + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html} + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf} + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with RIPEMD-160. + * ```ts + * ripemd160(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const ripemd160: TRet; +//# sourceMappingURL=legacy.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/legacy.d.ts.map b/node_modules/@noble/hashes/legacy.d.ts.map new file mode 100644 index 0000000..538ff86 --- /dev/null +++ b/node_modules/@noble/hashes/legacy.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"legacy.d.ts","sourceRoot":"","sources":["src/legacy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAO,MAAM,EAAO,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAE,KAAK,KAAK,EAA6B,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAU9E,uCAAuC;AACvC,qBAAa,KAAM,SAAQ,MAAM,CAAC,KAAK,CAAC;IACtC,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;IAC3B,OAAO,CAAC,CAAC,CAAkB;;IAK3B,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,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AAO,CAAC,EAAE,CAAkB;IAC5B,OAAO,CAAC,EAAE,CAAkB;;IAK5B,SAAS,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC;IAIzD,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,GAAG,IAAI;IAO/E,SAAS,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI;IAoCvD,SAAS,CAAC,UAAU,IAAI,IAAI;IAG5B,OAAO,IAAI,IAAI;CAKhB;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,KAAK,CAAwD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/legacy.js b/node_modules/@noble/hashes/legacy.js new file mode 100644 index 0000000..20c3b99 --- /dev/null +++ b/node_modules/@noble/hashes/legacy.js @@ -0,0 +1,327 @@ +/** + +SHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions. +RFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors, +not the base RIPEMD-160 compression spec. +Don't use them in a new protocol. What "weak" means: + +- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160. +- No practical pre-image attacks (only theoretical, 2^123.4) +- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151 + * @module + */ +import { Chi, HashMD, Maj } from "./_md.js"; +import { clean, createHasher, rotl } from "./utils.js"; +/** Initial SHA-1 state from RFC 3174 §6.1. */ +const SHA1_IV = /* @__PURE__ */ Uint32Array.from([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); +// Reusable 80-word SHA-1 message schedule buffer. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); +/** Internal SHA1 legacy hash class. */ +export class _SHA1 extends HashMD { + A = SHA1_IV[0] | 0; + B = SHA1_IV[1] | 0; + C = SHA1_IV[2] | 0; + D = SHA1_IV[3] | 0; + E = SHA1_IV[4] | 0; + constructor() { + super(64, 20, 8, false); + } + get() { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + set(A, B, C, D, E) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } + else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } + else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } + else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + roundClean() { + clean(SHA1_W); + } + destroy() { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0, 0); + clean(this.buffer); + } +} +/** + * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA1. + * ```ts + * sha1(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1()); +/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */ +const p32 = /* @__PURE__ */ Math.pow(2, 32); +/** RFC 1321 `T[1..64]` table. */ +const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1)))); +/** MD5 initial state from RFC 1321, stored as 4 u32 words. */ +const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4); +// Reusable 16-word MD5 message block buffer. +const MD5_W = /* @__PURE__ */ new Uint32Array(16); +/** Internal MD5 legacy hash class. */ +export class _MD5 extends HashMD { + A = MD5_IV[0] | 0; + B = MD5_IV[1] | 0; + C = MD5_IV[2] | 0; + D = MD5_IV[3] | 0; + constructor() { + super(64, 16, 8, true); + } + get() { + const { A, B, C, D } = this; + return [A, B, C, D]; + } + set(A, B, C, D) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + MD5_W[i] = view.getUint32(offset, true); + // Compression function main loop, 64 rounds + let { A, B, C, D } = this; + for (let i = 0; i < 64; i++) { + let F, g, s; + if (i < 16) { + F = Chi(B, C, D); + g = i; + s = [7, 12, 17, 22]; + } + else if (i < 32) { + // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`. + F = Chi(D, B, C); + g = (5 * i + 1) % 16; + s = [5, 9, 14, 20]; + } + else if (i < 48) { + F = B ^ C ^ D; + g = (3 * i + 5) % 16; + s = [4, 11, 16, 23]; + } + else { + F = C ^ (B | ~D); + g = (7 * i) % 16; + s = [6, 10, 15, 21]; + } + F = F + A + K[i] + MD5_W[g]; + A = D; + D = C; + C = B; + B = B + rotl(F, s[i % 4]); + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + this.set(A, B, C, D); + } + roundClean() { + clean(MD5_W); + } + destroy() { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0); + clean(this.buffer); + } +} +/** + * MD5 (RFC 1321) legacy hash function. It was cryptographically broken. + * MD5 architecture is similar to SHA1, with some differences: + * - Reduced output length: 16 bytes (128 bit) instead of 20 + * - 64 rounds, instead of 80 + * - Little-endian: could be faster, but will require more code + * - Non-linear index selection: huge speed-up for unroll + * - Per round constants: more memory accesses, additional speed-up for unroll + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with MD5. + * ```ts + * md5(new Uint8Array([97, 98, 99])); + * ``` + */ +export const md5 = /* @__PURE__ */ createHasher(() => new _MD5()); +// RIPEMD-160 +// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables. +const Rho160 = /* @__PURE__ */ Uint8Array.from([ + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, +]); +const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))(); +const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))(); +// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds. +const idxLR = /* @__PURE__ */ (() => { + const L = [Id160]; + const R = [Pi160]; + const res = [L, R]; + for (let i = 0; i < 4; i++) + for (let j of res) + j.push(j[i].map((k) => Rho160[k])); + return res; +})(); +const idxL = /* @__PURE__ */ (() => idxLR[0])(); +const idxR = /* @__PURE__ */ (() => idxLR[1])(); +// const [idxL, idxR] = idxLR; +// Base per-group shift table before the left/right message-order permutations are applied. +const shifts160 = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => Uint8Array.from(i)); +const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j])); +const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j])); +// Five left-lane additive constants for RIPEMD-160. +const Kl160 = /* @__PURE__ */ Uint32Array.from([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +// Five right-lane additive constants for RIPEMD-160. +const Kr160 = /* @__PURE__ */ Uint32Array.from([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range +// inputs currently fall through to the group-4 branch. +function ripemd_f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + if (group === 1) + return (x & y) | (~x & z); + if (group === 2) + return (x | ~y) ^ z; + if (group === 3) + return (x & z) | (y & ~z); + return x ^ (y | ~z); +} +// Reusable 16-word RIPEMD-160 message block buffer. +const BUF_160 = /* @__PURE__ */ new Uint32Array(16); +/** + * Internal RIPEMD-160 legacy hash class. + * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification. + */ +export class _RIPEMD160 extends HashMD { + h0 = 0x67452301 | 0; + h1 = 0xefcdab89 | 0; + h2 = 0x98badcfe | 0; + h3 = 0x10325476 | 0; + h4 = 0xc3d2e1f0 | 0; + constructor() { + super(64, 20, 8, true); + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF_160[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order. + this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0); + } + roundClean() { + clean(BUF_160); + } + destroy() { + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0); + } +} +/** + * RIPEMD-160 - a legacy hash function from 1990s. + * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point + * at the base RIPEMD-160 references. + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html} + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf} + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with RIPEMD-160. + * ```ts + * ripemd160(new Uint8Array([97, 98, 99])); + * ``` + */ +export const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160()); +//# sourceMappingURL=legacy.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/legacy.js.map b/node_modules/@noble/hashes/legacy.js.map new file mode 100644 index 0000000..c36f29e --- /dev/null +++ b/node_modules/@noble/hashes/legacy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"legacy.js","sourceRoot":"","sources":["src/legacy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC5C,OAAO,EAAc,KAAK,EAAE,YAAY,EAAE,IAAI,EAAa,MAAM,YAAY,CAAC;AAE9E,8CAA8C;AAC9C,MAAM,OAAO,GAAG,eAAe,CAAC,WAAW,CAAC,IAAI,CAAC;IAC/C,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,UAAU;CAC3D,CAAC,CAAC;AAEH,kDAAkD;AAClD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,WAAW,CAAC,EAAE,CAAC,CAAC;AAEnD,uCAAuC;AACvC,MAAM,OAAO,KAAM,SAAQ,MAAa;IAC9B,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACnB,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAE3B;QACE,KAAK,CAAC,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IAC1B,CAAC;IACS,GAAG;QACX,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,IAAI,CAAC;QAC/B,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AG,EAAE,CAAC,GAAG,CAAC,CACxB,CAAC;IACJ,CAAC;IACS,UAAU;QAClB,KAAK,CAAC,OAAO,CAAC,CAAC;IACjB,CAAC;IACD,OAAO;QACL,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;QACtB,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACnB,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,CAAC;CACF;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,SAAS,GAAgB,eAAe,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/package.json b/node_modules/@noble/hashes/package.json new file mode 100644 index 0000000..0ace74d --- /dev/null +++ b/node_modules/@noble/hashes/package.json @@ -0,0 +1,97 @@ +{ + "name": "@noble/hashes", + "version": "2.2.0", + "description": "Audited & minimal 0-dependency JS implementation of SHA, RIPEMD, BLAKE, HMAC, HKDF, PBKDF & Scrypt", + "files": [ + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map", + "src" + ], + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "@types/node": "25.3.0", + "fast-check": "4.2.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "node test/benchmark/noble.ts", + "bench:compare": "MBENCH_DIMS='algorithm,buffer,library' node test/benchmark/hashes.ts", + "bench:compare-scrypt": "MBENCH_DIMS='iters,library' MBENCH_FILTER='async' node test/benchmark/scrypt.ts", + "bench:install": "cd test/benchmark; npm install", + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts}'", + "test": "node test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts", + "test:node20": "cd test; npx tsc; node compiled/test/index.js", + "test:dos": "node test/slow-dos.test.ts", + "test:slow": "node test/slow-big.test.ts", + "test:acvp": "node test/slow-acvp.test.ts", + "test:kdf": "node test/slow-kdf.test.ts" + }, + "exports": { + ".": "./index.js", + "./_md.js": "./_md.js", + "./argon2.js": "./argon2.js", + "./blake1.js": "./blake1.js", + "./blake2.js": "./blake2.js", + "./blake3.js": "./blake3.js", + "./eskdf.js": "./eskdf.js", + "./hkdf.js": "./hkdf.js", + "./hmac.js": "./hmac.js", + "./legacy.js": "./legacy.js", + "./pbkdf2.js": "./pbkdf2.js", + "./scrypt.js": "./scrypt.js", + "./sha2.js": "./sha2.js", + "./sha3-addons.js": "./sha3-addons.js", + "./sha3.js": "./sha3.js", + "./webcrypto.js": "./webcrypto.js", + "./utils.js": "./utils.js" + }, + "engines": { + "node": ">= 20.19.0" + }, + "keywords": [ + "sha1", + "sha2", + "sha3", + "blake", + "blake2", + "blake3", + "hmac", + "hkdf", + "pbkdf2", + "scrypt", + "sha256", + "sha512", + "keccak", + "ripemd160", + "kdf", + "hash", + "cryptography", + "security", + "noble" + ], + "homepage": "https://paulmillr.com/noble/", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-hashes.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@noble/hashes/pbkdf2.d.ts b/node_modules/@noble/hashes/pbkdf2.d.ts new file mode 100644 index 0000000..cf4a659 --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.d.ts @@ -0,0 +1,56 @@ +import { type CHash, type KDFInput, type TArg, type TRet } from './utils.ts'; +/** + * PBKDF2 options: + * * c: iterations, should probably be higher than 100_000 + * * dkLen: desired length of derived key in bytes, must be `>= 1` per RFC 8018 §5.2 + * * asyncTick: max time in ms for which async function can block execution + */ +export type Pbkdf2Opt = { + /** Iteration count. Higher values increase CPU cost. */ + c: number; + /** Desired derived key length in bytes, must be `>= 1` per RFC 8018 §5.2. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variant. */ + asyncTick?: number; +}; +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2 } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export declare function pbkdf2(hash: TArg, password: TArg, salt: TArg, opts: TArg): TRet; +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. Async version. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local + * scheduler-yield knob for this JS wrapper, not part of RFC 8018. + * See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 }); + * ``` + */ +export declare function pbkdf2Async(hash: TArg, password: TArg, salt: TArg, opts: TArg): Promise>; +//# sourceMappingURL=pbkdf2.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/pbkdf2.d.ts.map b/node_modules/@noble/hashes/pbkdf2.d.ts.map new file mode 100644 index 0000000..2f7dc08 --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.d.ts","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":"AAMA,OAAO,EAGL,KAAK,KAAK,EAEV,KAAK,QAAQ,EACb,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAEpB;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GAAG;IACtB,wDAAwD;IACxD,CAAC,EAAE,MAAM,CAAC;IACV,6EAA6E;IAC7E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AA+CF;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,MAAM,CACpB,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EACxB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,GACpB,IAAI,CAAC,UAAU,CAAC,CAwBlB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,EACjB,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EACxB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,GACpB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAwB3B"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/pbkdf2.js b/node_modules/@noble/hashes/pbkdf2.js new file mode 100644 index 0000000..50ee4db --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.js @@ -0,0 +1,135 @@ +/** + * PBKDF (RFC 2898). Can be used to create a key from password and salt. + * @module + */ +import { hmac } from "./hmac.js"; +// prettier-ignore +import { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from "./utils.js"; +// Common start and end for sync/async functions +function pbkdf2Init(hash, _password, _salt, _opts) { + ahash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + anumber(c, 'c'); + anumber(dkLen, 'dkLen'); + anumber(asyncTick, 'asyncTick'); + if (c < 1) + throw new Error('iterations (c) must be >= 1'); + // RFC 8018 §5.2 defines `dkLen` as "a positive integer". + if (dkLen < 1) + throw new Error('"dkLen" must be >= 1'); + // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen` + // before allocating the destination buffer. + if (dkLen > (2 ** 32 - 1) * hash.outputLen) + throw new Error('derived key too long'); + const password = kdfInputToBytes(_password, 'password'); + const salt = kdfInputToBytes(_salt, 'salt'); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i). + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + // Shared sync/async cleanup point: wipe transient PRF state + // while preserving the derived key buffer. + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + clean(u); + return DK; +} +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2 } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export function pbkdf2(hash, password, salt, opts) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + // The last Ti view can be shorter than hLen, which applies + // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies. + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. Async version. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local + * scheduler-yield knob for this JS wrapper, not part of RFC 8018. + * See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 }); + * ``` + */ +export async function pbkdf2Async(hash, password, salt, opts) { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + // The last Ti view can be shorter than hLen, which applies + // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies. + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} +//# sourceMappingURL=pbkdf2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/pbkdf2.js.map b/node_modules/@noble/hashes/pbkdf2.js.map new file mode 100644 index 0000000..291eca4 --- /dev/null +++ b/node_modules/@noble/hashes/pbkdf2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"pbkdf2.js","sourceRoot":"","sources":["src/pbkdf2.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,kBAAkB;AAClB,OAAO,EACL,KAAK,EAAE,OAAO,EACd,SAAS,EAAE,SAAS,EAAE,KAAK,EAAE,UAAU,EAAE,eAAe,EAMzD,MAAM,YAAY,CAAC;AAgBpB,gDAAgD;AAChD,SAAS,UAAU,CACjB,IAAiB,EACjB,SAAyB,EACzB,KAAqB,EACrB,KAAsB;IAEtB,KAAK,CAAC,IAAI,CAAC,CAAC;IACZ,MAAM,IAAI,GAAG,SAAS,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,SAAS,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,CAAC;IAC5D,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC;IACrC,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAChB,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxB,OAAO,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IAChC,IAAI,CAAC,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;IAC1D,yDAAyD;IACzD,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IACvD,2DAA2D;IAC3D,4CAA4C;IAC5C,IAAI,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IACpF,MAAM,QAAQ,GAAG,eAAe,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AC3B,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;YAC7C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;gBAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,CAAC;IACL,CAAC;IACD,OAAO,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AACjD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.d.ts b/node_modules/@noble/hashes/scrypt.d.ts new file mode 100644 index 0000000..b23a26e --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.d.ts @@ -0,0 +1,65 @@ +import { type KDFInput, type TArg, type TRet } from './utils.ts'; +/** + * Scrypt options: + * - `N` is cpu/mem work factor (power of 2 e.g. `2**18`) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32, and must be `>= 1` per RFC 7914 §2. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + */ +export type ScryptOpts = { + /** CPU and memory work factor. Must be a power of two. */ + N: number; + /** Block size parameter. */ + r: number; + /** Parallelization factor. */ + p: number; + /** Desired derived key length in bytes, must be `>= 1` per RFC 7914 §2. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variant. */ + asyncTick?: number; + /** Maximum temporary memory budget in bytes. */ + maxmem?: number; + /** + * Optional progress callback invoked during long-running derivations. + * param progress - completion fraction in the `0..1` range + */ + onProgress?: (progress: number) => void; +}; +/** + * Scrypt KDF from RFC 7914. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. See {@link ScryptOpts}. + * @returns Derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt. + * ```ts + * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare function scrypt(password: TArg, salt: TArg, opts: TArg): TRet; +/** + * Scrypt KDF from RFC 7914. Async version. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. `asyncTick` is only a local + * scheduler-yield control for this JS wrapper, not part of RFC 7914. + * See {@link ScryptOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt asynchronously. + * ```ts + * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export declare function scryptAsync(password: TArg, salt: TArg, opts: TArg): Promise>; +//# sourceMappingURL=scrypt.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.d.ts.map b/node_modules/@noble/hashes/scrypt.d.ts.map new file mode 100644 index 0000000..4b642af --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.d.ts","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":"AAOA,OAAO,EAML,KAAK,QAAQ,EACb,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAkFpB;;;;;;;;;GASG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,0DAA0D;IAC1D,CAAC,EAAE,MAAM,CAAC;IACV,4BAA4B;IAC5B,CAAC,EAAE,MAAM,CAAC;IACV,8BAA8B;IAC9B,CAAC,EAAE,MAAM,CAAC;IACV,2EAA2E;IAC3E,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,CAAC;CACzC,CAAC;AAiFF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,MAAM,CACpB,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EACxB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GACrB,IAAI,CAAC,UAAU,CAAC,CAgClB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EACxB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GACrB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAiC3B"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.js b/node_modules/@noble/hashes/scrypt.js new file mode 100644 index 0000000..29ff883 --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.js @@ -0,0 +1,257 @@ +/** + * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt. + * @module + */ +import { pbkdf2 } from "./pbkdf2.js"; +import { sha256 } from "./sha2.js"; +// prettier-ignore +import { anumber, asyncLoop, checkOpts, clean, rotl, swap32IfBE, u32 } from "./utils.js"; +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// RFC 7914 §3 / §4 step 2 applies Salsa20/8 to one 16-word (64-byte) block +// after xor'ing two such blocks. +// The local `y*` snapshot keeps the xor input stable even when `out` aliases `prev` or `input`. +// prettier-ignore +function XorAndSalsa(prev, pi, input, ii, out, oi) { + // Based on https://cr.yp.to/salsa20.html and RFC 7914's Salsa20/8 core. + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + 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; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); + x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); + x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); + x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); + x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); + x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); + x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); + x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); + x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); + x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); + x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); + x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); + x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); + x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); + x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); + x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); + x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; + out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; + out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; + out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; + out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; + out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; + out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; + out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; + out[oi++] = (y15 + x15) | 0; +} +function BlockMix(input, ii, out, oi, r) { + // The block B is `r` 128-byte chunks, i.e. `2r` 16-word (64-byte) Salsa blocks. + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) + out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // RFC 7914 §4 step 3 outputs `Y[0], Y[2], ...` first, then `Y[1], Y[3], ...`; + // `head` and `tail` lay out those even/odd halves in place. + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) + tail += 16; // First iteration overwrites tmp value in tail + // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + XorAndSalsa(out, head, input, (ii += 16), out, tail); + } +} +// Common prologue and epilogue for sync/async functions +function scryptInit(password, salt, _opts) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts({ + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, _opts); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + anumber(N, 'N'); + anumber(r, 'r'); + anumber(p, 'p'); + anumber(dkLen, 'dkLen'); + anumber(asyncTick, 'asyncTick'); + anumber(maxmem, 'maxmem'); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb must be a function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + // Max N is 2^32 (Integrify is 32-bit). + // Real limit can be 2^22: some JS engines limit Uint8Array to 4GB. + // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs, + // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error: + // https://www.rfc-editor.org/errata_search.php?rfc=7914 + const pow32 = Math.pow(2, 32); + if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) + throw new Error('"N" expected a power of 2, and 2^1 <= N <= 2^32'); + if (p < 1 || p > ((pow32 - 1) * 32) / blockSize) + throw new Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)'); + // RFC 7914 §2 defines `dkLen` as a positive integer. + if (dkLen < 1 || dkLen > (pow32 - 1) * 32) + throw new Error('"dkLen" expected integer 1..(2^32 - 1) * 32'); + // Include the shared `tmp` scratch block so `maxmem` matches noble's actual temporary allocation. + // Node requires more headroom here, so this accounting is intentionally noble-specific. + const memUsed = blockSize * (N + p + 1); + if (memUsed > maxmem) + throw new Error('"maxmem" limit was hit: memUsed(128*r*(N+p+1))=' + memUsed + ', maxmem=' + maxmem); + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => { }; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} +function scryptOutput(password, dkLen, B, V, tmp) { + // Shared final PBKDF2-and-cleanup step: keep the derived key, wipe the scrypt workspace. + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + clean(B, V, tmp); + return res; +} +/** + * Scrypt KDF from RFC 7914. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. See {@link ScryptOpts}. + * @returns Derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt. + * ```ts + * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export function scrypt(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(password, salt, opts); + swap32IfBE(B32); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N + // only depends on the low word here because N is a power of two and + // this implementation caps N at 2^32. + // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked + // above; >>> 0 for unsigned, input fits in u32. + const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations + // tmp = B ^ V[j] + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + swap32IfBE(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +/** + * Scrypt KDF from RFC 7914. Async version. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. `asyncTick` is only a local + * scheduler-yield control for this JS wrapper, not part of RFC 7914. + * See {@link ScryptOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt asynchronously. + * ```ts + * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export async function scryptAsync(password, salt, opts) { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts); + swap32IfBE(B32); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) + V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N + // only depends on the low word here because N is a power of two and + // this implementation caps N at 2^32. + // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked + // above; >>> 0 for unsigned, input fits in u32. + const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations + // tmp = B ^ V[j] + for (let k = 0; k < blockSize32; k++) + tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + swap32IfBE(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} +//# sourceMappingURL=scrypt.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/scrypt.js.map b/node_modules/@noble/hashes/scrypt.js.map new file mode 100644 index 0000000..7daddda --- /dev/null +++ b/node_modules/@noble/hashes/scrypt.js.map @@ -0,0 +1 @@ +{"version":3,"file":"scrypt.js","sourceRoot":"","sources":["src/scrypt.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,kBAAkB;AAClB,OAAO,EACL,OAAO,EAAE,SAAS,EAClB,SAAS,EAAE,KAAK,EAChB,IAAI,EACJ,UAAU,EACV,GAAG,EAIJ,MAAM,YAAY,CAAC;AAEpB,gDAAgD;AAChD,oEAAoE;AACpE,2EAA2E;AAC3E,iCAAiC;AACjC,gGAAgG;AAChG,kBAAkB;AAClB,SAAS,WAAW,CAClB,IAAuB,EACvB,EAAU,EACV,KAAwB,EACxB,EAAU,EACV,GAAsB,EACtB,EAA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AG,CAAC,GAAG,CAAC,EAAE,GAAG,WAAW,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,gCAAgC;YACxF,iBAAiB;YACjB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,WAAW,EAAE,CAAC,EAAE;gBAAE,GAAG,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC;YACpF,QAAQ,CAAC,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,yBAAyB;YACvD,UAAU,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;IACD,UAAU,CAAC,GAAG,CAAC,CAAC;IAChB,OAAO,YAAY,CAAC,QAAQ,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC;AAClD,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha2.d.ts b/node_modules/@noble/hashes/sha2.d.ts new file mode 100644 index 0000000..b7a1d54 --- /dev/null +++ b/node_modules/@noble/hashes/sha2.d.ts @@ -0,0 +1,249 @@ +/** + * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256. + * SHA256 is the fastest hash implementable in JS, even faster than Blake3. + * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}. + * @module + */ +import { HashMD } from './_md.ts'; +import { type CHash, type TRet } from './utils.ts'; +/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */ +declare abstract class SHA2_32B> extends HashMD { + protected abstract A: number; + protected abstract B: number; + protected abstract C: number; + protected abstract D: number; + protected abstract E: number; + protected abstract F: number; + protected abstract G: number; + protected abstract H: number; + constructor(outputLen: number); + protected get(): [number, number, number, number, number, number, number, number]; + protected set(A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */ +export declare class _SHA256 extends SHA2_32B<_SHA256> { + protected A: number; + protected B: number; + protected C: number; + protected D: number; + protected E: number; + protected F: number; + protected G: number; + protected H: number; + constructor(); +} +/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */ +export declare class _SHA224 extends SHA2_32B<_SHA224> { + protected A: number; + protected B: number; + protected C: number; + protected D: number; + protected E: number; + protected F: number; + protected G: number; + protected H: number; + constructor(); +} +/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */ +declare abstract class SHA2_64B> extends HashMD { + protected abstract Ah: number; + protected abstract Al: number; + protected abstract Bh: number; + protected abstract Bl: number; + protected abstract Ch: number; + protected abstract Cl: number; + protected abstract Dh: number; + protected abstract Dl: number; + protected abstract Eh: number; + protected abstract El: number; + protected abstract Fh: number; + protected abstract Fl: number; + protected abstract Gh: number; + protected abstract Gl: number; + protected abstract Hh: number; + protected abstract Hl: number; + constructor(outputLen: number); + protected get(): [ + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number, + number + ]; + protected set(Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number): void; + protected process(view: DataView, offset: number): void; + protected roundClean(): void; + destroy(): void; +} +/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export declare class _SHA512 extends SHA2_64B<_SHA512> { + protected Ah: number; + protected Al: number; + protected Bh: number; + protected Bl: number; + protected Ch: number; + protected Cl: number; + protected Dh: number; + protected Dl: number; + protected Eh: number; + protected El: number; + protected Fh: number; + protected Fl: number; + protected Gh: number; + protected Gl: number; + protected Hh: number; + protected Hl: number; + constructor(); +} +/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export declare class _SHA384 extends SHA2_64B<_SHA384> { + protected Ah: number; + protected Al: number; + protected Bh: number; + protected Bl: number; + protected Ch: number; + protected Cl: number; + protected Dh: number; + protected Dl: number; + protected Eh: number; + protected El: number; + protected Fh: number; + protected Fl: number; + protected Gh: number; + protected Gl: number; + protected Hh: number; + protected Hl: number; + constructor(); +} +/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export declare class _SHA512_224 extends SHA2_64B<_SHA512_224> { + protected Ah: number; + protected Al: number; + protected Bh: number; + protected Bl: number; + protected Ch: number; + protected Cl: number; + protected Dh: number; + protected Dl: number; + protected Eh: number; + protected El: number; + protected Fh: number; + protected Fl: number; + protected Gh: number; + protected Gl: number; + protected Hh: number; + protected Hl: number; + constructor(); +} +/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export declare class _SHA512_256 extends SHA2_64B<_SHA512_256> { + protected Ah: number; + protected Al: number; + protected Bh: number; + protected Bl: number; + protected Ch: number; + protected Cl: number; + protected Dh: number; + protected Dl: number; + protected Eh: number; + protected El: number; + protected Fh: number; + protected Fl: number; + protected Gh: number; + protected Gl: number; + protected Hh: number; + protected Hl: number; + constructor(); +} +/** + * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info: + * + * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack. + * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025. + * - Each sha256 hash is executing 2^18 bit operations. + * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-256. + * ```ts + * sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha256: TRet>; +/** + * SHA2-224 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-224. + * ```ts + * sha224(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha224: TRet>; +/** + * SHA2-512 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512. + * ```ts + * sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha512: TRet>; +/** + * SHA2-384 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-384. + * ```ts + * sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha384: TRet>; +/** + * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/256. + * ```ts + * sha512_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha512_256: TRet>; +/** + * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/224. + * ```ts + * sha512_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha512_224: TRet>; +export {}; +//# sourceMappingURL=sha2.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha2.d.ts.map b/node_modules/@noble/hashes/sha2.d.ts.map new file mode 100644 index 0000000..717e788 --- /dev/null +++ b/node_modules/@noble/hashes/sha2.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.d.ts","sourceRoot":"","sources":["src/sha2.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAO,MAAM,EAAmD,MAAM,UAAU,CAAC;AAExF,OAAO,EAAE,KAAK,KAAK,EAAsC,KAAK,IAAI,EAAE,MAAM,YAAY,CAAC;AAqBvF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;;;;GAUG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAG/C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha2.js b/node_modules/@noble/hashes/sha2.js new file mode 100644 index 0000000..be20232 --- /dev/null +++ b/node_modules/@noble/hashes/sha2.js @@ -0,0 +1,458 @@ +/** + * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256. + * SHA256 is the fastest hash implementable in JS, even faster than Blake3. + * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}. + * @module + */ +import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from "./_md.js"; +import * as u64 from "./_u64.js"; +import { clean, createHasher, oidNist, rotr } from "./utils.js"; +/** + * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits + * of the cube roots of the first 64 primes (2..311). + */ +// prettier-ignore +const SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); +/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */ +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); +/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */ +class SHA2_32B extends HashMD { + constructor(outputLen) { + super(64, outputLen, 8, false); + } + get() { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + set(A, B, C, D, E, F, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +} +/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */ +export class _SHA256 extends SHA2_32B { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + A = SHA256_IV[0] | 0; + B = SHA256_IV[1] | 0; + C = SHA256_IV[2] | 0; + D = SHA256_IV[3] | 0; + E = SHA256_IV[4] | 0; + F = SHA256_IV[5] | 0; + G = SHA256_IV[6] | 0; + H = SHA256_IV[7] | 0; + constructor() { + super(32); + } +} +/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */ +export class _SHA224 extends SHA2_32B { + A = SHA224_IV[0] | 0; + B = SHA224_IV[1] | 0; + C = SHA224_IV[2] | 0; + D = SHA224_IV[3] | 0; + E = SHA224_IV[4] | 0; + F = SHA224_IV[5] | 0; + G = SHA224_IV[6] | 0; + H = SHA224_IV[7] | 0; + constructor() { + super(28); + } +} +// SHA2-512 is slower than sha256 in js because u64 operations are slow. +// SHA-384 / SHA-512 round constants from RFC 6234 §5.2: +// 80 full 64-bit words split into high/low halves. +// prettier-ignore +const K512 = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +const SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); +const SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); +// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words. +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words. +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */ +class SHA2_64B extends HashMD { + constructor(outputLen) { + super(128, outputLen, 16, false); + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + clean(SHA512_W_H, SHA512_W_L); + } + destroy() { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} +/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export class _SHA512 extends SHA2_64B { + Ah = SHA512_IV[0] | 0; + Al = SHA512_IV[1] | 0; + Bh = SHA512_IV[2] | 0; + Bl = SHA512_IV[3] | 0; + Ch = SHA512_IV[4] | 0; + Cl = SHA512_IV[5] | 0; + Dh = SHA512_IV[6] | 0; + Dl = SHA512_IV[7] | 0; + Eh = SHA512_IV[8] | 0; + El = SHA512_IV[9] | 0; + Fh = SHA512_IV[10] | 0; + Fl = SHA512_IV[11] | 0; + Gh = SHA512_IV[12] | 0; + Gl = SHA512_IV[13] | 0; + Hh = SHA512_IV[14] | 0; + Hl = SHA512_IV[15] | 0; + constructor() { + super(64); + } +} +/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export class _SHA384 extends SHA2_64B { + Ah = SHA384_IV[0] | 0; + Al = SHA384_IV[1] | 0; + Bh = SHA384_IV[2] | 0; + Bl = SHA384_IV[3] | 0; + Ch = SHA384_IV[4] | 0; + Cl = SHA384_IV[5] | 0; + Dh = SHA384_IV[6] | 0; + Dl = SHA384_IV[7] | 0; + Eh = SHA384_IV[8] | 0; + El = SHA384_IV[9] | 0; + Fh = SHA384_IV[10] | 0; + Fl = SHA384_IV[11] | 0; + Gh = SHA384_IV[12] | 0; + Gl = SHA384_IV[13] | 0; + Hh = SHA384_IV[14] | 0; + Hl = SHA384_IV[15] | 0; + constructor() { + super(48); + } +} +/** + * Truncated SHA512/256 and SHA512/224. + * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t. + * Then t hashes string to produce result IV. + * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`. + * These IV literals are checked against that script rather than a dedicated + * local RFC section. + */ +/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and + * stored as sixteen big-endian 32-bit halves. */ +const T224_IV = /* @__PURE__ */ Uint32Array.from([ + 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf, + 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1, +]); +/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and + * stored as sixteen big-endian 32-bit halves. */ +const T256_IV = /* @__PURE__ */ Uint32Array.from([ + 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd, + 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2, +]); +/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export class _SHA512_224 extends SHA2_64B { + Ah = T224_IV[0] | 0; + Al = T224_IV[1] | 0; + Bh = T224_IV[2] | 0; + Bl = T224_IV[3] | 0; + Ch = T224_IV[4] | 0; + Cl = T224_IV[5] | 0; + Dh = T224_IV[6] | 0; + Dl = T224_IV[7] | 0; + Eh = T224_IV[8] | 0; + El = T224_IV[9] | 0; + Fh = T224_IV[10] | 0; + Fl = T224_IV[11] | 0; + Gh = T224_IV[12] | 0; + Gl = T224_IV[13] | 0; + Hh = T224_IV[14] | 0; + Hl = T224_IV[15] | 0; + constructor() { + super(28); + } +} +/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export class _SHA512_256 extends SHA2_64B { + Ah = T256_IV[0] | 0; + Al = T256_IV[1] | 0; + Bh = T256_IV[2] | 0; + Bl = T256_IV[3] | 0; + Ch = T256_IV[4] | 0; + Cl = T256_IV[5] | 0; + Dh = T256_IV[6] | 0; + Dl = T256_IV[7] | 0; + Eh = T256_IV[8] | 0; + El = T256_IV[9] | 0; + Fh = T256_IV[10] | 0; + Fl = T256_IV[11] | 0; + Gh = T256_IV[12] | 0; + Gl = T256_IV[13] | 0; + Hh = T256_IV[14] | 0; + Hl = T256_IV[15] | 0; + constructor() { + super(32); + } +} +/** + * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info: + * + * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack. + * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025. + * - Each sha256 hash is executing 2^18 bit operations. + * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-256. + * ```ts + * sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), +/* @__PURE__ */ oidNist(0x01)); +/** + * SHA2-224 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-224. + * ```ts + * sha224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha224 = /* @__PURE__ */ createHasher(() => new _SHA224(), +/* @__PURE__ */ oidNist(0x04)); +/** + * SHA2-512 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512. + * ```ts + * sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512 = /* @__PURE__ */ createHasher(() => new _SHA512(), +/* @__PURE__ */ oidNist(0x03)); +/** + * SHA2-384 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-384. + * ```ts + * sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha384 = /* @__PURE__ */ createHasher(() => new _SHA384(), +/* @__PURE__ */ oidNist(0x02)); +/** + * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/256. + * ```ts + * sha512_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512_256 = /* @__PURE__ */ createHasher(() => new _SHA512_256(), +/* @__PURE__ */ oidNist(0x06)); +/** + * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/224. + * ```ts + * sha512_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512_224 = /* @__PURE__ */ createHasher(() => new _SHA512_224(), +/* @__PURE__ */ oidNist(0x05)); +//# sourceMappingURL=sha2.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha2.js.map b/node_modules/@noble/hashes/sha2.js.map new file mode 100644 index 0000000..9c8bb3d --- /dev/null +++ b/node_modules/@noble/hashes/sha2.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha2.js","sourceRoot":"","sources":["src/sha2.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AACxF,OAAO,KAAK,GAAG,MAAM,WAAW,CAAC;AACjC,OAAO,EAAc,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAa,MAAM,YAAY,CAAC;AAEvF;;;GAGG;AACH,kBAAkB;AAClB,MAAM,Q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,CAC9E,GAAG,EAAE,CAAC,IAAI,WAAW,EAAE;AACvB,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAC9B,CAAC;AACF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,UAAU,GAA6B,eAAe,CAAC,YAAY,CAC9E,GAAG,EAAE,CAAC,IAAI,WAAW,EAAE;AACvB,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAC9B,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.d.ts b/node_modules/@noble/hashes/sha3-addons.d.ts new file mode 100644 index 0000000..762b044 --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.d.ts @@ -0,0 +1,461 @@ +/** + * SHA3 (keccak) addons. + * + * * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants from + * {@link https://csrc.nist.gov/pubs/sp/800/185/final | NIST SP 800-185} + * * KangarooTwelve 🦘 and TurboSHAKE - reduced-round keccak from + * {@link https://datatracker.ietf.org/doc/rfc9861/ | RFC 9861} + * * KeccakPRG: Pseudo-random generator based on Keccak + * ({@link https://keccak.team/files/CSF-0.1.pdf | pdf}) + * @module + */ +import { Keccak, type ShakeOpts } from './sha3.ts'; +import { type CHash, type CHashXOF, type Hash, type HashXOF, type KDFInput, type PRG, type TArg, type TRet } from './utils.ts'; +/** Options for cSHAKE and related SP 800-185 functions. */ +export type cShakeOpts = ShakeOpts & { + /** Optional personalization string mixed into domain separation. */ + personalization?: Uint8Array; + /** + * Optional NIST function-name string used for domain separation. + * SP 800-185 reserves this for standardized function names; applications + * should generally stick to `personalization`. + */ + NISTfn?: KDFInput; +}; +/** TupleHash callable interface. */ +export type ITupleHash = { + /** + * Hashes an ordered tuple of byte arrays. + * @param messages - Ordered byte-array tuple to hash. + * @param opts - TupleHash output and personalization options. See {@link cShakeOpts}. + * @returns Digest bytes. + */ + (messages: TArg, opts?: TArg): TRet; + /** + * Creates an incremental TupleHash state. + * @param opts - TupleHash output and personalization options. See {@link cShakeOpts}. + * @returns Stateful TupleHash instance. + */ + create(opts?: cShakeOpts): _TupleHash; +}; +/** + * 128-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE128. Defaults to 16 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE128. + * ```ts + * cshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export declare const cshake128: TRet>; +/** + * 256-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE256. Defaults to 32 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE256. + * ```ts + * cshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export declare const cshake256: TRet>; +/** + * Internal KMAC class. + * SP 800-185 §8.4.1 still recommends keys at least as long as the target + * security strength. + */ +export declare class _KMAC extends Keccak implements HashXOF<_KMAC> { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, key: TArg, opts?: TArg); + protected finish(): void; + _cloneInto(to?: _KMAC): _KMAC; + clone(): _KMAC; +} +/** KMAC callable interface. */ +export type IKMAC = { + /** + * Computes a keyed KMAC digest for one message. + * @param key - Secret key bytes. + * @param message - Message bytes to authenticate. + * @param opts - KMAC output and personalization options. See {@link KangarooOpts}. + * @returns Authentication tag bytes. + */ + (key: TArg, message: TArg, opts?: TArg): TRet; + /** + * Creates an incremental KMAC state. + * @param key - Secret key bytes. + * @param opts - KMAC output and personalization options. See {@link cShakeOpts}. + * @returns Stateful KMAC instance. + */ + create(key: TArg, opts?: TArg): _KMAC; +}; +/** + * 128-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128. + * ```ts + * kmac128(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export declare const kmac128: TRet; +/** + * 256-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256. + * ```ts + * kmac256(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export declare const kmac256: TRet; +/** + * 128-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128 XOF output. + * ```ts + * kmac128xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 32 }); + * ``` + */ +export declare const kmac128xof: TRet; +/** + * 256-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256 XOF output. + * ```ts + * kmac256xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 64 }); + * ``` + */ +export declare const kmac256xof: TRet; +/** + * Internal TupleHash class for byte-array tuple elements. + * This implementation relies on SP 800-185's byte-oriented encoding form + * rather than arbitrary bit strings. + */ +export declare class _TupleHash extends Keccak implements HashXOF<_TupleHash> { + constructor(blockLen: number, outputLen: number, enableXOF: boolean, opts?: TArg); + protected finish(): void; + _cloneInto(to?: _TupleHash): _TupleHash; + clone(): _TupleHash; +} +/** + * 128-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128. + * ```ts + * tuplehash128([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export declare const tuplehash128: TRet; +/** + * 256-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256. + * ```ts + * tuplehash256([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export declare const tuplehash256: TRet; +/** + * 128-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128 XOF output. + * ```ts + * tuplehash128xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 32 }); + * ``` + */ +export declare const tuplehash128xof: TRet; +/** + * 256-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256 XOF output. + * ```ts + * tuplehash256xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 64 }); + * ``` + */ +export declare const tuplehash256xof: TRet; +type ParallelOpts = KangarooOpts & { + blockLen?: number; +}; +/** Internal Parallel Keccak Hash class. */ +export declare class _ParallelHash extends Keccak implements HashXOF<_ParallelHash> { + private leafHash?; + protected leafCons: () => Hash; + private chunkPos; + private chunksDone; + private chunkLen; + constructor(blockLen: number, outputLen: number, leafCons: () => Hash, enableXOF: boolean, opts?: TArg); + protected finish(): void; + _cloneInto(to?: _ParallelHash): _ParallelHash; + destroy(): void; + clone(): _ParallelHash; +} +/** + * 128-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128. + * ```ts + * parallelhash128(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const parallelhash128: TRet>; +/** + * 256-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256. + * ```ts + * parallelhash256(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const parallelhash256: TRet>; +/** + * 128-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128 XOF output. + * ```ts + * parallelhash128xof(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export declare const parallelhash128xof: TRet>; +/** + * 256-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256 XOF output. + * ```ts + * parallelhash256xof(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export declare const parallelhash256xof: TRet>; +/** + * TurboSHAKE options. + * `D` is the domain separation byte; RFC 9861 defines output length `L` + * as a positive integer. + */ +export type TurboshakeOpts = ShakeOpts & { + /** Optional domain separation byte in the `0x01..0x7f` range. */ + D?: number; +}; +/** + * TurboSHAKE 128-bit: reduced 12-round keccak. + * Should've been a simple "shake with 12 rounds", but we got a whole new + * spec about Turbo SHAKE Pro MAX. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 32 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE128. + * ```ts + * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export declare const turboshake128: TRet>; +/** + * TurboSHAKE 256-bit: reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 64 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE256. + * ```ts + * turboshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export declare const turboshake256: TRet>; +/** K12 options. */ +export type KangarooOpts = { + /** + * Desired digest length in bytes. + * RFC 9861 §3 defines output length `L` as a positive integer. + */ + dkLen?: number; + /** + * Optional personalization string mixed into the sponge state. + * Stateful K12 instances keep an internal copy so caller buffers can be + * wiped independently. + */ + personalization?: Uint8Array; +}; +/** Internal K12 hash class. */ +export declare class _KangarooTwelve extends Keccak implements HashXOF<_KangarooTwelve> { + readonly chunkLen = 8192; + private leafHash?; + protected leafLen: number; + private personalization; + private chunkPos; + private chunksDone; + constructor(blockLen: number, leafLen: number, outputLen: number, rounds: number, opts: TArg); + update(data: TArg): this; + protected finish(): void; + destroy(): void; + _cloneInto(to?: _KangarooTwelve): _KangarooTwelve; + clone(): _KangarooTwelve; +} +/** + * 128-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-128. + * ```ts + * kt128(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const kt128: TRet>; +/** + * 256-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 64 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-256. + * ```ts + * kt256(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare const kt256: TRet>; +/** KangarooTwelve-based MAC function type. */ +export type HopMAC = (key: TArg, message: TArg, personalization: TArg, dkLen?: number) => TRet; +/** + * 128-bit KangarooTwelve-based MAC. + * + * These untested (there is no test vectors or implementation available). Use at your own risk. + * HopMAC128(Key, M, C, L) = KT128(Key, KT128(M, C, 32), L) + * HopMAC256(Key, M, C, L) = KT256(Key, KT256(M, C, 64), L) + * The inner KangarooTwelve call always uses a fixed 32-byte digest here, + * regardless of the outer `dkLen`. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC128. + * ```ts + * HopMAC128(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 32); + * ``` + */ +export declare const HopMAC128: TRet; +/** + * 256-bit KangarooTwelve-based MAC. + * Like `HopMAC128`, there are no test vectors or known independent + * implementations available for cross-checking. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes. The inner KangarooTwelve + * call still uses a fixed 64-byte digest here, regardless of the outer + * `dkLen`. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC256. + * ```ts + * HopMAC256(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 64); + * ``` + */ +export declare const HopMAC256: TRet; +/** + * More at + * {@link https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG}. + * Accepted capacities must keep `rho = 1598 - capacity` byte-aligned, and + * `.clean()` later also requires `rate > 801`. + */ +export declare class _KeccakPRG extends Keccak implements PRG { + protected rate: number; + constructor(capacity: number); + protected keccak(): void; + update(data: TArg): this; + protected finish(): void; + digestInto(_out: TArg): void; + addEntropy(seed: TArg): void; + randomBytes(length: number): TRet; + clean(): void; + _cloneInto(to?: _KeccakPRG): _KeccakPRG; + clone(): _KeccakPRG; +} +/** + * KeccakPRG: pseudo-random generator based on Keccak. + * See {@link https://keccak.team/files/CSF-0.1.pdf}. + * @param capacity - sponge capacity in bits. Accepted values are those that + * keep `rho = 1598 - capacity` byte-aligned; the default `254` is chosen + * because it satisfies that duplex layout while leaving a wide byte-aligned + * rate. + * @returns PRG instance backed by a Keccak sponge. + * @example + * Create a Keccak-based pseudorandom generator and read bytes from it. + * ```ts + * const prg = keccakprg(254); + * prg.randomBytes(8); + * ``` + */ +export declare const keccakprg: (capacity?: number) => TRet<_KeccakPRG>; +export {}; +//# sourceMappingURL=sha3-addons.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.d.ts.map b/node_modules/@noble/hashes/sha3-addons.d.ts.map new file mode 100644 index 0000000..e43e1e3 --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.d.ts","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,MAAM,EAAE,KAAK,SAAS,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAIL,KAAK,KAAK,EACV,KAAK,QAAQ,EAIb,KAAK,IAAI,EACT,KAAK,OAAO,EACZ,KAAK,QAAQ,EAEb,KAAK,GAAG,EACR,KAAK,IAAI,EACT,KAAK,IAAI,EAEV,MAAM,YAAY,CAAC;AA4CpB,2DAA2D;AAC3D,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG;IACnC,oEAAoE;IACpE,eAAe,CAAC,EAAE,UAAU,CAAC;IAC7B;;;;O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AAC,UAAU,CAAC,EACrB,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,EACzB,eAAe,EAAE,IAAI,CAAC,UAAU,CAAC,EACjC,KAAK,CAAC,EAAE,MAAM,KACX,IAAI,CAAC,UAAU,CAAC,CAAC;AAatB;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,MAAM,CAAoC,CAAC;AACxE;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,MAAM,CAAoC,CAAC;AAExE;;;;;GAKG;AACH,qBAAa,UAAW,SAAQ,MAAO,YAAW,GAAG;IACnD,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;gBACX,QAAQ,EAAE,MAAM;IAW5B,SAAS,CAAC,MAAM,IAAI,IAAI;IAQxB,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAKpC,SAAS,CAAC,MAAM,IAAI,IAAI;IACxB,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAGxC,UAAU,CAAC,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,IAAI;IAGxC,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC;IAG7C,KAAK,IAAI,IAAI;IAWb,UAAU,CAAC,EAAE,CAAC,EAAE,UAAU,GAAG,UAAU;IAOvC,KAAK,IAAI,UAAU;CAGpB;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,SAAS,GAAI,iBAAc,KAAG,IAAI,CAAC,UAAU,CACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.js b/node_modules/@noble/hashes/sha3-addons.js new file mode 100644 index 0000000..21229ed --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.js @@ -0,0 +1,783 @@ +/** + * SHA3 (keccak) addons. + * + * * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants from + * {@link https://csrc.nist.gov/pubs/sp/800/185/final | NIST SP 800-185} + * * KangarooTwelve 🦘 and TurboSHAKE - reduced-round keccak from + * {@link https://datatracker.ietf.org/doc/rfc9861/ | RFC 9861} + * * KeccakPRG: Pseudo-random generator based on Keccak + * ({@link https://keccak.team/files/CSF-0.1.pdf | pdf}) + * @module + */ +import { Keccak } from "./sha3.js"; +import { abytes, aexists, anumber, clean, copyBytes, createHasher, kdfInputToBytes, u32, } from "./utils.js"; +// cSHAKE && KMAC (NIST SP800-185) +const _8n = /* @__PURE__ */ BigInt(8); +const _ffn = /* @__PURE__ */ BigInt(0xff); +// It is safe to use bigints here, since they used only for length encoding (not actual data). +// We use bigints in sha256 for lengths too. +// Callers are still expected to supply SP 800-185-valid lengths +// (`0 <= x < 2^2040`); this helper does not enforce that bound. +function leftEncode(n) { + n = BigInt(n); + const res = [Number(n & _ffn)]; + n >>= _8n; + for (; n > 0; n >>= _8n) + res.unshift(Number(n & _ffn)); + res.unshift(res.length); + return new Uint8Array(res); +} +// Same caller contract as `leftEncode(...)`: lengths must already satisfy SP 800-185 §2.3.1. +function rightEncode(n) { + n = BigInt(n); + const res = [Number(n & _ffn)]; + n >>= _8n; + for (; n > 0; n >>= _8n) + res.unshift(Number(n & _ffn)); + res.push(res.length); + return new Uint8Array(res); +} +// `dkLen` validation is deferred to the downstream Keccak constructor. +function chooseLen(opts, outputLen) { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} +const abytesOrZero = (buf, title = '') => { + if (buf === undefined) + return EMPTY_BUFFER; + abytes(buf, undefined, title); + return buf; +}; +// NOTE: second modulo is necessary since we don't need to add padding if the +// current element takes a whole block. +// Callers only pass the fixed positive Keccak rates here (`168` or `136`); +// `block <= 0` is not validated locally. +const getPadding = (len, block) => new Uint8Array((block - (len % block)) % block); +// Personalization +function cshakePers(hash, opts = {}) { + const h = hash; + if (!opts || (opts.personalization === undefined && opts.NISTfn === undefined)) + return h; + // Encode and pad inplace to avoid unneccesary memory copies/slices so we + // don't need to zero them later. + // bytepad(encode_string(N) || encode_string(S), rate), where `rate` is the + // current cSHAKE/KMAC/TupleHash/ParallelHash block length. + const blockLenBytes = leftEncode(h.blockLen); + const fn = opts.NISTfn === undefined ? EMPTY_BUFFER : kdfInputToBytes(opts.NISTfn); + const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits + const pers = abytesOrZero(opts.personalization, 'personalization'); + const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits + if (!fn.length && !pers.length) + return h; + // SP 800-185 cSHAKE appends `00` instead of SHAKE's `1111`; in this Keccak implementation + // that changes the delimited suffix byte from `0x1f` to `0x04` once N or S is non-empty. + h.suffix = 0x04; + h.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + h.update(getPadding(totalLen, h.blockLen)); + return h; +} +const gencShake = (suffix, blockLen, outputLen) => createHasher((opts = {}) => cshakePers(new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true), opts)); +/** + * 128-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE128. Defaults to 16 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE128. + * ```ts + * cshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const cshake128 = /* @__PURE__ */ gencShake(0x1f, 168, 16); +/** + * 256-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE256. Defaults to 32 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE256. + * ```ts + * cshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const cshake256 = /* @__PURE__ */ gencShake(0x1f, 136, 32); +/** + * Internal KMAC class. + * SP 800-185 §8.4.1 still recommends keys at least as long as the target + * security strength. + */ +export class _KMAC extends Keccak { + constructor(blockLen, outputLen, enableXOF, key, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + // Preload T = bytepad(encode_string("KMAC") || encode_string(S), rate); later updates append + // newX = bytepad(encode_string(K), rate) || X and `finish()` appends right_encode(L or 0). + cshakePers(this, { + NISTfn: 'KMAC', + personalization: opts.personalization, + }); + abytes(key, undefined, 'key'); + // 1. newX = bytepad(encode_string(K), rate) || X || right_encode(L), + // with `rate = this.blockLen`. + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(_8n * BigInt(key.length)); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + finish() { + // SP 800-185 uses right_encode(L) for fixed-length KMAC and right_encode(0) for KMACXOF. + // outputLen in bits + if (!this.finished) + this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to) { + // Create new instance without calling constructor since the key + // is already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}); + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genKmac(blockLen, outputLen, xof = false) { + // One-shot XOF wrappers still finalize via `.digest()` because `_KMAC` + // already bakes the requested output length into the state. + const kmac = (key, message, opts) => kmac.create(key, opts).update(message).digest(); + kmac.create = (key, opts = {}) => new _KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac; +} +/** + * 128-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128. + * ```ts + * kmac128(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export const kmac128 = /* @__PURE__ */ genKmac(168, 16); +/** + * 256-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256. + * ```ts + * kmac256(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export const kmac256 = /* @__PURE__ */ genKmac(136, 32); +/** + * 128-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128 XOF output. + * ```ts + * kmac128xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 32 }); + * ``` + */ +export const kmac128xof = /* @__PURE__ */ genKmac(168, 16, true); +/** + * 256-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256 XOF output. + * ```ts + * kmac256xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 64 }); + * ``` + */ +export const kmac256xof = /* @__PURE__ */ genKmac(136, 32, true); +/** + * Internal TupleHash class for byte-array tuple elements. + * This implementation relies on SP 800-185's byte-oriented encoding form + * rather than arbitrary bit strings. + */ +export class _TupleHash extends Keccak { + constructor(blockLen, outputLen, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { + NISTfn: 'TupleHash', + personalization: opts.personalization, + }); + // Change update after cshake processed + this.update = (data) => { + abytes(data); + // SP 800-185 encodes each tuple element as + // encode_string(X[i]) = left_encode(len(X[i])) || X[i]. + super.update(leftEncode(_8n * BigInt(data.length))); + super.update(data); + return this; + }; + } + finish() { + // SP 800-185 uses right_encode(L) for fixed-length TupleHash + // and right_encode(0) for TupleHashXOF. + if (!this.finished) + // outputLen in bits + super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to) { + to ||= new _TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to); + } + clone() { + return this._cloneInto(); + } +} +function genTuple(blockLen, outputLen, xof = false) { + // One-shot XOF wrappers still use `.digest()` because `_TupleHash` stores + // the requested output length in the state itself. + const tuple = (messages, opts) => { + const h = tuple.create(opts); + if (!Array.isArray(messages)) + throw new Error('expected array of messages'); + for (const msg of messages) + h.update(msg); + return h.digest(); + }; + tuple.create = (opts = {}) => new _TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple; +} +/** + * 128-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128. + * ```ts + * tuplehash128([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export const tuplehash128 = /* @__PURE__ */ genTuple(168, 16); +/** + * 256-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256. + * ```ts + * tuplehash256([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export const tuplehash256 = /* @__PURE__ */ genTuple(136, 32); +/** + * 128-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128 XOF output. + * ```ts + * tuplehash128xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 32 }); + * ``` + */ +export const tuplehash128xof = /* @__PURE__ */ genTuple(168, 16, true); +/** + * 256-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256 XOF output. + * ```ts + * tuplehash256xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 64 }); + * ``` + */ +export const tuplehash256xof = /* @__PURE__ */ genTuple(136, 32, true); +/** Internal Parallel Keccak Hash class. */ +export class _ParallelHash extends Keccak { + leafHash; + leafCons; + chunkPos = 0; // Position of current block in chunk + chunksDone = 0; // How many chunks we already have + chunkLen; + constructor(blockLen, outputLen, leafCons, enableXOF, opts = {}) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this, { + NISTfn: 'ParallelHash', + personalization: opts.personalization, + }); + this.leafCons = leafCons; + let { blockLen: B = 8 } = opts; + anumber(B); + // blockLen=0 makes take=0 in update(), so pos never advances and the hash hangs. + if (B < 1) + throw new Error('"blockLen" must be >= 1, got ' + B); + this.chunkLen = B; + // SP 800-185 initializes z = left_encode(B); each completed chunk appends + // one fixed-size cSHAKE leaf digest before finish() adds right_encode(n) + // and right_encode(L or 0). + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data) => { + abytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + finish() { + if (this.finished) + return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + // SP 800-185 finishes ParallelHash as + // z || right_encode(n) || right_encode(L); XOF mode replaces + // right_encode(L) with right_encode(0). + super.update(rightEncode(this.chunksDone)); + // outputLen in bits + super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to) { + to ||= new _ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + to.leafCons = this.leafCons; + // Reused destinations can carry a stale partial leaf + // when the source is still on the root sponge. + if (this.leafHash) + to.leafHash = this.leafHash._cloneInto(to.leafHash); + else if (to.leafHash) { + to.leafHash.destroy(); + to.leafHash = undefined; + } + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + } + clone() { + return this._cloneInto(); + } +} +function genPrl(blockLen, outputLen, leaf, xof = false) { + const parallel = (message, opts) => parallel.create(opts).update(message).digest(); + parallel.create = (opts = {}) => new _ParallelHash(blockLen, chooseLen(opts, outputLen), + // SP 800-185 fixes leaf digests at 256 bits for ParallelHash128 and + // 512 bits for ParallelHash256; only the final cSHAKE output uses the + // caller-selected dkLen. + () => leaf.create({ dkLen: 2 * outputLen }), xof, opts); + parallel.outputLen = outputLen; + parallel.blockLen = blockLen; + parallel.canXOF = xof; + return parallel; +} +/** + * 128-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128. + * ```ts + * parallelhash128(new Uint8Array([1, 2, 3])); + * ``` + */ +export const parallelhash128 = /* @__PURE__ */ genPrl(168, 16, cshake128); +/** + * 256-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256. + * ```ts + * parallelhash256(new Uint8Array([1, 2, 3])); + * ``` + */ +export const parallelhash256 = /* @__PURE__ */ genPrl(136, 32, cshake256); +/** + * 128-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128 XOF output. + * ```ts + * parallelhash128xof(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const parallelhash128xof = /* @__PURE__ */ genPrl(168, 16, cshake128, true); +/** + * 256-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256 XOF output. + * ```ts + * parallelhash256xof(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const parallelhash256xof = /* @__PURE__ */ genPrl(136, 32, cshake256, true); +const genTurbo = (blockLen, outputLen) => createHasher((opts = {}) => { + const D = opts.D === undefined ? 0x1f : opts.D; + // RFC 9861 §2.1 fixes the default `D = 0x1f`; §2.2 defines the 12-round + // TurboSHAKE family selected here. + if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f) + throw new Error('"D" (domain separation byte) must be 0x01..0x7f, got: ' + D); + const dkLen = opts.dkLen === undefined ? outputLen : opts.dkLen; + // RFC 9861 §§2.1-2.2 define output length L as a positive integer. + if (dkLen < 1) + throw new Error('"dkLen" must be >= 1'); + return new Keccak(blockLen, D, dkLen, true, 12); +}); +/** + * TurboSHAKE 128-bit: reduced 12-round keccak. + * Should've been a simple "shake with 12 rounds", but we got a whole new + * spec about Turbo SHAKE Pro MAX. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 32 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE128. + * ```ts + * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const turboshake128 = /* @__PURE__ */ genTurbo(168, 32); +/** + * TurboSHAKE 256-bit: reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 64 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE256. + * ```ts + * turboshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const turboshake256 = /* @__PURE__ */ genTurbo(136, 64); +// Same as NIST rightEncode, but returns `[0]` for the zero string. +// Callers still need to keep `x < 256^255` per RFC 9861 §3.3. +function rightEncodeK12(n) { + n = BigInt(n); + const res = []; + for (; n > 0; n >>= _8n) + res.unshift(Number(n & _ffn)); + res.push(res.length); + return Uint8Array.from(res); +} +const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); +/** Internal K12 hash class. */ +export class _KangarooTwelve extends Keccak { + chunkLen = 8192; + leafHash; + leafLen; + personalization; + chunkPos = 0; // Position of current block in chunk + chunksDone = 0; // How many chunks we already have + constructor(blockLen, leafLen, outputLen, rounds, opts) { + super(blockLen, 0x07, outputLen, true, rounds); + // RFC 9861 §3 defines output length L as a positive integer. + if (outputLen < 1) + throw new Error('"dkLen" must be >= 1'); + this.leafLen = leafLen; + this.personalization = + opts.personalization === undefined + ? EMPTY_BUFFER + : copyBytes(abytes(opts.personalization, undefined, 'personalization')); + } + update(data) { + abytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len;) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) + super.update(this.leafHash.digest()); + else { + // RFC 9861 §3.2 switches from SingleNode (`07`) to FinalNode (`06`) + // once S exceeds 8192 bytes and prefixes S_0 with + // `03 00 00 00 00 00 00 00`. + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(Uint8Array.from([3, 0, 0, 0, 0, 0, 0, 0])); + } + // Secondary chunks S_1..S_(n-1) become fixed-length + // CV_i = TurboSHAKE*(S_i, `0B`, 32|64) chaining values. + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) + this.leafHash.update(chunk); + else + super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + finish() { + if (this.finished) + return; + const { personalization } = this; + // RFC 9861 §3.2 forms S = M || C || length_encode(|C|) before any tree hashing logic. + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + // Multi-chunk K12 appends + // CV_1..CV_(n-1) || length_encode(n-1) || `FF FF` + // before the final TurboSHAKE call. + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(Uint8Array.from([0xff, 0xff])); + } + super.finish.call(this); + } + destroy() { + super.destroy.call(this); + if (this.leafHash) + this.leafHash.destroy(); + // Personalization is copied on create/clone, so destroy can wipe it + // without touching caller input. + if (this.personalization !== EMPTY_BUFFER) + clean(this.personalization); + this.personalization = EMPTY_BUFFER; + } + _cloneInto(to) { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + const personalization = this.personalization === EMPTY_BUFFER ? EMPTY_BUFFER : copyBytes(this.personalization); + // Personalization is absorbed only during finish(), so clones need the same pending value. + to ||= new _KangarooTwelve(blockLen, leafLen, outputLen, rounds, { + personalization, + }); + super._cloneInto(to); + // Reused destinations can carry a stale leaf from an older multi-chunk state. + if (leafHash) + to.leafHash = leafHash._cloneInto(to.leafHash); + else if (to.leafHash) { + to.leafHash.destroy(); + to.leafHash = undefined; + } + // Snapshot the pending personalization so clone state does not alias caller-owned input. + to.personalization = personalization; + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone() { + return this._cloneInto(); + } +} +/** + * 128-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-128. + * ```ts + * kt128(new Uint8Array([1, 2, 3])); + * ``` + */ +export const kt128 = /* @__PURE__ */ createHasher((opts = {}) => new _KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts)); +/** + * 256-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 64 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-256. + * ```ts + * kt256(new Uint8Array([1, 2, 3])); + * ``` + */ +export const kt256 = /* @__PURE__ */ createHasher((opts = {}) => new _KangarooTwelve(136, 64, chooseLen(opts, 64), 12, opts)); +const genHopMAC = (hash) => (key, message, personalization, dkLen) => { + const h = hash; + return h(key, { personalization: h(message, { personalization }), dkLen }); +}; +/** + * 128-bit KangarooTwelve-based MAC. + * + * These untested (there is no test vectors or implementation available). Use at your own risk. + * HopMAC128(Key, M, C, L) = KT128(Key, KT128(M, C, 32), L) + * HopMAC256(Key, M, C, L) = KT256(Key, KT256(M, C, 64), L) + * The inner KangarooTwelve call always uses a fixed 32-byte digest here, + * regardless of the outer `dkLen`. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC128. + * ```ts + * HopMAC128(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 32); + * ``` + */ +export const HopMAC128 = /* @__PURE__ */ genHopMAC(kt128); +/** + * 256-bit KangarooTwelve-based MAC. + * Like `HopMAC128`, there are no test vectors or known independent + * implementations available for cross-checking. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes. The inner KangarooTwelve + * call still uses a fixed 64-byte digest here, regardless of the outer + * `dkLen`. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC256. + * ```ts + * HopMAC256(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 64); + * ``` + */ +export const HopMAC256 = /* @__PURE__ */ genHopMAC(kt256); +/** + * More at + * {@link https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG}. + * Accepted capacities must keep `rho = 1598 - capacity` byte-aligned, and + * `.clean()` later also requires `rate > 801`. + */ +export class _KeccakPRG extends Keccak { + rate; + constructor(capacity) { + anumber(capacity); + const rate = 1600 - capacity; + const rho = rate - 2; + // Rho must be full bytes + if (capacity < 0 || capacity > 1600 - 10 || rho % 8) + throw new Error('invalid capacity'); + // blockLen = rho in bytes + super(rho / 8, 0, 0, true); + this.rate = rate; + this.posOut = Math.floor((rate + 7) / 8); + } + keccak() { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data) { + super.update(data); + this.posOut = this.blockLen; + return this; + } + finish() { } + digestInto(_out) { + throw new Error('digest is not allowed, use .randomBytes() instead'); + } + addEntropy(seed) { + this.update(seed); + } + randomBytes(length) { + return this.xof(length); + } + clean() { + // clean() mutates live sponge state just like randomBytes(), + // so destroyed instances must reject it. + aexists(this, false); + if (this.rate < 1600 / 2 + 1) + throw new Error('rate is too low to use .forget()'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) + this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to) { + const { rate } = this; + to ||= new _KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone() { + return this._cloneInto(); + } +} +/** + * KeccakPRG: pseudo-random generator based on Keccak. + * See {@link https://keccak.team/files/CSF-0.1.pdf}. + * @param capacity - sponge capacity in bits. Accepted values are those that + * keep `rho = 1598 - capacity` byte-aligned; the default `254` is chosen + * because it satisfies that duplex layout while leaving a wide byte-aligned + * rate. + * @returns PRG instance backed by a Keccak sponge. + * @example + * Create a Keccak-based pseudorandom generator and read bytes from it. + * ```ts + * const prg = keccakprg(254); + * prg.randomBytes(8); + * ``` + */ +export const keccakprg = (capacity = 254) => new _KeccakPRG(capacity); +//# sourceMappingURL=sha3-addons.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3-addons.js.map b/node_modules/@noble/hashes/sha3-addons.js.map new file mode 100644 index 0000000..1065329 --- /dev/null +++ b/node_modules/@noble/hashes/sha3-addons.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3-addons.js","sourceRoot":"","sources":["src/sha3-addons.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,MAAM,EAAkB,MAAM,WAAW,CAAC;AACnD,OAAO,EACL,MAAM,EACN,OAAO,EACP,OAAO,EAGP,KAAK,EACL,SAAS,EACT,YAAY,EAIZ,eAAe,EAIf,GAAG,GACJ,MAAM,YAAY,CAAC;AAEpB,kCAAkC;AAClC,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,IAAI,GAAG,eAAe,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAE1C,8FAA8F;AAC9F,4CAA4C;AAC5C,gEAAgE;AAChE,gEAAgE;AAChE,SAAS,UAAU,CAAC,CAAkB;IACpC,CAAC,GAAG,MA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,CAAC;QACrB,EAAE,CAAC,IAAI,GAAG,IAAI,CAAC;QACf,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,KAAK;QACH,OAAO,IAAI,CAAC,UAAU,EAAE,CAAC;IAC3B,CAAC;CACF;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC,QAAQ,GAAG,GAAG,EAAoB,EAAE,CAC5D,IAAI,UAAU,CAAC,QAAQ,CAAqB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.d.ts b/node_modules/@noble/hashes/sha3.d.ts new file mode 100644 index 0000000..19e8075 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.d.ts @@ -0,0 +1,199 @@ +import { type CHash, type CHashXOF, type Hash, type HashXOF, type TArg, type TRet } from './utils.ts'; +/** + * `keccakf1600` internal permutation, additionally allows adjusting the round count. + * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words + * in this file's local little-endian lane-word order + * @param rounds - number of rounds to execute + * @throws If `rounds` is outside the supported `1..24` range. {@link Error} + * @example + * Permute a Keccak state with the default 24 rounds. + * ```ts + * keccakP(new Uint32Array(50)); + * ``` + */ +export declare function keccakP(s: TArg, rounds?: number): void; +/** + * Keccak sponge function. + * @param blockLen - absorb/squeeze rate in bytes + * @param suffix - domain separation suffix byte + * @param outputLen - default digest length in bytes. This base sponge only + * requires a non-negative integer; wrappers that need positive output + * lengths must enforce that themselves. + * @param enableXOF - whether XOF output is allowed + * @param rounds - number of Keccak-f rounds + * @example + * Build a sponge state, absorb bytes, then finalize a digest. + * ```ts + * const hash = new Keccak(136, 0x06, 32); + * hash.update(new Uint8Array([1, 2, 3])); + * hash.digest(); + * ``` + */ +export declare class Keccak implements Hash, HashXOF { + protected state: Uint8Array; + protected pos: number; + protected posOut: number; + protected finished: boolean; + protected state32: Uint32Array; + protected destroyed: boolean; + blockLen: number; + suffix: number; + outputLen: number; + canXOF: boolean; + protected enableXOF: boolean; + protected rounds: number; + constructor(blockLen: number, suffix: number, outputLen: number, enableXOF?: boolean, rounds?: number); + clone(): Keccak; + protected keccak(): void; + update(data: TArg): this; + protected finish(): void; + protected writeInto(out: TArg): TRet; + xofInto(out: TArg): TRet; + xof(bytes: number): TRet; + digestInto(out: TArg): void; + digest(): TRet; + destroy(): void; + _cloneInto(to?: Keccak): Keccak; +} +/** + * SHA3-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-224. + * ```ts + * sha3_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha3_224: TRet; +/** + * SHA3-256 hash function. Different from keccak-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-256. + * ```ts + * sha3_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha3_256: TRet; +/** + * SHA3-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-384. + * ```ts + * sha3_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha3_384: TRet; +/** + * SHA3-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-512. + * ```ts + * sha3_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha3_512: TRet; +/** + * Keccak-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-224. + * ```ts + * keccak_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const keccak_224: TRet; +/** + * Keccak-256 hash function. Different from SHA3-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-256. + * ```ts + * keccak_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const keccak_256: TRet; +/** + * Keccak-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-384. + * ```ts + * keccak_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const keccak_384: TRet; +/** + * Keccak-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-512. + * ```ts + * keccak_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const keccak_512: TRet; +/** Options for SHAKE XOF. */ +export type ShakeOpts = { + /** Desired number of output bytes. */ + dkLen?: number; +}; +/** + * SHAKE128 XOF with 128-bit security and a 16-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128. + * ```ts + * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export declare const shake128: TRet>; +/** + * SHAKE256 XOF with 256-bit security and a 32-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256. + * ```ts + * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export declare const shake256: TRet>; +/** + * SHAKE128 XOF with 256-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128 using a 32-byte default output. + * ```ts + * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export declare const shake128_32: TRet>; +/** + * SHAKE256 XOF with 512-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256 using a 64-byte default output. + * ```ts + * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export declare const shake256_64: TRet>; +//# sourceMappingURL=sha3.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.d.ts.map b/node_modules/@noble/hashes/sha3.d.ts.map new file mode 100644 index 0000000..12d5be2 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sha3.d.ts","sourceR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AQ,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAEC,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAEF,CAAC;AACzD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,WAAW,EAAE,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,CAEF,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.js b/node_modules/@noble/hashes/sha3.js new file mode 100644 index 0000000..02e6432 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.js @@ -0,0 +1,431 @@ +/** + * SHA3 (keccak) hash function, based on a new "Sponge function" design. + * Different from older hashes, the internal state is bigger than output size. + * + * Check out + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202}, + * {@link https://keccak.team/keccak.html | Website}, and + * {@link https://crypto.stackexchange.com/q/15727 | the differences between + * SHA-3 and Keccak}. + * + * Check out `sha3-addons` module for cSHAKE, k12, and others. + * @module + */ +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from "./_u64.js"; +// prettier-ignore +import { abytes, aexists, anumber, aoutput, clean, createHasher, oidNist, swap32IfBE, u32 } from "./utils.js"; +// No __PURE__ annotations in sha3 header: +// EVERYTHING is in fact used on every export. +// Various per round constants calculations +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors +// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`. +const _0x71n = BigInt(0x71); +const SHA3_PI = []; +const SHA3_ROTL = []; +const _SHA3_IOTA = []; // no pure annotation: var is always used +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) + t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const IOTAS = split(_SHA3_IOTA, true); +// `split(..., true)` keeps the local little-endian lane-word layout used by +// `state32`, so these `H` / `L` tables follow the file's first-word / +// second-word lane slots rather than `_u64.ts`'s usual high/low naming. +const SHA3_IOTA_H = IOTAS[0]; +const SHA3_IOTA_L = IOTAS[1]; +// Left rotation (without 0, 32, 64) +const rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); +/** + * `keccakf1600` internal permutation, additionally allows adjusting the round count. + * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words + * in this file's local little-endian lane-word order + * @param rounds - number of rounds to execute + * @throws If `rounds` is outside the supported `1..24` range. {@link Error} + * @example + * Permute a Keccak state with the default 24 rounds. + * ```ts + * keccakP(new Uint32Array(50)); + * ``` + */ +export function keccakP(s, rounds = 24) { + anumber(rounds, 'rounds'); + // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table. + if (rounds < 1 || rounds > 24) + throw new Error('"rounds" expected integer 1..24'); + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + // Same as: + // for (let x = 0; x < 10; x++) B[x] = s[y + x]; + // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + for (let y = 0; y < 50; y += 10) { + const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3]; + s[y] ^= ~s[y + 2] & s[y + 4]; + s[y + 1] ^= ~s[y + 3] & s[y + 5]; + s[y + 2] ^= ~s[y + 4] & s[y + 6]; + s[y + 3] ^= ~s[y + 5] & s[y + 7]; + s[y + 4] ^= ~s[y + 6] & s[y + 8]; + s[y + 5] ^= ~s[y + 7] & s[y + 9]; + s[y + 6] ^= ~s[y + 8] & b0; + s[y + 7] ^= ~s[y + 9] & b1; + s[y + 8] ^= ~b0 & b2; + s[y + 9] ^= ~b1 & b3; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + clean(B); +} +/** + * Keccak sponge function. + * @param blockLen - absorb/squeeze rate in bytes + * @param suffix - domain separation suffix byte + * @param outputLen - default digest length in bytes. This base sponge only + * requires a non-negative integer; wrappers that need positive output + * lengths must enforce that themselves. + * @param enableXOF - whether XOF output is allowed + * @param rounds - number of Keccak-f rounds + * @example + * Build a sponge state, absorb bytes, then finalize a digest. + * ```ts + * const hash = new Keccak(136, 0x06, 32); + * hash.update(new Uint8Array([1, 2, 3])); + * hash.digest(); + * ``` + */ +export class Keccak { + state; + pos = 0; + posOut = 0; + finished = false; + state32; + destroyed = false; + blockLen; + suffix; + outputLen; + canXOF; + enableXOF = false; + rounds; + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.canXOF = enableXOF; + this.rounds = rounds; + // Can be passed from user as dkLen + anumber(outputLen, 'outputLen'); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + // 0 < blockLen < 200 + if (!(0 < blockLen && blockLen < 200)) + throw new Error('only keccak-f1600 function is supported'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + clone() { + return this._cloneInto(); + } + keccak() { + swap32IfBE(this.state32); + keccakP(this.state32, this.rounds); + swap32IfBE(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + abytes(data); + const { blockLen, state } = this; + const len = data.length; + for (let pos = 0; pos < len;) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1. + // These byte values already include the first padding bit, while the + // final `0x80` below supplies the closing `1` bit in the last rate byte. + state[pos] ^= suffix; + // If that combined suffix lands in the last rate byte and already sets + // bit 7, absorb it first so the final pad10*1 bit can be xored into a + // fresh block. + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len;) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base + // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/ + // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF. + if (!this.enableXOF) + throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error('digest() was already called'); + // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest. + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out; + } + destroy() { + this.destroyed = true; + clean(this.state); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + // Reused destinations can come from a different rate/capacity variant, so clone must rewrite + // the sponge geometry as well as the state words. + to.blockLen = blockLen; + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone + // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie. + to.canXOF = this.canXOF; + to.destroyed = this.destroyed; + return to; + } +} +const genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); +/** + * SHA3-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-224. + * ```ts + * sha3_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_224 = /* @__PURE__ */ genKeccak(0x06, 144, 28, +/* @__PURE__ */ oidNist(0x07)); +/** + * SHA3-256 hash function. Different from keccak-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-256. + * ```ts + * sha3_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_256 = /* @__PURE__ */ genKeccak(0x06, 136, 32, +/* @__PURE__ */ oidNist(0x08)); +/** + * SHA3-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-384. + * ```ts + * sha3_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_384 = /* @__PURE__ */ genKeccak(0x06, 104, 48, +/* @__PURE__ */ oidNist(0x09)); +/** + * SHA3-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-512. + * ```ts + * sha3_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_512 = /* @__PURE__ */ genKeccak(0x06, 72, 64, +/* @__PURE__ */ oidNist(0x0a)); +/** + * Keccak-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-224. + * ```ts + * keccak_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_224 = /* @__PURE__ */ genKeccak(0x01, 144, 28); +/** + * Keccak-256 hash function. Different from SHA3-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-256. + * ```ts + * keccak_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_256 = /* @__PURE__ */ genKeccak(0x01, 136, 32); +/** + * Keccak-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-384. + * ```ts + * keccak_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_384 = /* @__PURE__ */ genKeccak(0x01, 104, 48); +/** + * Keccak-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-512. + * ```ts + * keccak_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_512 = /* @__PURE__ */ genKeccak(0x01, 72, 64); +const genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), info); +/** + * SHAKE128 XOF with 128-bit security and a 16-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128. + * ```ts + * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export const shake128 = +/* @__PURE__ */ +genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b)); +/** + * SHAKE256 XOF with 256-bit security and a 32-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256. + * ```ts + * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export const shake256 = +/* @__PURE__ */ +genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c)); +/** + * SHAKE128 XOF with 256-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128 using a 32-byte default output. + * ```ts + * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export const shake128_32 = +/* @__PURE__ */ +genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b)); +/** + * SHAKE256 XOF with 512-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256 using a 64-byte default output. + * ```ts + * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export const shake256_64 = +/* @__PURE__ */ +genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c)); +//# sourceMappingURL=sha3.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/sha3.js.map b/node_modules/@noble/hashes/sha3.js.map new file mode 100644 index 0000000..4be5999 --- /dev/null +++ b/node_modules/@noble/hashes/sha3.js.map @@ -0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CACV,CAAC,OAAkB,EAAE,EAAE,EAAE,CACvB,IAAI,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,EACvF,IAAI,CACL,CAAC;AAEJ;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ;AACnB,eAAe;AACf,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AACzD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,QAAQ;AACnB,eAAe;AACf,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AAEzD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,WAAW;AACtB,eAAe;AACf,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;AACzD;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,WAAW;AACtB,eAAe;AACf,QAAQ,CAAC,IAAI,EAAE,GAAG,EAAE,EAAE,EAAE,eAAe,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/src/_blake.ts b/node_modules/@noble/hashes/src/_blake.ts new file mode 100644 index 0000000..7433033 --- /dev/null +++ b/node_modules/@noble/hashes/src/_blake.ts @@ -0,0 +1,57 @@ +/** + * Internal helpers for blake hash. + * @module + */ +import { rotr, type TRet } from './utils.ts'; + +/** + * Internal blake permutation table. + * Rows `0..9` serve BLAKE2s, rows `0..11` serve BLAKE2b with `10..11 = 0..1`, and Blake1 also + * reuses the later rows shown below. Blake1 expands rounds `10..15` as `SIGMA[i % 10]`, so rows + * `10..15` intentionally repeat rows `0..5` for the 14-round (256) and 16-round (512) variants. + */ +// prettier-ignore +export const BSIGMA: TRet = /* @__PURE__ */ Uint8Array.from([ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, + 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, + 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, + 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, + 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, + // Blake1, unused in others + 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, + 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, + 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, + 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, +]); + +// prettier-ignore +export type Num4 = { a: number; b: number; c: number; d: number; }; + +// 32-bit / BLAKE2s first half of G, with the fixed `(16, 12)` rotation pair. +// Parameter `x` is the RFC 7693 first-half message word, or Blake1's pre-mixed +// `m[sigma[r][2i]] ^ u[sigma[r][2i+1]]` addend in the 32-bit path. +export function G1s(a: number, b: number, c: number, d: number, x: number): Num4 { + a = (a + b + x) | 0; + d = rotr(d ^ a, 16); + c = (c + d) | 0; + b = rotr(b ^ c, 12); + return { a, b, c, d }; +} + +// 32-bit / BLAKE2s second half of G. +// Parameter `x` is the RFC 7693 second-half (`y`) message word, or Blake1's pre-mixed +// `m[sigma[r][2i + 1]] ^ u[sigma[r][2i]]` addend in the 32-bit path. +export function G2s(a: number, b: number, c: number, d: number, x: number): Num4 { + a = (a + b + x) | 0; + d = rotr(d ^ a, 8); + c = (c + d) | 0; + b = rotr(b ^ c, 7); + return { a, b, c, d }; +} diff --git a/node_modules/@noble/hashes/src/_md.ts b/node_modules/@noble/hashes/src/_md.ts new file mode 100644 index 0000000..1de1258 --- /dev/null +++ b/node_modules/@noble/hashes/src/_md.ts @@ -0,0 +1,222 @@ +/** + * Internal Merkle-Damgard hash utils. + * @module + */ +import { + abytes, + aexists, + aoutput, + clean, + createView, + type Hash, + type TArg, + type TRet, +} from './utils.ts'; + +/** + * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`. + * Returns bits from `b` when `a` is set, otherwise from `c`. + * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never + * set the same bit. + * @param a - selector word + * @param b - word chosen when selector bit is set + * @param c - word chosen when selector bit is clear + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit choice primitive. + * ```ts + * Chi(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Chi(a: number, b: number, c: number): number { + return (a & b) ^ (~a & c); +} + +/** + * Shared 32-bit majority primitive reused by SHA-256 and SHA-1. + * Returns bits shared by at least two inputs. + * @param a - first input word + * @param b - second input word + * @param c - third input word + * @returns Mixed 32-bit word. + * @example + * Combine three words with the shared 32-bit majority primitive. + * ```ts + * Maj(0xffffffff, 0x12345678, 0x87654321); + * ``` + */ +export function Maj(a: number, b: number, c: number): number { + return (a & b) ^ (a & c) ^ (b & c); +} + +/** + * Merkle-Damgard hash construction base class. + * Could be used to create MD5, RIPEMD, SHA1, SHA2. + * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit + * strings with partial-byte tails. + * @param blockLen - internal block size in bytes + * @param outputLen - digest size in bytes + * @param padOffset - trailing length field size in bytes + * @param isLE - whether length and state words are encoded in little-endian + * @example + * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow. + * ```ts + * import { _SHA1 } from '@noble/hashes/legacy.js'; + * const hash = new _SHA1(); + * hash.update(new Uint8Array([97, 98, 99])); + * hash.digest(); + * ``` + */ +export abstract class HashMD> implements Hash { + // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input + // when it can process whole blocks without buffering first. + protected abstract process(buf: DataView, offset: number): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected abstract roundClean(): void; + + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF = false; + readonly padOffset: number; + readonly isLE: boolean; + + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + + constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) { + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data: TArg): this { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out: TArg): void { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + // We can avoid allocation of buffer for padding completely if it + // was previously not allocated here. But it won't change performance. + const { buffer, view, blockLen, isLE } = this; + let { pos } = this; + // append the bit '1' to the message + buffer[pos++] = 0b10000000; + clean(this.buffer.subarray(pos)); + // we have less than padOffset left in buffer, so we cannot put length in + // current block, need process it and pad again + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + // Pad until full block byte with zeros + for (let i = pos; i < blockLen; i++) buffer[i] = 0; + // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from + // the padding fill above, and JS will overflow before user input can make that half non-zero. + // So we only need to write the low 64 bits here. + view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT + if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit'); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state'); + for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE); + } + digest(): TRet { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return + // fresh bytes to the caller. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res as TRet; + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and + // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it. + if (length % blockLen) to.buffer.set(buffer); + return to as unknown as any; + } + clone(): T { + return this._cloneInto(); + } +} + +/** + * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53. + * Check out `test/misc/sha2-gen-iv.js` for recomputation guide. + */ + +/** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the + * square roots of the first eight prime numbers. Exported as a shared table; callers must treat + * it as read-only because constructors copy words from it by index. */ +export const SHA256_IV: TRet = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, +]); + +/** Initial SHA224 state `H(0)` from RFC 6234 §6.1. Exported as a shared table; callers must + * treat it as read-only because constructors copy words from it by index. */ +export const SHA224_IV: TRet = /* @__PURE__ */ Uint32Array.from([ + 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4, +]); + +/** Initial SHA384 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the ninth + * through sixteenth prime numbers. Exported as a shared table; callers must treat it as read-only + * because constructors copy halves from it by index. */ +export const SHA384_IV: TRet = /* @__PURE__ */ Uint32Array.from([ + 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939, + 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4, +]); + +/** Initial SHA512 state from RFC 6234 §6.3: eight RFC 64-bit `H(0)` words stored as sixteen + * big-endian 32-bit halves. Derived from the fractional parts of the square roots of the first + * eight prime numbers. Exported as a shared table; callers must treat it as read-only because + * constructors copy halves from it by index. */ +export const SHA512_IV: TRet = /* @__PURE__ */ Uint32Array.from([ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, +]); diff --git a/node_modules/@noble/hashes/src/_u64.ts b/node_modules/@noble/hashes/src/_u64.ts new file mode 100644 index 0000000..2b7c593 --- /dev/null +++ b/node_modules/@noble/hashes/src/_u64.ts @@ -0,0 +1,117 @@ +/** + * Internal helpers for u64. + * BigUint64Array is too slow as per 2026, so we implement it using + * Uint32Array. + * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588} + * @module + */ +import type { TRet } from './utils.ts'; + +const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +const _32n = /* @__PURE__ */ BigInt(32); + +// Split bigint into two 32-bit halves. With `le=true`, returned fields become `{ h: low, l: high +// }` to match little-endian word order rather than the property names. +function fromBig( + n: bigint, + le = false +): { + h: number; + l: number; +} { + if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) }; + return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} + +// Split bigint list into `[highWords, lowWords]` when `le=false`; with `le=true`, the first array +// holds the low halves because `fromBig(...)` swaps the semantic meaning of `h` and `l`. +function split(lst: bigint[], le = false): TRet { + const len = lst.length; + let Ah = new Uint32Array(len); + let Al = new Uint32Array(len); + for (let i = 0; i < len; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al] as TRet; +} + +// Combine explicit `(high, low)` 32-bit halves into a bigint; `>>> 0` normalizes signed JS +// bitwise results back to uint32 first, and little-endian callers must swap. +const toBig = (h: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0); +// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`. +const shrSH = (h: number, _l: number, s: number): number => h >>> s; +// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`. +const shrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSH = (h: number, l: number, s: number): number => (h >>> s) | (l << (32 - s)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `1..31`. +const rotrSL = (h: number, l: number, s: number): number => (h << (32 - s)) | (l >>> s); +// High 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBH = (h: number, l: number, s: number): number => (h << (64 - s)) | (l >>> (s - 32)); +// Low 32-bit half of a 64-bit right rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotrBL = (h: number, l: number, s: number): number => (h >>> (s - 32)) | (l << (64 - s)); +// High 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped low half. +const rotr32H = (_h: number, l: number): number => l; +// Low 32-bit half of a 64-bit right rotate for `s === 32`; this is just the swapped high half. +const rotr32L = (h: number, _l: number): number => h; +// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`. +const rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s)); +// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`. +const rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s)); +// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s)); +// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`. +const rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s)); + +// Add two split 64-bit words and return the split `{ h, l }` sum. +// JS uses 32-bit signed integers for bitwise operations, so we cannot simply shift the carry out +// of the low sum and instead use division. +function add( + Ah: number, + Al: number, + Bh: number, + Bl: number +): { + h: number; + l: number; +} { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 }; +} +// Addition with more than 2 elements +// Unmasked low-word accumulator for 3-way addition; pass the raw result into `add3H(...)`. +const add3L = (Al: number, Bl: number, Cl: number): number => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +// High-word finalize step for 3-way addition; `low` must be the untruncated output of `add3L(...)`. +const add3H = (low: number, Ah: number, Bh: number, Ch: number): number => + (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 4-way addition; pass the raw result into `add4H(...)`. +const add4L = (Al: number, Bl: number, Cl: number, Dl: number): number => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +// High-word finalize step for 4-way addition; `low` must be the untruncated output of `add4L(...)`. +const add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number): number => + (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0; +// Unmasked low-word accumulator for 5-way addition; pass the raw result into `add5H(...)`. +const add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number): number => + (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +// High-word finalize step for 5-way addition; `low` must be the untruncated output of `add5L(...)`. +const add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number => + (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0; + +// prettier-ignore +export { + add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig +}; +// Canonical grouped namespace for callers that prefer one object. +// Named exports stay for direct imports. +// prettier-ignore +const u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = { + fromBig, split, toBig, + shrSH, shrSL, + rotrSH, rotrSL, rotrBH, rotrBL, + rotr32H, rotr32L, + rotlSH, rotlSL, rotlBH, rotlBL, + add, add3L, add3H, add4L, add4H, add5H, add5L, +}; +// Default export mirrors named `u64` for compatibility with object-style imports. +export default u64; diff --git a/node_modules/@noble/hashes/src/argon2.ts b/node_modules/@noble/hashes/src/argon2.ts new file mode 100644 index 0000000..51fd315 --- /dev/null +++ b/node_modules/@noble/hashes/src/argon2.ts @@ -0,0 +1,667 @@ +/** + * Argon2 KDF from RFC 9106. Can be used to create a key from password and salt. + * We suggest to use Scrypt. JS Argon is 2-10x slower than native code because of 64-bitness: + * * argon uses uint64, but JS doesn't have fast uint64array + * * uint64 multiplication is 1/3 of time + * * `P` function would be very nice with u64, because most of value will be in registers, + * hovewer with u32 it will require 32 registers, which is too much. + * * JS arrays do slow bound checks, so reading from `A2_BUF` slows it down + * @module + */ +import { add3H, add3L, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL } from './_u64.ts'; +import { blake2b } from './blake2.ts'; +import { + anumber, + clean, + kdfInputToBytes, + nextTick, + swap32IfBE, + swap8IfBE, + u32, + u8, + type KDFInput, + type TArg, + type TRet, +} from './utils.ts'; + +// RFC 9106 §3.1 type `y`: 0 = Argon2d, 1 = Argon2i, 2 = Argon2id. The numeric values are the +// spec-bound part here; the object keys are internal labels. +const AT = { Argond2d: 0, Argon2i: 1, Argon2id: 2 } as const; +type Types = (typeof AT)[keyof typeof AT]; + +// RFC 9106 sync points constant `SL = 4`, fixed by the design rather than exposed as a tuning knob. +const ARGON2_SYNC_POINTS = 4; +// Preserve Argon2's `LE32(len(X)) || X` encoding for omitted +// optional fields by emitting empty bytes. +const abytesOrZero = (buf?: TArg, errorTitle = ''): TRet => { + if (buf === undefined) return Uint8Array.of(); + return kdfInputToBytes(buf, errorTitle); +}; + +// Unsigned `u32 * u32 = { h, l }`, returned as split 64-bit halves. +function mul(a: number, b: number) { + // Split into 16-bit limbs so each partial product stays exact under `Math.imul`. + const aL = a & 0xffff; + const aH = a >>> 16; + const bL = b & 0xffff; + const bH = b >>> 16; + const ll = Math.imul(aL, bL); + const hl = Math.imul(aH, bL); + const lh = Math.imul(aL, bH); + const hh = Math.imul(aH, bH); + const carry = (ll >>> 16) + (hl & 0xffff) + lh; + const high = (hh + (hl >>> 16) + (carry >>> 16)) | 0; + const low = (carry << 16) | (ll & 0xffff); + return { h: high, l: low }; +} + +function mul2(a: number, b: number) { + // Double the split 64-bit product; carry from `l` is folded back into `h` via `l >>> 31`. + const { h, l } = mul(a, b); + return { h: ((h << 1) | (l >>> 31)) & 0xffff_ffff, l: (l << 1) & 0xffff_ffff }; +} + +// BlaMka permutation for Argon2 +// `A + B + 2 * trunc(A) * trunc(B)`, where `trunc(...)` means the low 32-bit halves. +function blamka(Ah: number, Al: number, Bh: number, Bl: number) { + const { h: Ch, l: Cl } = mul2(Al, Bl); + // A + B + (2 * A * B) + const Rll = add3L(Al, Bl, Cl); + return { h: add3H(Rll, Ah, Bh, Ch), l: Rll | 0 }; +} + +// Temporary block buffer. +// 1024-byte block: 256 u32 = 128 interleaved low/high halves = RFC's +// 8x8 matrix of 16-byte registers. +const A2_BUF = new Uint32Array(256); + +// Quarter-round over 64-bit word indices into `A2_BUF`; each index maps to adjacent low/high u32s. +function G(a: number, b: number, c: number, d: number) { + let Al = A2_BUF[2*a], Ah = A2_BUF[2*a + 1]; // prettier-ignore + let Bl = A2_BUF[2*b], Bh = A2_BUF[2*b + 1]; // prettier-ignore + let Cl = A2_BUF[2*c], Ch = A2_BUF[2*c + 1]; // prettier-ignore + let Dl = A2_BUF[2*d], Dh = A2_BUF[2*d + 1]; // prettier-ignore + + // RFC 9106 Figure 19 GB rotates by 32, 24, 16, and 63 bits after each XOR step. + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh, Dl) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) }); + + ({ h: Ah, l: Al } = blamka(Ah, Al, Bh, Bl)); + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) }); + + ({ h: Ch, l: Cl } = blamka(Ch, Cl, Dh, Dl)); + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) }); + + ((A2_BUF[2 * a] = Al), (A2_BUF[2 * a + 1] = Ah)); + ((A2_BUF[2 * b] = Bl), (A2_BUF[2 * b + 1] = Bh)); + ((A2_BUF[2 * c] = Cl), (A2_BUF[2 * c + 1] = Ch)); + ((A2_BUF[2 * d] = Dl), (A2_BUF[2 * d + 1] = Dh)); +} + +// Argon2 permutation over 16 register indices into `A2_BUF`, not the register values themselves. +// RFC 9106 Figure 17: these arguments are the 16 `v0..v15` 64-bit word +// indices inside eight 16-byte inputs, not copied word values. +// prettier-ignore +function P( + v00: number, v01: number, v02: number, v03: number, v04: number, v05: number, v06: number, v07: number, + v08: number, v09: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +) { + // RFC 9106 Figure 18: first apply GB across rows, then across columns of the 8x8 register matrix. + G(v00, v04, v08, v12); + G(v01, v05, v09, v13); + G(v02, v06, v10, v14); + G(v03, v07, v11, v15); + G(v00, v05, v10, v15); + G(v01, v06, v11, v12); + G(v02, v07, v08, v13); + G(v03, v04, v09, v14); +} + +function block(x: TArg, xPos: number, yPos: number, outPos: number, needXor: boolean) { + for (let i = 0; i < 256; i++) A2_BUF[i] = x[xPos + i] ^ x[yPos + i]; + // rows (8 consecutive 16-register groups) + for (let i = 0; i < 128; i += 16) { + // prettier-ignore + P( + i, i + 1, i + 2, i + 3, i + 4, i + 5, i + 6, i + 7, + i + 8, i + 9, i + 10, i + 11, i + 12, i + 13, i + 14, i + 15 + ); + } + // columns (8 strided 16-register groups) + for (let i = 0; i < 16; i += 2) { + // prettier-ignore + P( + i, i + 1, i + 16, i + 17, i + 32, i + 33, i + 48, i + 49, + i + 64, i + 65, i + 80, i + 81, i + 96, i + 97, i + 112, i + 113 + ); + } + + // RFC 9106 step 6: passes after the first XOR the old destination block into the new G(X, Y). + if (needXor) for (let i = 0; i < 256; i++) x[outPos + i] ^= A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + else for (let i = 0; i < 256; i++) x[outPos + i] = A2_BUF[i] ^ x[xPos + i] ^ x[yPos + i]; + clean(A2_BUF); +} + +// Variable-Length Hash Function H' +// Returns bytes, not words; 1024-byte block callers explicitly reinterpret with `u32(...)`. +function Hp(A: TArg, dkLen: number): TRet { + const A8 = u8(A); + const T = new Uint32Array(1); + const T8 = u8(T); + // Argon2 H' prefixes dkLen as LE32; native Uint32Array writes would serialize as BE on s390x. + T[0] = swap8IfBE(dkLen); + // Fast path + if (dkLen <= 64) return blake2b.create({ dkLen }).update(T8).update(A8).digest(); + const out = new Uint8Array(dkLen); + let V = blake2b.create({}).update(T8).update(A8).digest(); + let pos = 0; + // RFC 9106 Figure 8: each intermediate `V_i` contributes only `W_i`, its first 32 bytes; only + // `V_{r+1}` is emitted in full at the remaining length. + out.set(V.subarray(0, 32)); + pos += 32; + // Rest blocks + for (; dkLen - pos > 64; pos += 32) { + const Vh = blake2b.create({}).update(V); + Vh.digestInto(V); + Vh.destroy(); + out.set(V.subarray(0, 32), pos); + } + // Last block + out.set(blake2b(V, { dkLen: dkLen - pos }), pos); + clean(V, T); + // H' is byte-oriented; returning `u32(out)` would silently drop dkLen % 4 tail bytes. + return out as TRet; +} + +// Used only inside process block! +function indexAlpha( + r: number, + s: number, + laneLen: number, + segmentLen: number, + index: number, + randL: number, + sameLane: boolean = false +) { + // RFC 9106 §3.4.2 Figures 12-13: map `J1` / `J2` into the current lane's reference area `W`. + let area: number; + if (r === 0) { + if (s === 0) area = index - 1; + else if (sameLane) area = s * segmentLen + index - 1; + else area = s * segmentLen + (index == 0 ? -1 : 0); + } else if (sameLane) area = laneLen - segmentLen + index - 1; + else area = laneLen - segmentLen + (index == 0 ? -1 : 0); + const startPos = r !== 0 && s !== ARGON2_SYNC_POINTS - 1 ? (s + 1) * segmentLen : 0; + // RFC 9106 Figure 13: `mul(randL, randL).h` is `floor(J_1^2 / 2^32)`, and the outer high-half + // multiply computes `floor(|W| * x / 2^32)` without floating-point math. + const rel = area - 1 - mul(area, mul(randL, randL).h).h; + return (startPos + rel) % laneLen; +} + +/** Argon2 cost, output, and optional secret/personalization inputs. */ +export type ArgonOpts = { + /** Time cost measured in iterations. */ + t: number; + /** Memory cost in kibibytes. */ + m: number; + /** Parallelization parameter. */ + p: number; + /** Argon2 version number. Defaults to `0x13`. */ + version?: number; + /** Optional secret key mixed into initialization. */ + key?: KDFInput; + /** Optional personalization string or bytes. */ + personalization?: KDFInput; + /** Desired output length in bytes. RFC 9106 §3.1 requires `T` in the 4..(2^32 - 1) range. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variants. */ + asyncTick?: number; + /** Maximum temporary memory budget in bytes. */ + maxmem?: number; + /** + * Optional progress callback invoked during long-running derivations. + * param progress - completion fraction in the `0..1` range + */ + onProgress?: (progress: number) => void; +}; + +// Exclusive `2^32` sentinel used by `isU32(...)`, not the inclusive maximum u32 value. +const maxUint32 = Math.pow(2, 32); +// Validate safe JS integers in `[0, 2^32 - 1]`. +function isU32(num: number) { + return Number.isSafeInteger(num) && num >= 0 && num < maxUint32; +} + +function argon2Opts(opts: TArg) { + const merged: any = { + version: 0x13, + dkLen: 32, + maxmem: maxUint32 - 1, + asyncTick: 10, + }; + // Unknown keys are copied through unchanged here and later ignored unless + // destructuring consumes them. + for (let [k, v] of Object.entries(opts)) if (v !== undefined) merged[k] = v; + + const { dkLen, p, m, t, version, onProgress, asyncTick } = merged; + // RFC 9106 §3.1: tag length `T` MUST be an integer number of bytes from 4 to 2^32-1. + if (!isU32(dkLen) || dkLen < 4) throw new Error('"dkLen" must be 4..'); + if (!isU32(p) || p < 1 || p >= Math.pow(2, 24)) throw new Error('"p" must be 1..2^24'); + if (!isU32(m)) throw new Error('"m" must be 0..2^32'); + if (!isU32(t) || t < 1) throw new Error('"t" (iterations) must be 1..2^32'); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('"progressCb" must be a function'); + anumber(asyncTick, 'asyncTick'); + /* + Memory size m MUST be an integer number of kibibytes from 8*p + to 2^(32)-1. The actual number of blocks is m', which is m + rounded down to the nearest multiple of 4*p. + */ + if (!isU32(m) || m < 8 * p) throw new Error('"m" (memory) must be at least 8*p bytes'); + // Accept legacy `0x10` for compatibility even though RFC 9106 profiles standardize `0x13`. + if (version !== 0x10 && version !== 0x13) + throw new Error('"version" must be 0x10 or 0x13, got ' + version); + return merged; +} + +function argon2Init( + password: TArg, + salt: TArg, + type: Types, + opts: TArg +) { + password = kdfInputToBytes(password, 'password'); + salt = kdfInputToBytes(salt, 'salt'); + if (!isU32(password.length)) throw new Error('"password" must be less of length 1..4Gb'); + // RFC 9106 §3.1 only requires S <= 2^32-1 bytes and says 16 bytes is RECOMMENDED for password + // hashing; this library intentionally takes the stricter common >=8-byte salt path. + if (!isU32(salt.length) || salt.length < 8) throw new Error('"salt" must be of length 8..4Gb'); + if (!Object.values(AT).includes(type)) throw new Error('"type" was invalid'); + let { p, dkLen, m, t, version, key, personalization, maxmem, onProgress, asyncTick } = + argon2Opts(opts); + // Validation + key = abytesOrZero(key, 'key'); + personalization = abytesOrZero(personalization, 'personalization'); + // H_0 = H^(64)(LE32(p) || LE32(T) || LE32(m) || LE32(t) || + // LE32(v) || LE32(y) || LE32(length(P)) || P || + // LE32(length(S)) || S || LE32(length(K)) || K || + // LE32(length(X)) || X) + const h = blake2b.create(); + const BUF = new Uint32Array(1); + const BUF8 = u8(BUF); + for (let item of [p, dkLen, m, t, version, type]) { + // RFC 9106 H0 encodes these scalars as LE32, so normalize the host word before exposing bytes. + BUF[0] = swap8IfBE(item); + h.update(BUF8); + } + for (let i of [password, salt, key, personalization]) { + BUF[0] = swap8IfBE(i.length); // BUF is u32 array, this is valid once normalized to LE bytes + h.update(BUF8).update(i); + } + // Reserve two extra LE32 words after the 64-byte `H_0` so Figures 3-4 can append + // `LE32(0 or 1) || LE32(i)` in place for the lane-starting blocks. + const H0 = new Uint32Array(18); + const H0_8 = u8(H0); + h.digestInto(H0_8); + // 256 u32 = 1024 (BLOCK_SIZE), fills A2_BUF on processing + + // Params + const lanes = p; + // m' = 4 * p * floor (m / 4p) + const mP = 4 * p * Math.floor(m / (ARGON2_SYNC_POINTS * p)); + //q = m' / p columns + const laneLen = Math.floor(mP / p); + const segmentLen = Math.floor(laneLen / ARGON2_SYNC_POINTS); + // `maxmem` is documented in bytes; compare against the actual 1024-byte block allocation. + const memUsed = mP * 1024; + if (!isU32(maxmem)) throw new Error('"maxmem" expected <2**32, got ' + maxmem); + if (memUsed > maxmem) + throw new Error('"maxmem" limit was hit: memUsed(mP*1024)=' + memUsed + ', maxmem=' + maxmem); + const B = new Uint32Array(memUsed / 4); + // Fill first blocks + for (let l = 0; l < p; l++) { + const i = 256 * laneLen * l; + // B[i][0] = H'^(1024)(H_0 || LE32(0) || LE32(i)) + H0[17] = swap8IfBE(l); + H0[16] = swap8IfBE(0); + B.set(swap32IfBE(u32(Hp(H0, 1024))), i); + // B[i][1] = H'^(1024)(H_0 || LE32(1) || LE32(i)) + H0[16] = swap8IfBE(1); + B.set(swap32IfBE(u32(Hp(H0, 1024))), i + 256); + } + let perBlock = () => {}; + if (onProgress) { + // The first segment of the first pass skips two preinitialized blocks per lane. + const totalBlock = t * ARGON2_SYNC_POINTS * p * segmentLen - 2 * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlock / 10000), 1); + let blockCnt = 0; + perBlock = () => { + blockCnt++; + if (onProgress && (!(blockCnt % callbackPer) || blockCnt === totalBlock)) + onProgress(blockCnt / totalBlock); + }; + } + clean(BUF, H0); + return { type, mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick }; +} + +function argon2Output( + B: TArg, + p: number, + laneLen: number, + dkLen: number +): TRet { + const B_final = new Uint32Array(256); + for (let l = 0; l < p; l++) + for (let j = 0; j < 256; j++) B_final[j] ^= B[256 * (laneLen * l + laneLen - 1) + j]; + // RFC 9106 steps 7-8 feed the byte string `C` into `H'^T(C)`, so normalize the xor'ed words + // back to spec byte order before `Hp(...)` reinterprets them as bytes. + const res = Hp(swap32IfBE(B_final), dkLen); + // Wipe both the xor scratch and the full working matrix once final digest bytes exist. + // JS cleanup is still only best-effort, but this local buffer is no longer needed here. + clean(B, B_final); + return res; +} + +function processBlock( + B: TArg, + address: TArg, + l: number, + r: number, + s: number, + index: number, + laneLen: number, + segmentLen: number, + lanes: number, + offset: number, + prev: number, + dataIndependent: boolean, + needXor: boolean +) { + if (offset % laneLen) prev = offset - 1; + let randL, randH; + if (dataIndependent) { + let i128 = index % 128; + // RFC 9106 §3.4.1.2: each 1024-byte address block yields 128 `(J1, J2)` pairs, so regenerate + // it whenever the segment index crosses a multiple of 128. + if (i128 === 0) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + randL = address[2 * i128]; + randH = address[2 * i128 + 1]; + } else { + const T = 256 * prev; + randL = B[T]; + randH = B[T + 1]; + } + // Address-block path selects `J1` / `J2`, then maps them to the reference + // lane/block per RFC 9106 §3.4. + const refLane = r === 0 && s === 0 ? l : randH % lanes; + const refPos = indexAlpha(r, s, laneLen, segmentLen, index, randL, refLane == l); + const refBlock = laneLen * refLane + refPos; + // B[i][j] = G(B[i][j-1], B[l][z]) + block(B, 256 * prev, 256 * refBlock, offset * 256, needXor); +} + +function argon2( + type: Types, + password: TArg, + salt: TArg, + opts: TArg +): TRet { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock } = argon2Init( + password, + salt, + type, + opts + ); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + for (let r = 0; r < t; r++) { + // RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy + // `0x10` keeps the older overwrite behavior used by the v16 test vectors. + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + // RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only + // in pass 0, slices 0 and 1; Argon2i uses it in every segment. + const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + } + } + } + } + clean(address); + return argon2Output(B, p, laneLen, dkLen); +} + +/** + * Argon2d GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d. + * ```ts + * argon2d('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2d = ( + password: TArg, + salt: TArg, + opts: TArg +): TRet => argon2(AT.Argond2d, password, salt, opts); +/** + * Argon2i side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i. + * ```ts + * argon2i('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2i = ( + password: TArg, + salt: TArg, + opts: TArg +): TRet => argon2(AT.Argon2i, password, salt, opts); +/** + * Argon2id, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id. + * ```ts + * argon2id('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2id = ( + password: TArg, + salt: TArg, + opts: TArg +): TRet => argon2(AT.Argon2id, password, salt, opts); + +async function argon2Async( + type: Types, + password: TArg, + salt: TArg, + opts: TArg +): Promise> { + const { mP, p, t, version, B, laneLen, lanes, segmentLen, dkLen, perBlock, asyncTick } = + argon2Init(password, salt, type, opts); + // Pre-loop setup + // [address, input, zero_block] format so we can pass single U32 to block function + const address = new Uint32Array(3 * 256); + address[256 + 6] = mP; + address[256 + 8] = t; + address[256 + 10] = type; + let ts = Date.now(); + for (let r = 0; r < t; r++) { + // RFC 9106 step 6 applies the XOR-on-later-passes rule only for version `0x13`; legacy + // `0x10` keeps the older overwrite behavior used by the v16 test vectors. + const needXor = r !== 0 && version === 0x13; + address[256 + 0] = r; + for (let s = 0; s < ARGON2_SYNC_POINTS; s++) { + address[256 + 4] = s; + // RFC 9106 §3.4.1.3: Argon2id uses Argon2i's data-independent `J1` / `J2` generation only + // in pass 0, slices 0 and 1; Argon2i uses it in every segment. + const dataIndependent = type == AT.Argon2i || (type == AT.Argon2id && r === 0 && s < 2); + for (let l = 0; l < p; l++) { + address[256 + 2] = l; + address[256 + 12] = 0; + let startPos = 0; + if (r === 0 && s === 0) { + startPos = 2; + if (dataIndependent) { + address[256 + 12]++; + block(address, 256, 2 * 256, 0, false); + block(address, 0, 2 * 256, 0, false); + } + } + // current block postion + let offset = l * laneLen + s * segmentLen + startPos; + // previous block position + let prev = offset % laneLen ? offset - 1 : offset + laneLen - 1; + for (let index = startPos; index < segmentLen; index++, offset++, prev++) { + perBlock(); + processBlock( + B, + address, + l, + r, + s, + index, + laneLen, + segmentLen, + lanes, + offset, + prev, + dataIndependent, + needXor + ); + // Date.now() is not monotonic. If the clock goes backwards, + // still yield control. + const diff = Date.now() - ts; + if (!(diff >= 0 && diff < asyncTick)) { + await nextTick(); + ts += diff; + } + } + } + } + } + clean(address); + return argon2Output(B, p, laneLen, dkLen); +} + +/** + * Argon2d async GPU-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2d asynchronously. + * ```ts + * await argon2dAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2dAsync = ( + password: TArg, + salt: TArg, + opts: TArg +): Promise> => argon2Async(AT.Argond2d, password, salt, opts); +/** + * Argon2i async side-channel-resistant version. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2i asynchronously. + * ```ts + * await argon2iAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2iAsync = ( + password: TArg, + salt: TArg, + opts: TArg +): Promise> => argon2Async(AT.Argon2i, password, salt, opts); +/** + * Argon2id async, combining i+d, the most popular version from RFC 9106. + * @param password - password or input key material + * @param salt - unique salt value + * @param opts - Argon2 cost and optional tuning parameters. See {@link ArgonOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Argon2 input or cost parameters are invalid. {@link Error} + * @example + * Derive a key with Argon2id asynchronously. + * ```ts + * await argon2idAsync('password', 'salt1234', { t: 1, m: 8, p: 1, dkLen: 32 }); + * ``` + */ +export const argon2idAsync = ( + password: TArg, + salt: TArg, + opts: TArg +): Promise> => argon2Async(AT.Argon2id, password, salt, opts); diff --git a/node_modules/@noble/hashes/src/blake1.ts b/node_modules/@noble/hashes/src/blake1.ts new file mode 100644 index 0000000..72cb4f6 --- /dev/null +++ b/node_modules/@noble/hashes/src/blake1.ts @@ -0,0 +1,614 @@ +/** + * Blake1 legacy hash function, one of SHA3 proposals. + * Rarely used. Check out blake2 or blake3 instead. + * {@link https://www.aumasson.jp/blake/blake.pdf} + * + * In the best case, there are 0 allocations. + * + * Differences from blake2: + * + * - BE instead of LE + * - Paddings, similar to MD5, RIPEMD, SHA1, SHA2, but: + * - length flag is located before actual length + * - padding block is compressed differently (no lengths) + * Instead of msg[sigma[k]], we have `msg[sigma[k]] ^ constants[sigma[k-1]]` + * (-1 for g1, g2 without -1) + * - Salt is XOR-ed into constants instead of state + * - Salt is XOR-ed with output in `compress` + * - Additional rows (+64 bytes) in SIGMA for new rounds + * - Different round count: + * - 14 / 10 rounds in blake256 / blake2s + * - 16 / 12 rounds in blake512 / blake2b + * - blake512: G1b: rotr 24 -> 25, G2b: rotr 63 -> 11 + * @module + */ +import { BSIGMA, G1s, G2s } from './_blake.ts'; +import { SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts'; +import * as u64 from './_u64.ts'; +// prettier-ignore +import { + abytes, aexists, aoutput, + clean, createHasher, + createView, + type CHash, + type Hash, + type TArg, + type TRet +} from './utils.ts'; + +/** Blake1 options. Basically just `salt`. */ +export type BlakeOpts = { + /** Optional salt mixed into initialization. */ + salt?: Uint8Array; +}; + +// Shared unsalted sentinel, sized for the 64-bit path and reused by the 32-bit path via prefix. +const EMPTY_SALT = /* @__PURE__ */ new Uint32Array(8); + +// Base destroy logic only clears salt-derived state; the partial message buffer and length/position +// bookkeeping remain until the instance or backing buffer is reused. +abstract class BLAKE1> implements Hash { + readonly canXOF = false; + protected finished = false; + protected length = 0; + protected pos = 0; + protected destroyed = false; + // For partial updates less than block size + protected buffer: Uint8Array; + protected view: DataView; + protected salt: Uint32Array; + abstract compress(view: DataView, offset: number, withLength?: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + + readonly blockLen: number; + readonly outputLen: number; + private lengthFlag: number; + private counterLen: number; + protected constants: Uint32Array; + + constructor( + blockLen: number, + outputLen: number, + lengthFlag: number, + counterLen: number, + saltLen: number, + constants: Uint32Array, + opts: BlakeOpts = {} + ) { + const { salt } = opts; + this.blockLen = blockLen; + this.outputLen = outputLen; + this.lengthFlag = lengthFlag; + this.counterLen = counterLen; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + if (salt !== undefined) { + let slt = salt; + abytes(slt, 4 * saltLen, 'salt'); + // if (slt.length !== 4 * saltLen) throw new Error('wrong salt length'); + const salt32 = (this.salt = new Uint32Array(saltLen)); + const sv = createView(slt); + this.constants = constants.slice(); + for (let i = 0, offset = 0; i < salt32.length; i++, offset += 4) { + salt32[i] = sv.getUint32(offset, false); + this.constants[i] ^= salt32[i]; + } + } else { + this.salt = EMPTY_SALT; + this.constants = constants; + } + } + update(data: TArg): this { + aexists(this); + abytes(data); + // From _md, but update length before each compress + const { view, buffer, blockLen } = this; + const len = data.length; + let dataView; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + // Fast path only when there is no buffered partial block: `take === blockLen` implies + // `this.pos === 0`, so we can process full blocks directly from the input view. + if (take === blockLen) { + if (!dataView) dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) { + this.length += blockLen; + this.compress(dataView, pos); + } + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.length += blockLen; + this.compress(view, 0, true); + this.pos = 0; + } + } + return this; + } + destroy(): void { + this.destroyed = true; + if (this.salt !== EMPTY_SALT) { + clean(this.salt, this.constants); + } + } + _cloneInto(to?: T): T { + to ||= new (this.constructor as any)() as T; + to.set(...this.get()); + const { buffer, length, finished, destroyed, constants, salt, pos } = this; + to.buffer.set(buffer); + // Clone salt-derived arrays by value so destroying the clone cannot wipe the source instance. + to.constants = constants.slice(); + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + to.salt = salt.slice(); + return to; + } + clone(): T { + return this._cloneInto(); + } + digestInto(out: TArg): void { + aexists(this); + aoutput(out, this); + this.finished = true; + // Padding + const { buffer, blockLen, counterLen, lengthFlag, view } = this; + clean(buffer.subarray(this.pos)); // clean buf + const counter = BigInt((this.length + this.pos) * 8); + const counterPos = blockLen - counterLen - 1; + buffer[this.pos] |= 0b1000_0000; // End block flag + this.length += this.pos; // add unwritten length + // Not enough in buffer for length: write what we have. + if (this.pos > counterPos) { + this.compress(view, 0); + clean(buffer); + this.pos = 0; + } + // Difference with md: here we have lengthFlag! + buffer[counterPos] |= lengthFlag; // Length flag + // We always set 8 byte length flag. Because length will overflow significantly sooner. + view.setBigUint64(blockLen - 8, counter, false); + // Blake1 omits the counter from the extra all-padding block; only the block that still carries + // message bytes mixes in the final bit length. + this.compress(view, 0, this.pos !== 0); + // Write output + clean(buffer); + const v = createView(out); + const state = this.get(); + for (let i = 0; i < this.outputLen / 4; ++i) v.setUint32(i * 4, state[i]); + } + digest(): TRet { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Return a copy so callers do not alias the instance scratch buffer used during finalization. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res as TRet; + } +} + +// Blake1-512 / Blake1-384 constant table `C512`. +// Stored as sixteen 64-bit constants split into `[high32, low32]` halves so +// the Blake1-64 path can reuse one layout for both `v8..v15` initialization +// and the permuted constant lookups. +const B64C = /* @__PURE__ */ Uint32Array.from([ + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, + 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, + 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, +]); +// Blake1-256 / Blake1-224 constant table `C256`, derived as the first half of `C512`. +const B32C = /* @__PURE__ */ B64C.slice(0, 16); + +// Blake1-256 IV cloned from SHA-256. +const B256_IV = /* @__PURE__ */ SHA256_IV.slice(); +// Blake1-224 IV cloned from SHA-224. +const B224_IV = /* @__PURE__ */ SHA224_IV.slice(); +// Blake1-384 IV cloned from the SHA-384 high-then-low 32-bit halves. +const B384_IV = /* @__PURE__ */ SHA384_IV.slice(); +// Blake1-512 IV cloned from the SHA-512 high-then-low 32-bit halves. +const B512_IV = /* @__PURE__ */ SHA512_IV.slice(); + +// Precompute the odd/even companion constants used by all 14 Blake1-32 rounds. +// Each pair stores `u[sigma[2i + 1]]` then `u[sigma[2i]]`, matching the `G1s` / `G2s` xor order. +function generateTBL256() { + const TBL = []; + for (let i = 0, j = 0; i < 14; i++, j += 16) { + for (let offset = 1; offset < 16; offset += 2) { + TBL.push(B32C[BSIGMA[j + offset]]); + TBL.push(B32C[BSIGMA[j + offset - 1]]); + } + } + return new Uint32Array(TBL); +} +// Full 14-round companion-constant table for Blake1-32. +const TBL256 = /* @__PURE__ */ generateTBL256(); + +// Shared synchronous message-word scratch for the 32-bit Blake1 path. +const BLAKE256_W = /* @__PURE__ */ new Uint32Array(16); + +class BLAKE1_32B extends BLAKE1 { + private v0: number; + private v1: number; + private v2: number; + private v3: number; + private v4: number; + private v5: number; + private v6: number; + private v7: number; + constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts: BlakeOpts = {}) { + super(64, outputLen, lengthFlag, 8, 4, B32C, opts); + this.v0 = IV[0] | 0; + this.v1 = IV[1] | 0; + this.v2 = IV[2] | 0; + this.v3 = IV[3] | 0; + this.v4 = IV[4] | 0; + this.v5 = IV[5] | 0; + this.v6 = IV[6] | 0; + this.v7 = IV[7] | 0; + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ): void { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + destroy(): void { + super.destroy(); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } + compress(view: DataView, offset: number, withLength = true): void { + for (let i = 0; i < 16; i++, offset += 4) BLAKE256_W[i] = view.getUint32(offset, false); + // Cannot reuse blake2s compress: Blake1 mixes each message word with the companion constants + // precomputed in `TBL256`, rather than using the raw schedule words directly. + let v00 = this.v0 | 0; + let v01 = this.v1 | 0; + let v02 = this.v2 | 0; + let v03 = this.v3 | 0; + let v04 = this.v4 | 0; + let v05 = this.v5 | 0; + let v06 = this.v6 | 0; + let v07 = this.v7 | 0; + let v08 = this.constants[0] | 0; + let v09 = this.constants[1] | 0; + let v10 = this.constants[2] | 0; + let v11 = this.constants[3] | 0; + // Blake1-32 injects the 64-bit bit counter as `[t0, t0, t1, t1]` across `v12..v15`; the + // final all-padding block passes `withLength = false`, leaving these lanes as raw constants. + const { h, l } = u64.fromBig(BigInt(withLength ? this.length * 8 : 0)); + let v12 = (this.constants[4] ^ l) >>> 0; + let v13 = (this.constants[5] ^ l) >>> 0; + let v14 = (this.constants[6] ^ h) >>> 0; + let v15 = (this.constants[7] ^ h) >>> 0; + // prettier-ignore + for (let i = 0, k = 0, j = 0; i < 14; i++) { + ({ a: v00, b: v04, c: v08, d: v12 } = G1s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v04, c: v08, d: v12 } = G2s(v00, v04, v08, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v05, c: v09, d: v13 } = G1s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v05, c: v09, d: v13 } = G2s(v01, v05, v09, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v06, c: v10, d: v14 } = G1s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v06, c: v10, d: v14 } = G2s(v02, v06, v10, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v07, c: v11, d: v15 } = G1s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v07, c: v11, d: v15 } = G2s(v03, v07, v11, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v05, c: v10, d: v15 } = G1s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v00, b: v05, c: v10, d: v15 } = G2s(v00, v05, v10, v15, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v06, c: v11, d: v12 } = G1s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v01, b: v06, c: v11, d: v12 } = G2s(v01, v06, v11, v12, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v07, c: v08, d: v13 } = G1s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v02, b: v07, c: v08, d: v13 } = G2s(v02, v07, v08, v13, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v04, c: v09, d: v14 } = G1s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + ({ a: v03, b: v04, c: v09, d: v14 } = G2s(v03, v04, v09, v14, BLAKE256_W[BSIGMA[k++]] ^ TBL256[j++])); + } + this.v0 = (this.v0 ^ v00 ^ v08 ^ this.salt[0]) >>> 0; + this.v1 = (this.v1 ^ v01 ^ v09 ^ this.salt[1]) >>> 0; + this.v2 = (this.v2 ^ v02 ^ v10 ^ this.salt[2]) >>> 0; + this.v3 = (this.v3 ^ v03 ^ v11 ^ this.salt[3]) >>> 0; + this.v4 = (this.v4 ^ v04 ^ v12 ^ this.salt[0]) >>> 0; + this.v5 = (this.v5 ^ v05 ^ v13 ^ this.salt[1]) >>> 0; + this.v6 = (this.v6 ^ v06 ^ v14 ^ this.salt[2]) >>> 0; + this.v7 = (this.v7 ^ v07 ^ v15 ^ this.salt[3]) >>> 0; + clean(BLAKE256_W); + } +} + +// Shared Blake1-64 work vector storing 16 working words as adjacent high/low 32-bit halves. +const BBUF = /* @__PURE__ */ new Uint32Array(32); +// Shared synchronous message-word scratch for the 64-bit Blake1 path. +const BLAKE512_W = /* @__PURE__ */ new Uint32Array(32); + +// Precompute the high/low companion constants used by all 16 Blake1-64 rounds. +// Each quartet stores `u[sigma[2i + 1]]` high/low halves, then `u[sigma[2i]]` high/low halves. +function generateTBL512() { + const TBL = []; + for (let r = 0, k = 0; r < 16; r++, k += 16) { + for (let offset = 1; offset < 16; offset += 2) { + TBL.push(B64C[BSIGMA[k + offset] * 2 + 0]); + TBL.push(B64C[BSIGMA[k + offset] * 2 + 1]); + TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 0]); + TBL.push(B64C[BSIGMA[k + offset - 1] * 2 + 1]); + } + } + return new Uint32Array(TBL); +} +// Full 16-round companion-constant table as high/low halves. +const TBL512 = /* @__PURE__ */ generateTBL512(); + +// Blake1-64 first half-round with rotations `32` and `25`; `k` is the half-call schedule index. +function G1b(a: number, b: number, c: number, d: number, msg: TArg, k: number) { + const Xpos = 2 * BSIGMA[k]; + const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore + let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore + let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore + let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore + let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh) >>> 0; + Al = (ll | 0) >>> 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 25) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 25), Bl: u64.rotrSL(Bh, Bl, 25) }); + ((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah)); + ((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh)); + ((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch)); + ((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh)); +} + +// Blake1-64 second half-round with rotations `16` and `11`; `k` is the half-call schedule index. +function G2b(a: number, b: number, c: number, d: number, msg: TArg, k: number) { + const Xpos = 2 * BSIGMA[k]; + const Xl = msg[Xpos + 1] ^ TBL512[k * 2 + 1], Xh = msg[Xpos] ^ TBL512[k * 2]; // prettier-ignore + let Al = BBUF[2 * a + 1], Ah = BBUF[2 * a]; // prettier-ignore + let Bl = BBUF[2 * b + 1], Bh = BBUF[2 * b]; // prettier-ignore + let Cl = BBUF[2 * c + 1], Ch = BBUF[2 * c]; // prettier-ignore + let Dl = BBUF[2 * d + 1], Dh = BBUF[2 * d]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 11) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 11), Bl: u64.rotrSL(Bh, Bl, 11) }); + ((BBUF[2 * a + 1] = Al), (BBUF[2 * a] = Ah)); + ((BBUF[2 * b + 1] = Bl), (BBUF[2 * b] = Bh)); + ((BBUF[2 * c + 1] = Cl), (BBUF[2 * c] = Ch)); + ((BBUF[2 * d + 1] = Dl), (BBUF[2 * d] = Dh)); +} + +// Legacy field names keep the local `l/h` spelling, but array/state order stays `[high, low]` to +// match the IV tables and `BBUF` layout. +class BLAKE1_64B extends BLAKE1 { + private v0l: number; + private v0h: number; + private v1l: number; + private v1h: number; + private v2l: number; + private v2h: number; + private v3l: number; + private v3h: number; + private v4l: number; + private v4h: number; + private v5l: number; + private v5h: number; + private v6l: number; + private v6h: number; + private v7l: number; + private v7h: number; + constructor(outputLen: number, IV: Uint32Array, lengthFlag: number, opts: BlakeOpts = {}) { + super(128, outputLen, lengthFlag, 16, 8, B64C, opts); + this.v0l = IV[0] | 0; + this.v0h = IV[1] | 0; + this.v1l = IV[2] | 0; + this.v1h = IV[3] | 0; + this.v2l = IV[4] | 0; + this.v2h = IV[5] | 0; + this.v3l = IV[6] | 0; + this.v3h = IV[7] | 0; + this.v4l = IV[8] | 0; + this.v4h = IV[9] | 0; + this.v5l = IV[10] | 0; + this.v5h = IV[11] | 0; + this.v6l = IV[12] | 0; + this.v6h = IV[13] | 0; + this.v7l = IV[14] | 0; + this.v7h = IV[15] | 0; + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ): void { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + destroy(): void { + super.destroy(); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } + compress(view: DataView, offset: number, withLength = true): void { + for (let i = 0; i < 32; i++, offset += 4) BLAKE512_W[i] = view.getUint32(offset, false); + + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(this.constants.subarray(0, 16), 16); + if (withLength) { + // Blake1-64 injects the 64-bit bit counter into `v12` and `v13`; the final all-padding + // block passes `withLength = false`, leaving the trailing constant lanes untouched. + const { h, l } = u64.fromBig(BigInt(this.length * 8)); + BBUF[24] = (BBUF[24] ^ h) >>> 0; + BBUF[25] = (BBUF[25] ^ l) >>> 0; + BBUF[26] = (BBUF[26] ^ h) >>> 0; + BBUF[27] = (BBUF[27] ^ l) >>> 0; + } + for (let i = 0, k = 0; i < 16; i++) { + G1b(0, 4, 8, 12, BLAKE512_W, k++); + G2b(0, 4, 8, 12, BLAKE512_W, k++); + G1b(1, 5, 9, 13, BLAKE512_W, k++); + G2b(1, 5, 9, 13, BLAKE512_W, k++); + G1b(2, 6, 10, 14, BLAKE512_W, k++); + G2b(2, 6, 10, 14, BLAKE512_W, k++); + G1b(3, 7, 11, 15, BLAKE512_W, k++); + G2b(3, 7, 11, 15, BLAKE512_W, k++); + + G1b(0, 5, 10, 15, BLAKE512_W, k++); + G2b(0, 5, 10, 15, BLAKE512_W, k++); + G1b(1, 6, 11, 12, BLAKE512_W, k++); + G2b(1, 6, 11, 12, BLAKE512_W, k++); + G1b(2, 7, 8, 13, BLAKE512_W, k++); + G2b(2, 7, 8, 13, BLAKE512_W, k++); + G1b(3, 4, 9, 14, BLAKE512_W, k++); + G2b(3, 4, 9, 14, BLAKE512_W, k++); + } + this.v0l ^= BBUF[0] ^ BBUF[16] ^ this.salt[0]; + this.v0h ^= BBUF[1] ^ BBUF[17] ^ this.salt[1]; + this.v1l ^= BBUF[2] ^ BBUF[18] ^ this.salt[2]; + this.v1h ^= BBUF[3] ^ BBUF[19] ^ this.salt[3]; + this.v2l ^= BBUF[4] ^ BBUF[20] ^ this.salt[4]; + this.v2h ^= BBUF[5] ^ BBUF[21] ^ this.salt[5]; + this.v3l ^= BBUF[6] ^ BBUF[22] ^ this.salt[6]; + this.v3h ^= BBUF[7] ^ BBUF[23] ^ this.salt[7]; + this.v4l ^= BBUF[8] ^ BBUF[24] ^ this.salt[0]; + this.v4h ^= BBUF[9] ^ BBUF[25] ^ this.salt[1]; + this.v5l ^= BBUF[10] ^ BBUF[26] ^ this.salt[2]; + this.v5h ^= BBUF[11] ^ BBUF[27] ^ this.salt[3]; + this.v6l ^= BBUF[12] ^ BBUF[28] ^ this.salt[4]; + this.v6h ^= BBUF[13] ^ BBUF[29] ^ this.salt[5]; + this.v7l ^= BBUF[14] ^ BBUF[30] ^ this.salt[6]; + this.v7h ^= BBUF[15] ^ BBUF[31] ^ this.salt[7]; + clean(BBUF, BLAKE512_W); + } +} + +/** Internal blake1-224 hash class. */ +export class _BLAKE224 extends BLAKE1_32B { + constructor(opts: BlakeOpts = {}) { + super(28, B224_IV, 0b0000_0000, opts); + } +} +/** Internal blake1-256 hash class. */ +export class _BLAKE256 extends BLAKE1_32B { + constructor(opts: BlakeOpts = {}) { + super(32, B256_IV, 0b0000_0001, opts); + } +} +/** Internal blake1-384 hash class. */ +export class _BLAKE384 extends BLAKE1_64B { + constructor(opts: BlakeOpts = {}) { + super(48, B384_IV, 0b0000_0000, opts); + } +} +/** Internal blake1-512 hash class. */ +export class _BLAKE512 extends BLAKE1_64B { + constructor(opts: BlakeOpts = {}) { + super(64, B512_IV, 0b0000_0001, opts); + } +} +/** + * Blake1-224 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-224. + * ```ts + * blake224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake224: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE224(opts) +); +/** + * Blake1-256 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 16 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-256. + * ```ts + * blake256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake256: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE256(opts) +); +/** + * Blake1-384 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-384. + * ```ts + * blake384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake384: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE384(opts) +); +/** + * Blake1-512 hash function. + * @param msg - message bytes to hash + * @param opts - Optional Blake1 settings. See {@link BlakeOpts}. If set, + * `opts.salt` must be exactly 32 bytes. + * @returns Digest bytes. + * @example + * Hash a message with Blake1-512. + * ```ts + * blake512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake512: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE512(opts) +); diff --git a/node_modules/@noble/hashes/src/blake2.ts b/node_modules/@noble/hashes/src/blake2.ts new file mode 100644 index 0000000..01f6046 --- /dev/null +++ b/node_modules/@noble/hashes/src/blake2.ts @@ -0,0 +1,582 @@ +/** + * blake2b (64-bit) & blake2s (8 to 32-bit) hash functions. + * b could have been faster, but there is no fast u64 in js, so s is 1.5x faster. + * @module + */ +import { BSIGMA, G1s, G2s } from './_blake.ts'; +import { SHA256_IV } from './_md.ts'; +import * as u64 from './_u64.ts'; +// prettier-ignore +import { + abytes, aexists, anumber, aoutput, + clean, createHasher, + swap32IfBE, swap8IfBE, + u32, + type CHash, + type Hash, + type TArg, + type TRet +} from './utils.ts'; + +/** + * Blake hash options. + * `dkLen` is output length. `key` is used in MAC mode. `salt` is used in + * KDF mode. + */ +export type Blake2Opts = { + /** Desired digest length in bytes. RFC 7693 uses 1..64 for blake2b and 1..32 for blake2s. */ + dkLen?: number; + /** Optional MAC key. */ + key?: Uint8Array; + /** Optional salt mixed into initialization. */ + salt?: Uint8Array; + /** Optional personalization bytes. */ + personalization?: Uint8Array; +}; + +// Same IV words as `SHA512_IV`, but endian-swapped into LE u32 low/high halves +// for the BLAKE2b u64 helpers below. +const B2B_IV = /* @__PURE__ */ Uint32Array.from([ + 0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a, + 0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19, +]); +// Shared synchronous BLAKE2b work vector as LE u32 low/high halves. +const BBUF = /* @__PURE__ */ new Uint32Array(32); + +// BLAKE2b G mix split into two half-rounds over LE u32 low/high limbs. +function G1b(a: number, b: number, c: number, d: number, msg: TArg, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 32) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotr32H(Dh, Dl), Dl: u64.rotr32L(Dh, Dl) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 24) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrSH(Bh, Bl, 24), Bl: u64.rotrSL(Bh, Bl, 24) }); + ((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah)); + ((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh)); + ((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch)); + ((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh)); +} + +// Second half-round of the same LE-limb BLAKE2b G mix; `x` is the message word offset. +function G2b(a: number, b: number, c: number, d: number, msg: TArg, x: number) { + // NOTE: V is LE here + const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore + let Al = BBUF[2 * a], Ah = BBUF[2 * a + 1]; // prettier-ignore + let Bl = BBUF[2 * b], Bh = BBUF[2 * b + 1]; // prettier-ignore + let Cl = BBUF[2 * c], Ch = BBUF[2 * c + 1]; // prettier-ignore + let Dl = BBUF[2 * d], Dh = BBUF[2 * d + 1]; // prettier-ignore + // v[a] = (v[a] + v[b] + x) | 0; + let ll = u64.add3L(Al, Bl, Xl); + Ah = u64.add3H(ll, Ah, Bh, Xh); + Al = ll | 0; + // v[d] = rotr(v[d] ^ v[a], 16) + ({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al }); + ({ Dh, Dl } = { Dh: u64.rotrSH(Dh, Dl, 16), Dl: u64.rotrSL(Dh, Dl, 16) }); + // v[c] = (v[c] + v[d]) | 0; + ({ h: Ch, l: Cl } = u64.add(Ch, Cl, Dh, Dl)); + // v[b] = rotr(v[b] ^ v[c], 63) + ({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl }); + ({ Bh, Bl } = { Bh: u64.rotrBH(Bh, Bl, 63), Bl: u64.rotrBL(Bh, Bl, 63) }); + ((BBUF[2 * a] = Al), (BBUF[2 * a + 1] = Ah)); + ((BBUF[2 * b] = Bl), (BBUF[2 * b + 1] = Bh)); + ((BBUF[2 * c] = Cl), (BBUF[2 * c + 1] = Ch)); + ((BBUF[2 * d] = Dl), (BBUF[2 * d + 1] = Dh)); +} + +function checkBlake2Opts( + outputLen: number, + opts: TArg = {}, + keyLen: number, + saltLen: number, + persLen: number +) { + anumber(keyLen); + // RFC 7693 §2.1 requires digest length nn in 1..keyLen. + if (outputLen <= 0 || outputLen > keyLen) throw new Error('outputLen bigger than keyLen'); + const { key, salt, personalization } = opts; + // This API uses `undefined` for the RFC 7693 `kk = 0` case, so a provided key must be non-empty. + if (key !== undefined && (key.length < 1 || key.length > keyLen)) + throw new Error('"key" expected to be undefined or of length=1..' + keyLen); + if (salt !== undefined) abytes(salt, saltLen, 'salt'); + if (personalization !== undefined) abytes(personalization, persLen, 'personalization'); +} + +/** Internal base class for BLAKE2. */ +export abstract class _BLAKE2> implements Hash { + protected abstract compress(msg: Uint32Array, offset: number, isLast: boolean): void; + protected abstract get(): number[]; + protected abstract set(...args: number[]): void; + abstract destroy(): void; + protected buffer: Uint8Array; + protected buffer32: Uint32Array; + protected finished = false; + protected destroyed = false; + protected length: number = 0; + protected pos: number = 0; + readonly blockLen: number; + readonly outputLen: number; + readonly canXOF: boolean = false; + + constructor(blockLen: number, outputLen: number) { + anumber(blockLen); + anumber(outputLen); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.buffer = new Uint8Array(blockLen); + this.buffer32 = u32(this.buffer); + } + update(data: TArg): this { + aexists(this); + abytes(data); + // Main difference with other hashes: there is flag for last block, + // so we cannot process current block before we know that there + // is the next one. This significantly complicates logic and reduces ability + // to do zero-copy processing + const { blockLen, buffer, buffer32 } = this; + const len = data.length; + const offset = data.byteOffset; + const buf = data.buffer; + for (let pos = 0; pos < len; ) { + // If buffer is full and we still have input (don't process last block, same as blake2s) + if (this.pos === blockLen) { + swap32IfBE(buffer32); + this.compress(buffer32, 0, false); + swap32IfBE(buffer32); + this.pos = 0; + } + const take = Math.min(blockLen - this.pos, len - pos); + const dataOffset = offset + pos; + // Zero-copy only for full, 4-byte-aligned, non-final blocks. + if (take === blockLen && !(dataOffset % 4) && pos + take < len) { + const data32 = new Uint32Array(buf, dataOffset, Math.floor((len - pos) / 4)); + swap32IfBE(data32); + for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) { + this.length += blockLen; + this.compress(data32, pos32, false); + } + swap32IfBE(data32); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + this.length += take; + pos += take; + } + return this; + } + digestInto(out: TArg): void { + aexists(this); + aoutput(out, this); + const { pos, buffer32 } = this; + this.finished = true; + // Padding + clean(this.buffer.subarray(pos)); + swap32IfBE(buffer32); + this.compress(buffer32, 0, true); + swap32IfBE(buffer32); + // Reject unaligned views explicitly instead of hiding them behind a full scratch copy. + if (out.byteOffset & 3) + throw new RangeError( + '"digestInto() output" expected 4-byte aligned byteOffset, got ' + out.byteOffset + ); + const state = this.get(); + const out32 = u32(out); + const full = Math.floor(this.outputLen / 4); + for (let i = 0; i < full; i++) out32[i] = swap8IfBE(state[i]); + const tail = this.outputLen % 4; + if (!tail) return; + const off = full * 4; + const word = state[full]; + for (let i = 0; i < tail; i++) out[off + i] = word >>> (8 * i); + } + digest(): TRet { + const { buffer, outputLen } = this; + this.digestInto(buffer); + // Return a copy so callers do not alias the instance scratch buffer used during finalization. + const res = buffer.slice(0, outputLen); + this.destroy(); + return res as TRet; + } + _cloneInto(to?: T): T { + const { buffer, length, finished, destroyed, outputLen, pos } = this; + // Recreate only `dkLen`; key/salt/personalization are already absorbed into the copied state. + to ||= new (this.constructor as any)({ dkLen: outputLen }) as T; + to.set(...this.get()); + to.buffer.set(buffer); + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + // @ts-ignore + to.outputLen = outputLen; + return to; + } + clone(): T { + return this._cloneInto(); + } +} + +/** Internal blake2b hash class with state stored as LE u32 low/high halves. */ +export class _BLAKE2b extends _BLAKE2<_BLAKE2b> { + // Same IV words as SHA-512 / BLAKE2b, encoded as LE u32 low/high halves. + private v0l = B2B_IV[0] | 0; + private v0h = B2B_IV[1] | 0; + private v1l = B2B_IV[2] | 0; + private v1h = B2B_IV[3] | 0; + private v2l = B2B_IV[4] | 0; + private v2h = B2B_IV[5] | 0; + private v3l = B2B_IV[6] | 0; + private v3h = B2B_IV[7] | 0; + private v4l = B2B_IV[8] | 0; + private v4h = B2B_IV[9] | 0; + private v5l = B2B_IV[10] | 0; + private v5h = B2B_IV[11] | 0; + private v6l = B2B_IV[12] | 0; + private v6h = B2B_IV[13] | 0; + private v7l = B2B_IV[14] | 0; + private v7h = B2B_IV[15] | 0; + + constructor(opts: Blake2Opts = {}) { + const olen = opts.dkLen === undefined ? 64 : opts.dkLen; + super(128, olen); + checkBlake2Opts(olen, opts, 64, 16, 16); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` into the low 32 bits of `h[0]`; + // the high 32 bits stay at `IV[0]`. + this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + const slt = u32(salt); + this.v4l ^= swap8IfBE(slt[0]); + this.v4h ^= swap8IfBE(slt[1]); + this.v5l ^= swap8IfBE(slt[2]); + this.v5h ^= swap8IfBE(slt[3]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + const pers = u32(personalization); + this.v6l ^= swap8IfBE(pers[0]); + this.v6h ^= swap8IfBE(pers[1]); + this.v7l ^= swap8IfBE(pers[2]); + this.v7h ^= swap8IfBE(pers[3]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + } + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this; + return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h]; + } + // prettier-ignore + protected set( + v0l: number, v0h: number, v1l: number, v1h: number, + v2l: number, v2h: number, v3l: number, v3h: number, + v4l: number, v4h: number, v5l: number, v5h: number, + v6l: number, v6h: number, v7l: number, v7h: number + ): void { + this.v0l = v0l | 0; + this.v0h = v0h | 0; + this.v1l = v1l | 0; + this.v1h = v1h | 0; + this.v2l = v2l | 0; + this.v2h = v2h | 0; + this.v3l = v3l | 0; + this.v3h = v3h | 0; + this.v4l = v4l | 0; + this.v4h = v4h | 0; + this.v5l = v5l | 0; + this.v5h = v5h | 0; + this.v6l = v6l | 0; + this.v6h = v6h | 0; + this.v7l = v7l | 0; + this.v7h = v7h | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void { + this.get().forEach((v, i) => (BBUF[i] = v)); // First half from state. + BBUF.set(B2B_IV, 16); // Second half from IV. + let { h, l } = u64.fromBig(BigInt(this.length)); + BBUF[24] = B2B_IV[8] ^ l; // Low word of the offset. + BBUF[25] = B2B_IV[9] ^ h; // High word. + // Invert all bits for last block + if (isLast) { + BBUF[28] = ~BBUF[28]; + BBUF[29] = ~BBUF[29]; + } + let j = 0; + const s = BSIGMA; + // SIGMA selects 64-bit message words; multiply by 2 because `msg` stores + // each word as [low32, high32]. + for (let i = 0; i < 12; i++) { + G1b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G2b(0, 4, 8, 12, msg, offset + 2 * s[j++]); + G1b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G2b(1, 5, 9, 13, msg, offset + 2 * s[j++]); + G1b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G2b(2, 6, 10, 14, msg, offset + 2 * s[j++]); + G1b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + G2b(3, 7, 11, 15, msg, offset + 2 * s[j++]); + + G1b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G2b(0, 5, 10, 15, msg, offset + 2 * s[j++]); + G1b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G2b(1, 6, 11, 12, msg, offset + 2 * s[j++]); + G1b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G2b(2, 7, 8, 13, msg, offset + 2 * s[j++]); + G1b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + G2b(3, 4, 9, 14, msg, offset + 2 * s[j++]); + } + this.v0l ^= BBUF[0] ^ BBUF[16]; + this.v0h ^= BBUF[1] ^ BBUF[17]; + this.v1l ^= BBUF[2] ^ BBUF[18]; + this.v1h ^= BBUF[3] ^ BBUF[19]; + this.v2l ^= BBUF[4] ^ BBUF[20]; + this.v2h ^= BBUF[5] ^ BBUF[21]; + this.v3l ^= BBUF[6] ^ BBUF[22]; + this.v3h ^= BBUF[7] ^ BBUF[23]; + this.v4l ^= BBUF[8] ^ BBUF[24]; + this.v4h ^= BBUF[9] ^ BBUF[25]; + this.v5l ^= BBUF[10] ^ BBUF[26]; + this.v5h ^= BBUF[11] ^ BBUF[27]; + this.v6l ^= BBUF[12] ^ BBUF[28]; + this.v6h ^= BBUF[13] ^ BBUF[29]; + this.v7l ^= BBUF[14] ^ BBUF[30]; + this.v7h ^= BBUF[15] ^ BBUF[31]; + clean(BBUF); + } + destroy(): void { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * Blake2b hash function. 64-bit. 1.5x slower than blake2s in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..64 bytes; `salt` and `personalization`, if present, + * must be 16 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2b. + * ```ts + * blake2b(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake2b: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE2b(opts) +); + +// ================= +// Blake2S +// ================= + +/** Internal type, 16 numbers. */ +// prettier-ignore +export type _Num16 = { + v0: number; v1: number; v2: number; v3: number; + v4: number; v5: number; v6: number; v7: number; + v8: number; v9: number; v10: number; v11: number; + v12: number; v13: number; v14: number; v15: number; +}; + +/** + * BLAKE2-compress core method. + * Runs only the round function over a caller-supplied local vector; callers initialize `v0..v15` + * and apply the final `h[i] ^= v[i] ^ v[i + 8]` fold themselves. + * @param s - flattened sigma schedule bytes + * @param offset - starting word offset inside `msg`, not a byte offset + * @param msg - message words + * @param rounds - round count to execute + * @param v0 - state word 0 + * @param v1 - state word 1 + * @param v2 - state word 2 + * @param v3 - state word 3 + * @param v4 - state word 4 + * @param v5 - state word 5 + * @param v6 - state word 6 + * @param v7 - state word 7 + * @param v8 - state word 8 + * @param v9 - state word 9 + * @param v10 - state word 10 + * @param v11 - state word 11 + * @param v12 - state word 12 + * @param v13 - state word 13 + * @param v14 - state word 14 + * @param v15 - state word 15 + * @returns Updated compression state words. + * @example + * Run the BLAKE2 compression core on zeroed state and message words. + * ```ts + * import { compress } from '@noble/hashes/blake2.js'; + * const state = compress( + * new Uint8Array(16), + * 0, + * new Uint32Array(16), + * 1, + * 0, 0, 0, 0, 0, 0, 0, 0, + * 0, 0, 0, 0, 0, 0, 0, 0 + * ); + * state.v0; + * ``` + */ +// prettier-ignore +export function compress(s: TArg, offset: number, msg: TArg, rounds: number, + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, + v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, +): _Num16 { + let j = 0; + for (let i = 0; i < rounds; i++) { + ({ a: v0, b: v4, c: v8, d: v12 } = G1s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v0, b: v4, c: v8, d: v12 } = G2s(v0, v4, v8, v12, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G1s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v1, b: v5, c: v9, d: v13 } = G2s(v1, v5, v9, v13, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G1s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v2, b: v6, c: v10, d: v14 } = G2s(v2, v6, v10, v14, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G1s(v3, v7, v11, v15, msg[offset + s[j++]])); + ({ a: v3, b: v7, c: v11, d: v15 } = G2s(v3, v7, v11, v15, msg[offset + s[j++]])); + + ({ a: v0, b: v5, c: v10, d: v15 } = G1s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v0, b: v5, c: v10, d: v15 } = G2s(v0, v5, v10, v15, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G1s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v1, b: v6, c: v11, d: v12 } = G2s(v1, v6, v11, v12, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G1s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v2, b: v7, c: v8, d: v13 } = G2s(v2, v7, v8, v13, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G1s(v3, v4, v9, v14, msg[offset + s[j++]])); + ({ a: v3, b: v4, c: v9, d: v14 } = G2s(v3, v4, v9, v14, msg[offset + s[j++]])); + } + return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +// Blake2s reuses the SHA-256 IV words as-is. +const B2S_IV = /* @__PURE__ */ SHA256_IV.slice(); + +/** Internal blake2s hash class. */ +export class _BLAKE2s extends _BLAKE2<_BLAKE2s> { + // Internal state, same as SHA-256 + private v0 = B2S_IV[0] | 0; + private v1 = B2S_IV[1] | 0; + private v2 = B2S_IV[2] | 0; + private v3 = B2S_IV[3] | 0; + private v4 = B2S_IV[4] | 0; + private v5 = B2S_IV[5] | 0; + private v6 = B2S_IV[6] | 0; + private v7 = B2S_IV[7] | 0; + + constructor(opts: Blake2Opts = {}) { + const olen = opts.dkLen === undefined ? 32 : opts.dkLen; + super(64, olen); + checkBlake2Opts(olen, opts, 32, 8, 8); + let { key, personalization, salt } = opts; + let keyLength = 0; + if (key !== undefined) { + abytes(key, undefined, 'key'); + keyLength = key.length; + } + // RFC 7693 §2.5: xor `p[0] = 0x0101kknn` directly into `h[0]`, since + // BLAKE2s stores each state word as one `u32`. + this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24); + if (salt !== undefined) { + abytes(salt, undefined, 'salt'); + const slt = u32(salt as Uint8Array); + this.v4 ^= swap8IfBE(slt[0]); + this.v5 ^= swap8IfBE(slt[1]); + } + if (personalization !== undefined) { + abytes(personalization, undefined, 'personalization'); + const pers = u32(personalization as Uint8Array); + this.v6 ^= swap8IfBE(pers[0]); + this.v7 ^= swap8IfBE(pers[1]); + } + if (key !== undefined) { + // Pad to blockLen and update + const tmp = new Uint8Array(this.blockLen); + tmp.set(key); + this.update(tmp); + } + } + protected get(): [number, number, number, number, number, number, number, number] { + const { v0, v1, v2, v3, v4, v5, v6, v7 } = this; + return [v0, v1, v2, v3, v4, v5, v6, v7]; + } + // prettier-ignore + protected set( + v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number + ): void { + this.v0 = v0 | 0; + this.v1 = v1 | 0; + this.v2 = v2 | 0; + this.v3 = v3 | 0; + this.v4 = v4 | 0; + this.v5 = v5 | 0; + this.v6 = v6 | 0; + this.v7 = v7 | 0; + } + protected compress(msg: Uint32Array, offset: number, isLast: boolean): void { + const { h, l } = u64.fromBig(BigInt(this.length)); + // Seed v8..v15 from the IV, xor the low/high 32-bit byte counter into + // v12/v13, and invert v14 on the final block. + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + BSIGMA, offset, msg, 10, + this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, + B2S_IV[0], B2S_IV[1], B2S_IV[2], B2S_IV[3], l ^ B2S_IV[4], h ^ B2S_IV[5], isLast ? ~B2S_IV[6] : B2S_IV[6], B2S_IV[7] + ); + this.v0 ^= v0 ^ v8; + this.v1 ^= v1 ^ v9; + this.v2 ^= v2 ^ v10; + this.v3 ^= v3 ^ v11; + this.v4 ^= v4 ^ v12; + this.v5 ^= v5 ^ v13; + this.v6 ^= v6 ^ v14; + this.v7 ^= v7 ^ v15; + } + destroy(): void { + this.destroyed = true; + clean(this.buffer32); + this.set(0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** + * Blake2s hash function. Focuses on 8-bit to 32-bit platforms. 1.5x faster than blake2b in JS. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, salt, and personalization settings. + * `dkLen` must be 1..32 bytes; `salt` and `personalization`, if present, + * must be 8 bytes each. See {@link Blake2Opts}. + * @returns Digest bytes. + * @example + * Hash a message with Blake2s. + * ```ts + * blake2s(new Uint8Array([97, 98, 99])); + * ``` + */ +export const blake2s: TRet> = /* @__PURE__ */ createHasher( + (opts) => new _BLAKE2s(opts) +); diff --git a/node_modules/@noble/hashes/src/blake3.ts b/node_modules/@noble/hashes/src/blake3.ts new file mode 100644 index 0000000..bb96a5a --- /dev/null +++ b/node_modules/@noble/hashes/src/blake3.ts @@ -0,0 +1,317 @@ +/** + * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF. + * + * It is advertised as "the fastest cryptographic hash". However, it isn't true in JS. + * Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%: + * + * * There is only 30% reduction in number of rounds from blake2s + * * Speed-up comes from tree structure, which is parallelized using SIMD & threading. + * These features are not present in JS, so we only get overhead from trees. + * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs. + * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm + * @module + */ +import { SHA256_IV } from './_md.ts'; +import { fromBig } from './_u64.ts'; +import { _BLAKE2, compress } from './blake2.ts'; +// prettier-ignore +import { + abytes, aexists, anumber, aoutput, + clean, + copyBytes, + createHasher, swap32IfBE, + u32, u8, + type CHashXOF, + type HashXOF, + type TArg, + type TRet +} from './utils.ts'; + +// Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree +// flags (`CHUNK_*`, `PARENT`, `ROOT`). +const B3_Flags = { + CHUNK_START: 0b1, + CHUNK_END: 0b10, + PARENT: 0b100, + ROOT: 0b1000, + KEYED_HASH: 0b10000, + DERIVE_KEY_CONTEXT: 0b100000, + DERIVE_KEY_MATERIAL: 0b1000000, +} as const; + +// Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis. +const B3_IV = /* @__PURE__ */ SHA256_IV.slice(); + +// Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly +// permuting the identity row. +const B3_SIGMA: TRet = /* @__PURE__ */ (() => { + const Id = Array.from({ length: 16 }, (_, i) => i); + const permute = (arr: number[]) => + [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]); + const res: number[] = []; + for (let i = 0, v = Id; i < 7; i++, v = permute(v)) res.push(...v); + return Uint8Array.from(res); +})(); + +/** + * Ensure to use EITHER `key` OR `context`, not both. + * + * * `key`: 32-byte MAC key. + * * `context`: caller-encoded KDF context bytes. If your protocol defines a + * string context, encode it before passing it here. + * A good default format for the original context string is + * "[application] [commit timestamp] [purpose]". + */ +export type Blake3Opts = { + /** Desired digest length in bytes. The BLAKE3 spec allows 0..2^64-1 bytes of output. */ + dkLen?: number; + /** Optional 32-byte MAC key. */ + key?: Uint8Array; + /** Optional KDF context bytes. */ + context?: Uint8Array; +}; + +/** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */ +export class _BLAKE3 extends _BLAKE2<_BLAKE3> implements HashXOF<_BLAKE3> { + readonly canXOF = true; + private chunkPos = 0; // Position of current block in chunk + // How many chunks we already have; exact while this stays within + // JS's safe-integer range. + private chunksDone = 0; + private flags = 0 | 0; + private IV: Uint32Array; + private state: Uint32Array; + private stack: Uint32Array[] = []; + // Output + private posOut = 0; + private bufferOut32 = new Uint32Array(16); + private bufferOut: Uint8Array; + // Index of output chunk; exact while this stays within JS's + // safe-integer range. + private chunkOut = 0; + private enableXOF = true; + + constructor(opts: Blake3Opts = {}, flags = 0) { + super(64, opts.dkLen === undefined ? 32 : opts.dkLen); + const { key, context } = opts; + const hasContext = context !== undefined; + if (key !== undefined) { + if (hasContext) throw new Error('Only "key" or "context" can be specified at same time'); + abytes(key, 32, 'key'); + const k = copyBytes(key); + this.IV = u32(k); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.KEYED_HASH; + } else if (hasContext) { + abytes(context, undefined, 'context'); + const ctx = context; + const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT) + .update(ctx) + .digest(); + this.IV = u32(contextKey); + swap32IfBE(this.IV); + this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL; + } else { + this.IV = B3_IV.slice(); + this.flags = flags; + } + this.state = this.IV.slice(); + this.bufferOut = u8(this.bufferOut32); + } + // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and + // copies it directly in _cloneInto(). + protected get(): [] { + return []; + } + protected set(): void {} + // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1, + // block length, and flags, then keep only the first 8 output words. + private b2Compress(counter: number, flags: number, buf: Uint32Array, bufPos: number = 0) { + const { state: s, pos } = this; + const { h, l } = fromBig(BigInt(counter), true); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + B3_SIGMA, bufPos, buf, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags + ); + s[0] = v0 ^ v8; + s[1] = v1 ^ v9; + s[2] = v2 ^ v10; + s[3] = v3 ^ v11; + s[4] = v4 ^ v12; + s[5] = v5 ^ v13; + s[6] = v6 ^ v14; + s[7] = v7 ^ v15; + } + protected compress(buf: Uint32Array, bufPos: number = 0, isLast: boolean = false): void { + // Compress last block + let flags = this.flags; + if (!this.chunkPos) flags |= B3_Flags.CHUNK_START; + if (this.chunkPos === 15 || isLast) flags |= B3_Flags.CHUNK_END; + if (!isLast) this.pos = this.blockLen; + this.b2Compress(this.chunksDone, flags, buf, bufPos); + this.chunkPos += 1; + // If current block is last in chunk (16 blocks), then compress chunks + if (this.chunkPos === 16 || isLast) { + let chunk = this.state; + this.state = this.IV.slice(); + // If not the last one, compress only when there are trailing zeros in chunk counter + // Chunks are used as a binary tree where the current stack is the path. + // Zero means the current leaf is finished and can be compressed. + // 1 (001) - leaf not finished (just push current chunk to stack) + // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back) + // 3 (011) - last leaf not finished + // 4 (100) - leafs finished at depth=1 and depth=2 + for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) { + if (!(last = this.stack.pop())) break; + this.buffer32.set(last, 0); + this.buffer32.set(chunk, 8); + this.pos = this.blockLen; + this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0); + chunk = this.state; + this.state = this.IV.slice(); + } + this.chunksDone++; + this.chunkPos = 0; + this.stack.push(chunk); + } + this.pos = 0; + } + _cloneInto(to?: _BLAKE3): _BLAKE3 { + to = super._cloneInto(to) as _BLAKE3; + const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this; + to.state.set(state.slice()); + // Clone each CV stack entry by value so extending or destroying the clone + // cannot alias the source tree state. + to.stack = stack.map((i) => Uint32Array.from(i)); + to.IV.set(IV); + to.flags = flags; + to.chunkPos = chunkPos; + to.chunksDone = chunksDone; + to.posOut = posOut; + to.chunkOut = chunkOut; + to.enableXOF = this.enableXOF; + to.bufferOut32.set(this.bufferOut32); + return to; + } + destroy(): void { + this.destroyed = true; + clean(this.state, this.buffer32, this.IV, this.bufferOut32); + clean(...this.stack); + } + // Root/XOF compression: rerun the same ROOT inputs with incrementing output + // counter `t` and materialize all 16 output words. + // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8) + private b2CompressOut() { + const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this; + const { h, l } = fromBig(BigInt(this.chunkOut++)); + swap32IfBE(buffer32); + // prettier-ignore + const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = + compress( + B3_SIGMA, 0, buffer32, 7, + s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], + B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags + ); + out32[0] = v0 ^ v8; + out32[1] = v1 ^ v9; + out32[2] = v2 ^ v10; + out32[3] = v3 ^ v11; + out32[4] = v4 ^ v12; + out32[5] = v5 ^ v13; + out32[6] = v6 ^ v14; + out32[7] = v7 ^ v15; + out32[8] = s[0] ^ v8; + out32[9] = s[1] ^ v9; + out32[10] = s[2] ^ v10; + out32[11] = s[3] ^ v11; + out32[12] = s[4] ^ v12; + out32[13] = s[5] ^ v13; + out32[14] = s[6] ^ v14; + out32[15] = s[7] ^ v15; + swap32IfBE(buffer32); + swap32IfBE(out32); + this.posOut = 0; + } + protected finish(): void { + if (this.finished) return; + this.finished = true; + // Padding + clean(this.buffer.subarray(this.pos)); + // Process last chunk + let flags = this.flags | B3_Flags.ROOT; + if (this.stack.length) { + // Finalize the current chunk first, then rerun the last parent + // compression as ROOT with t = 0 and b = 64. + flags |= B3_Flags.PARENT; + swap32IfBE(this.buffer32); + this.compress(this.buffer32, 0, true); + swap32IfBE(this.buffer32); + this.chunksDone = 0; + this.pos = this.blockLen; + } else { + flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END; + } + this.flags = flags; + this.b2CompressOut(); + } + private writeInto(out: TArg): TRet { + aexists(this, false); + abytes(out); + this.finish(); + const { blockLen, bufferOut } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.b2CompressOut(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out as TRet; + } + xofInto(out: TArg): TRet { + if (!this.enableXOF) throw new Error('XOF is not possible after digest call'); + return this.writeInto(out); + } + xof(bytes: number): TRet { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: TArg): void { + aoutput(out, this); + if (this.finished) throw new Error('digest() was already called'); + this.enableXOF = false; + // `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest. + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest(): TRet { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out as TRet; + } +} + +/** + * BLAKE3 hash function. Can be used as MAC and KDF. + * @param msg - message that would be hashed + * @param opts - Optional output, MAC, or KDF configuration. `key` must be + * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be + * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}. + * @returns Digest bytes. + * @example + * Hash, MAC, or derive key material with BLAKE3. + * ```ts + * import { blake3 } from '@noble/hashes/blake3.js'; + * import { utf8ToBytes } from '@noble/hashes/utils.js'; + * const data = new Uint8Array(32); + * const hash = blake3(data); + * const mac = blake3(data, { key: new Uint8Array(32) }); + * const kdf = blake3(data, { context: utf8ToBytes('application name') }); + * ``` + */ +export const blake3: TRet> = /* @__PURE__ */ createHasher( + (opts = {}) => new _BLAKE3(opts) +); diff --git a/node_modules/@noble/hashes/src/eskdf.ts b/node_modules/@noble/hashes/src/eskdf.ts new file mode 100644 index 0000000..08d50cd --- /dev/null +++ b/node_modules/@noble/hashes/src/eskdf.ts @@ -0,0 +1,259 @@ +/** + * Experimental KDF for AES. + * @module + */ +import { hkdf } from './hkdf.ts'; +import { pbkdf2 as _pbkdf2 } from './pbkdf2.ts'; +import { scrypt as _scrypt } from './scrypt.ts'; +import { sha256 } from './sha2.ts'; +import { + abytes, + bytesToHex, + clean, + createView, + hexToBytes, + kdfInputToBytes, + type TArg, + type TRet, +} from './utils.ts'; + +// A tiny KDF for various applications like AES key-gen. +// Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure". +// Which is good enough: assume sha2-256 retained preimage resistance. + +// Fixed ESKDF scrypt work factor: interactive-latency target with about 512 MiB RAM per derivation. +const SCRYPT_FACTOR = /* @__PURE__ */ (() => 2 ** 19)(); +// Fixed ESKDF PBKDF2 work factor: CPU-only companion branch in the same rough +// interactive-latency range. +const PBKDF2_FACTOR = /* @__PURE__ */ (() => 2 ** 17)(); + +/** + * Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering RFC 7914 + * @param salt - unique salt string, UTF-8 encoded before entering RFC 7914 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte scrypt key used by ESKDF. + * ```ts + * scrypt('password123', 'user@example.com'); + * ``` + */ +export function scrypt(password: string, salt: string): TRet { + return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 }); +} + +/** + * PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`. + * @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256 + * @returns Derived 32-byte key. + * @example + * Derive the 32-byte PBKDF2 key used by ESKDF. + * ```ts + * pbkdf2('password123', 'user@example.com'); + * ``` + */ +export function pbkdf2(password: string, salt: string): TRet { + return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 }); +} + +// Combines two 32-byte byte arrays into a fresh 32-byte result without aliasing either input. +function xor32(a: TArg, b: TArg): TRet { + abytes(a, 32); + abytes(b, 32); + const arr = new Uint8Array(32); + for (let i = 0; i < 32; i++) { + arr[i] = a[i] ^ b[i]; + } + return arr as TRet; +} + +// All local string length checks are in JS UTF-16 code units, not UTF-8 bytes. +function strHasLength(str: string, min: number, max: number): boolean { + return typeof str === 'string' && str.length >= min && str.length <= max; +} + +/** + * Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)` + * flow unless you specifically need the raw main seed. + * Derives the main seed by xor'ing two branches: + * the scrypt branch uses a `0x01` separator byte on username/password, + * and the PBKDF2 branch uses `0x02`. + * Username and password strings are encoded by the underlying KDFs after the + * local separator bytes are appended. + * @param username - account identifier used as public salt + * @param password - user password string + * @returns Main 32-byte seed for the account. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive the main ESKDF seed from username and password. + * ```ts + * deriveMainSeed('example-user', 'example-password'); + * ``` + */ +export function deriveMainSeed(username: string, password: string): TRet { + if (!strHasLength(username, 8, 255)) throw new Error('invalid username'); + if (!strHasLength(password, 8, 255)) throw new Error('invalid password'); + // Keep the protocol separators as the literal bytes 0x01 / 0x02 even after minification. + // Embedding them as non-printable characters directly can be awkward across + // JS tooling and environments. + const codes = { _1: 1, _2: 2 }; + const sep = { s: String.fromCharCode(codes._1), p: String.fromCharCode(codes._2) }; + const scr = scrypt(password + sep.s, username + sep.s); + const pbk = pbkdf2(password + sep.p, username + sep.p); + const res = xor32(scr, pbk); + clean(scr, pbk); + return res; +} + +type AccountID = number | string; + +/** + * Converts protocol & accountId pair to HKDF params: + * `info` is UTF-8 protocol bytes, numeric ids become 4-byte BE `salt`, + * and string ids become UTF-8 `salt` bytes. + */ +function getSaltInfo(protocol: string, accountId: AccountID = 0) { + // Note that length here also repeats two lines below + // We do an additional length check here to reduce the scope of DoS attacks + if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) { + throw new Error('invalid protocol'); + } + + // Exact-match only: substring matches like `assh` / `mentor` must not widen the public whitelist. + const allowsStr = /^(password\d{0,3}|ssh|tor|file)$/.test(protocol); + let salt: Uint8Array; // Assigned below: either 4-byte BE account bytes or UTF-8 account bytes. + if (typeof accountId === 'string') { + if (!allowsStr) throw new Error('accountId must be a number'); + if (!strHasLength(accountId, 1, 255)) + throw new Error('accountId must be string of length 1..255'); + salt = kdfInputToBytes(accountId); + } else if (Number.isSafeInteger(accountId)) { + if (accountId < 0 || accountId > Math.pow(2, 32) - 1) throw new Error('invalid accountId'); + // Convert to Big Endian Uint32 + salt = new Uint8Array(4); + createView(salt).setUint32(0, accountId, false); + } else { + throw new Error('accountId must be a number' + (allowsStr ? ' or string' : '')); + } + const info = kdfInputToBytes(protocol); + return { salt, info }; +} + +type OptsLength = { keyLength: number }; +type OptsMod = { modulus: bigint }; +type KeyOpts = undefined | OptsLength | OptsMod; + +// Local modulus-size helper, not a general bigint-byte-length primitive: +// `<= 128n` is rejected by ESKDF policy. +function countBytes(num: bigint): number { + if (typeof num !== 'bigint' || num <= BigInt(128)) throw new Error('invalid number'); + return Math.ceil(num.toString(2).length / 8); +} + +/** + * Parses keyLength and modulus options to extract length of result key. + * If modulus is used, adds 64 bits to it per the FIPS 186-5 Appendix A.3.1 / + * A.4.1 extra-bits guidance. + */ +function getKeyLength(options: KeyOpts): number { + if (!options || typeof options !== 'object') return 32; + const hasLen = 'keyLength' in options; + const hasMod = 'modulus' in options; + if (hasLen && hasMod) throw new Error('cannot combine keyLength and modulus options'); + if (!hasLen && !hasMod) throw new Error('must have either keyLength or modulus option'); + // FIPS 186-5 Appendix A.3.1 / A.4.1 calls for at least 64 extra bits. + const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength; + if (!(typeof l === 'number' && l >= 16 && l <= 8192)) throw new Error('invalid keyLength'); + return l; +} + +/** + * Converts key to bigint and divides it by modulus. Big Endian. + * Adapts FIPS 186-5 Appendix A.4.1: `getKeyLength()` already requested the + * extra 64-bit margin, and this step maps the result into `1..modulus-1`. + */ +function modReduceKey(key: TArg, modulus: bigint): TRet { + const _1 = BigInt(1); + const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber() + const res = (num % (modulus - _1)) + _1; // Remove 0 from output + if (res < _1) throw new Error('expected positive number'); // Guard against bad values + // Strip the extra 64-bit margin that `getKeyLength()` requested + // for bias reduction. + const len = key.length - 8; + const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex() + const bytes = hexToBytes(hex); + if (bytes.length !== len) throw new Error('invalid length of result key'); + return bytes; +} + +/** Not using classes because constructor cannot be async. */ +export interface ESKDF { + /** + * Derives a child key. Child key will not be associated with any + * other child key because of properties of underlying KDF. + * + * @param protocol - 3-15 character protocol name + * @param accountId - numeric account identifier, or a string id for + * `password\d{0,3}`, `ssh`, `tor`, or `file` + * @param options - Optional child-key shaping parameters. See {@link KeyOpts}. + * @returns Derived child key bytes. + */ + deriveChildKey: (protocol: string, accountId: AccountID, options?: KeyOpts) => TRet; + /** Deletes the main seed from the ESKDF instance. */ + expire: () => void; + /** + * Human-readable fingerprint: first 6 bytes of + * `deriveChildKey('fingerprint', 0)`, formatted as uppercase + * colon-separated hex. + */ + fingerprint: string; +} + +/** + * ESKDF + * @param username - username, email, or identifier, min: 8 characters, should have enough entropy + * @param password - password, min: 8 characters, should have enough entropy + * @returns Frozen API that derives child keys and exposes the account fingerprint. + * @throws If the username or password length is invalid. {@link Error} + * @example + * Derive account-specific child keys from the main ESKDF seed. + * ```ts + * const kdf = await eskdf('example-university', 'beginning-new-example'); + * const key = kdf.deriveChildKey('aes', 0); + * const fingerprint = kdf.fingerprint; + * kdf.expire(); + * ``` + */ +export async function eskdf(username: string, password: string): Promise> { + // We are using closure + object instead of class because + // we want to make `seed` non-accessible for any external function. + let seed: Uint8Array | undefined = deriveMainSeed(username, password); + + function deriveCK( + protocol: string, + accountId: AccountID = 0, + options?: KeyOpts + ): TRet { + // Reject expired instances before deriving any HKDF inputs from the closure-held seed. + abytes(seed!, 32); + const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId + // Validate option shape and coarse length bounds; + // `hkdf()` still rejects non-integer lengths. + const keyLength = getKeyLength(options); + const key = hkdf(sha256, seed!, salt, info, keyLength); + // Modulus has already been validated + return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key; + } + function expire() { + // Overwrite the closure-held seed before dropping the reference. + if (seed) seed.fill(1); + seed = undefined; + } + // prettier-ignore + const fingerprint = Array.from(deriveCK('fingerprint', 0)) + .slice(0, 6) + .map((char) => char.toString(16).padStart(2, '0').toUpperCase()) + .join(':'); + return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint }); +} diff --git a/node_modules/@noble/hashes/src/hkdf.ts b/node_modules/@noble/hashes/src/hkdf.ts new file mode 100644 index 0000000..1adbc7e --- /dev/null +++ b/node_modules/@noble/hashes/src/hkdf.ts @@ -0,0 +1,133 @@ +/** + * HKDF (RFC 5869): extract + expand in one step. + * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}. + * @module + */ +import { hmac } from './hmac.ts'; +import { abytes, ahash, anumber, type CHash, clean, type TArg, type TRet } from './utils.ts'; + +/** + * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK` + * Arguments position differs from spec (IKM is first one, since it is not optional) + * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`. + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @returns Pseudorandom key derived from input keying material. + * @example + * Run the HKDF extract step. + * ```ts + * import { extract } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export function extract( + hash: TArg, + ikm: TArg, + salt?: TArg +): TRet { + ahash(hash); + // NOTE: some libraries treat zero-length array as 'not provided'; + // we don't, since we have undefined as 'not provided' + // https://github.com/RustCrypto/KDFs/issues/15 + if (salt === undefined) salt = new Uint8Array(hash.outputLen); + return hmac(hash, salt, ikm); +} + +// Shared mutable scratch byte for the RFC 5869 block counter `N`. +// Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning. +const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); +// Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input. +const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); + +/** + * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM` + * @param hash - hash function that would be used (e.g. sha256) + * @param prk - a pseudorandom key of at least HashLen octets + * (usually, the output from the extract step) + * @param info - optional context and application specific information (can be a zero-length string) + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material with the requested length. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * Run the HKDF expand step. + * ```ts + * import { expand } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16); + * ``` + */ +export function expand( + hash: TArg, + prk: TArg, + info?: TArg, + length: number = 32 +): TRet { + ahash(hash); + anumber(length, 'length'); + abytes(prk, undefined, 'prk'); + const olen = hash.outputLen; + // RFC 5869 §2.3: PRK is "a pseudorandom key of at least HashLen octets". + if (prk.length < olen) throw new Error('"prk" must be at least HashLen octets'); + // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM. + if (length > 255 * olen) throw new Error('Length must be <= 255*HashLen'); + const blocks = Math.ceil(length / olen); + if (info === undefined) info = EMPTY_BUFFER; + else abytes(info, undefined, 'info'); + // first L(ength) octets of T + const okm = new Uint8Array(blocks * olen); + // Re-use HMAC instance between blocks + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + // T(0) = empty string (zero length) + // T(N) = HMAC-Hash(PRK, T(N-1) | info | N) + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T) + .update(info) + .update(HKDF_COUNTER) + .digestInto(T); + okm.set(T, olen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + clean(T, HKDF_COUNTER); + return okm.slice(0, length) as TRet; +} + +/** + * HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256) + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM. + * @returns Output keying material derived from the input key. + * @throws If the requested output length exceeds the HKDF limit + * for the selected hash. {@link Error} + * @example + * HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf } from '@noble/hashes/hkdf.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export const hkdf = ( + hash: TArg, + ikm: TArg, + salt: TArg, + info: TArg, + length: number +): TRet => expand(hash, extract(hash, ikm, salt), info, length); diff --git a/node_modules/@noble/hashes/src/hmac.ts b/node_modules/@noble/hashes/src/hmac.ts new file mode 100644 index 0000000..b914ebf --- /dev/null +++ b/node_modules/@noble/hashes/src/hmac.ts @@ -0,0 +1,126 @@ +/** + * HMAC: RFC2104 message authentication code. + * @module + */ +import { + abytes, + aexists, + ahash, + aoutput, + clean, + type CHash, + type Hash, + type TArg, + type TRet, +} from './utils.ts'; + +/** + * Internal class for HMAC. + * Accepts any byte key, although RFC 2104 §3 recommends keys at least + * `HashLen` bytes long. + */ +export class _HMAC> implements Hash<_HMAC> { + oHash: T; + iHash: T; + blockLen: number; + outputLen: number; + canXOF = false; + private finished = false; + private destroyed = false; + + constructor(hash: TArg, key: TArg) { + ahash(hash); + abytes(key, undefined, 'key'); + this.iHash = hash.create() as T; + if (typeof this.iHash.update !== 'function') + throw new Error('Expected instance of class which extends utils.Hash'); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + // blockLen can be bigger than outputLen + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36; + this.iHash.update(pad); + // By doing update (processing of the first block) of the outer hash here, + // we can re-use it between multiple calls via clone. + this.oHash = hash.create() as T; + // Undo internal XOR && apply outer XOR + for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c; + this.oHash.update(pad); + clean(pad); + } + update(buf: TArg): this { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out: TArg): void { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before + // overwriting that same prefix with the final tag, leaving any oversized tail untouched. + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest(): TRet { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out as TRet; + } + _cloneInto(to?: _HMAC): _HMAC { + // Create new instance without calling constructor since the key + // is already in state and we don't know it. + to ||= Object.create(Object.getPrototypeOf(this), {}); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to as this; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone(): _HMAC { + return this._cloneInto(); + } + destroy(): void { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +} + +/** + * HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256 + * @param key - authentication key bytes + * @param message - message bytes to authenticate + * @returns Authentication tag bytes. + * @example + * Compute an RFC 2104 HMAC. + * ```ts + * import { hmac } from '@noble/hashes/hmac.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +type HmacFn = { + (hash: TArg, key: TArg, message: TArg): TRet; + create(hash: TArg, key: TArg): TRet<_HMAC>; +}; +export const hmac: TRet = /* @__PURE__ */ (() => { + const hmac_ = (( + hash: TArg, + key: TArg, + message: TArg + ): TRet => new _HMAC(hash, key).update(message).digest()) as TRet; + hmac_.create = (hash: TArg, key: TArg): TRet<_HMAC> => + new _HMAC(hash, key) as TRet<_HMAC>; + return hmac_; +})(); diff --git a/node_modules/@noble/hashes/src/index.ts b/node_modules/@noble/hashes/src/index.ts new file mode 100644 index 0000000..c6a9c23 --- /dev/null +++ b/node_modules/@noble/hashes/src/index.ts @@ -0,0 +1,33 @@ +/** + * Audited & minimal JS implementation of hash functions, MACs, and KDFs. + * Check out individual modules. + * @module + * @example +```js +import { + sha256, sha384, sha512, sha224, sha512_224, sha512_256 +} from '@noble/hashes/sha2.js'; +import { + sha3_224, sha3_256, sha3_384, sha3_512, + keccak_224, keccak_256, keccak_384, keccak_512, + shake128, shake256 +} from '@noble/hashes/sha3.js'; +import { + cshake128, cshake256, + turboshake128, turboshake256, + kt128, kt256, + kmac128, kmac256, + tuplehash256, parallelhash256, + keccakprg +} from '@noble/hashes/sha3-addons.js'; +import { blake3 } from '@noble/hashes/blake3.js'; +import { blake2b, blake2s } from '@noble/hashes/blake2.js'; +import { hmac } from '@noble/hashes/hmac.js'; +import { hkdf } from '@noble/hashes/hkdf.js'; +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { scrypt, scryptAsync } from '@noble/hashes/scrypt.js'; +import { md5, ripemd160, sha1 } from '@noble/hashes/legacy.js'; +import * as utils from '@noble/hashes/utils.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/node_modules/@noble/hashes/src/legacy.ts b/node_modules/@noble/hashes/src/legacy.ts new file mode 100644 index 0000000..0e185fb --- /dev/null +++ b/node_modules/@noble/hashes/src/legacy.ts @@ -0,0 +1,339 @@ +/** + +SHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions. +RFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors, +not the base RIPEMD-160 compression spec. +Don't use them in a new protocol. What "weak" means: + +- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160. +- No practical pre-image attacks (only theoretical, 2^123.4) +- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151 + * @module + */ +import { Chi, HashMD, Maj } from './_md.ts'; +import { type CHash, clean, createHasher, rotl, type TRet } from './utils.ts'; + +/** Initial SHA-1 state from RFC 3174 §6.1. */ +const SHA1_IV = /* @__PURE__ */ Uint32Array.from([ + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0, +]); + +// Reusable 80-word SHA-1 message schedule buffer. +const SHA1_W = /* @__PURE__ */ new Uint32Array(80); + +/** Internal SHA1 legacy hash class. */ +export class _SHA1 extends HashMD<_SHA1> { + private A = SHA1_IV[0] | 0; + private B = SHA1_IV[1] | 0; + private C = SHA1_IV[2] | 0; + private D = SHA1_IV[3] | 0; + private E = SHA1_IV[4] | 0; + + constructor() { + super(64, 20, 8, false); + } + protected get(): [number, number, number, number, number] { + const { A, B, C, D, E } = this; + return [A, B, C, D, E]; + } + protected set(A: number, B: number, C: number, D: number, E: number): void { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 80; i++) + SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1); + // Compression function main loop, 80 rounds + let { A, B, C, D, E } = this; + for (let i = 0; i < 80; i++) { + let F, K; + if (i < 20) { + F = Chi(B, C, D); + K = 0x5a827999; + } else if (i < 40) { + F = B ^ C ^ D; + K = 0x6ed9eba1; + } else if (i < 60) { + F = Maj(B, C, D); + K = 0x8f1bbcdc; + } else { + F = B ^ C ^ D; + K = 0xca62c1d6; + } + const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0; + E = D; + D = C; + C = rotl(B, 30); + B = A; + A = T; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + this.set(A, B, C, D, E); + } + protected roundClean(): void { + clean(SHA1_W); + } + destroy(): void { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0, 0); + clean(this.buffer); + } +} + +/** + * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA1. + * ```ts + * sha1(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha1: TRet = /* @__PURE__ */ createHasher(() => new _SHA1()); + +/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */ +const p32 = /* @__PURE__ */ Math.pow(2, 32); +/** RFC 1321 `T[1..64]` table. */ +const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => + Math.floor(p32 * Math.abs(Math.sin(i + 1))) +); + +/** MD5 initial state from RFC 1321, stored as 4 u32 words. */ +const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4); + +// Reusable 16-word MD5 message block buffer. +const MD5_W = /* @__PURE__ */ new Uint32Array(16); +/** Internal MD5 legacy hash class. */ +export class _MD5 extends HashMD<_MD5> { + private A = MD5_IV[0] | 0; + private B = MD5_IV[1] | 0; + private C = MD5_IV[2] | 0; + private D = MD5_IV[3] | 0; + + constructor() { + super(64, 16, 8, true); + } + protected get(): [number, number, number, number] { + const { A, B, C, D } = this; + return [A, B, C, D]; + } + protected set(A: number, B: number, C: number, D: number): void { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true); + // Compression function main loop, 64 rounds + let { A, B, C, D } = this; + for (let i = 0; i < 64; i++) { + let F, g, s; + if (i < 16) { + F = Chi(B, C, D); + g = i; + s = [7, 12, 17, 22]; + } else if (i < 32) { + // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`. + F = Chi(D, B, C); + g = (5 * i + 1) % 16; + s = [5, 9, 14, 20]; + } else if (i < 48) { + F = B ^ C ^ D; + g = (3 * i + 5) % 16; + s = [4, 11, 16, 23]; + } else { + F = C ^ (B | ~D); + g = (7 * i) % 16; + s = [6, 10, 15, 21]; + } + F = F + A + K[i] + MD5_W[g]; + A = D; + D = C; + C = B; + B = B + rotl(F, s[i % 4]); + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + this.set(A, B, C, D); + } + protected roundClean(): void { + clean(MD5_W); + } + destroy(): void { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0); + clean(this.buffer); + } +} + +/** + * MD5 (RFC 1321) legacy hash function. It was cryptographically broken. + * MD5 architecture is similar to SHA1, with some differences: + * - Reduced output length: 16 bytes (128 bit) instead of 20 + * - 64 rounds, instead of 80 + * - Little-endian: could be faster, but will require more code + * - Non-linear index selection: huge speed-up for unroll + * - Per round constants: more memory accesses, additional speed-up for unroll + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with MD5. + * ```ts + * md5(new Uint8Array([97, 98, 99])); + * ``` + */ +export const md5: TRet = /* @__PURE__ */ createHasher(() => new _MD5()); + +// RIPEMD-160 + +// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables. +const Rho160 = /* @__PURE__ */ Uint8Array.from([ + 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, +]); +const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))(); +const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))(); +// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds. +const idxLR = /* @__PURE__ */ (() => { + const L = [Id160]; + const R = [Pi160]; + const res = [L, R]; + for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k])); + return res; +})(); +const idxL = /* @__PURE__ */ (() => idxLR[0])(); +const idxR = /* @__PURE__ */ (() => idxLR[1])(); +// const [idxL, idxR] = idxLR; + +// Base per-group shift table before the left/right message-order permutations are applied. +const shifts160 = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5], +].map((i) => Uint8Array.from(i)); +const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j])); +const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j])); +// Five left-lane additive constants for RIPEMD-160. +const Kl160 = /* @__PURE__ */ Uint32Array.from([ + 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e, +]); +// Five right-lane additive constants for RIPEMD-160. +const Kr160 = /* @__PURE__ */ Uint32Array.from([ + 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000, +]); +// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range +// inputs currently fall through to the group-4 branch. +function ripemd_f(group: number, x: number, y: number, z: number): number { + if (group === 0) return x ^ y ^ z; + if (group === 1) return (x & y) | (~x & z); + if (group === 2) return (x | ~y) ^ z; + if (group === 3) return (x & z) | (y & ~z); + return x ^ (y | ~z); +} +// Reusable 16-word RIPEMD-160 message block buffer. +const BUF_160 = /* @__PURE__ */ new Uint32Array(16); +/** + * Internal RIPEMD-160 legacy hash class. + * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification. + */ +export class _RIPEMD160 extends HashMD<_RIPEMD160> { + private h0 = 0x67452301 | 0; + private h1 = 0xefcdab89 | 0; + private h2 = 0x98badcfe | 0; + private h3 = 0x10325476 | 0; + private h4 = 0xc3d2e1f0 | 0; + + constructor() { + super(64, 20, 8, true); + } + protected get(): [number, number, number, number, number] { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + protected process(view: DataView, offset: number): void { + for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true); + // prettier-ignore + let al = this.h0 | 0, ar = al, + bl = this.h1 | 0, br = bl, + cl = this.h2 | 0, cr = cl, + dl = this.h3 | 0, dr = dl, + el = this.h4 | 0, er = el; + + // Instead of iterating 0 to 80, we split it into 5 groups + // And use the groups in constants, functions, etc. Much simpler + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore + const rl = idxL[group], rr = idxR[group]; // prettier-ignore + const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore + for (let i = 0; i < 16; i++) { + const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore + } + // 2 loops are 10% faster + for (let i = 0; i < 16; i++) { + const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore + } + } + // Add the compressed chunk to the current hash value + // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order. + this.set( + (this.h1 + cl + dr) | 0, + (this.h2 + dl + er) | 0, + (this.h3 + el + ar) | 0, + (this.h4 + al + br) | 0, + (this.h0 + bl + cr) | 0 + ); + } + protected roundClean(): void { + clean(BUF_160); + } + destroy(): void { + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0); + } +} + +/** + * RIPEMD-160 - a legacy hash function from 1990s. + * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point + * at the base RIPEMD-160 references. + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html} + * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf} + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with RIPEMD-160. + * ```ts + * ripemd160(new Uint8Array([97, 98, 99])); + * ``` + */ +export const ripemd160: TRet = /* @__PURE__ */ createHasher(() => new _RIPEMD160()); diff --git a/node_modules/@noble/hashes/src/pbkdf2.ts b/node_modules/@noble/hashes/src/pbkdf2.ts new file mode 100644 index 0000000..ea7cda6 --- /dev/null +++ b/node_modules/@noble/hashes/src/pbkdf2.ts @@ -0,0 +1,175 @@ +/** + * PBKDF (RFC 2898). Can be used to create a key from password and salt. + * @module + */ +import { hmac } from './hmac.ts'; +// prettier-ignore +import { + ahash, anumber, + asyncLoop, checkOpts, clean, createView, kdfInputToBytes, + type CHash, + type Hash, + type KDFInput, + type TArg, + type TRet +} from './utils.ts'; + +/** + * PBKDF2 options: + * * c: iterations, should probably be higher than 100_000 + * * dkLen: desired length of derived key in bytes, must be `>= 1` per RFC 8018 §5.2 + * * asyncTick: max time in ms for which async function can block execution + */ +export type Pbkdf2Opt = { + /** Iteration count. Higher values increase CPU cost. */ + c: number; + /** Desired derived key length in bytes, must be `>= 1` per RFC 8018 §5.2. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variant. */ + asyncTick?: number; +}; +// Common start and end for sync/async functions +function pbkdf2Init( + hash: TArg, + _password: TArg, + _salt: TArg, + _opts: TArg +) { + ahash(hash); + const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts; + anumber(c, 'c'); + anumber(dkLen, 'dkLen'); + anumber(asyncTick, 'asyncTick'); + if (c < 1) throw new Error('iterations (c) must be >= 1'); + // RFC 8018 §5.2 defines `dkLen` as "a positive integer". + if (dkLen < 1) throw new Error('"dkLen" must be >= 1'); + // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen` + // before allocating the destination buffer. + if (dkLen > (2 ** 32 - 1) * hash.outputLen) throw new Error('derived key too long'); + const password = kdfInputToBytes(_password, 'password'); + const salt = kdfInputToBytes(_salt, 'salt'); + // DK = PBKDF2(PRF, Password, Salt, c, dkLen); + const DK = new Uint8Array(dkLen); + // U1 = PRF(Password, Salt + INT_32_BE(i)) + const PRF = hmac.create(hash, password); + // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i). + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} + +function pbkdf2Output>( + PRF: TArg>, + PRFSalt: TArg>, + DK: TArg, + prfW: TArg | undefined>, + u: TArg +): TRet { + // Shared sync/async cleanup point: wipe transient PRF state + // while preserving the derived key buffer. + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) prfW.destroy(); + clean(u); + return DK as TRet; +} + +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2 } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export function pbkdf2( + hash: TArg, + password: TArg, + salt: TArg, + opts: TArg +): TRet { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + // The last Ti view can be shorter than hLen, which applies + // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies. + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +/** + * PBKDF2-HMAC: RFC 8018 key derivation function. Async version. + * @param hash - hash function that would be used e.g. sha256 + * @param password - password from which a derived key is generated; + * JS string inputs are UTF-8 encoded first + * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local + * scheduler-yield knob for this JS wrapper, not part of RFC 8018. + * See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error} + * @example + * PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 }); + * ``` + */ +export async function pbkdf2Async( + hash: TArg, + password: TArg, + salt: TArg, + opts: TArg +): Promise> { + const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts); + let prfW: any; // Working copy + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + // DK = T1 + T2 + ⋯ + Tdklen/hlen + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + // Ti = F(Password, Salt, c, i) + // The last Ti view can be shorter than hLen, which applies + // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies. + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc + // U1 = PRF(Password, Salt + INT_32_BE(i)) + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + await asyncLoop(c - 1, asyncTick, () => { + // Uc = PRF(Password, Uc−1) + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i]; + }); + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} diff --git a/node_modules/@noble/hashes/src/scrypt.ts b/node_modules/@noble/hashes/src/scrypt.ts new file mode 100644 index 0000000..a68c890 --- /dev/null +++ b/node_modules/@noble/hashes/src/scrypt.ts @@ -0,0 +1,315 @@ +/** + * RFC 7914 Scrypt KDF. Can be used to create a key from password and salt. + * @module + */ +import { pbkdf2 } from './pbkdf2.ts'; +import { sha256 } from './sha2.ts'; +// prettier-ignore +import { + anumber, asyncLoop, + checkOpts, clean, + rotl, + swap32IfBE, + u32, + type KDFInput, + type TArg, + type TRet +} from './utils.ts'; + +// The main Scrypt loop: uses Salsa extensively. +// Six versions of the function were tried, this is the fastest one. +// RFC 7914 §3 / §4 step 2 applies Salsa20/8 to one 16-word (64-byte) block +// after xor'ing two such blocks. +// The local `y*` snapshot keeps the xor input stable even when `out` aliases `prev` or `input`. +// prettier-ignore +function XorAndSalsa( + prev: TArg, + pi: number, + input: TArg, + ii: number, + out: TArg, + oi: number +) { + // Based on https://cr.yp.to/salsa20.html and RFC 7914's Salsa20/8 core. + // Xor blocks + let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++]; + let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++]; + let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++]; + let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++]; + let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++]; + let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++]; + let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++]; + let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++]; + // Save state to temporary variables (salsa) + 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; + // Main loop (salsa) + for (let i = 0; i < 8; i += 2) { + x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9); + x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18); + x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9); + x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18); + x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9); + x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18); + x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9); + x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18); + x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9); + x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18); + x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9); + x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18); + x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9); + x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18); + x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9); + x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18); + } + // Write output (salsa) + out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0; + out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0; + out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0; + out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0; + out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0; + out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0; + out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0; + out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0; +} + +function BlockMix( + input: TArg, + ii: number, + out: TArg, + oi: number, + r: number +) { + // The block B is `r` 128-byte chunks, i.e. `2r` 16-word (64-byte) Salsa blocks. + let head = oi + 0; + let tail = oi + 16 * r; + for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1] + for (let i = 0; i < r; i++, head += 16, ii += 16) { + // RFC 7914 §4 step 3 outputs `Y[0], Y[2], ...` first, then `Y[1], Y[3], ...`; + // `head` and `tail` lay out those even/odd halves in place. + XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1]) + if (i > 0) tail += 16; // First iteration overwrites tmp value in tail + // tail[i] = Salsa(blockIn[2*i+1] ^ head[i]) + XorAndSalsa(out, head, input, (ii += 16), out, tail); + } +} + +/** + * Scrypt options: + * - `N` is cpu/mem work factor (power of 2 e.g. `2**18`) + * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance + * - `p` is parallelization factor (1 is common) + * - `dkLen` is output key length in bytes e.g. 32, and must be `>= 1` per RFC 7914 §2. + * - `asyncTick` - (default: 10) max time in ms for which async function can block execution + * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt + * - `onProgress` - callback function that would be executed for progress report + */ +export type ScryptOpts = { + /** CPU and memory work factor. Must be a power of two. */ + N: number; + /** Block size parameter. */ + r: number; + /** Parallelization factor. */ + p: number; + /** Desired derived key length in bytes, must be `>= 1` per RFC 7914 §2. */ + dkLen?: number; + /** Max scheduler block time in milliseconds for the async variant. */ + asyncTick?: number; + /** Maximum temporary memory budget in bytes. */ + maxmem?: number; + /** + * Optional progress callback invoked during long-running derivations. + * param progress - completion fraction in the `0..1` range + */ + onProgress?: (progress: number) => void; +}; + +// Common prologue and epilogue for sync/async functions +function scryptInit(password: TArg, salt: TArg, _opts?: TArg) { + // Maxmem - 1GB+1KB by default + const opts = checkOpts( + { + dkLen: 32, + asyncTick: 10, + maxmem: 1024 ** 3 + 1024, + }, + _opts + ); + const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts; + anumber(N, 'N'); + anumber(r, 'r'); + anumber(p, 'p'); + anumber(dkLen, 'dkLen'); + anumber(asyncTick, 'asyncTick'); + anumber(maxmem, 'maxmem'); + if (onProgress !== undefined && typeof onProgress !== 'function') + throw new Error('progressCb must be a function'); + const blockSize = 128 * r; + const blockSize32 = blockSize / 4; + + // Max N is 2^32 (Integrify is 32-bit). + // Real limit can be 2^22: some JS engines limit Uint8Array to 4GB. + // Spec check `N >= 2^(blockSize / 8)` is not done for compat with popular libs, + // which used incorrect r: 1, p: 8. Also, the check seems to be a spec error: + // https://www.rfc-editor.org/errata_search.php?rfc=7914 + const pow32 = Math.pow(2, 32); + if (N <= 1 || (N & (N - 1)) !== 0 || N > pow32) + throw new Error('"N" expected a power of 2, and 2^1 <= N <= 2^32'); + if (p < 1 || p > ((pow32 - 1) * 32) / blockSize) + throw new Error('"p" expected integer 1..((2^32 - 1) * 32) / (128 * r)'); + // RFC 7914 §2 defines `dkLen` as a positive integer. + if (dkLen < 1 || dkLen > (pow32 - 1) * 32) + throw new Error('"dkLen" expected integer 1..(2^32 - 1) * 32'); + // Include the shared `tmp` scratch block so `maxmem` matches noble's actual temporary allocation. + // Node requires more headroom here, so this accounting is intentionally noble-specific. + const memUsed = blockSize * (N + p + 1); + if (memUsed > maxmem) + throw new Error( + '"maxmem" limit was hit: memUsed(128*r*(N+p+1))=' + memUsed + ', maxmem=' + maxmem + ); + // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor) + // Since it has only one iteration there is no reason to use async variant + const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p }); + const B32 = u32(B); + // Re-used between parallel iterations. Array(iterations) of B + const V = u32(new Uint8Array(blockSize * N)); + const tmp = u32(new Uint8Array(blockSize)); + let blockMixCb = () => {}; + if (onProgress) { + const totalBlockMix = 2 * N * p; + // Invoke callback if progress changes from 10.01 to 10.02 + // Allows to draw smooth progress bar on up to 8K screen + const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1); + let blockMixCnt = 0; + blockMixCb = () => { + blockMixCnt++; + if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) + onProgress(blockMixCnt / totalBlockMix); + }; + } + return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick }; +} + +function scryptOutput( + password: TArg, + dkLen: number, + B: TArg, + V: TArg, + tmp: TArg +): TRet { + // Shared final PBKDF2-and-cleanup step: keep the derived key, wipe the scrypt workspace. + const res = pbkdf2(sha256, password, B, { c: 1, dkLen }); + clean(B, V, tmp); + return res; +} + +/** + * Scrypt KDF from RFC 7914. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. See {@link ScryptOpts}. + * @returns Derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt. + * ```ts + * scrypt('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export function scrypt( + password: TArg, + salt: TArg, + opts: TArg +): TRet { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit( + password, + salt, + opts + ); + swap32IfBE(B32); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + for (let i = 0, pos = 0; i < N - 1; i++) { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + } + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + for (let i = 0; i < N; i++) { + // First u32 of the last 64-byte block (u32 is LE) + // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N + // only depends on the low word here because N is a power of two and + // this implementation caps N at 2^32. + // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked + // above; >>> 0 for unsigned, input fits in u32. + const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations + // tmp = B ^ V[j] + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + } + } + swap32IfBE(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} + +/** + * Scrypt KDF from RFC 7914. Async version. See {@link ScryptOpts}. + * @param password - password or key material to derive from; + * JS string inputs are UTF-8 encoded first + * @param salt - unique salt bytes or string; JS string inputs are UTF-8 encoded first + * @param opts - Scrypt cost and memory parameters. `dkLen`, if provided, + * must be `>= 1` per RFC 7914 §2. `asyncTick` is only a local + * scheduler-yield control for this JS wrapper, not part of RFC 7914. + * See {@link ScryptOpts}. + * @returns Promise resolving to derived key bytes. + * @throws If the Scrypt cost, memory, or callback options are invalid. {@link Error} + * @example + * Derive a key with scrypt asynchronously. + * ```ts + * await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 }); + * ``` + */ +export async function scryptAsync( + password: TArg, + salt: TArg, + opts: TArg +): Promise> { + const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit( + password, + salt, + opts + ); + swap32IfBE(B32); + for (let pi = 0; pi < p; pi++) { + const Pi = blockSize32 * pi; + for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i] + let pos = 0; + await asyncLoop(N - 1, asyncTick, () => { + BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]); + blockMixCb(); + }); + BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element + blockMixCb(); + await asyncLoop(N, asyncTick, () => { + // First u32 of the last 64-byte block (u32 is LE) + // RFC 7914 Integerify(X) uses the whole last 64-byte block, but mod N + // only depends on the low word here because N is a power of two and + // this implementation caps N at 2^32. + // & (N - 1) is % N as N is a power of 2, N & (N - 1) = 0 is checked + // above; >>> 0 for unsigned, input fits in u32. + const j = (B32[Pi + blockSize32 - 16] & (N - 1)) >>> 0; // j = Integrify(X) % iterations + // tmp = B ^ V[j] + for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; + BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j]) + blockMixCb(); + }); + } + swap32IfBE(B32); + return scryptOutput(password, dkLen, B, V, tmp); +} diff --git a/node_modules/@noble/hashes/src/sha2.ts b/node_modules/@noble/hashes/src/sha2.ts new file mode 100644 index 0000000..2ff7e65 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha2.ts @@ -0,0 +1,530 @@ +/** + * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256. + * SHA256 is the fastest hash implementable in JS, even faster than Blake3. + * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}. + * @module + */ +import { Chi, HashMD, Maj, SHA224_IV, SHA256_IV, SHA384_IV, SHA512_IV } from './_md.ts'; +import * as u64 from './_u64.ts'; +import { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts'; + +/** + * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits + * of the cube roots of the first 64 primes (2..311). + */ +// prettier-ignore +const SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 +]); + +/** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */ +const SHA256_W = /* @__PURE__ */ new Uint32Array(64); + +/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */ +abstract class SHA2_32B> extends HashMD { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + protected abstract A: number; + protected abstract B: number; + protected abstract C: number; + protected abstract D: number; + protected abstract E: number; + protected abstract F: number; + protected abstract G: number; + protected abstract H: number; + + constructor(outputLen: number) { + super(64, outputLen, 8, false); + } + protected get(): [number, number, number, number, number, number, number, number] { + const { A, B, C, D, E, F, G, H } = this; + return [A, B, C, D, E, F, G, H]; + } + // prettier-ignore + protected set( + A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number + ): void { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D | 0; + this.E = E | 0; + this.F = F | 0; + this.G = G | 0; + this.H = H | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3); + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10); + SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0; + } + // Compression function main loop, 64 rounds + let { A, B, C, D, E, F, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = (sigma0 + Maj(A, B, C)) | 0; + H = G; + G = F; + F = E; + E = (D + T1) | 0; + D = C; + C = B; + B = A; + A = (T1 + T2) | 0; + } + // Add the compressed chunk to the current hash value + A = (A + this.A) | 0; + B = (B + this.B) | 0; + C = (C + this.C) | 0; + D = (D + this.D) | 0; + E = (E + this.E) | 0; + F = (F + this.F) | 0; + G = (G + this.G) | 0; + H = (H + this.H) | 0; + this.set(A, B, C, D, E, F, G, H); + } + protected roundClean(): void { + clean(SHA256_W); + } + destroy(): void { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +} + +/** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */ +export class _SHA256 extends SHA2_32B<_SHA256> { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + protected A: number = SHA256_IV[0] | 0; + protected B: number = SHA256_IV[1] | 0; + protected C: number = SHA256_IV[2] | 0; + protected D: number = SHA256_IV[3] | 0; + protected E: number = SHA256_IV[4] | 0; + protected F: number = SHA256_IV[5] | 0; + protected G: number = SHA256_IV[6] | 0; + protected H: number = SHA256_IV[7] | 0; + constructor() { + super(32); + } +} + +/** Internal SHA-224 hash class grounded in RFC 6234 §6.2 and §8.5. */ +export class _SHA224 extends SHA2_32B<_SHA224> { + protected A: number = SHA224_IV[0] | 0; + protected B: number = SHA224_IV[1] | 0; + protected C: number = SHA224_IV[2] | 0; + protected D: number = SHA224_IV[3] | 0; + protected E: number = SHA224_IV[4] | 0; + protected F: number = SHA224_IV[5] | 0; + protected G: number = SHA224_IV[6] | 0; + protected H: number = SHA224_IV[7] | 0; + constructor() { + super(28); + } +} + +// SHA2-512 is slower than sha256 in js because u64 operations are slow. + +// SHA-384 / SHA-512 round constants from RFC 6234 §5.2: +// 80 full 64-bit words split into high/low halves. +// prettier-ignore +const K512 = /* @__PURE__ */ (() => u64.split([ + '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc', + '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118', + '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2', + '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694', + '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65', + '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5', + '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4', + '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70', + '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df', + '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b', + '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30', + '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8', + '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8', + '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3', + '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec', + '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b', + '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178', + '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b', + '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c', + '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817' +].map(n => BigInt(n))))(); +const SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); +const SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); + +// Reusable high-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words. +const SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +// Reusable low-half schedule buffer for the RFC 6234 §6.4 64-bit `W_t` words. +const SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); + +/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 §6.4. */ +abstract class SHA2_64B> extends HashMD { + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + // h -- high 32 bits, l -- low 32 bits + protected abstract Ah: number; + protected abstract Al: number; + protected abstract Bh: number; + protected abstract Bl: number; + protected abstract Ch: number; + protected abstract Cl: number; + protected abstract Dh: number; + protected abstract Dl: number; + protected abstract Eh: number; + protected abstract El: number; + protected abstract Fh: number; + protected abstract Fl: number; + protected abstract Gh: number; + protected abstract Gl: number; + protected abstract Hh: number; + protected abstract Hl: number; + + constructor(outputLen: number) { + super(128, outputLen, 16, false); + } + // prettier-ignore + protected get(): [ + number, number, number, number, number, number, number, number, + number, number, number, number, number, number, number, number + ] { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + protected set( + Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number, + Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number + ): void { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + protected process(view: DataView, offset: number): void { + // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32((offset += 4)); + } + for (let i = 16; i < 80; i++) { + // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7) + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7); + const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7); + // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6) + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6); + const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6); + // SHA512_W[i] = s0 + s1 + SHA512_W[i - 7] + SHA512_W[i - 16]; + const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + // Compression function main loop, 80 rounds + for (let i = 0; i < 80; i++) { + // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41) + const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41); + const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41); + //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0; + const CHIh = (Eh & Fh) ^ (~Eh & Gh); + const CHIl = (El & Fl) ^ (~El & Gl); + // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i] + // prettier-ignore + const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39) + const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39); + const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39); + const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch); + const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl); + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = u64.add3L(T1l, sigma0l, MAJl); + Ah = u64.add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + // Add the compressed chunk to the current hash value + ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + protected roundClean(): void { + clean(SHA512_W_H, SHA512_W_L); + } + destroy(): void { + // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves + // update()/digest() callable on reused instances. + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + +/** Internal SHA-512 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export class _SHA512 extends SHA2_64B<_SHA512> { + protected Ah: number = SHA512_IV[0] | 0; + protected Al: number = SHA512_IV[1] | 0; + protected Bh: number = SHA512_IV[2] | 0; + protected Bl: number = SHA512_IV[3] | 0; + protected Ch: number = SHA512_IV[4] | 0; + protected Cl: number = SHA512_IV[5] | 0; + protected Dh: number = SHA512_IV[6] | 0; + protected Dl: number = SHA512_IV[7] | 0; + protected Eh: number = SHA512_IV[8] | 0; + protected El: number = SHA512_IV[9] | 0; + protected Fh: number = SHA512_IV[10] | 0; + protected Fl: number = SHA512_IV[11] | 0; + protected Gh: number = SHA512_IV[12] | 0; + protected Gl: number = SHA512_IV[13] | 0; + protected Hh: number = SHA512_IV[14] | 0; + protected Hl: number = SHA512_IV[15] | 0; + + constructor() { + super(64); + } +} + +/** Internal SHA-384 hash class grounded in RFC 6234 §6.3 and §6.4. */ +export class _SHA384 extends SHA2_64B<_SHA384> { + protected Ah: number = SHA384_IV[0] | 0; + protected Al: number = SHA384_IV[1] | 0; + protected Bh: number = SHA384_IV[2] | 0; + protected Bl: number = SHA384_IV[3] | 0; + protected Ch: number = SHA384_IV[4] | 0; + protected Cl: number = SHA384_IV[5] | 0; + protected Dh: number = SHA384_IV[6] | 0; + protected Dl: number = SHA384_IV[7] | 0; + protected Eh: number = SHA384_IV[8] | 0; + protected El: number = SHA384_IV[9] | 0; + protected Fh: number = SHA384_IV[10] | 0; + protected Fl: number = SHA384_IV[11] | 0; + protected Gh: number = SHA384_IV[12] | 0; + protected Gl: number = SHA384_IV[13] | 0; + protected Hh: number = SHA384_IV[14] | 0; + protected Hl: number = SHA384_IV[15] | 0; + + constructor() { + super(48); + } +} + +/** + * Truncated SHA512/256 and SHA512/224. + * SHA512_IV is XORed with 0xa5a5a5a5a5a5a5a5, then used as "intermediary" IV of SHA512/t. + * Then t hashes string to produce result IV. + * See the repo-side derivation recipe in `test/misc/sha2-gen-iv.js`. + * These IV literals are checked against that script rather than a dedicated + * local RFC section. + */ + +/** SHA-512/224 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and + * stored as sixteen big-endian 32-bit halves. */ +const T224_IV = /* @__PURE__ */ Uint32Array.from([ + 0x8c3d37c8, 0x19544da2, 0x73e19966, 0x89dcd4d6, 0x1dfab7ae, 0x32ff9c82, 0x679dd514, 0x582f9fcf, + 0x0f6d2b69, 0x7bd44da8, 0x77e36f73, 0x04c48942, 0x3f9d85a8, 0x6a1d36c8, 0x1112e6ad, 0x91d692a1, +]); + +/** SHA-512/256 IV derived by the SHA-512/t recipe in `test/misc/sha2-gen-iv.js` and + * stored as sixteen big-endian 32-bit halves. */ +const T256_IV = /* @__PURE__ */ Uint32Array.from([ + 0x22312194, 0xfc2bf72c, 0x9f555fa3, 0xc84c64c2, 0x2393b86b, 0x6f53b151, 0x96387719, 0x5940eabd, + 0x96283ee2, 0xa88effe3, 0xbe5e1e25, 0x53863992, 0x2b0199fc, 0x2c85b8aa, 0x0eb72ddc, 0x81c52ca2, +]); + +/** Internal SHA-512/224 hash class using the derived `T224_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export class _SHA512_224 extends SHA2_64B<_SHA512_224> { + protected Ah: number = T224_IV[0] | 0; + protected Al: number = T224_IV[1] | 0; + protected Bh: number = T224_IV[2] | 0; + protected Bl: number = T224_IV[3] | 0; + protected Ch: number = T224_IV[4] | 0; + protected Cl: number = T224_IV[5] | 0; + protected Dh: number = T224_IV[6] | 0; + protected Dl: number = T224_IV[7] | 0; + protected Eh: number = T224_IV[8] | 0; + protected El: number = T224_IV[9] | 0; + protected Fh: number = T224_IV[10] | 0; + protected Fl: number = T224_IV[11] | 0; + protected Gh: number = T224_IV[12] | 0; + protected Gl: number = T224_IV[13] | 0; + protected Hh: number = T224_IV[14] | 0; + protected Hl: number = T224_IV[15] | 0; + + constructor() { + super(28); + } +} + +/** Internal SHA-512/256 hash class using the derived `T256_IV` and the shared + * RFC 6234 §6.4 compression engine. */ +export class _SHA512_256 extends SHA2_64B<_SHA512_256> { + protected Ah: number = T256_IV[0] | 0; + protected Al: number = T256_IV[1] | 0; + protected Bh: number = T256_IV[2] | 0; + protected Bl: number = T256_IV[3] | 0; + protected Ch: number = T256_IV[4] | 0; + protected Cl: number = T256_IV[5] | 0; + protected Dh: number = T256_IV[6] | 0; + protected Dl: number = T256_IV[7] | 0; + protected Eh: number = T256_IV[8] | 0; + protected El: number = T256_IV[9] | 0; + protected Fh: number = T256_IV[10] | 0; + protected Fl: number = T256_IV[11] | 0; + protected Gh: number = T256_IV[12] | 0; + protected Gl: number = T256_IV[13] | 0; + protected Hh: number = T256_IV[14] | 0; + protected Hl: number = T256_IV[15] | 0; + + constructor() { + super(32); + } +} + +/** + * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info: + * + * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack. + * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025. + * - Each sha256 hash is executing 2^18 bit operations. + * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-256. + * ```ts + * sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha256: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(0x01) +); +/** + * SHA2-224 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-224. + * ```ts + * sha224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha224: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA224(), + /* @__PURE__ */ oidNist(0x04) +); + +/** + * SHA2-512 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512. + * ```ts + * sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA512(), + /* @__PURE__ */ oidNist(0x03) +); +/** + * SHA2-384 hash function from RFC 4634. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-384. + * ```ts + * sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha384: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA384(), + /* @__PURE__ */ oidNist(0x02) +); + +/** + * SHA2-512/256 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/256. + * ```ts + * sha512_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512_256: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA512_256(), + /* @__PURE__ */ oidNist(0x06) +); +/** + * SHA2-512/224 "truncated" hash function, with improved resistance to length extension attacks. + * See the paper on {@link https://eprint.iacr.org/2010/548.pdf | truncated SHA512}. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA2-512/224. + * ```ts + * sha512_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512_224: TRet> = /* @__PURE__ */ createHasher( + () => new _SHA512_224(), + /* @__PURE__ */ oidNist(0x05) +); diff --git a/node_modules/@noble/hashes/src/sha3-addons.ts b/node_modules/@noble/hashes/src/sha3-addons.ts new file mode 100644 index 0000000..a50a2ac --- /dev/null +++ b/node_modules/@noble/hashes/src/sha3-addons.ts @@ -0,0 +1,983 @@ +/** + * SHA3 (keccak) addons. + * + * * cSHAKE, KMAC, TupleHash, ParallelHash + XOF variants from + * {@link https://csrc.nist.gov/pubs/sp/800/185/final | NIST SP 800-185} + * * KangarooTwelve 🦘 and TurboSHAKE - reduced-round keccak from + * {@link https://datatracker.ietf.org/doc/rfc9861/ | RFC 9861} + * * KeccakPRG: Pseudo-random generator based on Keccak + * ({@link https://keccak.team/files/CSF-0.1.pdf | pdf}) + * @module + */ +import { Keccak, type ShakeOpts } from './sha3.ts'; +import { + abytes, + aexists, + anumber, + type CHash, + type CHashXOF, + clean, + copyBytes, + createHasher, + type Hash, + type HashXOF, + type KDFInput, + kdfInputToBytes, + type PRG, + type TArg, + type TRet, + u32, +} from './utils.ts'; + +// cSHAKE && KMAC (NIST SP800-185) +const _8n = /* @__PURE__ */ BigInt(8); +const _ffn = /* @__PURE__ */ BigInt(0xff); + +// It is safe to use bigints here, since they used only for length encoding (not actual data). +// We use bigints in sha256 for lengths too. +// Callers are still expected to supply SP 800-185-valid lengths +// (`0 <= x < 2^2040`); this helper does not enforce that bound. +function leftEncode(n: number | bigint): TRet { + n = BigInt(n); + const res = [Number(n & _ffn)]; + n >>= _8n; + for (; n > 0; n >>= _8n) res.unshift(Number(n & _ffn)); + res.unshift(res.length); + return new Uint8Array(res) as TRet; +} + +// Same caller contract as `leftEncode(...)`: lengths must already satisfy SP 800-185 §2.3.1. +function rightEncode(n: number | bigint): TRet { + n = BigInt(n); + const res = [Number(n & _ffn)]; + n >>= _8n; + for (; n > 0; n >>= _8n) res.unshift(Number(n & _ffn)); + res.push(res.length); + return new Uint8Array(res) as TRet; +} + +// `dkLen` validation is deferred to the downstream Keccak constructor. +function chooseLen(opts: ShakeOpts, outputLen: number): number { + return opts.dkLen === undefined ? outputLen : opts.dkLen; +} + +const abytesOrZero = (buf?: TArg, title = '') => { + if (buf === undefined) return EMPTY_BUFFER; + abytes(buf, undefined, title); + return buf; +}; +// NOTE: second modulo is necessary since we don't need to add padding if the +// current element takes a whole block. +// Callers only pass the fixed positive Keccak rates here (`168` or `136`); +// `block <= 0` is not validated locally. +const getPadding = (len: number, block: number) => new Uint8Array((block - (len % block)) % block); +/** Options for cSHAKE and related SP 800-185 functions. */ +export type cShakeOpts = ShakeOpts & { + /** Optional personalization string mixed into domain separation. */ + personalization?: Uint8Array; + /** + * Optional NIST function-name string used for domain separation. + * SP 800-185 reserves this for standardized function names; applications + * should generally stick to `personalization`. + */ + NISTfn?: KDFInput; +}; + +// Personalization +function cshakePers(hash: TArg, opts: TArg = {}): TRet { + const h = hash as unknown as Keccak; + if (!opts || (opts.personalization === undefined && opts.NISTfn === undefined)) + return h as TRet; + // Encode and pad inplace to avoid unneccesary memory copies/slices so we + // don't need to zero them later. + // bytepad(encode_string(N) || encode_string(S), rate), where `rate` is the + // current cSHAKE/KMAC/TupleHash/ParallelHash block length. + const blockLenBytes = leftEncode(h.blockLen); + const fn = opts.NISTfn === undefined ? EMPTY_BUFFER : kdfInputToBytes(opts.NISTfn); + const fnLen = leftEncode(_8n * BigInt(fn.length)); // length in bits + const pers = abytesOrZero(opts.personalization, 'personalization'); + const persLen = leftEncode(_8n * BigInt(pers.length)); // length in bits + if (!fn.length && !pers.length) return h as TRet; + // SP 800-185 cSHAKE appends `00` instead of SHAKE's `1111`; in this Keccak implementation + // that changes the delimited suffix byte from `0x1f` to `0x04` once N or S is non-empty. + h.suffix = 0x04; + h.update(blockLenBytes).update(fnLen).update(fn).update(persLen).update(pers); + let totalLen = blockLenBytes.length + fnLen.length + fn.length + persLen.length + pers.length; + h.update(getPadding(totalLen, h.blockLen)); + return h as TRet; +} + +const gencShake = ( + suffix: number, + blockLen: number, + outputLen: number +): TRet> => + createHasher( + (opts: TArg = {}) => + cshakePers( + new Keccak(blockLen, suffix, chooseLen(opts, outputLen), true) as unknown as TArg, + opts + ) as Keccak + ); + +/** TupleHash callable interface. */ +export type ITupleHash = { + /** + * Hashes an ordered tuple of byte arrays. + * @param messages - Ordered byte-array tuple to hash. + * @param opts - TupleHash output and personalization options. See {@link cShakeOpts}. + * @returns Digest bytes. + */ + (messages: TArg, opts?: TArg): TRet; + /** + * Creates an incremental TupleHash state. + * @param opts - TupleHash output and personalization options. See {@link cShakeOpts}. + * @returns Stateful TupleHash instance. + */ + create(opts?: cShakeOpts): _TupleHash; +}; +/** + * 128-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE128. Defaults to 16 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE128. + * ```ts + * cshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const cshake128: TRet> = /* @__PURE__ */ gencShake( + 0x1f, + 168, + 16 +); +/** + * 256-bit NIST cSHAKE XOF. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and NIST function-name + * settings. When both `NISTfn` and `personalization` are empty, + * SP 800-185 defines this as plain SHAKE256. Defaults to 32 output bytes + * when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with cSHAKE256. + * ```ts + * cshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const cshake256: TRet> = /* @__PURE__ */ gencShake( + 0x1f, + 136, + 32 +); + +/** + * Internal KMAC class. + * SP 800-185 §8.4.1 still recommends keys at least as long as the target + * security strength. + */ +export class _KMAC extends Keccak implements HashXOF<_KMAC> { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + key: TArg, + opts: TArg = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + // Preload T = bytepad(encode_string("KMAC") || encode_string(S), rate); later updates append + // newX = bytepad(encode_string(K), rate) || X and `finish()` appends right_encode(L or 0). + cshakePers(this as unknown as TArg, { + NISTfn: 'KMAC', + personalization: opts.personalization, + }); + abytes(key, undefined, 'key'); + // 1. newX = bytepad(encode_string(K), rate) || X || right_encode(L), + // with `rate = this.blockLen`. + const blockLenBytes = leftEncode(this.blockLen); + const keyLen = leftEncode(_8n * BigInt(key.length)); + this.update(blockLenBytes).update(keyLen).update(key); + const totalLen = blockLenBytes.length + keyLen.length + key.length; + this.update(getPadding(totalLen, this.blockLen)); + } + protected finish(): void { + // SP 800-185 uses right_encode(L) for fixed-length KMAC and right_encode(0) for KMACXOF. + // outputLen in bits + if (!this.finished) this.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to?: _KMAC): _KMAC { + // Create new instance without calling constructor since the key + // is already in state and we don't know it. + // Force "to" to be instance of KMAC instead of Sha3. + if (!to) { + to = Object.create(Object.getPrototypeOf(this), {}) as _KMAC; + to.state = this.state.slice(); + to.blockLen = this.blockLen; + to.state32 = u32(to.state); + } + return super._cloneInto(to) as _KMAC; + } + clone(): _KMAC { + return this._cloneInto(); + } +} + +function genKmac(blockLen: number, outputLen: number, xof = false): TRet { + // One-shot XOF wrappers still finalize via `.digest()` because `_KMAC` + // already bakes the requested output length into the state. + const kmac = ( + key: TArg, + message: TArg, + opts?: TArg + ): TRet => kmac.create(key, opts).update(message).digest(); + kmac.create = (key: TArg, opts: TArg = {}) => + new _KMAC(blockLen, chooseLen(opts, outputLen), xof, key, opts); + return kmac as TRet; +} + +/** KMAC callable interface. */ +export type IKMAC = { + /** + * Computes a keyed KMAC digest for one message. + * @param key - Secret key bytes. + * @param message - Message bytes to authenticate. + * @param opts - KMAC output and personalization options. See {@link KangarooOpts}. + * @returns Authentication tag bytes. + */ + (key: TArg, message: TArg, opts?: TArg): TRet; + /** + * Creates an incremental KMAC state. + * @param key - Secret key bytes. + * @param opts - KMAC output and personalization options. See {@link cShakeOpts}. + * @returns Stateful KMAC instance. + */ + create(key: TArg, opts?: TArg): _KMAC; +}; +/** + * 128-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128. + * ```ts + * kmac128(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export const kmac128: TRet = /* @__PURE__ */ genKmac(168, 16); +/** + * 256-bit Keccak MAC. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256. + * ```ts + * kmac256(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +export const kmac256: TRet = /* @__PURE__ */ genKmac(136, 32); +/** + * 128-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC128 XOF output. + * ```ts + * kmac128xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 32 }); + * ``` + */ +export const kmac128xof: TRet = /* @__PURE__ */ genKmac(168, 16, true); +/** + * 256-bit Keccak-MAC XOF. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with KMAC256 XOF output. + * ```ts + * kmac256xof(new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]), { dkLen: 64 }); + * ``` + */ +export const kmac256xof: TRet = /* @__PURE__ */ genKmac(136, 32, true); + +/** + * Internal TupleHash class for byte-array tuple elements. + * This implementation relies on SP 800-185's byte-oriented encoding form + * rather than arbitrary bit strings. + */ +export class _TupleHash extends Keccak implements HashXOF<_TupleHash> { + constructor( + blockLen: number, + outputLen: number, + enableXOF: boolean, + opts: TArg = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this as unknown as TArg, { + NISTfn: 'TupleHash', + personalization: opts.personalization, + }); + // Change update after cshake processed + this.update = (data: TArg) => { + abytes(data); + // SP 800-185 encodes each tuple element as + // encode_string(X[i]) = left_encode(len(X[i])) || X[i]. + super.update(leftEncode(_8n * BigInt(data.length))); + super.update(data); + return this; + }; + } + protected finish(): void { + // SP 800-185 uses right_encode(L) for fixed-length TupleHash + // and right_encode(0) for TupleHashXOF. + if (!this.finished) + // outputLen in bits + super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to?: _TupleHash): _TupleHash { + to ||= new _TupleHash(this.blockLen, this.outputLen, this.enableXOF); + return super._cloneInto(to) as _TupleHash; + } + clone(): _TupleHash { + return this._cloneInto(); + } +} + +function genTuple(blockLen: number, outputLen: number, xof = false): TRet { + // One-shot XOF wrappers still use `.digest()` because `_TupleHash` stores + // the requested output length in the state itself. + const tuple = (messages: TArg, opts?: TArg): TRet => { + const h = tuple.create(opts); + if (!Array.isArray(messages)) throw new Error('expected array of messages'); + for (const msg of messages) h.update(msg); + return h.digest(); + }; + tuple.create = (opts: TArg = {}) => + new _TupleHash(blockLen, chooseLen(opts, outputLen), xof, opts); + return tuple as TRet; +} + +/** + * 128-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128. + * ```ts + * tuplehash128([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export const tuplehash128: TRet = /* @__PURE__ */ genTuple(168, 16); +/** + * 256-bit TupleHASH. `tuple(['ab', 'cd']) != tuple(['a', 'bcd'])`. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256. + * ```ts + * tuplehash256([new Uint8Array([1]), new Uint8Array([2])]); + * ``` + */ +export const tuplehash256: TRet = /* @__PURE__ */ genTuple(136, 32); +/** + * 128-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 16 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash128 XOF output. + * ```ts + * tuplehash128xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 32 }); + * ``` + */ +export const tuplehash128xof: TRet = /* @__PURE__ */ genTuple(168, 16, true); +/** + * 256-bit TupleHASH XOF. + * @param messages - ordered byte-array tuple + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link cShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a tuple of byte arrays with TupleHash256 XOF output. + * ```ts + * tuplehash256xof([new Uint8Array([1]), new Uint8Array([2])], { dkLen: 64 }); + * ``` + */ +export const tuplehash256xof: TRet = /* @__PURE__ */ genTuple(136, 32, true); + +// Same as K12/M14, but without speedup for inputs less 8kb, +// reduced number of rounds and simpler. +type ParallelOpts = KangarooOpts & { blockLen?: number }; + +/** Internal Parallel Keccak Hash class. */ +export class _ParallelHash extends Keccak implements HashXOF<_ParallelHash> { + private leafHash?: Hash; + protected leafCons: () => Hash; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + private chunkLen: number; + constructor( + blockLen: number, + outputLen: number, + leafCons: () => Hash, + enableXOF: boolean, + opts: TArg = {} + ) { + super(blockLen, 0x1f, outputLen, enableXOF); + cshakePers(this as unknown as TArg, { + NISTfn: 'ParallelHash', + personalization: opts.personalization, + }); + this.leafCons = leafCons; + let { blockLen: B = 8 } = opts; + anumber(B); + // blockLen=0 makes take=0 in update(), so pos never advances and the hash hangs. + if (B < 1) throw new Error('"blockLen" must be >= 1, got ' + B); + this.chunkLen = B; + // SP 800-185 initializes z = left_encode(B); each completed chunk appends + // one fixed-size cSHAKE leaf digest before finish() adds right_encode(n) + // and right_encode(L or 0). + super.update(leftEncode(B)); + // Change update after cshake processed + this.update = (data: TArg) => { + abytes(data); + const { chunkLen, leafCons } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen || !this.leafHash) { + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + this.leafHash = leafCons(); + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + this.leafHash.update(data.subarray(pos, pos + take)); + this.chunkPos += take; + pos += take; + } + return this; + }; + } + protected finish(): void { + if (this.finished) return; + if (this.leafHash) { + super.update(this.leafHash.digest()); + this.chunksDone++; + } + // SP 800-185 finishes ParallelHash as + // z || right_encode(n) || right_encode(L); XOF mode replaces + // right_encode(L) with right_encode(0). + super.update(rightEncode(this.chunksDone)); + // outputLen in bits + super.update(rightEncode(this.enableXOF ? 0 : _8n * BigInt(this.outputLen))); + super.finish(); + } + _cloneInto(to?: _ParallelHash): _ParallelHash { + to ||= new _ParallelHash(this.blockLen, this.outputLen, this.leafCons, this.enableXOF); + to.leafCons = this.leafCons; + // Reused destinations can carry a stale partial leaf + // when the source is still on the root sponge. + if (this.leafHash) to.leafHash = this.leafHash._cloneInto(to.leafHash as Keccak); + else if (to.leafHash) { + to.leafHash.destroy(); + to.leafHash = undefined; + } + to.chunkPos = this.chunkPos; + to.chunkLen = this.chunkLen; + to.chunksDone = this.chunksDone; + return super._cloneInto(to) as _ParallelHash; + } + destroy(): void { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + } + clone(): _ParallelHash { + return this._cloneInto(); + } +} + +function genPrl( + blockLen: number, + outputLen: number, + leaf: ReturnType, + xof = false +): TRet> { + const parallel = (message: TArg, opts?: TArg): TRet => + parallel.create(opts).update(message).digest(); + parallel.create = (opts: TArg = {}) => + new _ParallelHash( + blockLen, + chooseLen(opts, outputLen), + // SP 800-185 fixes leaf digests at 256 bits for ParallelHash128 and + // 512 bits for ParallelHash256; only the final cSHAKE output uses the + // caller-selected dkLen. + () => leaf.create({ dkLen: 2 * outputLen }), + xof, + opts + ); + parallel.outputLen = outputLen; + parallel.blockLen = blockLen; + parallel.canXOF = xof; + return parallel as TRet>; +} + +/** + * 128-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128. + * ```ts + * parallelhash128(new Uint8Array([1, 2, 3])); + * ``` + */ +export const parallelhash128: TRet> = /* @__PURE__ */ genPrl( + 168, + 16, + cshake128 +); +/** + * 256-bit ParallelHash. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256. + * ```ts + * parallelhash256(new Uint8Array([1, 2, 3])); + * ``` + */ +export const parallelhash256: TRet> = /* @__PURE__ */ genPrl( + 136, + 32, + cshake256 +); +/** + * 128-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 16 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash128 XOF output. + * ```ts + * parallelhash128xof(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const parallelhash128xof: TRet> = /* @__PURE__ */ genPrl( + 168, + 16, + cshake128, + true +); +/** + * 256-bit ParallelHash XOF. In JS, it is not parallel. + * @param msg - message bytes to hash + * @param opts - Optional output, personalization, and chunking settings. + * Defaults to 32 output bytes when `dkLen` is omitted. + * See {@link ParallelOpts}. + * @returns Digest bytes. + * @example + * Hash a message with ParallelHash256 XOF output. + * ```ts + * parallelhash256xof(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const parallelhash256xof: TRet> = /* @__PURE__ */ genPrl( + 136, + 32, + cshake256, + true +); + +/** + * TurboSHAKE options. + * `D` is the domain separation byte; RFC 9861 defines output length `L` + * as a positive integer. + */ +export type TurboshakeOpts = ShakeOpts & { + /** Optional domain separation byte in the `0x01..0x7f` range. */ + D?: number; +}; + +const genTurbo = (blockLen: number, outputLen: number) => + createHasher((opts: TArg = {}) => { + const D = opts.D === undefined ? 0x1f : opts.D; + // RFC 9861 §2.1 fixes the default `D = 0x1f`; §2.2 defines the 12-round + // TurboSHAKE family selected here. + if (!Number.isSafeInteger(D) || D < 0x01 || D > 0x7f) + throw new Error('"D" (domain separation byte) must be 0x01..0x7f, got: ' + D); + const dkLen = opts.dkLen === undefined ? outputLen : opts.dkLen; + // RFC 9861 §§2.1-2.2 define output length L as a positive integer. + if (dkLen < 1) throw new Error('"dkLen" must be >= 1'); + return new Keccak(blockLen, D, dkLen, true, 12); + }); + +/** + * TurboSHAKE 128-bit: reduced 12-round keccak. + * Should've been a simple "shake with 12 rounds", but we got a whole new + * spec about Turbo SHAKE Pro MAX. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 32 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE128. + * ```ts + * turboshake128(new Uint8Array([1, 2, 3]), { dkLen: 32 }); + * ``` + */ +export const turboshake128: TRet> = /* @__PURE__ */ genTurbo( + 168, + 32 +); +/** + * TurboSHAKE 256-bit: reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output-length and domain-separation settings. + * RFC 9861 §2.1 defaults `D` to `0x1f`. Defaults to 64 output bytes when + * `dkLen` is omitted. See {@link TurboshakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with TurboSHAKE256. + * ```ts + * turboshake256(new Uint8Array([1, 2, 3]), { dkLen: 64 }); + * ``` + */ +export const turboshake256: TRet> = /* @__PURE__ */ genTurbo( + 136, + 64 +); + +// Same as NIST rightEncode, but returns `[0]` for the zero string. +// Callers still need to keep `x < 256^255` per RFC 9861 §3.3. +function rightEncodeK12(n: number | bigint): TRet { + n = BigInt(n); + const res: number[] = []; + for (; n > 0; n >>= _8n) res.unshift(Number(n & _ffn)); + res.push(res.length); + return Uint8Array.from(res); +} + +/** K12 options. */ +export type KangarooOpts = { + /** + * Desired digest length in bytes. + * RFC 9861 §3 defines output length `L` as a positive integer. + */ + dkLen?: number; + /** + * Optional personalization string mixed into the sponge state. + * Stateful K12 instances keep an internal copy so caller buffers can be + * wiped independently. + */ + personalization?: Uint8Array; +}; +const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); + +/** Internal K12 hash class. */ +export class _KangarooTwelve extends Keccak implements HashXOF<_KangarooTwelve> { + readonly chunkLen = 8192; + private leafHash?: Keccak; + protected leafLen: number; + private personalization: Uint8Array; + private chunkPos = 0; // Position of current block in chunk + private chunksDone = 0; // How many chunks we already have + constructor( + blockLen: number, + leafLen: number, + outputLen: number, + rounds: number, + opts: TArg + ) { + super(blockLen, 0x07, outputLen, true, rounds); + // RFC 9861 §3 defines output length L as a positive integer. + if (outputLen < 1) throw new Error('"dkLen" must be >= 1'); + this.leafLen = leafLen; + this.personalization = + opts.personalization === undefined + ? EMPTY_BUFFER + : copyBytes(abytes(opts.personalization, undefined, 'personalization')); + } + update(data: TArg): this { + abytes(data); + const { chunkLen, blockLen, leafLen, rounds } = this; + for (let pos = 0, len = data.length; pos < len; ) { + if (this.chunkPos == chunkLen) { + if (this.leafHash) super.update(this.leafHash.digest()); + else { + // RFC 9861 §3.2 switches from SingleNode (`07`) to FinalNode (`06`) + // once S exceeds 8192 bytes and prefixes S_0 with + // `03 00 00 00 00 00 00 00`. + this.suffix = 0x06; // Its safe to change suffix here since its used only in digest() + super.update(Uint8Array.from([3, 0, 0, 0, 0, 0, 0, 0])); + } + // Secondary chunks S_1..S_(n-1) become fixed-length + // CV_i = TurboSHAKE*(S_i, `0B`, 32|64) chaining values. + this.leafHash = new Keccak(blockLen, 0x0b, leafLen, false, rounds); + this.chunksDone++; + this.chunkPos = 0; + } + const take = Math.min(chunkLen - this.chunkPos, len - pos); + const chunk = data.subarray(pos, pos + take); + if (this.leafHash) this.leafHash.update(chunk); + else super.update(chunk); + this.chunkPos += take; + pos += take; + } + return this; + } + protected finish(): void { + if (this.finished) return; + const { personalization } = this; + // RFC 9861 §3.2 forms S = M || C || length_encode(|C|) before any tree hashing logic. + this.update(personalization).update(rightEncodeK12(personalization.length)); + // Leaf hash + if (this.leafHash) { + // Multi-chunk K12 appends + // CV_1..CV_(n-1) || length_encode(n-1) || `FF FF` + // before the final TurboSHAKE call. + super.update(this.leafHash.digest()); + super.update(rightEncodeK12(this.chunksDone)); + super.update(Uint8Array.from([0xff, 0xff])); + } + super.finish.call(this); + } + destroy(): void { + super.destroy.call(this); + if (this.leafHash) this.leafHash.destroy(); + // Personalization is copied on create/clone, so destroy can wipe it + // without touching caller input. + if (this.personalization !== EMPTY_BUFFER) clean(this.personalization); + this.personalization = EMPTY_BUFFER; + } + _cloneInto(to?: _KangarooTwelve): _KangarooTwelve { + const { blockLen, leafLen, leafHash, outputLen, rounds } = this; + const personalization = + this.personalization === EMPTY_BUFFER ? EMPTY_BUFFER : copyBytes(this.personalization); + // Personalization is absorbed only during finish(), so clones need the same pending value. + to ||= new _KangarooTwelve(blockLen, leafLen, outputLen, rounds, { + personalization, + }); + super._cloneInto(to); + // Reused destinations can carry a stale leaf from an older multi-chunk state. + if (leafHash) to.leafHash = leafHash._cloneInto(to.leafHash); + else if (to.leafHash) { + to.leafHash.destroy(); + to.leafHash = undefined; + } + // Snapshot the pending personalization so clone state does not alias caller-owned input. + to.personalization = personalization; + to.leafLen = this.leafLen; + to.chunkPos = this.chunkPos; + to.chunksDone = this.chunksDone; + return to; + } + clone(): _KangarooTwelve { + return this._cloneInto(); + } +} + +/** + * 128-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 32 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-128. + * ```ts + * kt128(new Uint8Array([1, 2, 3])); + * ``` + */ +export const kt128: TRet> = /* @__PURE__ */ createHasher( + (opts: TArg = {}) => new _KangarooTwelve(168, 32, chooseLen(opts, 32), 12, opts) +); +/** + * 256-bit KangarooTwelve (k12): reduced 12-round keccak. + * @param msg - message bytes to hash + * @param opts - Optional output and personalization settings. Defaults to + * 64 output bytes when `dkLen` is omitted. See {@link KangarooOpts}. + * @returns Digest bytes. + * @example + * Hash a message with KangarooTwelve-256. + * ```ts + * kt256(new Uint8Array([1, 2, 3])); + * ``` + */ +export const kt256: TRet> = /* @__PURE__ */ createHasher( + (opts: TArg = {}) => new _KangarooTwelve(136, 64, chooseLen(opts, 64), 12, opts) +); + +// MarsupilamiFourteen (14-rounds) can be defined as: +// `new KangarooTwelve(136, 64, chooseLen(opts, 64), 14, opts)` + +/** KangarooTwelve-based MAC function type. */ +export type HopMAC = ( + key: TArg, + message: TArg, + personalization: TArg, + dkLen?: number +) => TRet; +const genHopMAC = + (hash: TArg>): TRet => + ( + key: TArg, + message: TArg, + personalization: TArg, + dkLen?: number + ) => { + const h = hash as unknown as CHash<_KangarooTwelve, KangarooOpts>; + return h(key, { personalization: h(message, { personalization }), dkLen }) as TRet; + }; + +/** + * 128-bit KangarooTwelve-based MAC. + * + * These untested (there is no test vectors or implementation available). Use at your own risk. + * HopMAC128(Key, M, C, L) = KT128(Key, KT128(M, C, 32), L) + * HopMAC256(Key, M, C, L) = KT256(Key, KT256(M, C, 64), L) + * The inner KangarooTwelve call always uses a fixed 32-byte digest here, + * regardless of the outer `dkLen`. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC128. + * ```ts + * HopMAC128(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 32); + * ``` + */ +export const HopMAC128: TRet = /* @__PURE__ */ genHopMAC(kt128); +/** + * 256-bit KangarooTwelve-based MAC. + * Like `HopMAC128`, there are no test vectors or known independent + * implementations available for cross-checking. + * @param key - MAC key bytes + * @param message - message bytes to authenticate + * @param personalization - personalization bytes mixed into the inner hash + * @param dkLen - optional output length in bytes. The inner KangarooTwelve + * call still uses a fixed 64-byte digest here, regardless of the outer + * `dkLen`. + * @returns Authentication tag bytes. + * @example + * Authenticate a message with HopMAC256. + * ```ts + * HopMAC256(new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3]), 64); + * ``` + */ +export const HopMAC256: TRet = /* @__PURE__ */ genHopMAC(kt256); + +/** + * More at + * {@link https://github.com/XKCP/XKCP/tree/master/lib/high/Keccak/PRG}. + * Accepted capacities must keep `rho = 1598 - capacity` byte-aligned, and + * `.clean()` later also requires `rate > 801`. + */ +export class _KeccakPRG extends Keccak implements PRG { + protected rate: number; + constructor(capacity: number) { + anumber(capacity); + const rate = 1600 - capacity; + const rho = rate - 2; + // Rho must be full bytes + if (capacity < 0 || capacity > 1600 - 10 || rho % 8) throw new Error('invalid capacity'); + // blockLen = rho in bytes + super(rho / 8, 0, 0, true); + this.rate = rate; + this.posOut = Math.floor((rate + 7) / 8); + } + protected keccak(): void { + // Duplex padding + this.state[this.pos] ^= 0x01; + this.state[this.blockLen] ^= 0x02; // Rho is full bytes + super.keccak(); + this.pos = 0; + this.posOut = 0; + } + update(data: TArg): this { + super.update(data); + this.posOut = this.blockLen; + return this; + } + protected finish(): void {} + digestInto(_out: TArg): void { + throw new Error('digest is not allowed, use .randomBytes() instead'); + } + addEntropy(seed: TArg): void { + this.update(seed); + } + randomBytes(length: number): TRet { + return this.xof(length); + } + clean(): void { + // clean() mutates live sponge state just like randomBytes(), + // so destroyed instances must reject it. + aexists(this, false); + if (this.rate < 1600 / 2 + 1) throw new Error('rate is too low to use .forget()'); + this.keccak(); + for (let i = 0; i < this.blockLen; i++) this.state[i] = 0; + this.pos = this.blockLen; + this.keccak(); + this.posOut = this.blockLen; + } + _cloneInto(to?: _KeccakPRG): _KeccakPRG { + const { rate } = this; + to ||= new _KeccakPRG(1600 - rate); + super._cloneInto(to); + to.rate = rate; + return to; + } + clone(): _KeccakPRG { + return this._cloneInto(); + } +} + +/** + * KeccakPRG: pseudo-random generator based on Keccak. + * See {@link https://keccak.team/files/CSF-0.1.pdf}. + * @param capacity - sponge capacity in bits. Accepted values are those that + * keep `rho = 1598 - capacity` byte-aligned; the default `254` is chosen + * because it satisfies that duplex layout while leaving a wide byte-aligned + * rate. + * @returns PRG instance backed by a Keccak sponge. + * @example + * Create a Keccak-based pseudorandom generator and read bytes from it. + * ```ts + * const prg = keccakprg(254); + * prg.randomBytes(8); + * ``` + */ +export const keccakprg = (capacity = 254): TRet<_KeccakPRG> => + new _KeccakPRG(capacity) as TRet<_KeccakPRG>; diff --git a/node_modules/@noble/hashes/src/sha3.ts b/node_modules/@noble/hashes/src/sha3.ts new file mode 100644 index 0000000..c81af06 --- /dev/null +++ b/node_modules/@noble/hashes/src/sha3.ts @@ -0,0 +1,485 @@ +/** + * SHA3 (keccak) hash function, based on a new "Sponge function" design. + * Different from older hashes, the internal state is bigger than output size. + * + * Check out + * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf | FIPS-202}, + * {@link https://keccak.team/keccak.html | Website}, and + * {@link https://crypto.stackexchange.com/q/15727 | the differences between + * SHA-3 and Keccak}. + * + * Check out `sha3-addons` module for cSHAKE, k12, and others. + * @module + */ +import { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts'; +// prettier-ignore +import { + abytes, aexists, anumber, aoutput, + clean, createHasher, + oidNist, + swap32IfBE, + u32, + type CHash, type CHashXOF, + type Hash, + type HashInfo, + type HashXOF, + type TArg, + type TRet +} from './utils.ts'; + +// No __PURE__ annotations in sha3 header: +// EVERYTHING is in fact used on every export. +// Various per round constants calculations +const _0n = BigInt(0); +const _1n = BigInt(1); +const _2n = BigInt(2); +const _7n = BigInt(7); +const _256n = BigInt(256); +// FIPS 202 Algorithm 5 rc(): when the outgoing bit is 1, the 8-bit LFSR xors +// taps 0, 4, 5, and 6, which compresses to the feedback mask `0x71`. +const _0x71n = BigInt(0x71); +const SHA3_PI: number[] = []; +const SHA3_ROTL: number[] = []; +const _SHA3_IOTA: bigint[] = []; // no pure annotation: var is always used +for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) { + // Pi + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + // Rotational + SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64); + // Iota + let t = _0n; + for (let j = 0; j < 7; j++) { + R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n; + if (R & _2n) t ^= _1n << ((_1n << BigInt(j)) - _1n); + } + _SHA3_IOTA.push(t); +} +const IOTAS = split(_SHA3_IOTA, true); +// `split(..., true)` keeps the local little-endian lane-word layout used by +// `state32`, so these `H` / `L` tables follow the file's first-word / +// second-word lane slots rather than `_u64.ts`'s usual high/low naming. +const SHA3_IOTA_H = IOTAS[0]; +const SHA3_IOTA_L = IOTAS[1]; + +// Left rotation (without 0, 32, 64) +const rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s)); +const rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s)); + +/** + * `keccakf1600` internal permutation, additionally allows adjusting the round count. + * @param s - 5x5 Keccak state encoded as 25 lanes split into 50 uint32 words + * in this file's local little-endian lane-word order + * @param rounds - number of rounds to execute + * @throws If `rounds` is outside the supported `1..24` range. {@link Error} + * @example + * Permute a Keccak state with the default 24 rounds. + * ```ts + * keccakP(new Uint32Array(50)); + * ``` + */ +export function keccakP(s: TArg, rounds: number = 24): void { + anumber(rounds, 'rounds'); + // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table. + if (rounds < 1 || rounds > 24) throw new Error('"rounds" expected integer 1..24'); + const B = new Uint32Array(5 * 2); + // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js) + for (let round = 24 - rounds; round < 24; round++) { + // Theta θ + for (let x = 0; x < 10; x++) B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + // Rho (ρ) and Pi (π) + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + // Chi (χ) + // Same as: + // for (let x = 0; x < 10; x++) B[x] = s[y + x]; + // for (let x = 0; x < 10; x++) s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10]; + for (let y = 0; y < 50; y += 10) { + const b0 = s[y], + b1 = s[y + 1], + b2 = s[y + 2], + b3 = s[y + 3]; + s[y] ^= ~s[y + 2] & s[y + 4]; + s[y + 1] ^= ~s[y + 3] & s[y + 5]; + s[y + 2] ^= ~s[y + 4] & s[y + 6]; + s[y + 3] ^= ~s[y + 5] & s[y + 7]; + s[y + 4] ^= ~s[y + 6] & s[y + 8]; + s[y + 5] ^= ~s[y + 7] & s[y + 9]; + s[y + 6] ^= ~s[y + 8] & b0; + s[y + 7] ^= ~s[y + 9] & b1; + s[y + 8] ^= ~b0 & b2; + s[y + 9] ^= ~b1 & b3; + } + // Iota (ι) + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + clean(B); +} + +/** + * Keccak sponge function. + * @param blockLen - absorb/squeeze rate in bytes + * @param suffix - domain separation suffix byte + * @param outputLen - default digest length in bytes. This base sponge only + * requires a non-negative integer; wrappers that need positive output + * lengths must enforce that themselves. + * @param enableXOF - whether XOF output is allowed + * @param rounds - number of Keccak-f rounds + * @example + * Build a sponge state, absorb bytes, then finalize a digest. + * ```ts + * const hash = new Keccak(136, 0x06, 32); + * hash.update(new Uint8Array([1, 2, 3])); + * hash.digest(); + * ``` + */ +export class Keccak implements Hash, HashXOF { + protected state: Uint8Array; + protected pos = 0; + protected posOut = 0; + protected finished = false; + protected state32: Uint32Array; + protected destroyed = false; + + public blockLen: number; + public suffix: number; + public outputLen: number; + public canXOF: boolean; + protected enableXOF = false; + protected rounds: number; + + // NOTE: we accept arguments in bytes instead of bits here. + constructor( + blockLen: number, + suffix: number, + outputLen: number, + enableXOF = false, + rounds: number = 24 + ) { + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.canXOF = enableXOF; + this.rounds = rounds; + // Can be passed from user as dkLen + anumber(outputLen, 'outputLen'); + // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes + // 0 < blockLen < 200 + if (!(0 < blockLen && blockLen < 200)) + throw new Error('only keccak-f1600 function is supported'); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + clone(): Keccak { + return this._cloneInto(); + } + protected keccak(): void { + swap32IfBE(this.state32); + keccakP(this.state32, this.rounds); + swap32IfBE(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data: TArg): this { + aexists(this); + abytes(data); + const { blockLen, state } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) this.keccak(); + } + return this; + } + protected finish(): void { + if (this.finished) return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + // FIPS 202 appends the SHA3/SHAKE domain-separation suffix before pad10*1. + // These byte values already include the first padding bit, while the + // final `0x80` below supplies the closing `1` bit in the last rate byte. + state[pos] ^= suffix; + // If that combined suffix lands in the last rate byte and already sets + // bit 7, absorb it first so the final pad10*1 bit can be xored into a + // fresh block. + if ((suffix & 0x80) !== 0 && pos === blockLen - 1) this.keccak(); + state[blockLen - 1] ^= 0x80; + this.keccak(); + } + protected writeInto(out: TArg): TRet { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out as TRet; + } + xofInto(out: TArg): TRet { + // Plain SHA3/Keccak usage with XOF is probably a mistake, but this base + // class is also reused by SHAKE/cSHAKE/KMAC/TupleHash/ParallelHash/ + // TurboSHAKE/KangarooTwelve wrappers that intentionally enable XOF. + if (!this.enableXOF) throw new Error('XOF is not possible for this instance'); + return this.writeInto(out); + } + xof(bytes: number): TRet { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out: TArg): void { + aoutput(out, this); + if (this.finished) throw new Error('digest() was already called'); + // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest. + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest(): TRet { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out as TRet; + } + destroy(): void { + this.destroyed = true; + clean(this.state); + } + _cloneInto(to?: Keccak): Keccak { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + // Reused destinations can come from a different rate/capacity variant, so clone must rewrite + // the sponge geometry as well as the state words. + to.blockLen = blockLen; + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + // Suffix can change in cSHAKE + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + // Clones must preserve the public capability bit too; `_KMAC` reuses this path and deep clone + // tests compare instance fields directly, so leaving `canXOF` behind makes the clone lie. + to.canXOF = this.canXOF; + to.destroyed = this.destroyed; + return to; + } +} + +const genKeccak = ( + suffix: number, + blockLen: number, + outputLen: number, + info: TArg = {} +) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); + +/** + * SHA3-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-224. + * ```ts + * sha3_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_224: TRet = /* @__PURE__ */ genKeccak( + 0x06, + 144, + 28, + /* @__PURE__ */ oidNist(0x07) +); +/** + * SHA3-256 hash function. Different from keccak-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-256. + * ```ts + * sha3_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_256: TRet = /* @__PURE__ */ genKeccak( + 0x06, + 136, + 32, + /* @__PURE__ */ oidNist(0x08) +); +/** + * SHA3-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-384. + * ```ts + * sha3_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_384: TRet = /* @__PURE__ */ genKeccak( + 0x06, + 104, + 48, + /* @__PURE__ */ oidNist(0x09) +); +/** + * SHA3-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with SHA3-512. + * ```ts + * sha3_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha3_512: TRet = /* @__PURE__ */ genKeccak( + 0x06, + 72, + 64, + /* @__PURE__ */ oidNist(0x0a) +); + +/** + * Keccak-224 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-224. + * ```ts + * keccak_224(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_224: TRet = /* @__PURE__ */ genKeccak(0x01, 144, 28); +/** + * Keccak-256 hash function. Different from SHA3-256. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-256. + * ```ts + * keccak_256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_256: TRet = /* @__PURE__ */ genKeccak(0x01, 136, 32); +/** + * Keccak-384 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-384. + * ```ts + * keccak_384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_384: TRet = /* @__PURE__ */ genKeccak(0x01, 104, 48); +/** + * Keccak-512 hash function. + * @param msg - message bytes to hash + * @returns Digest bytes. + * @example + * Hash a message with Keccak-512. + * ```ts + * keccak_512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const keccak_512: TRet = /* @__PURE__ */ genKeccak(0x01, 72, 64); + +/** Options for SHAKE XOF. */ +export type ShakeOpts = { + /** Desired number of output bytes. */ + dkLen?: number; +}; + +const genShake = (suffix: number, blockLen: number, outputLen: number, info: TArg = {}) => + createHasher( + (opts: ShakeOpts = {}) => + new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true), + info + ); + +/** + * SHAKE128 XOF with 128-bit security and a 16-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128. + * ```ts + * shake128(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export const shake128: TRet> = + /* @__PURE__ */ + genShake(0x1f, 168, 16, /* @__PURE__ */ oidNist(0x0b)); +/** + * SHAKE256 XOF with 256-bit security and a 32-byte default output. + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256. + * ```ts + * shake256(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export const shake256: TRet> = + /* @__PURE__ */ + genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c)); + +/** + * SHAKE128 XOF with 256-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE128 using a 32-byte default output. + * ```ts + * shake128_32(new Uint8Array([97, 98, 99]), { dkLen: 32 }); + * ``` + */ +export const shake128_32: TRet> = + /* @__PURE__ */ + genShake(0x1f, 168, 32, /* @__PURE__ */ oidNist(0x0b)); +/** + * SHAKE256 XOF with 512-bit output (NIST version). + * @param msg - message bytes to hash + * @param opts - Optional output-length override. See {@link ShakeOpts}. + * @returns Digest bytes. + * @example + * Hash a message with SHAKE256 using a 64-byte default output. + * ```ts + * shake256_64(new Uint8Array([97, 98, 99]), { dkLen: 64 }); + * ``` + */ +export const shake256_64: TRet> = + /* @__PURE__ */ + genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c)); diff --git a/node_modules/@noble/hashes/src/utils.ts b/node_modules/@noble/hashes/src/utils.ts new file mode 100644 index 0000000..961dab2 --- /dev/null +++ b/node_modules/@noble/hashes/src/utils.ts @@ -0,0 +1,848 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array + ? BigInt64Array + : T extends BigUint64Array + ? BigUint64Array + : T extends Float32Array + ? Float32Array + : T extends Float64Array + ? Float64Array + : T extends Int16Array + ? Int16Array + : T extends Int32Array + ? Int32Array + : T extends Int8Array + ? Int8Array + : T extends Uint16Array + ? Uint16Array + : T extends Uint32Array + ? Uint32Array + : T extends Uint8ClampedArray + ? Uint8ClampedArray + : T extends Uint8Array + ? Uint8Array + : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array + ? ReturnType + : T extends BigUint64Array + ? ReturnType + : T extends Float32Array + ? ReturnType + : T extends Float64Array + ? ReturnType + : T extends Int16Array + ? ReturnType + : T extends Int32Array + ? ReturnType + : T extends Int8Array + ? ReturnType + : T extends Uint16Array + ? ReturnType + : T extends Uint32Array + ? ReturnType + : T extends Uint8ClampedArray + ? ReturnType + : T extends Uint8Array + ? ReturnType + : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = + | T + | ([TypedArg] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TRet }) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; + } + : T extends [infer A, ...infer R] + ? [TArg, ...{ [K in keyof R]: TArg }] + : T extends readonly [infer A, ...infer R] + ? readonly [TArg, ...{ [K in keyof R]: TArg }] + : T extends (infer A)[] + ? TArg[] + : T extends readonly (infer A)[] + ? readonly TArg[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TArg } + : T + : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown + ? T & + ([TypedRet] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TArg }) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; + } + : T extends [infer A, ...infer R] + ? [TRet, ...{ [K in keyof R]: TRet }] + : T extends readonly [infer A, ...infer R] + ? readonly [TRet, ...{ [K in keyof R]: TRet }] + : T extends (infer A)[] + ? TRet[] + : T extends readonly (infer A)[] + ? readonly TRet[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TRet } + : T + : TypedRet) + : never; +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function isBytes(a: unknown): a is Uint8Array { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. + // The fallback still requires a real ArrayBuffer view, so plain + // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and + // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return ( + a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1) + ); +} + +/** + * Asserts something is a non-negative integer. + * @param n - number to validate + * @param title - label included in thrown errors + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a non-negative integer option. + * ```ts + * anumber(32, 'length'); + * ``` + */ +export function anumber(n: number, title: string = ''): void { + if (typeof n !== 'number') { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n}`); + } + if (!Number.isSafeInteger(n) || n < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); + } +} + +/** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function abytes( + value: TArg, + length?: number, + title: string = '' +): TRet { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== undefined; + if (!bytes || (needsLen && len !== length)) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ''; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) throw new TypeError(message); + throw new RangeError(message); + } + return value as TRet; +} + +/** + * Copies bytes into a fresh Uint8Array. + * Buffer-style slices can alias the same backing store, so callers that need ownership should copy. + * @param bytes - source bytes to clone + * @returns Freshly allocated copy of `bytes`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Clone a byte array before mutating it. + * ```ts + * const copy = copyBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function copyBytes(bytes: TArg): TRet { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)) as TRet; +} + +/** + * Asserts something is a wrapped hash constructor. + * @param h - hash constructor to validate + * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError} + * @throws On invalid hash metadata ranges or values. {@link RangeError} + * @throws If the hash metadata allows empty outputs or block sizes. {@link Error} + * @example + * Validate a callable hash wrapper. + * ```ts + * import { ahash } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * ahash(sha256); + * ``` + */ +export function ahash(h: TArg): void { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new TypeError('Hash must wrapped by utils.createHasher'); + anumber(h.outputLen); + anumber(h.blockLen); + // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass + // validation and can produce empty outputs instead of failing fast. + if (h.outputLen < 1) throw new Error('"outputLen" must be >= 1'); + if (h.blockLen < 1) throw new Error('"blockLen" must be >= 1'); +} + +/** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ +export function aexists(instance: any, checkFinished = true): void { + if (instance.destroyed) throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called'); +} + +/** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ +export function aoutput(out: any, instance: any): void { + abytes(out, undefined, 'digestInto() output'); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); + } +} + +/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */ +// prettier-ignore +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | + Uint16Array | Int16Array | Uint32Array | Int32Array; + +/** + * Casts a typed array view to Uint8Array. + * @param arr - source typed array + * @returns Uint8Array view over the same buffer. + * @example + * Reinterpret a typed array as bytes. + * ```ts + * u8(new Uint32Array([1, 2])); + * ``` + */ +export function u8(arr: TArg): TRet { + return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet; +} + +/** + * Casts a typed array view to Uint32Array. + * `arr.byteOffset` must already be 4-byte aligned or the platform + * Uint32Array constructor will throw. + * @param arr - source typed array + * @returns Uint32Array view over the same buffer. + * @example + * Reinterpret a byte array as 32-bit words. + * ```ts + * u32(new Uint8Array(8)); + * ``` + */ +export function u32(arr: TArg): TRet { + return new Uint32Array( + arr.buffer, + arr.byteOffset, + Math.floor(arr.byteLength / 4) + ) as TRet; +} + +/** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ +export function clean(...arrays: TArg): void { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} + +/** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export function createView(arr: TArg): DataView { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} + +/** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ +export function rotr(word: number, shift: number): number { + return (word << (32 - shift)) | (word >>> shift); +} + +/** + * Rotate-left operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the left. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export function rotl(word: number, shift: number): number { + return (word << shift) | ((word >>> (32 - shift)) >>> 0); +} + +/** Whether the current platform is little-endian. */ +export const isLE: boolean = /* @__PURE__ */ (() => + new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); + +/** + * Byte-swap operation for uint32 values. + * @param word - source word + * @returns Word with reversed byte order. + * @example + * Reverse the byte order of a 32-bit word. + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export function byteSwap(word: number): number { + return ( + ((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff) + ); +} +/** + * Conditionally byte-swaps one 32-bit word on big-endian platforms. + * @param n - source word + * @returns Original or byte-swapped word depending on platform endianness. + * @example + * Normalize a 32-bit word for host endianness. + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export const swap8IfBE: (n: number) => number = isLE + ? (n: number) => n + : (n: number) => byteSwap(n) >>> 0; + +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - array to mutate + * @returns The same array after mutation; callers pass live state arrays here. + * @example + * Reverse the byte order of every word in place. + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export function byteSwap32(arr: TArg): TRet { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr as TRet; +} + +/** + * Conditionally byte-swaps a Uint32Array on big-endian platforms. + * @param u - array to normalize for host endianness + * @returns Original or byte-swapped array depending on platform endianness. + * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`. + * @example + * Normalize a word array for host endianness. + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export const swap32IfBE: (u: TArg) => TRet = isLE + ? (u: TArg) => u as TRet + : byteSwap32; + +// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex +const hasHexBuiltin: boolean = /* @__PURE__ */ (() => + // @ts-ignore + typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); + +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => + i.toString(16).padStart(2, '0') +); + +/** + * Convert byte array to hex string. + * Uses the built-in function when available and assumes it matches the tested + * fallback semantics. + * @param bytes - bytes to encode + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Convert bytes to lowercase hexadecimal. + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export function bytesToHex(bytes: TArg): string { + abytes(bytes); + // @ts-ignore + if (hasHexBuiltin) return bytes.toHex(); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} + +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const; +function asciiToBase16(ch: number): number | undefined { + if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48 + if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10) + if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10) + return; +} + +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - hexadecimal string to decode + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode lowercase hexadecimal into bytes. + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export function hexToBytes(hex: string): TRet { + if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex); + if (hasHexBuiltin) { + try { + return (Uint8Array as any).fromHex(hex); + } catch (error) { + if (error instanceof SyntaxError) throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) throw new RangeError('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError( + 'hex string expected, got non-hex character "' + char + '" at index ' + hi + ); + } + array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163 + } + return array; +} + +/** + * There is no setImmediate in browser and setTimeout is slow. + * This yields to the Promise/microtask scheduler queue, not to timers or the + * full macrotask event loop. + * @example + * Yield to the next scheduler tick. + * ```ts + * await nextTick(); + * ``` + */ +export const nextTick = async (): Promise => {}; + +/** + * Returns control to the Promise/microtask scheduler every `tick` + * milliseconds to avoid blocking long loops. + * @param iters - number of loop iterations to run + * @param tick - maximum time slice in milliseconds + * @param cb - callback executed on each iteration + * @example + * Run a loop that periodically yields back to the event loop. + * ```ts + * await asyncLoop(2, 0, () => {}); + * ``` + */ +export async function asyncLoop( + iters: number, + tick: number, + cb: (i: number) => void +): Promise { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) continue; + await nextTick(); + ts += diff; + } +} + +// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535 +declare const TextEncoder: any; + +/** + * Converts string to bytes using UTF8 encoding. + * Built-in doesn't validate input to be string: we do the check. + * Non-ASCII details are delegated to the platform `TextEncoder`. + * @param str - string to encode + * @returns UTF-8 encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode a string as UTF-8 bytes. + * ```ts + * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99]) + * ``` + */ +export function utf8ToBytes(str: string): TRet { + if (typeof str !== 'string') throw new TypeError('string expected'); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} + +/** KDFs can accept string or Uint8Array for user convenience. */ +export type KDFInput = string | Uint8Array; + +/** + * Helper for KDFs: consumes Uint8Array or string. + * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. + * @param data - user-provided KDF input + * @param errorTitle - label included in thrown errors + * @returns Byte representation of the input. + * @throws On wrong argument types. {@link TypeError} + * @example + * Normalize KDF input to bytes. + * ```ts + * kdfInputToBytes('password'); + * ``` + */ +export function kdfInputToBytes(data: TArg, errorTitle = ''): TRet { + if (typeof data === 'string') return utf8ToBytes(data); + return abytes(data, undefined, errorTitle); +} + +/** + * Copies several Uint8Arrays into one. + * @param arrays - arrays to concatenate + * @returns Concatenated byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Concatenate multiple byte arrays. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export function concatBytes(...arrays: TArg): TRet { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} + +type EmptyObj = {}; +/** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @returns Merged option object. The merge mutates `defaults` in place. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ +export function checkOpts( + defaults: T1, + opts?: T2 +): T1 & T2 { + if (opts !== undefined && {}.toString.call(opts) !== '[object Object]') + throw new TypeError('options must be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged as T1 & T2; +} + +/** Common interface for all hash instances. */ +export interface Hash { + /** Bytes processed per compression block. */ + blockLen: number; + /** Bytes produced by `digest()`. */ + outputLen: number; + /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */ + canXOF: boolean; + /** + * Absorbs more message bytes into the running hash state. + * @param buf - message chunk to absorb + * @returns The same hash instance for chaining. + */ + update(buf: TArg): this; + /** + * Finalizes the hash into a caller-provided buffer. + * @param buf - destination buffer + * @returns Nothing. Implementations write into `buf` in place. + */ + digestInto(buf: TArg): void; + /** + * Finalizes the hash and returns a freshly allocated digest. + * @returns Digest bytes. + */ + digest(): TRet; + /** Wipes internal state and makes the instance unusable. */ + destroy(): void; + /** + * Copies the current hash state into an existing or new instance. + * @param to - Optional destination instance to reuse. + * @returns Cloned hash state. + */ + _cloneInto(to?: T): T; + /** + * Creates an independent copy of the current hash state. + * @returns Cloned hash instance. + */ + clone(): T; +} + +/** Pseudorandom generator interface. */ +export interface PRG { + /** + * Mixes more entropy into the generator state. + * @param seed - fresh entropy bytes + * @returns Nothing. Implementations update internal state in place. + */ + addEntropy(seed: TArg): void; + /** + * Generates pseudorandom output bytes. + * @param length - number of bytes to generate + * @returns Generated pseudorandom bytes. + */ + randomBytes(length: number): TRet; + /** Wipes generator state and makes the instance unusable. */ + clean(): void; +} + +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + /** + * Reads more bytes from the XOF stream. + * @param bytes - number of bytes to read + * @returns Requested digest bytes. + */ + xof(bytes: number): TRet; + /** + * Reads more bytes from the XOF stream into a caller-provided buffer. + * @param buf - destination buffer + * @returns Filled output buffer. + */ + xofInto(buf: TArg): TRet; +}; + +/** Hash constructor or factory type. */ +export type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T; +/** Optional hash metadata. */ +export type HashInfo = { + /** DER-encoded object identifier bytes for the hash algorithm. */ + oid?: TRet; +}; +/** Callable hash function type. */ +export type CHash = Hash, Opts = undefined> = { + /** Digest size in bytes. */ + outputLen: number; + /** Input block size in bytes. */ + blockLen: number; + /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */ + canXOF: boolean; +} & HashInfo & + (Opts extends undefined + ? { + (msg: TArg): TRet; + create(): T; + } + : { + (msg: TArg, opts?: TArg): TRet; + create(opts?: Opts): T; + }); +/** Callable extendable-output hash function type. */ +export type CHashXOF = HashXOF, Opts = undefined> = CHash; + +/** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ +export function createHasher, Opts = undefined>( + hashCons: HasherCons, + info: TArg = {} +): TRet> { + const hashC: any = (msg: TArg, opts?: TArg) => + hashCons(opts as Opts) + .update(msg) + .digest(); + const tmp = hashCons(undefined); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts?: Opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC) as TRet>; +} + +/** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ +export function randomBytes(bytesLength = 32): TRet { + // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion. + anumber(bytesLength, 'bytesLength'); + const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + // Web Cryptography API Level 2 §10.1.1: + // if `byteLength > 65536`, throw `QuotaExceededError`. + // Keep the guard explicit so callers can see the quota in code + // instead of discovering it by reading the spec or host errors. + // This wrapper surfaces the same quota as a stable library RangeError. + if (bytesLength > 65536) + throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} + +/** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ +export const oidNist = (suffix: number): TRet> => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]), +}); diff --git a/node_modules/@noble/hashes/src/webcrypto.ts b/node_modules/@noble/hashes/src/webcrypto.ts new file mode 100644 index 0000000..3f772e1 --- /dev/null +++ b/node_modules/@noble/hashes/src/webcrypto.ts @@ -0,0 +1,239 @@ +import { type Pbkdf2Opt } from './pbkdf2.ts'; +import { + abytes, + ahash, + anumber, + checkOpts, + kdfInputToBytes, + type CHash, + type KDFInput, + type TArg, + type TRet, +} from './utils.ts'; + +function _subtle(): typeof crypto.subtle { + const cr = typeof globalThis === 'object' ? (globalThis as any).crypto : null; + const sb = cr?.subtle; + if (typeof sb === 'object' && sb != null) return sb; + throw new Error('crypto.subtle must be defined'); +} + +/** Callable WebCrypto hash function descriptor. */ +export type WebHash = { + /** + * Hashes one message with the selected WebCrypto digest. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + */ + (msg: TArg): Promise>; + /** WebCrypto algorithm name passed to `crypto.subtle`. */ + webCryptoName: string; + /** Digest size in bytes. */ + outputLen: number; + /** Input block size in bytes. */ + blockLen: number; +}; + +function createWebHash(name: string, blockLen: number, outputLen: number): TRet { + const hashC: any = async (msg: TArg): Promise> => { + abytes(msg); + const crypto = _subtle(); + return new Uint8Array(await crypto.digest(name, msg as BufferSource)) as TRet; + }; + hashC.webCryptoName = name; // make sure it won't interfere with function name + hashC.outputLen = outputLen; + hashC.blockLen = blockLen; + hashC.create = () => { + // Present only so this async wrapper satisfies the shared + // hash-wrapper shape checked by `ahashWeb()`. + throw new Error('not implemented'); + }; + // Later WebCrypto HMAC/HKDF/PBKDF2 calls read descriptor metadata directly, so freezing prevents + // callers from retargeting a `sha256` wrapper into a different backend digest by mutation. + return Object.freeze(hashC) as TRet; +} + +function ahashWeb(hash: TArg) { + ahash(hash as unknown as TArg); + if (typeof hash.webCryptoName !== 'string') throw new Error('non-web hash'); +} + +/** WebCrypto SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */ +// export const sha1: WebHash = createHash('SHA-1', 64, 20); + +/** + * WebCrypto SHA2-256 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-256. + * ```ts + * await sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha256: TRet = /* @__PURE__ */ createWebHash('SHA-256', 64, 32); +/** + * WebCrypto SHA2-384 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-384. + * ```ts + * await sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha384: TRet = /* @__PURE__ */ createWebHash('SHA-384', 128, 48); +/** + * WebCrypto SHA2-512 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-512. + * ```ts + * await sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512: TRet = /* @__PURE__ */ createWebHash('SHA-512', 128, 64); + +/** + * WebCrypto HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256. Webcrypto version. + * @param key - authentication key bytes + * @param message - message bytes to authenticate + * @returns Promise resolving to authentication tag bytes. + * `.create()` exists only to mirror the synchronous API surface + * and always throws `not implemented`. + * @example + * Compute an RFC 2104 HMAC with WebCrypto. + * ```ts + * import { hmac, sha256 } from '@noble/hashes/webcrypto.js'; + * await hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +type WebHmacFn = { + ( + hash: TArg, + key: TArg, + message: TArg + ): Promise>; + create(hash: TArg, key: TArg): any; +}; +export const hmac: TRet = /* @__PURE__ */ (() => { + const hmac_ = async ( + hash: TArg, + key: TArg, + message: TArg + ): Promise> => { + const crypto = _subtle(); + abytes(key, undefined, 'key'); + abytes(message, undefined, 'message'); + ahashWeb(hash); + // WebCrypto keys can't be zeroized + // prettier-ignore + const wkey = await crypto.importKey( + 'raw', + key as BufferSource, + { name: 'HMAC', hash: hash.webCryptoName }, + false, + ['sign'] + ); + return new Uint8Array( + await crypto.sign('HMAC', wkey, message as BufferSource) + ) as TRet; + }; + hmac_.create = (_hash: TArg, _key: TArg) => { + throw new Error('not implemented'); + }; + return hmac_ as TRet; +})(); + +/** + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256). Webcrypto version. + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` requests an empty OKM. + * @returns Promise resolving to derived key bytes. + * The RFC `L <= 255 * HashLen` bound is currently enforced only by backend + * `deriveBits()` rejection, not by an explicit library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf, sha256 } from '@noble/hashes/webcrypto.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = await hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export async function hkdf( + hash: TArg, + ikm: TArg, + salt: TArg, + info: TArg, + length: number +): Promise> { + const crypto = _subtle(); + ahashWeb(hash); + abytes(ikm, undefined, 'ikm'); + anumber(length, 'length'); + if (salt !== undefined) abytes(salt, undefined, 'salt'); + if (info !== undefined) abytes(info, undefined, 'info'); + const wkey = await crypto.importKey('raw', ikm as BufferSource, 'HKDF', false, ['deriveBits']); + const opts = { + name: 'HKDF', + hash: hash.webCryptoName, + salt: salt === undefined ? new Uint8Array(0) : salt, + info: info === undefined ? new Uint8Array(0) : info, + }; + return new Uint8Array(await crypto.deriveBits(opts, wkey, 8 * length)) as TRet; +} + +/** + * WebCrypto PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256. Webcrypto version. + * @param password - password from which a derived key is generated; string + * inputs are normalized through `kdfInputToBytes()`, i.e. UTF-8 + * @param salt - cryptographic salt; string inputs are normalized through + * `kdfInputToBytes()`, i.e. UTF-8 + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * Positive-iteration enforcement is currently delegated to backend + * `deriveBits()` rejection (for example `c = 0`), not a dedicated + * library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2, sha256 } from '@noble/hashes/webcrypto.js'; + * const key = await pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export async function pbkdf2( + hash: TArg, + password: TArg, + salt: TArg, + opts: Pbkdf2Opt +): Promise> { + const crypto = _subtle(); + ahashWeb(hash); + const _opts = checkOpts({ dkLen: 32 }, opts); + const { c, dkLen } = _opts; + anumber(c, 'c'); + anumber(dkLen, 'dkLen'); + // RFC 8018 §5.2 defines dkLen as a positive integer. + if (dkLen < 1) throw new Error('"dkLen" must be >= 1'); + const _password = kdfInputToBytes(password, 'password'); + const _salt = kdfInputToBytes(salt, 'salt'); + const key = await crypto.importKey('raw', _password as BufferSource, 'PBKDF2', false, [ + 'deriveBits', + ]); + const deriveOpts = { name: 'PBKDF2', salt: _salt, iterations: c, hash: hash.webCryptoName }; + return new Uint8Array(await crypto.deriveBits(deriveOpts, key, 8 * dkLen)) as TRet; +} diff --git a/node_modules/@noble/hashes/utils.d.ts b/node_modules/@noble/hashes/utils.d.ts new file mode 100644 index 0000000..4033d83 --- /dev/null +++ b/node_modules/@noble/hashes/utils.d.ts @@ -0,0 +1,519 @@ +/** + * Utilities for hex, bytes, CSPRNG. + * @module + */ +/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function isBytes(a: unknown): a is Uint8Array; +/** + * Asserts something is a non-negative integer. + * @param n - number to validate + * @param title - label included in thrown errors + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a non-negative integer option. + * ```ts + * anumber(32, 'length'); + * ``` + */ +export declare function anumber(n: number, title?: string): void; +/** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function abytes(value: TArg, length?: number, title?: string): TRet; +/** + * Copies bytes into a fresh Uint8Array. + * Buffer-style slices can alias the same backing store, so callers that need ownership should copy. + * @param bytes - source bytes to clone + * @returns Freshly allocated copy of `bytes`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Clone a byte array before mutating it. + * ```ts + * const copy = copyBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function copyBytes(bytes: TArg): TRet; +/** + * Asserts something is a wrapped hash constructor. + * @param h - hash constructor to validate + * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError} + * @throws On invalid hash metadata ranges or values. {@link RangeError} + * @throws If the hash metadata allows empty outputs or block sizes. {@link Error} + * @example + * Validate a callable hash wrapper. + * ```ts + * import { ahash } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * ahash(sha256); + * ``` + */ +export declare function ahash(h: TArg): void; +/** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ +export declare function aexists(instance: any, checkFinished?: boolean): void; +/** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ +export declare function aoutput(out: any, instance: any): void; +/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */ +export type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array | Uint16Array | Int16Array | Uint32Array | Int32Array; +/** + * Casts a typed array view to Uint8Array. + * @param arr - source typed array + * @returns Uint8Array view over the same buffer. + * @example + * Reinterpret a typed array as bytes. + * ```ts + * u8(new Uint32Array([1, 2])); + * ``` + */ +export declare function u8(arr: TArg): TRet; +/** + * Casts a typed array view to Uint32Array. + * `arr.byteOffset` must already be 4-byte aligned or the platform + * Uint32Array constructor will throw. + * @param arr - source typed array + * @returns Uint32Array view over the same buffer. + * @example + * Reinterpret a byte array as 32-bit words. + * ```ts + * u32(new Uint8Array(8)); + * ``` + */ +export declare function u32(arr: TArg): TRet; +/** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ +export declare function clean(...arrays: TArg): void; +/** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export declare function createView(arr: TArg): DataView; +/** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ +export declare function rotr(word: number, shift: number): number; +/** + * Rotate-left operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the left. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export declare function rotl(word: number, shift: number): number; +/** Whether the current platform is little-endian. */ +export declare const isLE: boolean; +/** + * Byte-swap operation for uint32 values. + * @param word - source word + * @returns Word with reversed byte order. + * @example + * Reverse the byte order of a 32-bit word. + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export declare function byteSwap(word: number): number; +/** + * Conditionally byte-swaps one 32-bit word on big-endian platforms. + * @param n - source word + * @returns Original or byte-swapped word depending on platform endianness. + * @example + * Normalize a 32-bit word for host endianness. + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export declare const swap8IfBE: (n: number) => number; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - array to mutate + * @returns The same array after mutation; callers pass live state arrays here. + * @example + * Reverse the byte order of every word in place. + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export declare function byteSwap32(arr: TArg): TRet; +/** + * Conditionally byte-swaps a Uint32Array on big-endian platforms. + * @param u - array to normalize for host endianness + * @returns Original or byte-swapped array depending on platform endianness. + * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`. + * @example + * Normalize a word array for host endianness. + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export declare const swap32IfBE: (u: TArg) => TRet; +/** + * Convert byte array to hex string. + * Uses the built-in function when available and assumes it matches the tested + * fallback semantics. + * @param bytes - bytes to encode + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Convert bytes to lowercase hexadecimal. + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export declare function bytesToHex(bytes: TArg): string; +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - hexadecimal string to decode + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode lowercase hexadecimal into bytes. + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export declare function hexToBytes(hex: string): TRet; +/** + * There is no setImmediate in browser and setTimeout is slow. + * This yields to the Promise/microtask scheduler queue, not to timers or the + * full macrotask event loop. + * @example + * Yield to the next scheduler tick. + * ```ts + * await nextTick(); + * ``` + */ +export declare const nextTick: () => Promise; +/** + * Returns control to the Promise/microtask scheduler every `tick` + * milliseconds to avoid blocking long loops. + * @param iters - number of loop iterations to run + * @param tick - maximum time slice in milliseconds + * @param cb - callback executed on each iteration + * @example + * Run a loop that periodically yields back to the event loop. + * ```ts + * await asyncLoop(2, 0, () => {}); + * ``` + */ +export declare function asyncLoop(iters: number, tick: number, cb: (i: number) => void): Promise; +/** + * Converts string to bytes using UTF8 encoding. + * Built-in doesn't validate input to be string: we do the check. + * Non-ASCII details are delegated to the platform `TextEncoder`. + * @param str - string to encode + * @returns UTF-8 encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode a string as UTF-8 bytes. + * ```ts + * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99]) + * ``` + */ +export declare function utf8ToBytes(str: string): TRet; +/** KDFs can accept string or Uint8Array for user convenience. */ +export type KDFInput = string | Uint8Array; +/** + * Helper for KDFs: consumes Uint8Array or string. + * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. + * @param data - user-provided KDF input + * @param errorTitle - label included in thrown errors + * @returns Byte representation of the input. + * @throws On wrong argument types. {@link TypeError} + * @example + * Normalize KDF input to bytes. + * ```ts + * kdfInputToBytes('password'); + * ``` + */ +export declare function kdfInputToBytes(data: TArg, errorTitle?: string): TRet; +/** + * Copies several Uint8Arrays into one. + * @param arrays - arrays to concatenate + * @returns Concatenated byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Concatenate multiple byte arrays. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export declare function concatBytes(...arrays: TArg): TRet; +type EmptyObj = {}; +/** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @returns Merged option object. The merge mutates `defaults` in place. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ +export declare function checkOpts(defaults: T1, opts?: T2): T1 & T2; +/** Common interface for all hash instances. */ +export interface Hash { + /** Bytes processed per compression block. */ + blockLen: number; + /** Bytes produced by `digest()`. */ + outputLen: number; + /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */ + canXOF: boolean; + /** + * Absorbs more message bytes into the running hash state. + * @param buf - message chunk to absorb + * @returns The same hash instance for chaining. + */ + update(buf: TArg): this; + /** + * Finalizes the hash into a caller-provided buffer. + * @param buf - destination buffer + * @returns Nothing. Implementations write into `buf` in place. + */ + digestInto(buf: TArg): void; + /** + * Finalizes the hash and returns a freshly allocated digest. + * @returns Digest bytes. + */ + digest(): TRet; + /** Wipes internal state and makes the instance unusable. */ + destroy(): void; + /** + * Copies the current hash state into an existing or new instance. + * @param to - Optional destination instance to reuse. + * @returns Cloned hash state. + */ + _cloneInto(to?: T): T; + /** + * Creates an independent copy of the current hash state. + * @returns Cloned hash instance. + */ + clone(): T; +} +/** Pseudorandom generator interface. */ +export interface PRG { + /** + * Mixes more entropy into the generator state. + * @param seed - fresh entropy bytes + * @returns Nothing. Implementations update internal state in place. + */ + addEntropy(seed: TArg): void; + /** + * Generates pseudorandom output bytes. + * @param length - number of bytes to generate + * @returns Generated pseudorandom bytes. + */ + randomBytes(length: number): TRet; + /** Wipes generator state and makes the instance unusable. */ + clean(): void; +} +/** + * XOF: streaming API to read digest in chunks. + * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name. + * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot + * destroy state, next call can require more bytes. + */ +export type HashXOF> = Hash & { + /** + * Reads more bytes from the XOF stream. + * @param bytes - number of bytes to read + * @returns Requested digest bytes. + */ + xof(bytes: number): TRet; + /** + * Reads more bytes from the XOF stream into a caller-provided buffer. + * @param buf - destination buffer + * @returns Filled output buffer. + */ + xofInto(buf: TArg): TRet; +}; +/** Hash constructor or factory type. */ +export type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T; +/** Optional hash metadata. */ +export type HashInfo = { + /** DER-encoded object identifier bytes for the hash algorithm. */ + oid?: TRet; +}; +/** Callable hash function type. */ +export type CHash = Hash, Opts = undefined> = { + /** Digest size in bytes. */ + outputLen: number; + /** Input block size in bytes. */ + blockLen: number; + /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */ + canXOF: boolean; +} & HashInfo & (Opts extends undefined ? { + (msg: TArg): TRet; + create(): T; +} : { + (msg: TArg, opts?: TArg): TRet; + create(opts?: Opts): T; +}); +/** Callable extendable-output hash function type. */ +export type CHashXOF = HashXOF, Opts = undefined> = CHash; +/** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ +export declare function createHasher, Opts = undefined>(hashCons: HasherCons, info?: TArg): TRet>; +/** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ +export declare function randomBytes(bytesLength?: number): TRet; +/** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ +export declare const oidNist: (suffix: number) => TRet>; +export {}; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/utils.d.ts.map b/node_modules/@noble/hashes/utils.d.ts.map new file mode 100644 index 0000000..a76edfc --- /dev/null +++ b/node_modules/@noble/hashes/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;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GAgBG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,GAAG,SAAS,EAC9D,QAAQ,EAAE,UAAU,CAAC,CAAC,EAAE,IAAI,CAAC,EAC7B,IAAI,GAAE,IAAI,CAAC,QAAQ,CAAM,GACxB,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAYtB;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,WAAW,CAAC,WAAW,SAAK,GAAG,IAAI,CAAC,UAAU,CAAC,CAc9D;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,OAAO,GAAI,QAAQ,MAAM,KAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAI9D,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/utils.js b/node_modules/@noble/hashes/utils.js new file mode 100644 index 0000000..b4c71b6 --- /dev/null +++ b/node_modules/@noble/hashes/utils.js @@ -0,0 +1,578 @@ +/** + * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. + * @param a - value to test + * @returns `true` when the value is a Uint8Array-compatible view. + * @example + * Check whether a value is a Uint8Array-compatible view. + * ```ts + * isBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function isBytes(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. + // The fallback still requires a real ArrayBuffer view, so plain + // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and + // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); +} +/** + * Asserts something is a non-negative integer. + * @param n - number to validate + * @param title - label included in thrown errors + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a non-negative integer option. + * ```ts + * anumber(32, 'length'); + * ``` + */ +export function anumber(n, title = '') { + if (typeof n !== 'number') { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n}`); + } + if (!Number.isSafeInteger(n) || n < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); + } +} +/** + * Asserts something is Uint8Array. + * @param value - value to validate + * @param length - optional exact length constraint + * @param title - label included in thrown errors + * @returns The validated byte array. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate that a value is a byte array. + * ```ts + * abytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function abytes(value, length, title = '') { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== undefined; + if (!bytes || (needsLen && len !== length)) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ''; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + return value; +} +/** + * Copies bytes into a fresh Uint8Array. + * Buffer-style slices can alias the same backing store, so callers that need ownership should copy. + * @param bytes - source bytes to clone + * @returns Freshly allocated copy of `bytes`. + * @throws On wrong argument types. {@link TypeError} + * @example + * Clone a byte array before mutating it. + * ```ts + * const copy = copyBytes(new Uint8Array([1, 2, 3])); + * ``` + */ +export function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)); +} +/** + * Asserts something is a wrapped hash constructor. + * @param h - hash constructor to validate + * @throws On wrong argument types or invalid hash wrapper shape. {@link TypeError} + * @throws On invalid hash metadata ranges or values. {@link RangeError} + * @throws If the hash metadata allows empty outputs or block sizes. {@link Error} + * @example + * Validate a callable hash wrapper. + * ```ts + * import { ahash } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * ahash(sha256); + * ``` + */ +export function ahash(h) { + if (typeof h !== 'function' || typeof h.create !== 'function') + throw new TypeError('Hash must wrapped by utils.createHasher'); + anumber(h.outputLen); + anumber(h.blockLen); + // HMAC and KDF callers treat these as real byte lengths; allowing zero lets fake wrappers pass + // validation and can produce empty outputs instead of failing fast. + if (h.outputLen < 1) + throw new Error('"outputLen" must be >= 1'); + if (h.blockLen < 1) + throw new Error('"blockLen" must be >= 1'); +} +/** + * Asserts a hash instance has not been destroyed or finished. + * @param instance - hash instance to validate + * @param checkFinished - whether to reject finalized instances + * @throws If the hash instance has already been destroyed or finalized. {@link Error} + * @example + * Validate that a hash instance is still usable. + * ```ts + * import { aexists } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aexists(hash); + * ``` + */ +export function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error('Hash instance has been destroyed'); + if (checkFinished && instance.finished) + throw new Error('Hash#digest() has already been called'); +} +/** + * Asserts output is a sufficiently-sized byte array. + * @param out - destination buffer + * @param instance - hash instance providing output length + * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Validate a caller-provided digest buffer. + * ```ts + * import { aoutput } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const hash = sha256.create(); + * aoutput(new Uint8Array(hash.outputLen), hash); + * ``` + */ +export function aoutput(out, instance) { + abytes(out, undefined, 'digestInto() output'); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); + } +} +/** + * Casts a typed array view to Uint8Array. + * @param arr - source typed array + * @returns Uint8Array view over the same buffer. + * @example + * Reinterpret a typed array as bytes. + * ```ts + * u8(new Uint32Array([1, 2])); + * ``` + */ +export function u8(arr) { + return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Casts a typed array view to Uint32Array. + * `arr.byteOffset` must already be 4-byte aligned or the platform + * Uint32Array constructor will throw. + * @param arr - source typed array + * @returns Uint32Array view over the same buffer. + * @example + * Reinterpret a byte array as 32-bit words. + * ```ts + * u32(new Uint8Array(8)); + * ``` + */ +export function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +/** + * Zeroizes typed arrays in place. Warning: JS provides no guarantees. + * @param arrays - arrays to overwrite with zeros + * @example + * Zeroize sensitive buffers in place. + * ```ts + * clean(new Uint8Array([1, 2, 3])); + * ``` + */ +export function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +/** + * Creates a DataView for byte-level manipulation. + * @param arr - source typed array + * @returns DataView over the same buffer region. + * @example + * Create a DataView over an existing buffer. + * ```ts + * createView(new Uint8Array(4)); + * ``` + */ +export function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +/** + * Rotate-right operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the right. + * ```ts + * rotr(0x12345678, 8); + * ``` + */ +export function rotr(word, shift) { + return (word << (32 - shift)) | (word >>> shift); +} +/** + * Rotate-left operation for uint32 values. + * @param word - source word + * @param shift - shift amount in bits + * @returns Rotated word. + * @example + * Rotate a 32-bit word to the left. + * ```ts + * rotl(0x12345678, 8); + * ``` + */ +export function rotl(word, shift) { + return (word << shift) | ((word >>> (32 - shift)) >>> 0); +} +/** Whether the current platform is little-endian. */ +export const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)(); +/** + * Byte-swap operation for uint32 values. + * @param word - source word + * @returns Word with reversed byte order. + * @example + * Reverse the byte order of a 32-bit word. + * ```ts + * byteSwap(0x11223344); + * ``` + */ +export function byteSwap(word) { + return (((word << 24) & 0xff000000) | + ((word << 8) & 0xff0000) | + ((word >>> 8) & 0xff00) | + ((word >>> 24) & 0xff)); +} +/** + * Conditionally byte-swaps one 32-bit word on big-endian platforms. + * @param n - source word + * @returns Original or byte-swapped word depending on platform endianness. + * @example + * Normalize a 32-bit word for host endianness. + * ```ts + * swap8IfBE(0x11223344); + * ``` + */ +export const swap8IfBE = isLE + ? (n) => n + : (n) => byteSwap(n) >>> 0; +/** + * Byte-swaps every word of a Uint32Array in place. + * @param arr - array to mutate + * @returns The same array after mutation; callers pass live state arrays here. + * @example + * Reverse the byte order of every word in place. + * ```ts + * byteSwap32(new Uint32Array([0x11223344])); + * ``` + */ +export function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr; +} +/** + * Conditionally byte-swaps a Uint32Array on big-endian platforms. + * @param u - array to normalize for host endianness + * @returns Original or byte-swapped array depending on platform endianness. + * On big-endian runtimes this mutates `u` in place via `byteSwap32(...)`. + * @example + * Normalize a word array for host endianness. + * ```ts + * swap32IfBE(new Uint32Array([0x11223344])); + * ``` + */ +export const swap32IfBE = isLE + ? (u) => u + : byteSwap32; +// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex +const hasHexBuiltin = /* @__PURE__ */ (() => +// @ts-ignore +typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')(); +// Array where index 0xf0 (240) is mapped to string 'f0' +const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0')); +/** + * Convert byte array to hex string. + * Uses the built-in function when available and assumes it matches the tested + * fallback semantics. + * @param bytes - bytes to encode + * @returns Lowercase hexadecimal string. + * @throws On wrong argument types. {@link TypeError} + * @example + * Convert bytes to lowercase hexadecimal. + * ```ts + * bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])); // 'cafe0123' + * ``` + */ +export function bytesToHex(bytes) { + abytes(bytes); + // @ts-ignore + if (hasHexBuiltin) + return bytes.toHex(); + // pre-caching improves the speed 6x + let hex = ''; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +// We use optimized technique to convert hex string to byte array +const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; // '2' => 50-48 + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); // 'B' => 66-(65-10) + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); // 'b' => 98-(97-10) + return; +} +/** + * Convert hex string to byte array. Uses built-in function, when available. + * @param hex - hexadecimal string to decode + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode lowercase hexadecimal into bytes. + * ```ts + * hexToBytes('cafe0123'); // Uint8Array.from([0xca, 0xfe, 0x01, 0x23]) + * ``` + */ +export function hexToBytes(hex) { + if (typeof hex !== 'string') + throw new TypeError('hex string expected, got ' + typeof hex); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex); + } + catch (error) { + if (error instanceof SyntaxError) + throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError('hex string expected, got unpadded hex of length ' + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === undefined || n2 === undefined) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163 + } + return array; +} +/** + * There is no setImmediate in browser and setTimeout is slow. + * This yields to the Promise/microtask scheduler queue, not to timers or the + * full macrotask event loop. + * @example + * Yield to the next scheduler tick. + * ```ts + * await nextTick(); + * ``` + */ +export const nextTick = async () => { }; +/** + * Returns control to the Promise/microtask scheduler every `tick` + * milliseconds to avoid blocking long loops. + * @param iters - number of loop iterations to run + * @param tick - maximum time slice in milliseconds + * @param cb - callback executed on each iteration + * @example + * Run a loop that periodically yields back to the event loop. + * ```ts + * await asyncLoop(2, 0, () => {}); + * ``` + */ +export async function asyncLoop(iters, tick, cb) { + let ts = Date.now(); + for (let i = 0; i < iters; i++) { + cb(i); + // Date.now() is not monotonic, so in case if clock goes backwards we return return control too + const diff = Date.now() - ts; + if (diff >= 0 && diff < tick) + continue; + await nextTick(); + ts += diff; + } +} +/** + * Converts string to bytes using UTF8 encoding. + * Built-in doesn't validate input to be string: we do the check. + * Non-ASCII details are delegated to the platform `TextEncoder`. + * @param str - string to encode + * @returns UTF-8 encoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Encode a string as UTF-8 bytes. + * ```ts + * utf8ToBytes('abc'); // Uint8Array.from([97, 98, 99]) + * ``` + */ +export function utf8ToBytes(str) { + if (typeof str !== 'string') + throw new TypeError('string expected'); + return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809 +} +/** + * Helper for KDFs: consumes Uint8Array or string. + * String inputs are UTF-8 encoded; byte-array inputs stay aliased to the caller buffer. + * @param data - user-provided KDF input + * @param errorTitle - label included in thrown errors + * @returns Byte representation of the input. + * @throws On wrong argument types. {@link TypeError} + * @example + * Normalize KDF input to bytes. + * ```ts + * kdfInputToBytes('password'); + * ``` + */ +export function kdfInputToBytes(data, errorTitle = '') { + if (typeof data === 'string') + return utf8ToBytes(data); + return abytes(data, undefined, errorTitle); +} +/** + * Copies several Uint8Arrays into one. + * @param arrays - arrays to concatenate + * @returns Concatenated byte array. + * @throws On wrong argument types. {@link TypeError} + * @example + * Concatenate multiple byte arrays. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +export function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +/** + * Merges default options and passed options. + * @param defaults - base option object + * @param opts - user overrides + * @returns Merged option object. The merge mutates `defaults` in place. + * @throws On wrong argument types. {@link TypeError} + * @example + * Merge user overrides onto default options. + * ```ts + * checkOpts({ dkLen: 32 }, { asyncTick: 10 }); + * ``` + */ +export function checkOpts(defaults, opts) { + if (opts !== undefined && {}.toString.call(opts) !== '[object Object]') + throw new TypeError('options must be object or undefined'); + const merged = Object.assign(defaults, opts); + return merged; +} +/** + * Creates a callable hash function from a stateful class constructor. + * @param hashCons - hash constructor or factory + * @param info - optional metadata such as DER OID + * @returns Frozen callable hash wrapper with `.create()`. + * Wrapper construction eagerly calls `hashCons(undefined)` once to read + * `outputLen` / `blockLen`, so constructor side effects happen at module + * init time. + * @example + * Wrap a stateful hash constructor into a callable helper. + * ```ts + * import { createHasher } from '@noble/hashes/utils.js'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const wrapped = createHasher(sha256.create, { oid: sha256.oid }); + * wrapped(new Uint8Array([1])); + * ``` + */ +export function createHasher(hashCons, info = {}) { + const hashC = (msg, opts) => hashCons(opts) + .update(msg) + .digest(); + const tmp = hashCons(undefined); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); +} +/** + * Cryptographically secure PRNG backed by `crypto.getRandomValues`. + * @param bytesLength - number of random bytes to generate + * @returns Random bytes. + * The platform `getRandomValues()` implementation still defines any + * single-call length cap, and this helper rejects oversize requests + * with a stable library `RangeError` instead of host-specific errors. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @throws If the current runtime does not provide `crypto.getRandomValues`. {@link Error} + * @example + * Generate a fresh random key or nonce. + * ```ts + * const key = randomBytes(16); + * ``` + */ +export function randomBytes(bytesLength = 32) { + // Match the repo's other length-taking helpers instead of relying on Uint8Array coercion. + anumber(bytesLength, 'bytesLength'); + const cr = typeof globalThis === 'object' ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== 'function') + throw new Error('crypto.getRandomValues must be defined'); + // Web Cryptography API Level 2 §10.1.1: + // if `byteLength > 65536`, throw `QuotaExceededError`. + // Keep the guard explicit so callers can see the quota in code + // instead of discovering it by reading the spec or host errors. + // This wrapper surfaces the same quota as a stable library RangeError. + if (bytesLength > 65536) + throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +/** + * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`. + * @param suffix - final OID byte for the selected hash. + * The helper accepts any byte even though only the documented NIST hash + * suffixes are meaningful downstream. + * @returns Object containing the DER-encoded OID. + * @example + * Build OID metadata for a NIST hash. + * ```ts + * oidNist(0x01); + * ``` + */ +export const oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]), +}); +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/utils.js.map b/node_modules/@noble/hashes/utils.js.map new file mode 100644 index 0000000..76f809d --- /dev/null +++ b/node_modules/@noble/hashes/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AA8GA;;;;;;;;;GASG;AACH,MAAM,UAAU,OAAO,CAAC,CAAU;IAChC,2FAA2F;IAC3F,gEAAgE;IAChE,qEAAqE;IACrE,uEAAuE;IACvE,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YACpB,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,YAAY;YACnC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tD,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,WAAW,CAAC,WAAW,GAAG,EAAE;IAC1C,0FAA0F;IAC1F,OAAO,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IACpC,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAE,UAAkB,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9E,IAAI,OAAO,EAAE,EAAE,eAAe,KAAK,UAAU;QAC3C,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC5D,wCAAwC;IACxC,uDAAuD;IACvD,+DAA+D;IAC/D,gEAAgE;IAChE,uEAAuE;IACvE,IAAI,WAAW,GAAG,KAAK;QACrB,MAAM,IAAI,UAAU,CAAC,wCAAwC,WAAW,EAAE,CAAC,CAAC;IAC9E,OAAO,EAAE,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,WAAW,CAAC,CAAC,CAAC;AACzD,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,MAAc,EAA4B,EAAE,CAAC,CAAC;IACpE,+EAA+E;IAC/E,qFAAqF;IACrF,GAAG,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;CAC3F,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/webcrypto.d.ts b/node_modules/@noble/hashes/webcrypto.d.ts new file mode 100644 index 0000000..9226c66 --- /dev/null +++ b/node_modules/@noble/hashes/webcrypto.d.ts @@ -0,0 +1,120 @@ +import { type Pbkdf2Opt } from './pbkdf2.ts'; +import { type KDFInput, type TArg, type TRet } from './utils.ts'; +/** Callable WebCrypto hash function descriptor. */ +export type WebHash = { + /** + * Hashes one message with the selected WebCrypto digest. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + */ + (msg: TArg): Promise>; + /** WebCrypto algorithm name passed to `crypto.subtle`. */ + webCryptoName: string; + /** Digest size in bytes. */ + outputLen: number; + /** Input block size in bytes. */ + blockLen: number; +}; +/** WebCrypto SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */ +/** + * WebCrypto SHA2-256 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-256. + * ```ts + * await sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha256: TRet; +/** + * WebCrypto SHA2-384 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-384. + * ```ts + * await sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha384: TRet; +/** + * WebCrypto SHA2-512 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-512. + * ```ts + * await sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export declare const sha512: TRet; +/** + * WebCrypto HMAC: RFC2104 message authentication code. + * @param hash - function that would be used e.g. sha256. Webcrypto version. + * @param key - authentication key bytes + * @param message - message bytes to authenticate + * @returns Promise resolving to authentication tag bytes. + * `.create()` exists only to mirror the synchronous API surface + * and always throws `not implemented`. + * @example + * Compute an RFC 2104 HMAC with WebCrypto. + * ```ts + * import { hmac, sha256 } from '@noble/hashes/webcrypto.js'; + * await hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])); + * ``` + */ +type WebHmacFn = { + (hash: TArg, key: TArg, message: TArg): Promise>; + create(hash: TArg, key: TArg): any; +}; +export declare const hmac: TRet; +/** + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256). Webcrypto version. + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` requests an empty OKM. + * @returns Promise resolving to derived key bytes. + * The RFC `L <= 255 * HashLen` bound is currently enforced only by backend + * `deriveBits()` rejection, not by an explicit library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf, sha256 } from '@noble/hashes/webcrypto.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = await hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export declare function hkdf(hash: TArg, ikm: TArg, salt: TArg, info: TArg, length: number): Promise>; +/** + * WebCrypto PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256. Webcrypto version. + * @param password - password from which a derived key is generated; string + * inputs are normalized through `kdfInputToBytes()`, i.e. UTF-8 + * @param salt - cryptographic salt; string inputs are normalized through + * `kdfInputToBytes()`, i.e. UTF-8 + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * Positive-iteration enforcement is currently delegated to backend + * `deriveBits()` rejection (for example `c = 0`), not a dedicated + * library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2, sha256 } from '@noble/hashes/webcrypto.js'; + * const key = await pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export declare function pbkdf2(hash: TArg, password: TArg, salt: TArg, opts: Pbkdf2Opt): Promise>; +export {}; +//# sourceMappingURL=webcrypto.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/webcrypto.d.ts.map b/node_modules/@noble/hashes/webcrypto.d.ts.map new file mode 100644 index 0000000..be40d07 --- /dev/null +++ b/node_modules/@noble/hashes/webcrypto.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.d.ts","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAOL,KAAK,QAAQ,EACb,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AASpB,mDAAmD;AACnD,MAAM,MAAM,OAAO,GAAG;IACpB;;;;OAIG;IACH,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IACnD,0DAA0D;IAC1D,aAAa,EAAE,MAAM,CAAC;IACtB,4BAA4B;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,iCAAiC;IACjC,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AA0BF,uFAAuF;AAGvF;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,OAAO,CAAoD,CAAC;AACtF;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,OAAO,CAAqD,CAAC;AACvF;;;;;;;;;GASG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,OAAO,CAAqD,CAAC;AAEvF;;;;;;;;;;;;;;GAcG;AACH,KAAK,SAAS,GAAG;IACf,CACE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EACnB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,OAAO,EAAE,IAAI,CAAC,UAAU,CAAC,GACxB,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;IAC7B,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC;CACzD,CAAC;AACF,eAAO,MAAM,IAAI,EAAE,IAAI,CAAC,SAAS,CA2B7B,CAAC;AAEL;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,IAAI,CACxB,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EACnB,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,IAAI,EAAE,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,IAAI,EAAE,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC,EAClC,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAe3B;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,MAAM,CAC1B,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EACnB,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,EACxB,IAAI,EAAE,IAAI,CAAC,QAAQ,CAAC,EACpB,IAAI,EAAE,SAAS,GACd,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAgB3B"} \ No newline at end of file diff --git a/node_modules/@noble/hashes/webcrypto.js b/node_modules/@noble/hashes/webcrypto.js new file mode 100644 index 0000000..0818023 --- /dev/null +++ b/node_modules/@noble/hashes/webcrypto.js @@ -0,0 +1,165 @@ +import {} from "./pbkdf2.js"; +import { abytes, ahash, anumber, checkOpts, kdfInputToBytes, } from "./utils.js"; +function _subtle() { + const cr = typeof globalThis === 'object' ? globalThis.crypto : null; + const sb = cr?.subtle; + if (typeof sb === 'object' && sb != null) + return sb; + throw new Error('crypto.subtle must be defined'); +} +function createWebHash(name, blockLen, outputLen) { + const hashC = async (msg) => { + abytes(msg); + const crypto = _subtle(); + return new Uint8Array(await crypto.digest(name, msg)); + }; + hashC.webCryptoName = name; // make sure it won't interfere with function name + hashC.outputLen = outputLen; + hashC.blockLen = blockLen; + hashC.create = () => { + // Present only so this async wrapper satisfies the shared + // hash-wrapper shape checked by `ahashWeb()`. + throw new Error('not implemented'); + }; + // Later WebCrypto HMAC/HKDF/PBKDF2 calls read descriptor metadata directly, so freezing prevents + // callers from retargeting a `sha256` wrapper into a different backend digest by mutation. + return Object.freeze(hashC); +} +function ahashWeb(hash) { + ahash(hash); + if (typeof hash.webCryptoName !== 'string') + throw new Error('non-web hash'); +} +/** WebCrypto SHA1 (RFC 3174) legacy hash function. It was cryptographically broken. */ +// export const sha1: WebHash = createHash('SHA-1', 64, 20); +/** + * WebCrypto SHA2-256 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-256. + * ```ts + * await sha256(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha256 = /* @__PURE__ */ createWebHash('SHA-256', 64, 32); +/** + * WebCrypto SHA2-384 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-384. + * ```ts + * await sha384(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha384 = /* @__PURE__ */ createWebHash('SHA-384', 128, 48); +/** + * WebCrypto SHA2-512 hash function from RFC 6234. + * @param msg - message bytes to hash + * @returns Promise resolving to digest bytes. + * @example + * Hash a message with WebCrypto SHA2-512. + * ```ts + * await sha512(new Uint8Array([97, 98, 99])); + * ``` + */ +export const sha512 = /* @__PURE__ */ createWebHash('SHA-512', 128, 64); +export const hmac = /* @__PURE__ */ (() => { + const hmac_ = async (hash, key, message) => { + const crypto = _subtle(); + abytes(key, undefined, 'key'); + abytes(message, undefined, 'message'); + ahashWeb(hash); + // WebCrypto keys can't be zeroized + // prettier-ignore + const wkey = await crypto.importKey('raw', key, { name: 'HMAC', hash: hash.webCryptoName }, false, ['sign']); + return new Uint8Array(await crypto.sign('HMAC', wkey, message)); + }; + hmac_.create = (_hash, _key) => { + throw new Error('not implemented'); + }; + return hmac_; +})(); +/** + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * Combines hkdf_extract + hkdf_expand in one step + * @param hash - hash function that would be used (e.g. sha256). Webcrypto version. + * @param ikm - input keying material, the initial key + * @param salt - optional salt value (a non-secret random value) + * @param info - optional context and application specific information bytes + * @param length - length of output keying material in bytes. + * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` requests an empty OKM. + * @returns Promise resolving to derived key bytes. + * The RFC `L <= 255 * HashLen` bound is currently enforced only by backend + * `deriveBits()` rejection, not by an explicit library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto HKDF (RFC 5869): derive keys from an initial input. + * ```ts + * import { hkdf, sha256 } from '@noble/hashes/webcrypto.js'; + * import { randomBytes, utf8ToBytes } from '@noble/hashes/utils.js'; + * const inputKey = randomBytes(32); + * const salt = randomBytes(32); + * const info = utf8ToBytes('application-key'); + * const okm = await hkdf(sha256, inputKey, salt, info, 32); + * ``` + */ +export async function hkdf(hash, ikm, salt, info, length) { + const crypto = _subtle(); + ahashWeb(hash); + abytes(ikm, undefined, 'ikm'); + anumber(length, 'length'); + if (salt !== undefined) + abytes(salt, undefined, 'salt'); + if (info !== undefined) + abytes(info, undefined, 'info'); + const wkey = await crypto.importKey('raw', ikm, 'HKDF', false, ['deriveBits']); + const opts = { + name: 'HKDF', + hash: hash.webCryptoName, + salt: salt === undefined ? new Uint8Array(0) : salt, + info: info === undefined ? new Uint8Array(0) : info, + }; + return new Uint8Array(await crypto.deriveBits(opts, wkey, 8 * length)); +} +/** + * WebCrypto PBKDF2-HMAC: RFC 8018 key derivation function. + * @param hash - hash function that would be used e.g. sha256. Webcrypto version. + * @param password - password from which a derived key is generated; string + * inputs are normalized through `kdfInputToBytes()`, i.e. UTF-8 + * @param salt - cryptographic salt; string inputs are normalized through + * `kdfInputToBytes()`, i.e. UTF-8 + * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided, + * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}. + * @returns Promise resolving to derived key bytes. + * Positive-iteration enforcement is currently delegated to backend + * `deriveBits()` rejection (for example `c = 0`), not a dedicated + * library-side guard. + * @throws If the current runtime does not provide `crypto.subtle`. {@link Error} + * @example + * WebCrypto PBKDF2-HMAC: RFC 2898 key derivation function. + * ```ts + * import { pbkdf2, sha256 } from '@noble/hashes/webcrypto.js'; + * const key = await pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) }); + * ``` + */ +export async function pbkdf2(hash, password, salt, opts) { + const crypto = _subtle(); + ahashWeb(hash); + const _opts = checkOpts({ dkLen: 32 }, opts); + const { c, dkLen } = _opts; + anumber(c, 'c'); + anumber(dkLen, 'dkLen'); + // RFC 8018 §5.2 defines dkLen as a positive integer. + if (dkLen < 1) + throw new Error('"dkLen" must be >= 1'); + const _password = kdfInputToBytes(password, 'password'); + const _salt = kdfInputToBytes(salt, 'salt'); + const key = await crypto.importKey('raw', _password, 'PBKDF2', false, [ + 'deriveBits', + ]); + const deriveOpts = { name: 'PBKDF2', salt: _salt, iterations: c, hash: hash.webCryptoName }; + return new Uint8Array(await crypto.deriveBits(deriveOpts, key, 8 * dkLen)); +} +//# sourceMappingURL=webcrypto.js.map \ No newline at end of file diff --git a/node_modules/@noble/hashes/webcrypto.js.map b/node_modules/@noble/hashes/webcrypto.js.map new file mode 100644 index 0000000..f489b26 --- /dev/null +++ b/node_modules/@noble/hashes/webcrypto.js.map @@ -0,0 +1 @@ +{"version":3,"file":"webcrypto.js","sourceRoot":"","sources":["src/webcrypto.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,MAAM,aAAa,CAAC;AAC7C,OAAO,EACL,MAAM,EACN,KAAK,EACL,OAAO,EACP,SAAS,EACT,eAAe,GAKhB,MAAM,YAAY,CAAC;AAEpB,SAAS,OAAO;IACd,MAAM,EAAE,GAAG,OAAO,UAAU,KAAK,QAAQ,CAAC,CAAC,CAAE,UAAkB,CAAC,MAAM,CAAC,CAAC,CAAC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AAC,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE,IAAI,CAAC,CAAC;IAC7C,MAAM,EAAE,CAAC,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;IAC3B,OAAO,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAChB,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACxB,qDAAqD;IACrD,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAC;IACvD,MAAM,SAAS,GAAG,eAAe,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IACxD,MAAM,KAAK,GAAG,eAAe,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAC5C,MAAM,GAAG,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,SAAyB,EAAE,QAAQ,EAAE,KAAK,EAAE;QACpF,YAAY;KACb,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,UAAU,EAAE,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,CAAC;IAC5F,OAAO,IAAI,UAAU,CAAC,MAAM,MAAM,CAAC,UAAU,CAAC,UAAU,EAAE,GAAG,EAAE,CAAC,GAAG,KAAK,CAAC,CAAqB,CAAC;AACjG,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/LICENSE b/node_modules/@noble/post-quantum/LICENSE new file mode 100644 index 0000000..da95be3 --- /dev/null +++ b/node_modules/@noble/post-quantum/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2024 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/README.md b/node_modules/@noble/post-quantum/README.md new file mode 100644 index 0000000..23045ae --- /dev/null +++ b/node_modules/@noble/post-quantum/README.md @@ -0,0 +1,366 @@ +# noble-post-quantum + +Auditable & minimal JS implementation of post-quantum public-key cryptography. + +- 🔒 Auditable +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🔍 Reliable: tests ensure correctness +- 🦾 ML-KEM & CRYSTALS-Kyber: lattice-based KEM from FIPS-203 +- 🔋 ML-DSA & CRYSTALS-Dilithium: lattice-based signatures from FIPS-204 +- 🐈 SLH-DSA & SPHINCS+: hash-based Winternitz signatures from FIPS-205 +- 🦅 Falcon: lattice-based signatures from Falcon Round 3 +- 🍡 Hybrid algorithms, combining classic & post-quantum: Concrete, XWing, KitchenSink +- 🪶 16KB (gzipped) for everything, including bundled hashes & curves + +Take a glance at [GitHub Discussions](https://github.com/paulmillr/noble-post-quantum/discussions) for questions and support. + +> [!IMPORTANT] +> NIST published [IR 8547](https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf), +> prohibiting classical cryptography (RSA, DSA, ECDSA, ECDH) after 2035. +> Australian ASD does same thing [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography). +> Take it into an account while designing a new cryptographic system. + +### This library belongs to _noble_ cryptography + +> **noble cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- All libraries: + [ciphers](https://github.com/paulmillr/noble-ciphers), + [curves](https://github.com/paulmillr/noble-curves), + [hashes](https://github.com/paulmillr/noble-hashes), + [post-quantum](https://github.com/paulmillr/noble-post-quantum), + 5kb [secp256k1](https://github.com/paulmillr/noble-secp256k1) / + [ed25519](https://github.com/paulmillr/noble-ed25519) +- [Check out the homepage](https://paulmillr.com/noble/) + for reading resources, documentation, and apps built with noble + +## Usage + +> `npm install @noble/post-quantum` + +> `deno add jsr:@noble/post-quantum` + +We support all major platforms and runtimes. +For React Native, you may need a +[polyfill for getRandomValues](https://github.com/LinusU/react-native-get-random-values). +A standalone file +[noble-post-quantum.js](https://github.com/paulmillr/noble-post-quantum/releases) is also available. + +```js +// import * from '@noble/post-quantum'; // Error: use sub-imports instead +import { ml_kem512, ml_kem768, ml_kem1024 } from '@noble/post-quantum/ml-kem.js'; +import { ml_dsa44, ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa.js'; +import { + slh_dsa_sha2_128f, + slh_dsa_sha2_128s, + slh_dsa_sha2_192f, + slh_dsa_sha2_192s, + slh_dsa_sha2_256f, + slh_dsa_sha2_256s, + slh_dsa_shake_128f, + slh_dsa_shake_128s, + slh_dsa_shake_192f, + slh_dsa_shake_192s, + slh_dsa_shake_256f, + slh_dsa_shake_256s, +} from '@noble/post-quantum/slh-dsa.js'; +import { + falcon512, falcon512padded, falcon1024, falcon1024padded, +} from '@noble/post-quantum/falcon.js'; +import { + ml_kem768_x25519, ml_kem768_p256, ml_kem1024_p384, + KitchenSink_ml_kem768_x25519, XWing, + QSF_ml_kem768_p256, QSF_ml_kem1024_p384, +} from '@noble/post-quantum/hybrid.js'; +``` + +- [ML-KEM / Kyber](#ml-kem--kyber-shared-secrets) +- [ML-DSA / Dilithium](#ml-dsa--dilithium-signatures) +- [SLH-DSA / SPHINCS+](#slh-dsa--sphincs-signatures) +- [Falcon](#falcon-signatures) +- [hybrid: XWing, KitchenSink and others](#hybrid-xwing-kitchensink-and-others) +- [What should I use?](#what-should-i-use) +- [Security](#security) +- [Speed](#speed) +- [Contributing & testing](#contributing--testing) +- [License](#license) + +### ML-KEM / Kyber shared secrets + +```ts +import { ml_kem512, ml_kem768, ml_kem1024 } from '@noble/post-quantum/ml-kem.js'; +import { randomBytes } from '@noble/post-quantum/utils.js'; +import { notDeepStrictEqual } from 'node:assert'; +const seed = randomBytes(64); // seed is optional +const aliceKeys = ml_kem768.keygen(seed); +const { cipherText, sharedSecret: bobShared } = ml_kem768.encapsulate(aliceKeys.publicKey); +const aliceShared = ml_kem768.decapsulate(cipherText, aliceKeys.secretKey); + +// Warning: Can be MITM-ed +const malloryKeys = ml_kem768.keygen(); +const malloryShared = ml_kem768.decapsulate(cipherText, malloryKeys.secretKey); // No error! +notDeepStrictEqual(aliceShared, malloryShared); // Different key! +``` + +Lattice-based key encapsulation mechanism, defined in [FIPS-203](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.203.pdf) ([website](https://www.pq-crystals.org/kyber/resources.shtml), [repo](https://github.com/pq-crystals/kyber)). +Can be used as follows: + +1. *Alice* generates secret & public keys, then sends publicKey to *Bob* +2. *Bob* generates shared secret for Alice publicKey. + bobShared never leaves *Bob* system and is unknown to other parties +3. *Alice* gets and decrypts cipherText from Bob + Now, both Alice and Bob have same sharedSecret key + without exchanging in plainText: aliceShared == bobShared. + +There are some concerns with regards to security: see +[djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and +[mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E). +Old, incompatible version (Kyber) is not provided. Open an issue if you need it. + +> [!WARNING] +> Unlike ECDH, KEM doesn't verify whether it was "Bob" who've sent the ciphertext. +> Instead of throwing an error when the ciphertext is encrypted by a different pubkey, +> `decapsulate` will simply return a different shared secret. +> ML-KEM is also probabilistic and relies on quality of CSPRNG. + +### ML-DSA / Dilithium signatures + +```ts +import { ml_dsa44, ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa.js'; +import { randomBytes } from '@noble/post-quantum/utils.js'; +const seed = randomBytes(32); // seed is optional +const keys = ml_dsa65.keygen(seed); +const msg = new TextEncoder().encode('hello noble'); +const sig = ml_dsa65.sign(msg, keys.secretKey); +const isValid = ml_dsa65.verify(sig, msg, keys.publicKey); +``` + +Lattice-based digital signature algorithm, defined in [FIPS-204](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.204.pdf) ([website](https://www.pq-crystals.org/dilithium/index.shtml), +[repo](https://github.com/pq-crystals/dilithium)). +The internals are similar to ML-KEM, but keys and params are different. + +### SLH-DSA / SPHINCS+ signatures + +```ts +import { + slh_dsa_sha2_128f as sph, + slh_dsa_sha2_128s, + slh_dsa_sha2_192f, + slh_dsa_sha2_192s, + slh_dsa_sha2_256f, + slh_dsa_sha2_256s, + slh_dsa_shake_128f, + slh_dsa_shake_128s, + slh_dsa_shake_192f, + slh_dsa_shake_192s, + slh_dsa_shake_256f, + slh_dsa_shake_256s, +} from '@noble/post-quantum/slh-dsa.js'; + +const keys2 = sph.keygen(); +const msg2 = new TextEncoder().encode('hello noble'); +const sig2 = sph.sign(msg2, keys2.secretKey); +const isValid2 = sph.verify(sig2, msg2, keys2.publicKey); +``` + +Hash-based digital signature algorithm, defined in [FIPS-205](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.205.pdf) ([website](https://sphincs.org), [repo](https://github.com/sphincs/sphincsplus)). We implement spec v3.1 with FIPS adjustments. + +- sha2 vs shake (sha3): indicates internal hash function used +- 128 / 192 / 256: indicates security level in bits +- s / f: indicates small vs fast trade-off + +SLH-DSA is slow: see [benchmarks](#speed) for key size & speed. + +### Falcon signatures + +```ts +import { falcon512, falcon1024 } from '@noble/post-quantum/falcon.js'; +import { randomBytes } from '@noble/post-quantum/utils.js'; +const seed3 = randomBytes(48); // seed is optional +const keys3 = falcon512.keygen(seed3); +const msg3 = new TextEncoder().encode('hello noble'); +const sig3 = falcon512.sign(msg3, keys3.secretKey); +const isValid3 = falcon512.verify(sig3, msg3, keys3.publicKey); +``` + +Lattice-based digital signature algorithm, submitted to NIST PQC Round 3 ([website](https://falcon-sign.info/), [Round 3 submissions](https://csrc.nist.gov/projects/post-quantum-cryptography/post-quantum-cryptography-standardization/round-3-submissions)). + +> [!WARNING] +> This is Falcon Round 3, not FN-DSA. FN-DSA is not final yet. +> FN-DSA (FIPS-206) would most likely be backwards-incompatible with Falcon. +> The implementation passes the published Round 3 KATs. + +- `falcon512`, `falcon1024`: variable-length detached signatures +- `falcon512padded`, `falcon1024padded`: fixed-length detached signatures +- `attached.seal(...)` / `attached.open(...)`: attached-signature API for Round 3 vectors and interop + +### hybrid: XWing, KitchenSink and others + +```js +import { + ml_kem768_x25519, ml_kem768_p256, ml_kem1024_p384, + KitchenSink_ml_kem768_x25519, XWing, + QSF_ml_kem768_p256, QSF_ml_kem1024_p384, +} from '@noble/post-quantum/hybrid.js'; +``` + +Hybrid submodule combine post-quantum algorithms with elliptic curve cryptography: + +- `ml_kem768_x25519`: ML-KEM-768 + X25519 (CG Framework, same as XWing) +- `ml_kem768_p256`: ML-KEM-768 + P-256 (CG Framework) +- `ml_kem1024_p384`: ML-KEM-1024 + P-384 (CG Framework) +- `KitchenSink_ml_kem768_x25519`: ML-KEM-768 + X25519 with HKDF-SHA256 combiner +- `QSF_ml_kem768_p256`: ML-KEM-768 + P-256 (QSF construction) +- `QSF_ml_kem1024_p384`: ML-KEM-1024 + P-384 (QSF construction) + +The following spec drafts are matched: + +- [irtf-cfrg-hybrid-kems-07](https://datatracker.ietf.org/doc/draft-irtf-cfrg-hybrid-kems/) +- [irtf-cfrg-concrete-hybrid-kems-02](https://datatracker.ietf.org/doc/draft-irtf-cfrg-concrete-hybrid-kems/) +- [connolly-cfrg-xwing-kem-09](https://datatracker.ietf.org/doc/draft-connolly-cfrg-xwing-kem/) +- [tls-westerbaan-xyber768d00-03](https://datatracker.ietf.org/doc/draft-tls-westerbaan-xyber768d00/) + +### What should I use? + +| | Speed | Key size | Sig size | Created in | Popularized in | Post-quantum? | +| ------- | ------ | ----------- | ----------- | ---------- | -------------- | ------------- | +| RSA | Normal | 256B - 2KB | 256B - 2KB | 1970s | 1990s | No | +| ECC | Normal | 32 - 256B | 48 - 128B | 1980s | 2010s | No | +| ML-KEM | Fast | 1.6 - 31KB | 1KB | 1990s | 2020s | Yes | +| ML-DSA | Normal | 1.3 - 2.5KB | 2.5 - 4.5KB | 1990s | 2020s | Yes | +| SLH-DSA | Slow | 32 - 128B | 17 - 50KB | 1970s | 2020s | Yes | +| FN-DSA | Slow | 0.9 - 1.8KB | 0.6 - 1.2KB | 1990s | 2020s | Yes | + +We suggest to use ECC + ML-KEM for key agreement, ECC + SLH-DSA for signatures. + +ML-KEM and ML-DSA are lattice-based. SLH-DSA is hash-based, which means it is built on top of older, more conservative primitives. NIST guidance for security levels: + +- Category 3 (~AES-192): ML-KEM-768, ML-DSA-65, SLH-DSA-192 +- Category 5 (~AES-256): ML-KEM-1024, ML-DSA-87, SLH-DSA-256 + +NIST recommends to use cat-3+, while australian [ASD only allows cat-5 after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography). + +It's also useful to check out [NIST SP 800-131Ar3](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar3.ipd.pdf) +for "Transitioning the Use of Cryptographic Algorithms and Key Lengths". + +For [hashes](https://github.com/paulmillr/noble-hashes), use SHA512 or SHA3-512 (not SHA256); and for [ciphers](https://github.com/paulmillr/noble-ciphers) ensure AES-256 or ChaCha. + +## Security + +The library has not been independently audited yet. + +- at version 0.6.1, in Apr 2026, it was audited by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/noble-post-quantum/compare/0.6.1..main) + +If you see anything unusual: investigate and report. + +### Constant-timeness + +There is no protection against side-channel attacks. +We actively research how to provide this property for post-quantum algorithms in JS. +Keep in mind that even hardware versions ML-KEM [are vulnerable](https://eprint.iacr.org/2023/1084). + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they're only used for development and build steps. + +For this package, there are 2 dependencies; and a few dev dependencies: + +- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality, used internally in every algorithm +- [noble-curves](https://github.com/paulmillr/noble-curves) provides elliptic curve cryptography for hybrid algorithms +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +### Randomness + +We rely on the built-in +[`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues), +which is considered a cryptographically secure PRNG. + +Browsers have had weaknesses in the past - and could again - but implementing a userspace CSPRNG is even worse, as there’s no reliable userspace source of high-quality entropy. + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run bench` will run benchmarks +- `npm run build:release` will build single file + +Check out [github.com/paulmillr/guidelines](https://github.com/paulmillr/guidelines) +for general coding practices and rules. + +See [paulmillr.com/noble](https://paulmillr.com/noble/) +for useful resources, articles, documentation and demos +related to the library. + +## Speed + +> `npm run bench` + +Noble is the fastest JS implementation of post-quantum algorithms. + +Benchmarks on Apple M4 (**higher is better**): + +``` +# ML-KEM768 +keygen x 4,277 ops/sec @ 233μs/op +encapsulate x 3,470 ops/sec @ 288μs/op +decapsulate x 3,757 ops/sec @ 266μs/op +# ML-DSA65 +keygen x 669 ops/sec @ 1ms/op +sign x 271 ops/sec @ 3ms/op +verify x 565 ops/sec @ 1ms/op +# SLH-DSA SHA2 192f +keygen x 235 ops/sec @ 4ms/op +sign x 8 ops/sec @ 117ms/op +verify x 159 ops/sec @ 6ms/op +# Falcon512 +keygen x 14 ops/sec @ 66ms/op ± 11.01% (56ms..96ms) +sign x 749 ops/sec @ 1ms/op +verify x 2,160 ops/sec @ 462μs/op +# Falcon1024 +keygen x 4 ops/sec @ 247ms/op ± 5.22% (234ms..266ms) +sign x 343 ops/sec @ 2ms/op +verify x 950 ops/sec @ 1ms/op +``` + +Compared with pre-quantum: + +| OPs/sec | Keygen | Signing | Verification | Shared secret | +| ----------------- | ------ | ------- | ------------ | ------------- | +| ECC x/ed25519 | 12648 | 6157 | 1255 | 1981 | +| ML-KEM-768 | 4277 | | | 3757 | +| ML-DSA65 | 669 | 271 | 565 | | +| SLH-DSA-SHA2-192f | 235 | 8 | 159 | | +| Falcon512 | 14 | 749 | 950 | | + +SLH-DSA: + +| | sig size | keygen | sign | verify | +| --------- | -------- | ------ | ------ | ------ | +| sha2_128f | 18088 | 4ms | 90ms | 6ms | +| sha2_192f | 35664 | 6ms | 160ms | 9ms | +| sha2_256f | 49856 | 15ms | 340ms | 9ms | +| sha2_128s | 7856 | 260ms | 2000ms | 2ms | +| sha2_192s | 16224 | 380ms | 3800ms | 3ms | +| sha2_256s | 29792 | 250ms | 3400ms | 4ms | +| shake_192f | 35664 | 21ms | 553ms | 29ms | +| shake_192s | 16224 | 260ms | 2635ms | 2ms | + +## License + +The MIT License (MIT) + +Copyright (c) 2024 Paul Miller [(https://paulmillr.com)](https://paulmillr.com) + +See LICENSE file. diff --git a/node_modules/@noble/post-quantum/_crystals.d.ts b/node_modules/@noble/post-quantum/_crystals.d.ts new file mode 100644 index 0000000..53ce5fe --- /dev/null +++ b/node_modules/@noble/post-quantum/_crystals.d.ts @@ -0,0 +1,120 @@ +import type { TypedArray } from '@noble/hashes/utils.js'; +import { type BytesCoderLen, type Coder, type TRet } from './utils.ts'; +/** Extendable-output reader used by the CRYSTALS implementations. */ +export type XOF = (seed: Uint8Array, blockLen?: number) => { + /** + * Read diagnostic counters for the current XOF session. + * @returns Current call and XOF block counters. + */ + stats: () => { + calls: number; + xofs: number; + }; + /** + * Select one `(x, y)` coordinate pair and get a block reader for it. + * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared + * SHAKE state and invalidates older readers. + * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they + * want to retain before the next read. + * @param x - First matrix coordinate. + * @param y - Second matrix coordinate. + * @returns Lazy block reader for that coordinate pair. + */ + get: (x: number, y: number) => () => Uint8Array; + /** Wipe any buffered state once the reader is no longer needed. */ + clean: () => void; +}; +/** CRYSTALS (ml-kem, ml-dsa) options */ +/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */ +export type CrystalOpts = { + /** + * Allocate one zeroed polynomial/vector container. + * @param n - Number of coefficients to allocate. + * @returns Fresh typed container. + */ + newPoly: TypedCons; + /** Polynomial size, typically `256`. */ + N: number; + /** Prime modulus used for all coefficient arithmetic. */ + Q: number; + /** Inverse transform normalization factor: + * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber. + */ + F: number; + /** Principal root of unity for the transform domain. */ + ROOT_OF_UNITY: number; + /** Number of bits used for bit-reversal ordering. */ + brvBits: number; + /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */ + isKyber: boolean; +}; +/** Constructor function for typed polynomial containers. */ +export type TypedCons = (n: number) => T; +type Crystals = { + mod: (a: number, modulo?: number) => number; + smod: (a: number, modulo?: number) => number; + nttZetas: T; + NTT: { + /** Forward transform in place. Mutates and returns `r`. */ + encode: (r: T) => T; + /** Inverse transform in place. Mutates and returns `r`. */ + decode: (r: T) => T; + }; + bitsCoder: (d: number, c: Coder) => BytesCoderLen; +}; +/** + * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes. + * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}. + * @returns CRYSTALS arithmetic and encoding helpers. + * @example + * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set. + * ```ts + * const crystals = genCrystals({ + * newPoly: (n) => new Uint16Array(n), + * N: 256, + * Q: 3329, + * F: 3303, + * ROOT_OF_UNITY: 17, + * brvBits: 7, + * isKyber: true, + * }); + * const reduced = crystals.mod(-1); + * ``` + */ +export declare const genCrystals: (opts: CrystalOpts) => TRet>; +/** + * SHAKE128-based extendable-output reader factory used by ML-KEM. + * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously + * returned readers, and each squeeze reuses one mutable internal output buffer. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-KEM SHAKE128 matrix expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF128 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF128(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export declare const XOF128: TRet; +/** + * SHAKE256-based extendable-output reader factory used by ML-DSA. + * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned + * readers, and reuses one mutable internal output buffer for each squeeze. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-DSA SHAKE256 coefficient expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF256 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF256(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export declare const XOF256: TRet; +export {}; +//# sourceMappingURL=_crystals.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/_crystals.d.ts.map b/node_modules/@noble/post-quantum/_crystals.d.ts.map new file mode 100644 index 0000000..e9b0cfd --- /dev/null +++ b/node_modules/@noble/post-quantum/_crystals.d.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EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAC5C,IAAI,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAC7C,QAAQ,EAAE,CAAC,CAAC;IACZ,GAAG,EAAE;QACH,2DAA2D;QAC3D,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;QACpB,2DAA2D;QAC3D,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,CAAC,CAAC;KACrB,CAAC;IACF,SAAS,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,aAAa,CAAC,CAAC,CAAC,CAAC;CACtE,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,WAAW,GAAI,CAAC,SAAS,UAAU,EAAE,MAAM,WAAW,CAAC,CAAC,CAAC,KAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAwGxF,CAAC;AAwCF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,GAAG,CAA4C,CAAC;AAC1E;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,MAAM,EAAE,IAAI,CAAC,GAAG,CAA4C,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/_crystals.js b/node_modules/@noble/post-quantum/_crystals.js new file mode 100644 index 0000000..4222184 --- /dev/null +++ b/node_modules/@noble/post-quantum/_crystals.js @@ -0,0 +1,201 @@ +/** + * Internal methods for lattice-based ML-KEM and ML-DSA. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js'; +import { shake128, shake256 } from '@noble/hashes/sha3.js'; +import { cleanBytes, getMask, } from "./utils.js"; +/** + * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes. + * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}. + * @returns CRYSTALS arithmetic and encoding helpers. + * @example + * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set. + * ```ts + * const crystals = genCrystals({ + * newPoly: (n) => new Uint16Array(n), + * N: 256, + * Q: 3329, + * F: 3303, + * ROOT_OF_UNITY: 17, + * brvBits: 7, + * isKyber: true, + * }); + * const reduced = crystals.mod(-1); + * ``` + */ +export const genCrystals = (opts) => { + // isKyber: true means Kyber, false means Dilithium + const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts; + // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by + // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic. + const mod = (a, modulo = Q) => { + const result = a % modulo | 0; + return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0; + }; + // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the + // positive midpoint when `modulo` is even. + // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`. + const smod = (a, modulo = Q) => { + const r = mod(a, modulo) | 0; + return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0; + }; + // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while + // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries. + function getZettas() { + const out = newPoly(N); + for (let i = 0; i < N; i++) { + const b = reverseBits(i, brvBits); + const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q); + out[i] = Number(p) | 0; + } + return out; + } + const nttZetas = getZettas(); + // Number-Theoretic Transform + // Explained: https://electricdusk.com/ntt.html + // Kyber has slightly different params, since there is no 512th primitive root of unity mod q, + // only 256th primitive root of unity mod. Which also complicates MultiplyNTT. + const field = { + add: (a, b) => mod((a | 0) + (b | 0)) | 0, + sub: (a, b) => mod((a | 0) - (b | 0)) | 0, + mul: (a, b) => mod((a | 0) * (b | 0)) | 0, + inv: (_a) => { + throw new Error('not implemented'); + }, + }; + const nttOpts = { + N, + roots: nttZetas, + invertButterflies: true, + skipStages: isKyber ? 1 : 0, + brp: false, + }; + const dif = FFTCore(field, { dit: false, ...nttOpts }); + const dit = FFTCore(field, { dit: true, ...nttOpts }); + const NTT = { + encode: (r) => { + return dif(r); + }, + decode: (r) => { + dit(r); + // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14 + // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`. + // kyber uses 128 here, because brv && stuff + for (let i = 0; i < r.length; i++) + r[i] = mod(F * r[i]); + return r; + }, + }; + // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode / + // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers. + const bitsCoder = (d, c) => { + const mask = getMask(d); + const bytesLen = d * (N / 8); + return { + bytesLen, + encode: (poly_) => { + const poly = poly_; + const r = new Uint8Array(bytesLen); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { + buf |= (c.encode(poly[i]) & mask) << bufLen; + bufLen += d; + for (; bufLen >= 8; bufLen -= 8, buf >>= 8) + r[pos++] = buf & getMask(bufLen); + } + return r; + }, + decode: (bytes) => { + const r = newPoly(N); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { + buf |= bytes[i] << bufLen; + bufLen += 8; + for (; bufLen >= d; bufLen -= d, buf >>= d) + r[pos++] = c.decode(buf & mask); + } + return r; + }, + }; + }; + return { + mod, + smod, + nttZetas: nttZetas, + NTT: { + encode: (r) => NTT.encode(r), + decode: (r) => NTT.decode(r), + }, + bitsCoder: bitsCoder, + }; +}; +const createXofShake = (shake) => (seed, blockLen) => { + if (!blockLen) + blockLen = shake.blockLen; + // Optimizations that won't mater: + // - cached seed update (two .update(), on start and on the end) + // - another cache which cloned into working copy + // Faster than multiple updates, since seed less than blockLen + const _seed = new Uint8Array(seed.length + 2); + _seed.set(seed); + const seedLen = seed.length; + const buf = new Uint8Array(blockLen); // == shake128.blockLen + let h = shake.create({}); + let calls = 0; + let xofs = 0; + return { + stats: () => ({ calls, xofs }), + get: (x, y) => { + // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate + // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`. + _seed[seedLen + 0] = x; + _seed[seedLen + 1] = y; + h.destroy(); + h = shake.create({}).update(_seed); + calls++; + return () => { + xofs++; + return h.xofInto(buf); + }; + }, + clean: () => { + h.destroy(); + cleanBytes(buf, _seed); + }, + }; +}; +/** + * SHAKE128-based extendable-output reader factory used by ML-KEM. + * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously + * returned readers, and each squeeze reuses one mutable internal output buffer. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-KEM SHAKE128 matrix expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF128 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF128(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export const XOF128 = /* @__PURE__ */ createXofShake(shake128); +/** + * SHAKE256-based extendable-output reader factory used by ML-DSA. + * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned + * readers, and reuses one mutable internal output buffer for each squeeze. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-DSA SHAKE256 coefficient expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF256 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF256(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export const XOF256 = /* @__PURE__ */ createXofShake(shake256); +//# sourceMappingURL=_crystals.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/_crystals.js.map b/node_modules/@noble/post-quantum/_crystals.js.map new file mode 100644 index 0000000..7f6a0ab --- /dev/null +++ b/node_modules/@noble/post-quantum/_crystals.js.map @@ -0,0 +1 @@ +{"version":3,"file":"_crystals.js","sourceRoot":"","sources":["src/_crystals.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,4EAA4E;AAC5E,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,EAEL,UAAU,EAEV,OAAO,GAGR,MAAM,YAAY,CAAC;AAoEpB;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAuB,IAAoB,EAAqB,EAAE;IAC3F,mDAAmD;IACnD,MAAM,EAAE,OAAO,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,aAAa,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC;IACnE,qFAAqF;IACrF,oEAAoE;IACpE,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,MAAM,GAAG,CAAC,EAAU,EAAE;QAC5C,MAAM,MAAM,GAAG,CAAC,GAAG,MAAM,GAAG,CAAC,CAAC;QAC9B,OAAO,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;IAChE,CAAC,CAAC;IACF,mFAAmF;IACnF,2CAA2C;IAC3C,uDAAuD;IACvD,MAAM,IAAI,GAAG,CAAC,CAAS,EAAE,MAAM,GAAG,CAAC,EAAU,EAAE;QAC7C,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7B,OAAO,CAAC,CAAC,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,GA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,CAAC,GAAG,CAAC,CAAC;YACvB,CAAC,CAAC,OAAO,EAAE,CAAC;YACZ,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACnC,KAAK,EAAE,CAAC;YACR,OAAO,GAAG,EAAE;gBACV,IAAI,EAAE,CAAC;gBACP,OAAO,CAAC,CAAC,OAAO,CAAC,GAAG,CAAqB,CAAC;YAC5C,CAAC,CAAC;QACJ,CAAC;QACD,KAAK,EAAE,GAAG,EAAE;YACV,CAAC,CAAC,OAAO,EAAE,CAAC;YACZ,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QACzB,CAAC;KACF,CAAC;AACJ,CAAC,CAAC;AAEJ;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,MAAM,GAAc,eAAe,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC;AAC1E;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,MAAM,MAAM,GAAc,eAAe,CAAC,cAAc,CAAC,QAAQ,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/falcon.d.ts b/node_modules/@noble/post-quantum/falcon.d.ts new file mode 100644 index 0000000..794cc99 --- /dev/null +++ b/node_modules/@noble/post-quantum/falcon.d.ts @@ -0,0 +1,84 @@ +import { type CryptoKeys, type Signer, type SigOpts, type TRet, type VerOpts } from './utils.ts'; +type FalconRandom = (bytesLength?: number) => TRet; +type FalconSigOpts = SigOpts & { + random?: FalconRandom; +}; +/** Falcon attached-signature API. */ +export type FalconAttached = CryptoKeys & { + /** Key lengths plus the 48-byte sampler-seed hook for signing. */ + lengths: CryptoKeys['lengths'] & { + signRand?: number; + }; + /** + * Signs a message and appends it to the returned attached signature. + * @param msg Message bytes to sign. + * @param secretKey Falcon secret key bytes. + * @param opts Optional Falcon signing options. + * @returns Attached signature containing both the message and signature. + */ + seal(msg: Uint8Array, secretKey: Uint8Array, opts?: FalconSigOpts): Uint8Array; + /** + * Verifies an attached signature and returns the embedded message. + * @param sig Attached Falcon signature bytes. + * @param publicKey Falcon public key bytes. + * @param opts Optional verification options. + * @returns Embedded message bytes when the signature is valid. + */ + open(sig: Uint8Array, publicKey: Uint8Array, opts?: VerOpts): Uint8Array; +}; +/** Falcon detached-signature API with an attached-signature helper. */ +export type Falcon = Signer & { + /** Attached-signature helper for the same Falcon parameter set. */ + attached: FalconAttached; +}; +/** + * Falcon-512 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512.sign(msg, secretKey); + * falcon512.verify(sig, msg, publicKey); + * ``` + */ +export declare const falcon512: TRet; +/** + * Falcon-512 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512padded.sign(msg, secretKey); + * falcon512padded.verify(sig, msg, publicKey); + * ``` + */ +export declare const falcon512padded: TRet; +/** + * Falcon-1024 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024.sign(msg, secretKey); + * falcon1024.verify(sig, msg, publicKey); + * ``` + */ +export declare const falcon1024: TRet; +/** + * Falcon-1024 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024padded.sign(msg, secretKey); + * falcon1024padded.verify(sig, msg, publicKey); + * ``` + */ +export declare const falcon1024padded: TRet; +export declare const __tests: any; +export {}; +//# sourceMappingURL=falcon.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/falcon.d.ts.map b/node_modules/@noble/post-quantum/falcon.d.ts.map new file mode 100644 index 0000000..a8e0661 --- /dev/null +++ b/node_modules/@noble/post-quantum/falcon.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"falcon.d.ts","sourceRoot":"","sources":["src/falcon.ts"],"names":[],"mappings":"AAyBA,OAAO,EAKL,KAAK,UAAU,EAEf,KAAK,MAAM,EACX,KAAK,OAAO,EAGZ,KAAK,IAAI,EAGT,KAAK,OAAO,EACb,MAAM,YAAY,CAAC;AA0oCpB,KAAK,YAAY,GAAG,CAAC,WAAW,CAAC,EAAE,MAAM,KAAK,IAAI,CAAC,UAAU,CAAC,CAAC;AAC/D,KAAK,aAAa,GAAG,OAAO,GAAG;IAAE,MAAM,CAAC,EAAE,YAAY,CAAA;CAAE,CAAC;AACzD,qCAAqC;AACrC,MAAM,MAAM,cAAc,GAAG,UAAU,GAAG;IACxC,kEAAkE;IAClE,OAAO,EAAE,UAAU,CAAC,SAAS,CAAC,GAAG;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACvD;;;;;;OAMG;IACH,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,aAAa,GAAG,UAAU,CAAC;IAC/E;;;;;;OAMG;IACH,IAAI,CAAC,GAAG,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,CAAC,EAAE,OAAO,GAAG,UAAU,CAAC;CAC1E,CAAC;AACF,uEAAuE;AACvE,MAAM,MAAM,MAAM,GAAG,MAAM,GAAG;IAC5B,mEAAmE;IACnE,QAAQ,EAAE,cAAc,CAAC;CAC1B,CAAC;AA+pCF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,MAAM,CACgB,CAAC;AACpD;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,MAAM,CAKlC,CAAC;AAaR;;;;;;;;;;GAUG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,MAAM,CAI7B,CAAC;AACR;;;;;;;;;;GAUG;AACH,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,MAAM,CAKnC,CAAC;AAGR,eAAO,MAAM,OAAO,EAAE,GAaf,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/falcon.js b/node_modules/@noble/post-quantum/falcon.js new file mode 100644 index 0000000..96c8cef --- /dev/null +++ b/node_modules/@noble/post-quantum/falcon.js @@ -0,0 +1,2385 @@ +/** + * Falcon pq-friendly signature algorithm. + * Will change in backwards-incompatible way once FIPS-206 gets finalized. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; +import { chacha20 } from '@noble/ciphers/chacha.js'; +import { FFTCore } from '@noble/curves/abstract/fft.js'; +import { invert } from '@noble/curves/abstract/modular.js'; +import { bytesToNumberLE, numberToHexUnpadded } from '@noble/curves/utils.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import { abytes, bytesToHex, createView, hexToBytes, randomBytes, swap32IfBE, u32, u8, } from '@noble/hashes/utils.js'; +import { genCrystals } from "./_crystals.js"; +import { baswap64If, cleanBytes, getMask, splitCoder, validateSigOpts, validateVerOpts, } from "./utils.js"; +/* +FIPS-206 would likely improve the situation with spec. + +Falcon (non-FIPS) spec is terrible. Two main issues: non-deterministic keys & floats. + +## Summary + +- NIST round3 KATs pass +- No interop with other JS libraries, because they are incorrect +- No recoverPublicKey: it requires s1, which is calculated from public+s2. Sig only has s2. +- Code has verify_recover, but it's unused +- Mediocre code quality, primarily because it follows implementation-specific (C lib) tidbits +- Samplers are fragile + +## Non-deterministic keys + +Falcon spec doesn't provide enough data to re-create keys from KAT vectors. Spec mentions: +> This process reduces the maximum sizes of coefficients of F and G +> by about 30 bits at each iteration +While actual implementation reduces them by 25 bits (scale_k), which is very important detail. + +There are also various implementation checks not mentioned in spec, like +> let's skip this perfectly valid key, because it doesn't fit into our bigint implementation + +Without these, it's hard to produce correct keys. This means that, +unless NIST specifies full process with all operations, +**all keys are implementation-specific**. + +Which means, we cannot use any key derivation schemes here: same seed will return +different keys in different implementations. + +This also complicates testing a lot. If a key succesfully signs a message and other implementations +confirm it, there is still zero assurance with regards to quality / entropy of the key. +One can create a valid key, which nevertheless doesn't have enough entropy. + +## Floats + +Partially fixed by "fixed point" primitive. Falcon basically impelements floats on top of u64. + +It's more constant-time, but in JS there is no **fast** u64: + +- Using bigint backend would drop const-timeness +- Using u32 {hi, low} tuples means unnecessary allocations / jit deopt, + and is still 4 times slower than Floats + +Then, there are rounding issues. This is implementation specific. +This matters more for C, since 'double' is not neccesarily binary64. +In js, floats guaranteed to be IEEE-754 binary64. + +In theory floats are nice, but since fixed point format is not specified in spec +(other that "it is binary64"), this is even more fragile, since it doesn't implement exact +full spec of binary64 (two zeros/subnomarls/nans/etc). Those parts should not be used inside falcon, +but may cause some differences. + +Lack of specification is also hard to debug, brings precision loss (a+b+c !== a+c+b): +there are no serialized floats, all float arithmetic happens inside of an algorithm, so +we can produce same results (small differences rounded at the end). + +For byte-to-byte result in falcon, one needs to copy implementation-specific details, unspecced. + +## CSPRNG + +NIST KATs randomness situation is bad: + +1. aes-drbg generates seed +2. The seed passes CSPRNG into sign, which uses shake256 to produce another seed and nonce +3. Then a separate rejection sampling chacha20 CSPRNG is created, based on that seed. + +## Detached vs non-detached + +The API is different between detached / non-detached signatures, +however only non-detached (sm) is included in KAT, so we implement them +(crypto_sign_open instead of crypto_sign_verify). +*/ +// Utils +// MSB first. Current Falcon uses are byte-aligned only, and outer wrappers must still enforce +// exact body lengths / canonical padding because this helper neither flushes nor rejects a final +// partial field on its own. +const bitsCoderMSB = (newPoly, N, d, c) => { + const mask = getMask(d); + const bytesLen = d * (N / 8); + return { + bytesLen, + encode: (poly) => { + if (poly.length !== N) + throw new Error(`wrong length: expected ${N}, got ${poly.length}`); + const r = new Uint8Array(bytesLen); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { + buf = (buf << d) | (c.encode(poly[i]) & mask); + bufLen += d; + for (; bufLen >= 8; bufLen -= 8) + r[pos++] = (buf >>> (bufLen - 8)) & 0xff; + } + return r; + }, + decode: (bytes) => { + const r = newPoly(N); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { + buf = (buf << 8) | bytes[i]; + bufLen += 8; + for (; bufLen >= d; bufLen -= d) + r[pos++] = c.decode((buf >>> (bufLen - d)) & mask); + } + return r; + }, + }; +}; +// Adds a single leading tag byte. Exact body validation is delegated to `restCoder.decode()`. +// encode() zeroizes the temporary encoded body after copying, so wrapped encoders must return +// owned scratch bytes rather than caller-owned buffers. +const headerCoder = (tag, restCoder) => { + const coder = restCoder; + return { + bytesLen: 1 + coder.bytesLen, + encode(value) { + const body = coder.encode(value); + const out = new Uint8Array(1 + body.length); + out[0] = tag; + out.set(body, 1); + cleanBytes(body); + return out; + }, + decode(data) { + if (data[0] !== tag) + throw new Error(`wrong tag: expected ${tag}, got 0x${data[0]}`); + return coder.decode(data.subarray(1)); + }, + }; +}; +// Fun, but overengineered. Hoping FIPS would fix this. +// Falcon-specific Golomb-Rice compressed format: +// Vec<[1bit sign, 7 bit low, array(1 terminated).length==high <<7]>. +// decode() returns only coefficients, so callers must still enforce exact consumed length / +// canonical framing around the payload. +const compCoder = (n) => { + const LIMIT = 2047; + return { + encode(data) { + // Algorithm 17: Compress(s, slen) (Page 47) + // Require: A polynomial s = Σ sᵢxⁱ ∈ Z[x] of degree < n, a string bitlength slen + // Ensure: A compressed representation str of s of slen bits, or ⊥ + // 1: str ← {} ▷ str is the empty string + // 2: for i from 0 to n-1 do ▷ At each step, str ← (str||strᵢ), where strᵢ encodes sᵢ + // 3: str ← (str||b), where b = 1 if sᵢ < 0, b = 0 otherwise ▷ Encode the sign of sᵢ + // 4: str ← (str||b₆b₅...b₀), where bⱼ = (|sᵢ| >> j) & 0x1 + // ▷ Encode in binary the low bits of |sᵢ| + // 5: k ← |sᵢ| >> 7 + // 6: str ← (str||0ᵏ1) ▷ Encode in unary the high bits of |sᵢ| + // 7: if |str| > slen then + // 8: str ← ⊥ ▷ Abort if str is too long + // 9: else + // 10: str ← (str||0^{slen-|str|}) ▷ Pad str to slen bits + // 11: return str + if (data.length !== n) + throw new Error('wrong length'); + const res = []; + let buf = 0; + let bufLen = 0; + const writeBits = (n, v) => { + bufLen += n; + buf = (buf << n) | v; + // flush buffer if bigger than byte + for (; bufLen >= 8; buf &= getMask(bufLen)) { + bufLen -= 8; + res.push((buf >>> bufLen) & 0xff); + } + }; + for (let i = 0; i < n; i++) { + let v = data[i]; + if (!Number.isInteger(v) || v < -LIMIT || v > LIMIT) + throw new Error(`data[${i}]=${v} out of range`); + const sign = v < 0 ? 1 : 0; + v = Math.abs(v); + writeBits(1, sign); + writeBits(7, v & 0b0111_1111); // low + writeBits((v >>> 7) + 1, 1); // high (unary) + } + if (bufLen > 0) + res.push((buf << (8 - bufLen)) & 0xff); + return new Uint8Array(res); + }, + decode(data) { + // Algorithm 18: Decompress(str, slen), (Page 48) + // Require: A bitstring str = (str[i])_{i=0,...,slen-1}, a bitlength slen + // Ensure: A polynomial s = Σ sᵢxⁱ ∈ Z[x], or ⊥ + // 1: if |str| ≠ slen then ▷ Enforce fixed bitlength + // 2: return ⊥ + // 3: for i from 0 to (n-1) do + // 4: s'ᵢ ← Σ_{j=0 to 6} 2⁶⁻ʲ · str[1 + j] ▷ We recover the lowest bits of |sᵢ|. + // 5: k ← 0 + // 6: while str[8 + k] = 0 do ▷ We recover the highest bits of |sᵢ|. + // 7: k ← k + 1 + // 8: sᵢ ← (-1)^{str[0]} · (s'ᵢ + 2⁷k) ▷ We recompute sᵢ. + // 9: if (sᵢ = 0) and (str[0] = 1) then ▷ Enforce unique encoding if sᵢ = 0 + // 10: return ⊥ + // 11: str ← str with first 9 + k bits removed ▷ We remove the bits of str that encode sᵢ. + // 12: if str contains any non-zero bits then ▷ Enforce trailing bits at 0 + // 13: return ⊥ + // 14: return s = Σ_{i=0}^{n-1} sᵢxⁱ + const res = new Int16Array(n); + let buf = 0; + let bufLen = 0; + let pos = 0; + const readBits = (n) => { + for (; bufLen < n && pos < data.length; bufLen += 8) + buf = (buf << 8) | data[pos++]; + if (bufLen < n) + throw new Error(`end of buffer: len=${bufLen} buf=${buf} lastByte=${data[pos]}`); + bufLen -= n; + const val = buf >>> bufLen; + buf &= getMask(bufLen); + return val; + }; + for (let resPos = 0; resPos < n; resPos++) { + const sign = readBits(1); + const low = readBits(7); + let high = 0; + for (; !readBits(1); high++) + ; + const v = low | (high << 7); + if (sign && v === 0) + throw new Error('negative zero encoding'); + if (v > LIMIT) + throw new Error(`limit: ${v} > ${LIMIT}`); + res[resPos] = sign ? -v : v; + } + if (buf) + throw new Error('non-empty accumulator'); + return res; + }, + }; +}; +// Falcon padded-signature helper. encode() assumes `data.length <= len`; decode() strips trailing +// zero padding and returns a subarray view, so it is not a generic byte-string codec. +const pad = (len) => ({ + encode(data) { + const res = new Uint8Array(len); + res.set(data); + return res; + }, + decode(data) { + let end = data.length; + while (end > 0 && data[end - 1] === 0) + end--; + return data.subarray(0, end); + }, +}); +// Zero complex-polynomial temporaries in place. Requires fully initialized `{ re, im }` entries. +const cleanCPoly = (...list) => { + for (const p of list) { + for (let i = 0; i < p.length; i++) { + p[i].re = 0; + p[i].im = 0; + } + } +}; +// Generic complex helper used by Falcon's FFT code. Current audited use relies on +// add/sub/mul/conj/scale/magSqSum/neg; inv() is intentionally unimplemented. +function getComplex(field) { + const F = field; + return { + lift: (x) => { + // Reuse existing complex objects verbatim; callers that need isolation must clone first. + if (x.re !== undefined && x.im !== undefined) + return x; + return { re: x, im: F.ZERO }; + }, + add: (a, b) => ({ + re: F.add(a.re, b.re), + im: F.add(a.im, b.im), + }), + sub: (a, b) => ({ + re: F.sub(a.re, b.re), + im: F.sub(a.im, b.im), + }), + mul: (a, b) => ({ + re: F.sub(F.mul(a.re, b.re), F.mul(a.im, b.im)), + im: F.add(F.mul(a.re, b.im), F.mul(a.im, b.re)), + }), + div: (a, b) => { + const denom = F.add(F.mul(b.re, b.re), F.mul(b.im, b.im)); + return { + re: F.div(F.add(F.mul(a.re, b.re), F.mul(a.im, b.im)), denom), + im: F.div(F.sub(F.mul(a.im, b.re), F.mul(a.re, b.im)), denom), + }; + }, + neg: (a) => ({ re: F.neg(a.re), im: F.neg(a.im) }), + conj: (a) => ({ re: a.re, im: F.neg(a.im) }), + scale: (a, x) => ({ + re: F.mul(a.re, x), + im: F.mul(a.im, x), + }), + // a.re * a.re + a.im * a.im + b.re * b.re + b.im * b.im; + magSqSum: (a, b) => F.add(F.add(F.add(F.mul(a.re, a.re), F.mul(a.im, a.im)), F.mul(b.re, b.re)), F.mul(b.im, b.im)), + eql: (a, b) => F.eql(a.re, b.re) && F.eql(a.im, b.im), + clone: (a) => ({ re: a.re, im: a.im }), + inv: () => { + throw new Error('not implemented'); + }, + }; +} +// Falcon real-polynomial FFT layout: [...re, ...im]. Requires an even-length flat array and +// copies into fresh JS objects / arrays instead of creating views. +const ComplexArr = { + decode(lst) { + const N = lst.length; + const hn = N >> 1; + const len = lst.length; + if (len === 0) + return []; + if (len % 2 !== 0) + throw new Error('Array length must be even to pair real and imaginary parts.'); + const res = []; + for (let i = 0; i < hn; i++) { + res.push({ re: lst[i], im: lst[i + hn] }); + } + return res; + }, + encode(lst) { + const re = []; + const im = []; + for (const i of lst) { + re.push(i.re); + im.push(i.im); + } + return [...re, ...im]; + }, +}; +// Precomputed root-table layout [re[0], im[0], re[1], im[1], ...]. Used for `COMPLEX_ROOTS`, +// not Falcon's packed polynomial FFT layout; encode() is currently unused. +// decode() / encode() copy between the flat root table +// and detached `{ re, im }` objects; they never create aliasing views. +const ComplexArrInterleaved = { + decode(lst) { + const len = lst.length; + if (len === 0) + return []; + if (len % 2 !== 0) + throw new Error('Array length must be even to pair real and imaginary parts.'); + const res = []; + // Iterate through the list, taking two elements at a time + for (let i = 0; i < len; i += 2) { + res.push({ re: lst[i], im: lst[i + 1] }); + } + return res; + }, + encode(lst) { + const res = []; + for (const complexNum of lst) { + res.push(complexNum.re); + res.push(complexNum.im); + } + return res; + }, +}; +// Alias a Float64Array as bytes for the root-table hash pin; not a portable serialization. +const u8f = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); +// Alias bytes as Float64Array lanes. Falcon's exact binary64 tables are stored as little-endian +// payload bytes, so BE runtimes must decode lane-by-lane instead of aliasing host-endian floats. +// Copy/truncate to whole 8-byte lanes first +// so BE byte swaps cannot mutate caller-owned bytes +// or read a partial float. +const f64a = (arr) => new Float64Array(baswap64If(Uint8Array.from(arr.subarray(0, Math.floor(arr.byteLength / 8) * 8))).buffer); +// Exact big-endian binary64 hex helper for constants. Only decode() is currently used; malformed +// inputs fail through lower-level hex / DataView checks instead of an explicit wrapper guard. +const Float = /* @__PURE__ */ Object.freeze({ + encode(n) { + const bytes = new Uint8Array(8); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + view.setFloat64(0, n, false); + return bytesToHex(bytes); + }, + decode(s) { + const bytes = hexToBytes(s); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return view.getFloat64(0, false); + }, +}); +// Decode a 64-bit bigint bit pattern into the exact binary64 value. +const f64b = (n) => Float.decode(numberToHexUnpadded(n)); +// Constants +const EMPTY_CHACHA20_BLOCK = /** @__PURE__ */ new Uint8Array(64); +// Falcon's randomized hashing salt r is always 320 bits / 40 bytes, and the same width +// also drives the detached and attached signature wire formats. +const NONCELEN = 40; +// Falcon's public modulus q = 12289 is also the NTT parameter chosen in round 3. +const Q = 12289; // 12 * 1024 + 1 +// Falcon's midpoint floor(q/2); the only live use is the mirrored G-reconstruction reduction below. +const Qhalf = Q >> 1; +const QBig = BigInt(Q); +//const R = 4091; // 2^16 mod q +// This 16-bit Montgomery kernel uses R = 2^16, so mul(x, R2) converts x into Montgomery form. +const R2 = 10952; // 2^32 mod q +// falcon.pdf page 55 says "1/q mod 2^16", +// but the reduction formula and the round-3 Falcon code both require -1/q. +const Q0I = 12287; // -1/q mod 2^16 +const F_INV_Q = 1.0 / Q; +const F_MINUS_INV_Q = -F_INV_Q; +// Round-3 bigint keygen keeps these tables coupled: MAX_BL_SMALL and MAX_BL_LARGE are measured +// 31-bit word bounds, and BITLENGTH is the measured avg/stddev heuristic. Edits must recheck the +// next-depth relation and the current 31 * wordCount headroom used by reduce(). +const MAX_BL_SMALL = [1, 1, 2, 2, 4, 7, 14, 27, 53, 106, 209]; +// Unreduced F/G word bounds for reduce(); the same round-3 source also couples this table to the +// top-10-word floating approximation there, +// so it must stay in sync with MAX_BL_SMALL and BITLENGTH. +const MAX_BL_LARGE = [2, 2, 5, 7, 12, 21, 40, 78, 157, 308]; +// Exact binary64 encoding of Falcon's Gram-Schmidt keygen bound (1.17^2) * q = 16822.4121. +const BNORM_MAX = f64b(BigInt('4670353323383631276')); +// Measured round-3 bigint-keygen heuristic, not a normative Falcon parameter table or proof bound. +const BITLENGTH = [ + { avg: 4, std: 0 }, + { avg: 11, std: 1 }, + { avg: 24, std: 1 }, + { avg: 50, std: 1 }, + { avg: 102, std: 1 }, + { avg: 202, std: 2 }, + { avg: 401, std: 4 }, + { avg: 794, std: 5 }, + { avg: 1577, std: 8 }, + { avg: 3138, std: 13 }, + { avg: 6308, std: 25 }, +]; +// First entry is P(x = 0); the remaining entries are conditional tail thresholds scaled by 2^63. +// Smaller Falcon dimensions reuse the N = 1024, q = 12289 table by summing 2^(10-logn) draws. +// The trailing 0 sentinel guarantees gaussSingle() +// always selects a tail bucket when x = 0 is missed. +const gauss_1024_12289 = [ + 1283868770400643928n, + 6416574995475331444n, + 4078260278032692663n, + 2353523259288686585n, + 1227179971273316331n, + 575931623374121527n, + 242543240509105209n, + 91437049221049666n, + 30799446349977173n, + 9255276791179340n, + 2478152334826140n, + 590642893610164n, + 125206034929641n, + 23590435911403n, + 3948334035941n, + 586753615614n, + 77391054539n, + 9056793210n, + 940121950n, + 86539696n, + 7062824n, + 510971n, + 32764n, + 1862n, + 94n, + 4n, + 0n, +]; +// Exact binary64 1/sigma payloads from round-3 fpr.h. Nearby decimal spellings round 1 ULP low in +// JS, so keep these as decoded bit patterns and recheck the raw payloads after edits. +const INV_SIGMA = /* @__PURE__ */ Object.freeze([ + 0.0, // unused + f64b(BigInt('4574611497772390042')), + f64b(BigInt('4574501679055810265')), + f64b(BigInt('4574396282908341804')), + f64b(BigInt('4574245855758572086')), + f64b(BigInt('4574103865040221165')), + f64b(BigInt('4573969550563515544')), + f64b(BigInt('4573842244705920822')), + f64b(BigInt('4573721358406441454')), + f64b(BigInt('4573606369665796042')), + f64b(BigInt('4573496814039276259')), +]); +// Exact binary64 sigma_min constants from round-3 fpr.h indexed by logn; despite one PQClean +// summary comment, these are sigma_min itself, not 1/sigma_min, which is why this table stays +// separate from INV_SIGMA. +const SIGMA_MIN = /* @__PURE__ */ Object.freeze([ + 0.0, // unused + f64b(BigInt('4607707126469777035')), + f64b(BigInt('4607777455861499430')), + f64b(BigInt('4607846828256951418')), + f64b(BigInt('4607949175006100261')), + f64b(BigInt('4608049571757433526')), + f64b(BigInt('4608148125896792003')), + f64b(BigInt('4608244935301382692')), + f64b(BigInt('4608340089478362016')), + f64b(BigInt('4608433670533905013')), + f64b(BigInt('4608525754002622308')), +]); +// Falcon Table 3.1 RCDT values for chi, split into 24-bit limbs; storage is [high, mid, low], +// so gaussian0() intentionally compares them against v0, v1, v2 in reverse order. The final +// RCDT[18] = 0 row is omitted because the algorithm iterates only over i = 0..17. +const GAUSS0 = new Uint32Array([ + 10745844, 3068844, 3741698, 5559083, 1580863, 8248194, 2260429, 13669192, 2736639, 708981, + 4421575, 10046180, 169348, 7122675, 4136815, 30538, 13063405, 7650655, 4132, 14505003, 7826148, + 417, 16768101, 11363290, 31, 8444042, 8086568, 1, 12844466, 265321, 0, 1232676, 13644283, 0, + 38047, 9111839, 0, 870, 6138264, 0, 14, 12545723, 0, 0, 3104126, 0, 0, 28824, 0, 0, 198, 0, 0, 1, +]); +// Inclusive floor(beta^2) signature-acceptance bounds indexed by logn; the Falcon PDF publishes +// only Falcon-512 and Falcon-1024 directly, while the smaller rows are mirrored from the round-3 +// NIST submission package. +const L2BOUND = [ + 0, // unused + 101498, + 208714, + 428865, + 892039, + 1852696, + 3842630, + 7959734, + 16468416, + 34034726, + 70265242, +]; +// 32kb in hex. +// Could be 4x smaller by using 2 bytes per root. However, that would mean using sin/cos. +// Different JS engines give different sin / cos result, which means the result would be unreliable. +// See "COMPLEX ROOT GENERATION FOR FALCON" in tests. +// Those exact roots are taken from the round-3 Falcon submission, preserving its original +// bit-reversed order here and remapping it only later for FFTCore. +const COMPLEX_ROOTS = /** @__PURE__ */ (() => { + const roots = f64a(hexToBytes('000000000000000000000000000000000000000000000080000000000000f03fcd3b7f669ea0e63fcd3b7f66' + + '9ea0e63fcd3b7f669ea0e6bfcd3b7f669ea0e63f468d32cf6b90ed3f63a9aea6e27dd83f63a9aea6e27dd8bf' + + '468d32cf6b90ed3f63a9aea6e27dd83f468d32cf6b90ed3f468d32cf6b90edbf63a9aea6e27dd83fb05cf7cf' + + '9762ef3f0ba6693cb8f8c83f0ba6693cb8f8c8bfb05cf7cf9762ef3fc868ae393bc7e13fa3a10e29669bea3f' + + 'a3a10e29669beabfc868ae393bc7e13fa3a10e29669bea3fc868ae393bc7e13fc868ae393bc7e1bfa3a10e29' + + '669bea3f0ba6693cb8f8c83fb05cf7cf9762ef3fb05cf7cf9762efbf0ba6693cb8f8c83f2625d1a38dd8ef3f' + + '2cb429bca617b93f2cb429bca617b9bf2625d1a38dd8ef3fd61d0925f34ce43f4117156b80bce83f4117156b' + + '80bce8bfd61d0925f34ce43fb1bd80f1b238ec3f3bf606385d2bde3f3bf606385d2bdebfb1bd80f1b238ec3f' + + '069fd52e0694d23fda2dc656419fee3fda2dc656419feebf069fd52e0694d23fda2dc656419fee3f069fd52e' + + '0694d23f069fd52e0694d2bfda2dc656419fee3f3bf606385d2bde3fb1bd80f1b238ec3fb1bd80f1b238ecbf' + + '3bf606385d2bde3f4117156b80bce83fd61d0925f34ce43fd61d0925f34ce4bf4117156b80bce83f2cb429bc' + + 'a617b93f2625d1a38dd8ef3f2625d1a38dd8efbf2cb429bca617b93f7e6d79e321f6ef3f14d80df1651fa93f' + + '14d80df1651fa9bf7e6d79e321f6ef3fa0ec8c34697de53fafaf6a22dfb5e73fafaf6a22dfb5e7bfa0ec8c34' + + '697de53f73c73cf47aedec3fc05ce109105ddb3fc05ce109105ddbbf73c73cf47aedec3fdd1fab759a8fd53f' + + 'e586f6042121ee3fe586f6042121eebfdd1fab759a8fd53fd73092fb7e0aef3f1b5f217bf919cf3f1b5f217b' + + 'f919cfbfd73092fb7e0aef3feeff22998773e03f3e6e19458372eb3f3e6e19458372ebbfeeff22998773e03f' + + '4187f347e0b3e93f3570e1fcf70fe33f3570e1fcf70fe3bf4187f347e0b3e93f3a618e6e10c8c23f17a5087f' + + '55a7ef3f17a5087f55a7efbf3a618e6e10c8c23f17a5087f55a7ef3f3a618e6e10c8c23f3a618e6e10c8c2bf' + + '17a5087f55a7ef3f3570e1fcf70fe33f4187f347e0b3e93f4187f347e0b3e9bf3570e1fcf70fe33f3e6e1945' + + '8372eb3feeff22998773e03feeff22998773e0bf3e6e19458372eb3f1b5f217bf919cf3fd73092fb7e0aef3f' + + 'd73092fb7e0aefbf1b5f217bf919cf3fe586f6042121ee3fdd1fab759a8fd53fdd1fab759a8fd5bfe586f604' + + '2121ee3fc05ce109105ddb3f73c73cf47aedec3f73c73cf47aedecbfc05ce109105ddb3fafaf6a22dfb5e73f' + + 'a0ec8c34697de53fa0ec8c34697de5bfafaf6a22dfb5e73f14d80df1651fa93f7e6d79e321f6ef3f7e6d79e3' + + '21f6efbf14d80df1651fa93f0dcd846088fdef3f7e66a3f75521993f7e66a3f7552199bf0dcd846088fdef3f' + + 'df2c1d55b710e63f96ffef37082de73f96ffef37082de7bfdf2c1d55b710e63f3ac94dd13441ed3f8aeda843' + + '79efd93f8aeda84379efd9bf3ac94dd13441ed3f9f45fa308508d73f3cc2ccb613dbed3f3cc2ccb613dbedbf' + + '9f45fa308508d73f89e564acf338ef3f634f7e6a820bcc3f634f7e6a820bccbf89e564acf338ef3f234b1b54' + + 'b31ee13f000215580a09eb3f000215580a09ebbf234b1b54b31ee13f822746a0a729ea3fdf12dd4c056de23f' + + 'df12dd4c056de2bf822746a0a729ea3fc63f8b4414e2c53fa94b71fa6487ef3fa94b71fa6487efbfc63f8b44' + + '14e2c53fd39fe17064c2ef3f0e73a9564e56bf3f0e73a9564e56bfbfd39fe17064c2ef3fb9502029faafe33f' + + 'fb639249223ae93ffb639249223ae9bfb9502029faafe33f2a956facc0d7eb3fba9af8dba48bdf3fba9af8db' + + 'a48bdfbf2a956facc0d7eb3f77f6b162d211d13f634968e740d7ee3f634968e740d7eebf77f6b162d211d13f' + + '12e148ec8862ee3f016617945c13d43f016617945c13d4bf12e148ec8862ee3f5ec431996ec6dc3ff5113421' + + '4b95ec3ff51134214b95ecbf5ec431996ec6dc3f6e97ff0b0e3be83fe9e5e3bbcae6e43fe9e5e3bbcae6e4bf' + + '6e97ff0b0e3be83ff619ce9220d5b23f3a8801adcde9ef3f3a8801adcde9efbff619ce9220d5b23f3a8801ad' + + 'cde9ef3ff619ce9220d5b23ff619ce9220d5b2bf3a8801adcde9ef3fe9e5e3bbcae6e43f6e97ff0b0e3be83f' + + '6e97ff0b0e3be8bfe9e5e3bbcae6e43ff51134214b95ec3f5ec431996ec6dc3f5ec431996ec6dcbff5113421' + + '4b95ec3f016617945c13d43f12e148ec8862ee3f12e148ec8862eebf016617945c13d43f634968e740d7ee3f' + + '77f6b162d211d13f77f6b162d211d1bf634968e740d7ee3fba9af8dba48bdf3f2a956facc0d7eb3f2a956fac' + + 'c0d7ebbfba9af8dba48bdf3ffb639249223ae93fb9502029faafe33fb9502029faafe3bffb639249223ae93f' + + '0e73a9564e56bf3fd39fe17064c2ef3fd39fe17064c2efbf0e73a9564e56bf3fa94b71fa6487ef3fc63f8b44' + + '14e2c53fc63f8b4414e2c5bfa94b71fa6487ef3fdf12dd4c056de23f822746a0a729ea3f822746a0a729eabf' + + 'df12dd4c056de23f000215580a09eb3f234b1b54b31ee13f234b1b54b31ee1bf000215580a09eb3f634f7e6a' + + '820bcc3f89e564acf338ef3f89e564acf338efbf634f7e6a820bcc3f3cc2ccb613dbed3f9f45fa308508d73f' + + '9f45fa308508d7bf3cc2ccb613dbed3f8aeda84379efd93f3ac94dd13441ed3f3ac94dd13441edbf8aeda843' + + '79efd93f96ffef37082de73fdf2c1d55b710e63fdf2c1d55b710e6bf96ffef37082de73f7e66a3f75521993f' + + '0dcd846088fdef3f0dcd846088fdefbf7e66a3f75521993fdb929b1662ffef3f84c7defcd121893f84c7defc' + + 'd12189bfdb929b1662ffef3f3d78f0251959e63fafa8ea5444e7e63fafa8ea5444e7e6bf3d78f0251959e63f' + + '8be6c9736169ed3fd793bc632a37d93fd793bc632a37d9bf8be6c9736169ed3fe7cc1d31a9c3d73f9ba03862' + + '52b6ed3f9ba0386252b6edbfe7cc1d31a9c3d73f2d2f0b3b604eef3f5104b025a082ca3f5104b025a082cabf' + + '2d2f0b3b604eef3f49dbde634d73e13f11d5219ebcd2ea3f11d5219ebcd2eabf49dbde634d73e13fe2fa021b' + + '0963ea3f59eb3399791ae23f59eb3399791ae2bfe2fa021b0963ea3f31bf50ded96dc73f7720a1a39975ef3f' + + '7720a1a39975efbf31bf50ded96dc73f7ba66dfd15ceef3fd5c29ec78537bc3fd5c29ec78537bcbf7ba66dfd' + + '15ceef3fd4564553d9fee33f0d94efa3ccfbe83f0d94efa3ccfbe8bfd4564553d9fee33f49557226c408ec3f' + + 'd678ef5219dcde3fd678ef5219dcdebf49557226c408ec3f3edb4c3f44d3d13f740bdfc8d8bbee3f740bdfc8' + + 'd8bbeebf3edb4c3f44d3d13f0dd14cab7b81ee3f5281e1c21054d33f5281e1c21054d3bf0dd14cab7b81ee3f' + + '89e3865b7779dd3f9b7388348b67ec3f9b7388348b67ecbf89e3865b7779dd3fbf2eba0f407ce83f39099b9b' + + '449ae43f39099b9b449ae4bfbf2eba0f407ce83f19a49a0ad0f6b53f095bbdfccae1ef3f095bbdfccae1efbf' + + '19a49a0ad0f6b53fad718e6595f0ef3fe020f8796e65af3fe020f8796e65afbfad718e6595f0ef3f9655a392' + + '8232e53f711757e3ecf8e73f711757e3ecf8e7bf9655a3928232e53f5cfcfcf3f0c1ec3fe71e01d84912dc3f' + + 'e71e01d84912dcbf5cfcfcf3f0c1ec3f6ae77842e2d1d43f7ec12b4b6a42ee3f7ec12b4b6a42eebf6ae77842' + + 'e2d1d43fc273e4a378f1ee3faefd370eb84fd03faefd370eb84fd0bfc273e4a378f1ee3fb73e4c87fc1ce03f' + + 'd2903567aaa5eb3fd2903567aaa5ebbfb73e4c87fc1ce03f42d7c7f47e77e93ff35906b15860e33ff35906b1' + + '5860e3bf42d7c7f47e77e93f77f5dacef039c13f41d7957179b5ef3f41d7957179b5efbf77f5dacef039c13f' + + '9b09c924f997ef3f5a3e29b17655c43f5a3e29b17655c4bf9b09c924f997ef3feaf3fa25dbbee23f94af29ef' + + '43efe93f94af29ef43efe9bfeaf3fa25dbbee23f1257f53e4d3eeb3f8f895d4d70c9e03f8f895d4d70c9e0bf' + + '1257f53e4d3eeb3f114345e54f93cd3fda3a76f75222ef3fda3a76f75222efbf114345e54f93cd3f2bbe2d62' + + 'aefeed3fc6273fdd7d4cd63fc6273fdd7d4cd6bf2bbe2d62aefeed3fca3f6d2bc8a6da3fdc353e74e717ed3f' + + 'dc353e74e717edbfca3f6d2bc8a6da3f6172035fe771e73f8c0165be7bc7e53f8c0165be7bc7e5bf6172035f' + + 'e771e73fcd55947565d8a23f5df7feef72faef3f5df7feef72faefbfcd55947565d8a23f5df7feef72faef3f' + + 'cd55947565d8a23fcd55947565d8a2bf5df7feef72faef3f8c0165be7bc7e53f6172035fe771e73f6172035f' + + 'e771e7bf8c0165be7bc7e53fdc353e74e717ed3fca3f6d2bc8a6da3fca3f6d2bc8a6dabfdc353e74e717ed3f' + + 'c6273fdd7d4cd63f2bbe2d62aefeed3f2bbe2d62aefeedbfc6273fdd7d4cd63fda3a76f75222ef3f114345e5' + + '4f93cd3f114345e54f93cdbfda3a76f75222ef3f8f895d4d70c9e03f1257f53e4d3eeb3f1257f53e4d3eebbf' + + '8f895d4d70c9e03f94af29ef43efe93feaf3fa25dbbee23feaf3fa25dbbee2bf94af29ef43efe93f5a3e29b1' + + '7655c43f9b09c924f997ef3f9b09c924f997efbf5a3e29b17655c43f41d7957179b5ef3f77f5dacef039c13f' + + '77f5dacef039c1bf41d7957179b5ef3ff35906b15860e33f42d7c7f47e77e93f42d7c7f47e77e9bff35906b1' + + '5860e33fd2903567aaa5eb3fb73e4c87fc1ce03fb73e4c87fc1ce0bfd2903567aaa5eb3faefd370eb84fd03f' + + 'c273e4a378f1ee3fc273e4a378f1eebfaefd370eb84fd03f7ec12b4b6a42ee3f6ae77842e2d1d43f6ae77842' + + 'e2d1d4bf7ec12b4b6a42ee3fe71e01d84912dc3f5cfcfcf3f0c1ec3f5cfcfcf3f0c1ecbfe71e01d84912dc3f' + + '711757e3ecf8e73f9655a3928232e53f9655a3928232e5bf711757e3ecf8e73fe020f8796e65af3fad718e65' + + '95f0ef3fad718e6595f0efbfe020f8796e65af3f095bbdfccae1ef3f19a49a0ad0f6b53f19a49a0ad0f6b5bf' + + '095bbdfccae1ef3f39099b9b449ae43fbf2eba0f407ce83fbf2eba0f407ce8bf39099b9b449ae43f9b738834' + + '8b67ec3f89e3865b7779dd3f89e3865b7779ddbf9b7388348b67ec3f5281e1c21054d33f0dd14cab7b81ee3f' + + '0dd14cab7b81eebf5281e1c21054d33f740bdfc8d8bbee3f3edb4c3f44d3d13f3edb4c3f44d3d1bf740bdfc8' + + 'd8bbee3fd678ef5219dcde3f49557226c408ec3f49557226c408ecbfd678ef5219dcde3f0d94efa3ccfbe83f' + + 'd4564553d9fee33fd4564553d9fee3bf0d94efa3ccfbe83fd5c29ec78537bc3f7ba66dfd15ceef3f7ba66dfd' + + '15ceefbfd5c29ec78537bc3f7720a1a39975ef3f31bf50ded96dc73f31bf50ded96dc7bf7720a1a39975ef3f' + + '59eb3399791ae23fe2fa021b0963ea3fe2fa021b0963eabf59eb3399791ae23f11d5219ebcd2ea3f49dbde63' + + '4d73e13f49dbde634d73e1bf11d5219ebcd2ea3f5104b025a082ca3f2d2f0b3b604eef3f2d2f0b3b604eefbf' + + '5104b025a082ca3f9ba0386252b6ed3fe7cc1d31a9c3d73fe7cc1d31a9c3d7bf9ba0386252b6ed3fd793bc63' + + '2a37d93f8be6c9736169ed3f8be6c9736169edbfd793bc632a37d93fafa8ea5444e7e63f3d78f0251959e63f' + + '3d78f0251959e6bfafa8ea5444e7e63f84c7defcd121893fdb929b1662ffef3fdb929b1662ffefbf84c7defc' + + 'd121893f928a8e85d8ffef3f710067fef021793f710067fef02179bf928a8e85d8ffef3f10af9184f77ce63f' + + '7582c1730dc4e63f7582c1730dc4e6bf10af9184f77ce63ff9ecb8020b7ded3fb0a4c82ea5dad83fb0a4c82e' + + 'a5dad8bff9ecb8020b7ded3fc4aa4eb0e320d83f888966a983a3ed3f888966a983a3edbfc4aa4eb0e320d83f' + + '849e78b1a258ef3f6643dcf2cbbdc93f6643dcf2cbbdc9bf849e78b1a258ef3fb8b9f2095a9de13fd4c01659' + + '32b7ea3fd4c0165932b7eabfb8b9f2095a9de13f9de69f52587fea3f1b86bc8bf0f0e13f1b86bc8bf0f0e1bf' + + '9de69f52587fea3fc6649ce86633c83fb7bbf57d3f6cef3fb7bbf57d3f6cefbfc6649ce86633c83f840b2214' + + '79d3ef3f035c4924b7a7ba3f035c4924b7a7babf840b221479d3ef3fb16b8e17ff25e43fcc98163345dce83f' + + 'cc98163345dce8bfb16b8e17ff25e43fb071a93fde20ec3f1451f8eae083de3f1451f8eae083debfb071a93f' + + 'de20ec3f71bbc3abbb33d23f8ea8e7e8b2adee3f8ea8e7e8b2adeebf71bbc3abbb33d23ff2f71d368490ee3f' + + '8703ecda22f4d23f8703ecda22f4d2bff2f71d368490ee3f58cc81148fd2dd3f07692b014250ec3f07692b01' + + '4250ecbf58cc81148fd2dd3faad44d9a7e9ce83f4773981bb573e43f4773981bb573e4bfaad44d9a7e9ce83f' + + '215b5d6a5887b73f56f4f19f53ddef3f56f4f19f53ddefbf215b5d6a5887b73f5c578d0f83f3ef3fe3d7c012' + + '8d42ac3fe3d7c0128d42acbf5c578d0f83f3ef3f375197381058e53fb23dc36c83d7e73fb23dc36c83d7e7bf' + + '375197381058e53ff6328b89d9d7ec3f01bd0423cfb7db3f01bd0423cfb7dbbff6328b89d9d7ec3f243caf80' + + 'd830d53f25ce70e8ea31ee3f25ce70e8ea31eebf243caf80d830d53fec950b0c22feee3ff9eddf1adcdccf3f' + + 'f9eddf1adcdccfbfec950b0c22feee3f1a22ae265648e03fe90475d2388ceb3fe90475d2388cebbf1a22ae26' + + '5648e03f220dd82ecf95e93f578e0c0d4038e33f578e0c0d4038e3bf220dd82ecf95e93fcf7becd41601c23f' + + 'bbcf468e8eaeef3fbbcf468e8eaeefbfcf7becd41601c23fc8b2ad55ce9fef3f148dcdb0db8ec33f148dcdb0' + + 'db8ec3bfc8b2ad55ce9fef3f17eae8e380e7e23fd580eaf5b1d1e93fd580eaf5b1d1e9bf17eae8e380e7e23f' + + '051492fe8958eb3fe1c51774909ee03fe1c51774909ee0bf051492fe8958eb3f1b1a101eca56ce3f5d20f753' + + '8f16ef3f5d20f7538f16efbf1b1a101eca56ce3fac8029ca0c10ee3f93a69e3727eed53f93a69e3727eed5bf' + + 'ac8029ca0c10ee3f09407f6c0d02db3f92bdb2fed402ed3f92bdb2fed402edbf09407f6c0d02db3fe5554f57' + + '0094e73f50725d2a8da2e53f50725d2a8da2e5bfe5554f570094e73f43cd90d200fca53fdf81dbda71f8ef3f' + + 'df81dbda71f8efbf43cd90d200fca53ff8d3f11d25fcef3f01cfd13137699f3f01cfd13137699fbff8d3f11d' + + '25fcef3f7470839534ece53f8dd2a88d944fe73f8dd2a88d944fe7bf7470839534ece53f9fefe020b22ced3f' + + 'e5a1de27414bda3fe5a1de27414bdabf9fefe020b22ced3f177ec77d9daad63fda47def705eded3fda47def7' + + '05ededbf177ec77d9daad63f9d9a08c9c92def3f86b212b38ccfcc3f86b212b38ccfccbf9d9a08c9c92def3f' + + '7e8e2abb26f4e03fb4130047cd23eb3fb4130047cd23ebbf7e8e2abb26f4e03f37f9baea950cea3fa89c6227' + + '0796e23fa89c62270796e2bf37f9baea950cea3ff2c59785df1bc53fdb41aeffd58fef3fdb41aeffd58fefbf' + + 'f2c59785df1bc53f8641e41716bcef3f1d83ba47a072c03f1d83ba47a072c0bf8641e41716bcef3f22ebdf85' + + '4188e33fd76d8ee4ef58e93fd76d8ee4ef58e9bf22ebdf854188e33fea8093c4d7beeb3f1012e74bf6e2df3f' + + '1012e74bf6e2dfbfea8093c4d7beeb3f90dbdbcfd9b0d03fbc9d5ae282e4ee3fbc9d5ae282e4eebf90dbdbcf' + + 'd9b0d03ffc9f72049f52ee3f541057a5b872d43f541057a5b872d4bffc9f72049f52ee3f0b0097497f6cdc3f' + + '00b9a069c1abec3f00b9a069c1abecbf0b0097497f6cdc3fcc7ab5331b1ae83f9ba0599fc00ce53f9ba0599f' + + 'c00ce5bfcc7ab5331b1ae83fb309d7340144b13fc473b6ec58edef3fc473b6ec58edefbfb309d7340144b13f' + + '40392eaff3e5ef3f962027791166b43f962027791166b4bf40392eaff3e5ef3f0400ec45a1c0e43fcc58e91a' + + 'c55be83fcc58e91ac55be8bf0400ec45a1c0e43ff33c23528e7eec3f5bdbe9e81620dd3f5bdbe9e81620ddbf' + + 'f33c23528e7eec3fb71404faceb3d33f44976adb2772ee3f44976adb2772eebfb71404faceb3d33f84bfc3d3' + + 'b2c9ee3f775176d7a072d13f775176d7a072d1bf84bfc3d3b2c9ee3f67d03f960534df3fdd7753e164f0eb3f' + + 'dd7753e164f0ebbf67d03f960534df3fa29dd46f161be93f4483c53882d7e33f4483c53882d7e3bfa29dd46f' + + '161be93fc99faecb0ec7bd3f21b7fe6c64c8ef3f21b7fe6c64c8efbfc99faecb0ec7bd3f6e3de629a67eef3f' + + 'b24af60413a8c63fb24af60413a8c6bf6e3de629a67eef3f1fac98fbd543e23fc89a11c87846ea3fc89a11c8' + + '7846eabf1fac98fbd543e23f74143cb404eeea3feb6c33af1549e13feb6c33af1549e1bf74143cb404eeea3f' + + '22673def3247cb3fdd92ff85d043ef3fdd92ff85d043efbf22673def3247cb3f600241cbd7c8ed3ff618240f' + + '3466d73ff618240f3466d7bf600241cbd7c8ed3fffbd41617193d93fb13ee9526f55ed3fb13ee9526f55edbf' + + 'ffbd41617193d93f7a6d17b3420ae73fe91b1ca30335e63fe91b1ca30335e6bf7a6d17b3420ae73ffd0ee3bb' + + '36d9923fa1514bb49cfeef3fa1514bb49cfeefbffd0ee3bb36d9923fa1514bb49cfeef3ffd0ee3bb36d9923f' + + 'fd0ee3bb36d992bfa1514bb49cfeef3fe91b1ca30335e63f7a6d17b3420ae73f7a6d17b3420ae7bfe91b1ca3' + + '0335e63fb13ee9526f55ed3fffbd41617193d93fffbd41617193d9bfb13ee9526f55ed3ff618240f3466d73f' + + '600241cbd7c8ed3f600241cbd7c8edbff618240f3466d73fdd92ff85d043ef3f22673def3247cb3f22673def' + + '3247cbbfdd92ff85d043ef3feb6c33af1549e13f74143cb404eeea3f74143cb404eeeabfeb6c33af1549e13f' + + 'c89a11c87846ea3f1fac98fbd543e23f1fac98fbd543e2bfc89a11c87846ea3fb24af60413a8c63f6e3de629' + + 'a67eef3f6e3de629a67eefbfb24af60413a8c63f21b7fe6c64c8ef3fc99faecb0ec7bd3fc99faecb0ec7bdbf' + + '21b7fe6c64c8ef3f4483c53882d7e33fa29dd46f161be93fa29dd46f161be9bf4483c53882d7e33fdd7753e1' + + '64f0eb3f67d03f960534df3f67d03f960534dfbfdd7753e164f0eb3f775176d7a072d13f84bfc3d3b2c9ee3f' + + '84bfc3d3b2c9eebf775176d7a072d13f44976adb2772ee3fb71404faceb3d33fb71404faceb3d3bf44976adb' + + '2772ee3f5bdbe9e81620dd3ff33c23528e7eec3ff33c23528e7eecbf5bdbe9e81620dd3fcc58e91ac55be83f' + + '0400ec45a1c0e43f0400ec45a1c0e4bfcc58e91ac55be83f962027791166b43f40392eaff3e5ef3f40392eaf' + + 'f3e5efbf962027791166b43fc473b6ec58edef3fb309d7340144b13fb309d7340144b1bfc473b6ec58edef3f' + + '9ba0599fc00ce53fcc7ab5331b1ae83fcc7ab5331b1ae8bf9ba0599fc00ce53f00b9a069c1abec3f0b009749' + + '7f6cdc3f0b0097497f6cdcbf00b9a069c1abec3f541057a5b872d43ffc9f72049f52ee3ffc9f72049f52eebf' + + '541057a5b872d43fbc9d5ae282e4ee3f90dbdbcfd9b0d03f90dbdbcfd9b0d0bfbc9d5ae282e4ee3f1012e74b' + + 'f6e2df3fea8093c4d7beeb3fea8093c4d7beebbf1012e74bf6e2df3fd76d8ee4ef58e93f22ebdf854188e33f' + + '22ebdf854188e3bfd76d8ee4ef58e93f1d83ba47a072c03f8641e41716bcef3f8641e41716bcefbf1d83ba47' + + 'a072c03fdb41aeffd58fef3ff2c59785df1bc53ff2c59785df1bc5bfdb41aeffd58fef3fa89c62270796e23f' + + '37f9baea950cea3f37f9baea950ceabfa89c62270796e23fb4130047cd23eb3f7e8e2abb26f4e03f7e8e2abb' + + '26f4e0bfb4130047cd23eb3f86b212b38ccfcc3f9d9a08c9c92def3f9d9a08c9c92defbf86b212b38ccfcc3f' + + 'da47def705eded3f177ec77d9daad63f177ec77d9daad6bfda47def705eded3fe5a1de27414bda3f9fefe020' + + 'b22ced3f9fefe020b22cedbfe5a1de27414bda3f8dd2a88d944fe73f7470839534ece53f7470839534ece5bf' + + '8dd2a88d944fe73f01cfd13137699f3ff8d3f11d25fcef3ff8d3f11d25fcefbf01cfd13137699f3fdf81dbda' + + '71f8ef3f43cd90d200fca53f43cd90d200fca5bfdf81dbda71f8ef3f50725d2a8da2e53fe5554f570094e73f' + + 'e5554f570094e7bf50725d2a8da2e53f92bdb2fed402ed3f09407f6c0d02db3f09407f6c0d02dbbf92bdb2fe' + + 'd402ed3f93a69e3727eed53fac8029ca0c10ee3fac8029ca0c10eebf93a69e3727eed53f5d20f7538f16ef3f' + + '1b1a101eca56ce3f1b1a101eca56cebf5d20f7538f16ef3fe1c51774909ee03f051492fe8958eb3f051492fe' + + '8958ebbfe1c51774909ee03fd580eaf5b1d1e93f17eae8e380e7e23f17eae8e380e7e2bfd580eaf5b1d1e93f' + + '148dcdb0db8ec33fc8b2ad55ce9fef3fc8b2ad55ce9fefbf148dcdb0db8ec33fbbcf468e8eaeef3fcf7becd4' + + '1601c23fcf7becd41601c2bfbbcf468e8eaeef3f578e0c0d4038e33f220dd82ecf95e93f220dd82ecf95e9bf' + + '578e0c0d4038e33fe90475d2388ceb3f1a22ae265648e03f1a22ae265648e0bfe90475d2388ceb3ff9eddf1a' + + 'dcdccf3fec950b0c22feee3fec950b0c22feeebff9eddf1adcdccf3f25ce70e8ea31ee3f243caf80d830d53f' + + '243caf80d830d5bf25ce70e8ea31ee3f01bd0423cfb7db3ff6328b89d9d7ec3ff6328b89d9d7ecbf01bd0423' + + 'cfb7db3fb23dc36c83d7e73f375197381058e53f375197381058e5bfb23dc36c83d7e73fe3d7c0128d42ac3f' + + '5c578d0f83f3ef3f5c578d0f83f3efbfe3d7c0128d42ac3f56f4f19f53ddef3f215b5d6a5887b73f215b5d6a' + + '5887b7bf56f4f19f53ddef3f4773981bb573e43faad44d9a7e9ce83faad44d9a7e9ce8bf4773981bb573e43f' + + '07692b014250ec3f58cc81148fd2dd3f58cc81148fd2ddbf07692b014250ec3f8703ecda22f4d23ff2f71d36' + + '8490ee3ff2f71d368490eebf8703ecda22f4d23f8ea8e7e8b2adee3f71bbc3abbb33d23f71bbc3abbb33d2bf' + + '8ea8e7e8b2adee3f1451f8eae083de3fb071a93fde20ec3fb071a93fde20ecbf1451f8eae083de3fcc981633' + + '45dce83fb16b8e17ff25e43fb16b8e17ff25e4bfcc98163345dce83f035c4924b7a7ba3f840b221479d3ef3f' + + '840b221479d3efbf035c4924b7a7ba3fb7bbf57d3f6cef3fc6649ce86633c83fc6649ce86633c8bfb7bbf57d' + + '3f6cef3f1b86bc8bf0f0e13f9de69f52587fea3f9de69f52587feabf1b86bc8bf0f0e13fd4c0165932b7ea3f' + + 'b8b9f2095a9de13fb8b9f2095a9de1bfd4c0165932b7ea3f6643dcf2cbbdc93f849e78b1a258ef3f849e78b1' + + 'a258efbf6643dcf2cbbdc93f888966a983a3ed3fc4aa4eb0e320d83fc4aa4eb0e320d8bf888966a983a3ed3f' + + 'b0a4c82ea5dad83ff9ecb8020b7ded3ff9ecb8020b7dedbfb0a4c82ea5dad83f7582c1730dc4e63f10af9184' + + 'f77ce63f10af9184f77ce6bf7582c1730dc4e63f710067fef021793f928a8e85d8ffef3f928a8e85d8ffefbf' + + '710067fef021793f021d6221f6ffef3fbaa4ccbef821693fbaa4ccbef82169bf021d6221f6ffef3f719ca1ea' + + 'd18ee63f9ce22fed5cb2e63f9ce22fed5cb2e6bf719ca1ead18ee63f4fa44584c486ed3f44edd5864bacd83f' + + '44edd5864bacd8bf4fa44584c486ed3f3f90f3aa6a4fd83f463d8bdd009aed3f463d8bdd009aedbf3f90f3aa' + + '6a4fd83f5d6843eda65def3ffa2ab6e9495bc93ffa2ab6e9495bc9bf5d6843eda65def3fbf73131750b2e13f' + + '8eb92c7a54a9ea3f8eb92c7a54a9eabfbf73131750b2e13fd25a546e678dea3f7248dc641bdce13f7248dc64' + + '1bdce1bfd25a546e678dea3f0418c4271796c83fee3c88567567ef3fee3c88567567efbf0418c4271796c83f' + + '9e5ca72d0dd6ef3f5ca824ebb6dfb93f5ca824ebb6dfb9bf9e5ca72d0dd6ef3f80432a5b7f39e43f55461875' + + '6acce83f554618756acce8bf80432a5b7f39e43ff1e33149d12cec3f25d83c6da857de3f25d83c6da857debf' + + 'f1e33149d12cec3fba545599e663d23f0058e69383a6ee3f0058e69383a6eebfba545599e663d23f306b0136' + + 'ec97ee3f2045954e1ac4d23f2045954e1ac4d2bf306b0136ec97ee3fde41a966fffedd3f04c041318344ec3f' + + '04c041318344ecbfde41a966fffedd3f881dde1e87ace83fa2322b695a60e43fa2322b695a60e4bf881dde1e' + + '87ace83fa130c112874fb83f8c531475fadaef3f8c531475fadaefbfa130c112874fb83fd3beb154dcf4ef3f' + + '17835fbd01b1aa3f17835fbd01b1aabfd3beb154dcf4ef3f9f649751c36ae53f33d3e29cb8c6e73f33d3e29c' + + 'b8c6e7bf9f649751c36ae53f60a09927b3e2ec3f9356fd14788adb3f9356fd14788adbbf60a09927b3e2ec3f' + + 'b467f4124060d53f7a1939448f29ee3f7a1939448f29eebfb467f4124060d53f8c73cf145a04ef3f0238bd80' + + '747bcf3f0238bd80747bcfbf8c73cf145a04ef3fb7b831ecf35de03fe992e786667feb3fe992e786667febbf' + + 'b7b831ecf35de03fb2062ba4dfa4e93f1fa649ec2124e33f1fa649ec2124e3bfb2062ba4dfa4e93f0934fd4d' + + '9964c23fdcfd0ccbfbaaef3fdcfd0ccbfbaaefbf0934fd4d9964c23f91177aac9ba3ef3fa71645f97b2bc33f' + + 'a71645f97b2bc3bf91177aac9ba3ef3f1510444bc2fbe23fc275f010d1c2e93fc275f010d1c2e9bf1510444b' + + 'c2fbe23f47bcfd148f65eb3f8cb032201189e03f8cb032201189e0bf47bcfd148f65eb3f48e32d466bb8ce3f' + + '5f8f89bc9010ef3f5f8f89bc9010efbf48e32d466bb8ce3fd966dc2fa018ee3fb6b39d8be7bed53fb6b39d8b' + + 'e7bed5bfd966dc2fa018ee3f7219b31d972fdb3f7b46cee830f8ec3f7b46cee830f8ecbf7219b31d972fdb3f' + + 'd297bf07f7a4e73fdf23f7d50190e53fdf23f7d50190e5bfd297bf07f7a4e73f864687a5ba8da73f64911bbb' + + '53f7ef3f64911bbb53f7efbf864687a5ba8da73f79a6e29ce0fcef3f1d3be54c4f459c3f1d3be54c4f459cbf' + + '79a6e29ce0fcef3f106ae5bd7cfee53f4299078e553ee73f4299078e553ee7bf106ae5bd7cfee53fdcfbcb7b' + + 'fc36ed3fc00ab543651dda3fc00ab543651ddabfdcfbcb7bfc36ed3fb60c8a6398d9d63f818d6d0f16e4ed3f' + + '818d6d0f16e4edbfb60c8a6398d9d63ff0ae3a5a6833ef3fdd745d53906dcc3fdd745d53906dccbff0ae3a5a' + + '6833ef3f57a9d0487209e13ff5a24c2a7416eb3ff5a24c2a7416ebbf57a9d0487209e13f5ea7c0d2261bea3f' + + 'ba3c4def8b81e23fba3c4def8b81e2bf5ea7c0d2261bea3fdecb5486007fc53f784bcb37a78bef3f784bcb37' + + 'a78befbfdecb5486007fc53f888d0a0f47bfef3f5bb86fade80ec03f5bb86fade80ec0bf888d0a0f47bfef3f' + + '2930d6e3239ce33f6c4aace39049e93f6c4aace39049e9bf2930d6e3239ce33f27230dcb54cbeb3fded2245c' + + '57b7df3fded2245c57b7dfbf27230dcb54cbeb3fce49174e5be1d03f5186076aebddee3f5186076aebddeebf' + + 'ce49174e5be1d03fd36704559d5aee3ff03689dc1043d43ff03689dc1043d4bfd36704559d5aee3f895386c3' + + '7f99dc3f49c4b9198fa0ec3f49c4b9198fa0ecbf895386c37f99dc3fff45f5139c2ae83f86a4cc25ccf9e43f' + + '86a4cc25ccf9e4bfff45f5139c2ae83f4d44ed74960cb23f0f4130259debef3f0f4130259debefbf4d44ed74' + + '960cb23f602d4885eae7ef3f99a2c5129f9db33f99a2c5129f9db3bf602d4885eae7ef3f7f9f586dbcd3e43f' + + 'fa83af11714be83ffa83af11714be8bf7f9f586dbcd3e43f139c0287f589ec3f21cde1ae4bf3dc3f21cde1ae' + + '4bf3dcbf139c0287f589ec3f71c26ee99be3d33fa7535dc5616aee3fa7535dc5616aeebf71c26ee99be3d33f' + + '0990995e83d0ee3f7893c6ef3e42d13f7893c6ef3e42d1bf0990995e83d0ee3fa3cd56e6de5fdf3fc1541161' + + '1be4eb3fc15411611be4ebbfa3cd56e6de5fdf3f15a8c51fa42ae93f18c58149c4c3e33f18c58149c4c3e3bf' + + '15a8c51fa42ae93f3faae4fdb78ebe3ff69a7d3b6ec5ef3ff69a7d3b6ec5efbf3faae4fdb78ebe3f0cc6404a' + + '0f83ef3f0d831d831a45c63f0d831d831a45c6bf0cc6404a0f83ef3f1071bb4c7358e23fc63b594a1838ea3f' + + 'c63b594a1838eabf1071bb4c7358e23fb6579fd88ffbea3f4f25eecfe933e13f4f25eecfe933e1bfb6579fd8' + + '8ffbea3fad5df13463a9cb3f65bc1bbc6b3eef3f65bc1bbc6b3eefbfad5df13463a9cb3f5a918af3fed1ed3f' + + '921026c96337d73f921026c96337d7bf5a918af3fed1ed3ff2f90d447dc1d93f2475181b5b4bed3f2475181b' + + '5b4bedbff2f90d447dc1d93fbf410e96ac1be73fff22ec4fe422e63fff22ec4fe422e6bfbf410e96ac1be73f' + + '26b2fa214dfd953f77cb70681cfeef3f77cb70681cfeefbf26b2fa214dfd953fd13bc54309ffef3fcb97b96a' + + '296a8f3fcb97b96a296a8fbfd13bc54309ffef3f5b537f431547e63f755bc999caf8e63f755bc999caf8e6bf' + + '5b537f431547e63f7f8a8872715fed3f8f94abb75565d93f8f94abb75565d9bf7f8a8872715fed3faedf13e6' + + 'f594d73f9a7595439ebfed3f9a7595439ebfedbfaedf13e6f594d73fb4abbc062249ef3fabb9f3d5f1e4ca3f' + + 'abb9f3d5f1e4cabfb4abbc062249ef3fbce2dbe4365ee13fefec45f368e0ea3fefec45f368e0eabfbce2dbe4' + + '365ee13f23f59010c954ea3fe2132c662d2fe23fe2132c662d2fe2bf23f59010c954ea3fffc4088dfd0ac73f' + + '2a321a9c297aef3f2a321a9c297aefbfffc4088dfd0ac73f5443910347cbef3fc17d303b53ffbc3fc17d303b' + + '53ffbcbf5443910347cbef3f8006beea33ebe33ffe5e5743790be93ffe5e5743790be9bf8006beea33ebe33f' + + '47b1a1259dfceb3ffef7bf061908df3ffef7bf061908dfbf47b1a1259dfceb3f43f2e8fbf7a2d13fb2f61a4b' + + 'cfc2ee3fb2f61a4bcfc2eebf43f2e8fbf7a2d13f5a16a529db79ee3fabb653e3f583d33fabb653e3f583d3bf' + + '5a16a529db79ee3f9d60a82bd04cdd3fd7aa9e891573ec3fd7aa9e891573ecbf9d60a82bd04cdd3f95a19a1d' + + '0a6ce83ff122675179ade43ff122675179ade4bf95a19a1d0a6ce83f0a4d4d4a772eb53f86d8e92be9e3ef3f' + + '86d8e92be9e3efbf0a4d4d4a772eb53f9161820201efef3f6430464e617bb03f6430464e617bb0bf91618202' + + '01efef3fa69ad91ca81fe53ffa526e758b09e83ffa526e758b09e8bfa69ad91ca81fe53f99da000ae2b6ec3f' + + '293126476d3fdc3f293126476d3fdcbf99da000ae2b6ec3ff3821bd153a2d43f5ece81ff8d4aee3f5ece81ff' + + '8d4aeebff3821bd153a2d43f44a5504c07ebee3f1e66eb054e80d03f1e66eb054e80d0bf44a5504c07ebee3f' + + 'e1822bc84007e03f0dc4b6a049b2eb3f0dc4b6a049b2ebbfe1822bc84007e03fe17fbd423f68e93f8d7f811b' + + '5374e33f8d7f811b5374e3bfe17fbd423f68e93f8667b2bc4dd6c03fb7ad668dd1b8ef3fb7ad668dd1b8efbf' + + '8667b2bc4dd6c03f08ac854ff193ef3f88fa797fb1b8c43f88fa797fb1b8c4bf08ac854ff193ef3f58eb7ae8' + + '76aae23fde4931f1f4fde93fde4931f1f4fde9bf58eb7ae876aae23ff37bf3a51531eb3fb6c44bb8d0dee03f' + + 'b6c44bb8d0dee0bff37bf3a51531eb3feebd2c4d7731cd3fce0946fc1728ef3fce0946fc1728efbfeebd2c4d' + + '7731cd3f9ca59b6ae3f5ed3fcb63ad9c947bd63fcb63ad9c947bd6bf9ca59b6ae3f5ed3f1bf3dbd30c79da3f' + + 'e1a4e5c65522ed3fe1a4e5c65522edbf1bf3dbd30c79da3f6447302cc560e73f5c343ee7ded9e53f5c343ee7' + + 'ded9e5bf6447302cc560e73f7fc142db8546a13faefd25e455fbef3faefd25e455fbefbf7fc142db8546a13f' + + '14c008427cf9ef3f7961f86f396aa43f7961f86f396aa4bf14c008427cf9ef3f48744f260bb5e53f5bb3901b' + + 'fb82e73f5bb3901bfb82e7bf48744f260bb5e53fb9d2592f670ded3f09dc5c1273d4da3f09dc5c1273d4dabf' + + 'b9d2592f670ded3f02c2885c591dd63f540f28d96607ee3f540f28d96607eebf02c2885c591dd63f084728be' + + '7a1cef3f9a09013f16f5cd3f9a09013f16f5cdbf084728be7a1cef3fec858f8705b4e03f2579de09744beb3f' + + '2579de09744bebbfec858f8705b4e03f7224b4ed82e0e93fb89b4ed333d3e23fb89b4ed333d3e2bf7224b4ed' + + '82e0e93f9348db572ff2c33f29defb7ced9bef3f29defb7ced9befbf9348db572ff2c33f4dd581c60db2ef3f' + + 'e724be40899dc13fe724be40899dc1bf4dd581c60db2ef3fe14dc152524ce33f947545f1ae86e93f947545f1' + + 'ae86e9bfe14dc152524ce33f5e15d91ffa98eb3f96bded55ae32e03f96bded55ae32e0bf5e15d91ffa98eb3f' + + 'd2fdb906181fd03fc0a31ce5d6f7ee3fc0a31ce5d6f7eebfd2fdb906181fd03f85ce75ec333aee3f487019dc' + + '6301d53f487019dc6301d5bf85ce75ec333aee3fd9c0ff1715e5db3fa0dec220eeccec3fa0dec220eeccecbf' + + 'd9c0ff1715e5db3f8636b0873fe8e73ffc9d15f54f45e53ffc9d15f54f45e5bf8636b0873fe8e73fc98e80f9' + + '06d4ad3fed31e11416f2ef3fed31e11416f2efbfc98e80f906d4ad3f0733f72299dfef3f29b1793e1bbfb63f' + + '29b1793e1bbfb6bf0733f72299dfef3fff9160300387e43fa11b48e7668ce83fa11b48e7668ce8bfff916030' + + '0387e43f5af8fe59ef5bec3fd910fa5c0ca6dd3fd910fa5c0ca6ddbf5af8fe59ef5bec3fafba38b61f24d33f' + + '2560ad5b0989ee3f2560ad5b0989eebfafba38b61f24d33f11885b51cfb4ee3fbe27d7838503d23fbe27d783' + + '8503d2bf11885b51cfb4ee3f2056f29506b0de3f575e46dcd914ec3f575e46dcd914ecbf2056f29506b0de3f' + + '496c489b10ece83f8c103d667212e43f8c103d667212e4bf496c489b10ece83f4cf638eca66fbb3f8760d858' + + 'd1d0ef3f8760d858d1d0efbf4cf638eca66fbb3fb77e4b43f670ef3f1ccbd2bba7d0c73f1ccbd2bba7d0c7bf' + + 'b77e4b43f670ef3fd66075a1ba05e23ff5609dde3871ea3ff5609dde3871eabfd66075a1ba05e23fc8fa3ebd' + + 'ffc4ea3fe5463a1f5988e13fe5463a1f5988e1bfc8fa3ebdffc4ea3fda31181b3e20ca3f072daf1f8b53ef3f' + + '072daf1f8b53efbfda31181b3e20ca3fb98ae62cf4aced3fe44173d34df2d73fe44173d34df2d7bfb98ae62c' + + 'f4aced3fd17bef81ef08d93fff0d8c503f73ed3fff0d8c503f73edbfd17bef81ef08d93fcdaf4aefafd5e63f' + + '86b3523f0f6be63f86b3523f0f6be6bfcdaf4aefafd5e63f0397500e6bd9823f4f8c972ca7ffef3f4f8c972c' + + 'a7ffefbf0397500e6bd9823f4f8c972ca7ffef3f0397500e6bd9823f0397500e6bd982bf4f8c972ca7ffef3f' + + '86b3523f0f6be63fcdaf4aefafd5e63fcdaf4aefafd5e6bf86b3523f0f6be63fff0d8c503f73ed3fd17bef81' + + 'ef08d93fd17bef81ef08d9bfff0d8c503f73ed3fe44173d34df2d73fb98ae62cf4aced3fb98ae62cf4acedbf' + + 'e44173d34df2d73f072daf1f8b53ef3fda31181b3e20ca3fda31181b3e20cabf072daf1f8b53ef3fe5463a1f' + + '5988e13fc8fa3ebdffc4ea3fc8fa3ebdffc4eabfe5463a1f5988e13ff5609dde3871ea3fd66075a1ba05e23f' + + 'd66075a1ba05e2bff5609dde3871ea3f1ccbd2bba7d0c73fb77e4b43f670ef3fb77e4b43f670efbf1ccbd2bb' + + 'a7d0c73f8760d858d1d0ef3f4cf638eca66fbb3f4cf638eca66fbbbf8760d858d1d0ef3f8c103d667212e43f' + + '496c489b10ece83f496c489b10ece8bf8c103d667212e43f575e46dcd914ec3f2056f29506b0de3f2056f295' + + '06b0debf575e46dcd914ec3fbe27d7838503d23f11885b51cfb4ee3f11885b51cfb4eebfbe27d7838503d23f' + + '2560ad5b0989ee3fafba38b61f24d33fafba38b61f24d3bf2560ad5b0989ee3fd910fa5c0ca6dd3f5af8fe59' + + 'ef5bec3f5af8fe59ef5becbfd910fa5c0ca6dd3fa11b48e7668ce83fff9160300387e43fff9160300387e4bf' + + 'a11b48e7668ce83f29b1793e1bbfb63f0733f72299dfef3f0733f72299dfefbf29b1793e1bbfb63fed31e114' + + '16f2ef3fc98e80f906d4ad3fc98e80f906d4adbfed31e11416f2ef3ffc9d15f54f45e53f8636b0873fe8e73f' + + '8636b0873fe8e7bffc9d15f54f45e53fa0dec220eeccec3fd9c0ff1715e5db3fd9c0ff1715e5dbbfa0dec220' + + 'eeccec3f487019dc6301d53f85ce75ec333aee3f85ce75ec333aeebf487019dc6301d53fc0a31ce5d6f7ee3f' + + 'd2fdb906181fd03fd2fdb906181fd0bfc0a31ce5d6f7ee3f96bded55ae32e03f5e15d91ffa98eb3f5e15d91f' + + 'fa98ebbf96bded55ae32e03f947545f1ae86e93fe14dc152524ce33fe14dc152524ce3bf947545f1ae86e93f' + + 'e724be40899dc13f4dd581c60db2ef3f4dd581c60db2efbfe724be40899dc13f29defb7ced9bef3f9348db57' + + '2ff2c33f9348db572ff2c3bf29defb7ced9bef3fb89b4ed333d3e23f7224b4ed82e0e93f7224b4ed82e0e9bf' + + 'b89b4ed333d3e23f2579de09744beb3fec858f8705b4e03fec858f8705b4e0bf2579de09744beb3f9a09013f' + + '16f5cd3f084728be7a1cef3f084728be7a1cefbf9a09013f16f5cd3f540f28d96607ee3f02c2885c591dd63f' + + '02c2885c591dd6bf540f28d96607ee3f09dc5c1273d4da3fb9d2592f670ded3fb9d2592f670dedbf09dc5c12' + + '73d4da3f5bb3901bfb82e73f48744f260bb5e53f48744f260bb5e5bf5bb3901bfb82e73f7961f86f396aa43f' + + '14c008427cf9ef3f14c008427cf9efbf7961f86f396aa43faefd25e455fbef3f7fc142db8546a13f7fc142db' + + '8546a1bfaefd25e455fbef3f5c343ee7ded9e53f6447302cc560e73f6447302cc560e7bf5c343ee7ded9e53f' + + 'e1a4e5c65522ed3f1bf3dbd30c79da3f1bf3dbd30c79dabfe1a4e5c65522ed3fcb63ad9c947bd63f9ca59b6a' + + 'e3f5ed3f9ca59b6ae3f5edbfcb63ad9c947bd63fce0946fc1728ef3feebd2c4d7731cd3feebd2c4d7731cdbf' + + 'ce0946fc1728ef3fb6c44bb8d0dee03ff37bf3a51531eb3ff37bf3a51531ebbfb6c44bb8d0dee03fde4931f1' + + 'f4fde93f58eb7ae876aae23f58eb7ae876aae2bfde4931f1f4fde93f88fa797fb1b8c43f08ac854ff193ef3f' + + '08ac854ff193efbf88fa797fb1b8c43fb7ad668dd1b8ef3f8667b2bc4dd6c03f8667b2bc4dd6c0bfb7ad668d' + + 'd1b8ef3f8d7f811b5374e33fe17fbd423f68e93fe17fbd423f68e9bf8d7f811b5374e33f0dc4b6a049b2eb3f' + + 'e1822bc84007e03fe1822bc84007e0bf0dc4b6a049b2eb3f1e66eb054e80d03f44a5504c07ebee3f44a5504c' + + '07ebeebf1e66eb054e80d03f5ece81ff8d4aee3ff3821bd153a2d43ff3821bd153a2d4bf5ece81ff8d4aee3f' + + '293126476d3fdc3f99da000ae2b6ec3f99da000ae2b6ecbf293126476d3fdc3ffa526e758b09e83fa69ad91c' + + 'a81fe53fa69ad91ca81fe5bffa526e758b09e83f6430464e617bb03f9161820201efef3f9161820201efefbf' + + '6430464e617bb03f86d8e92be9e3ef3f0a4d4d4a772eb53f0a4d4d4a772eb5bf86d8e92be9e3ef3ff1226751' + + '79ade43f95a19a1d0a6ce83f95a19a1d0a6ce8bff122675179ade43fd7aa9e891573ec3f9d60a82bd04cdd3f' + + '9d60a82bd04cddbfd7aa9e891573ec3fabb653e3f583d33f5a16a529db79ee3f5a16a529db79eebfabb653e3' + + 'f583d33fb2f61a4bcfc2ee3f43f2e8fbf7a2d13f43f2e8fbf7a2d1bfb2f61a4bcfc2ee3ffef7bf061908df3f' + + '47b1a1259dfceb3f47b1a1259dfcebbffef7bf061908df3ffe5e5743790be93f8006beea33ebe33f8006beea' + + '33ebe3bffe5e5743790be93fc17d303b53ffbc3f5443910347cbef3f5443910347cbefbfc17d303b53ffbc3f' + + '2a321a9c297aef3fffc4088dfd0ac73fffc4088dfd0ac7bf2a321a9c297aef3fe2132c662d2fe23f23f59010' + + 'c954ea3f23f59010c954eabfe2132c662d2fe23fefec45f368e0ea3fbce2dbe4365ee13fbce2dbe4365ee1bf' + + 'efec45f368e0ea3fabb9f3d5f1e4ca3fb4abbc062249ef3fb4abbc062249efbfabb9f3d5f1e4ca3f9a759543' + + '9ebfed3faedf13e6f594d73faedf13e6f594d7bf9a7595439ebfed3f8f94abb75565d93f7f8a8872715fed3f' + + '7f8a8872715fedbf8f94abb75565d93f755bc999caf8e63f5b537f431547e63f5b537f431547e6bf755bc999' + + 'caf8e63fcb97b96a296a8f3fd13bc54309ffef3fd13bc54309ffefbfcb97b96a296a8f3f77cb70681cfeef3f' + + '26b2fa214dfd953f26b2fa214dfd95bf77cb70681cfeef3fff22ec4fe422e63fbf410e96ac1be73fbf410e96' + + 'ac1be7bfff22ec4fe422e63f2475181b5b4bed3ff2f90d447dc1d93ff2f90d447dc1d9bf2475181b5b4bed3f' + + '921026c96337d73f5a918af3fed1ed3f5a918af3fed1edbf921026c96337d73f65bc1bbc6b3eef3fad5df134' + + '63a9cb3fad5df13463a9cbbf65bc1bbc6b3eef3f4f25eecfe933e13fb6579fd88ffbea3fb6579fd88ffbeabf' + + '4f25eecfe933e13fc63b594a1838ea3f1071bb4c7358e23f1071bb4c7358e2bfc63b594a1838ea3f0d831d83' + + '1a45c63f0cc6404a0f83ef3f0cc6404a0f83efbf0d831d831a45c63ff69a7d3b6ec5ef3f3faae4fdb78ebe3f' + + '3faae4fdb78ebebff69a7d3b6ec5ef3f18c58149c4c3e33f15a8c51fa42ae93f15a8c51fa42ae9bf18c58149' + + 'c4c3e33fc15411611be4eb3fa3cd56e6de5fdf3fa3cd56e6de5fdfbfc15411611be4eb3f7893c6ef3e42d13f' + + '0990995e83d0ee3f0990995e83d0eebf7893c6ef3e42d13fa7535dc5616aee3f71c26ee99be3d33f71c26ee9' + + '9be3d3bfa7535dc5616aee3f21cde1ae4bf3dc3f139c0287f589ec3f139c0287f589ecbf21cde1ae4bf3dc3f' + + 'fa83af11714be83f7f9f586dbcd3e43f7f9f586dbcd3e4bffa83af11714be83f99a2c5129f9db33f602d4885' + + 'eae7ef3f602d4885eae7efbf99a2c5129f9db33f0f4130259debef3f4d44ed74960cb23f4d44ed74960cb2bf' + + '0f4130259debef3f86a4cc25ccf9e43fff45f5139c2ae83fff45f5139c2ae8bf86a4cc25ccf9e43f49c4b919' + + '8fa0ec3f895386c37f99dc3f895386c37f99dcbf49c4b9198fa0ec3ff03689dc1043d43fd36704559d5aee3f' + + 'd36704559d5aeebff03689dc1043d43f5186076aebddee3fce49174e5be1d03fce49174e5be1d0bf5186076a' + + 'ebddee3fded2245c57b7df3f27230dcb54cbeb3f27230dcb54cbebbfded2245c57b7df3f6c4aace39049e93f' + + '2930d6e3239ce33f2930d6e3239ce3bf6c4aace39049e93f5bb86fade80ec03f888d0a0f47bfef3f888d0a0f' + + '47bfefbf5bb86fade80ec03f784bcb37a78bef3fdecb5486007fc53fdecb5486007fc5bf784bcb37a78bef3f' + + 'ba3c4def8b81e23f5ea7c0d2261bea3f5ea7c0d2261beabfba3c4def8b81e23ff5a24c2a7416eb3f57a9d048' + + '7209e13f57a9d0487209e1bff5a24c2a7416eb3fdd745d53906dcc3ff0ae3a5a6833ef3ff0ae3a5a6833efbf' + + 'dd745d53906dcc3f818d6d0f16e4ed3fb60c8a6398d9d63fb60c8a6398d9d6bf818d6d0f16e4ed3fc00ab543' + + '651dda3fdcfbcb7bfc36ed3fdcfbcb7bfc36edbfc00ab543651dda3f4299078e553ee73f106ae5bd7cfee53f' + + '106ae5bd7cfee5bf4299078e553ee73f1d3be54c4f459c3f79a6e29ce0fcef3f79a6e29ce0fcefbf1d3be54c' + + '4f459c3f64911bbb53f7ef3f864687a5ba8da73f864687a5ba8da7bf64911bbb53f7ef3fdf23f7d50190e53f' + + 'd297bf07f7a4e73fd297bf07f7a4e7bfdf23f7d50190e53f7b46cee830f8ec3f7219b31d972fdb3f7219b31d' + + '972fdbbf7b46cee830f8ec3fb6b39d8be7bed53fd966dc2fa018ee3fd966dc2fa018eebfb6b39d8be7bed53f' + + '5f8f89bc9010ef3f48e32d466bb8ce3f48e32d466bb8cebf5f8f89bc9010ef3f8cb032201189e03f47bcfd14' + + '8f65eb3f47bcfd148f65ebbf8cb032201189e03fc275f010d1c2e93f1510444bc2fbe23f1510444bc2fbe2bf' + + 'c275f010d1c2e93fa71645f97b2bc33f91177aac9ba3ef3f91177aac9ba3efbfa71645f97b2bc33fdcfd0ccb' + + 'fbaaef3f0934fd4d9964c23f0934fd4d9964c2bfdcfd0ccbfbaaef3f1fa649ec2124e33fb2062ba4dfa4e93f' + + 'b2062ba4dfa4e9bf1fa649ec2124e33fe992e786667feb3fb7b831ecf35de03fb7b831ecf35de0bfe992e786' + + '667feb3f0238bd80747bcf3f8c73cf145a04ef3f8c73cf145a04efbf0238bd80747bcf3f7a1939448f29ee3f' + + 'b467f4124060d53fb467f4124060d5bf7a1939448f29ee3f9356fd14788adb3f60a09927b3e2ec3f60a09927' + + 'b3e2ecbf9356fd14788adb3f33d3e29cb8c6e73f9f649751c36ae53f9f649751c36ae5bf33d3e29cb8c6e73f' + + '17835fbd01b1aa3fd3beb154dcf4ef3fd3beb154dcf4efbf17835fbd01b1aa3f8c531475fadaef3fa130c112' + + '874fb83fa130c112874fb8bf8c531475fadaef3fa2322b695a60e43f881dde1e87ace83f881dde1e87ace8bf' + + 'a2322b695a60e43f04c041318344ec3fde41a966fffedd3fde41a966fffeddbf04c041318344ec3f2045954e' + + '1ac4d23f306b0136ec97ee3f306b0136ec97eebf2045954e1ac4d23f0058e69383a6ee3fba545599e663d23f' + + 'ba545599e663d2bf0058e69383a6ee3f25d83c6da857de3ff1e33149d12cec3ff1e33149d12cecbf25d83c6d' + + 'a857de3f554618756acce83f80432a5b7f39e43f80432a5b7f39e4bf554618756acce83f5ca824ebb6dfb93f' + + '9e5ca72d0dd6ef3f9e5ca72d0dd6efbf5ca824ebb6dfb93fee3c88567567ef3f0418c4271796c83f0418c427' + + '1796c8bfee3c88567567ef3f7248dc641bdce13fd25a546e678dea3fd25a546e678deabf7248dc641bdce13f' + + '8eb92c7a54a9ea3fbf73131750b2e13fbf73131750b2e1bf8eb92c7a54a9ea3ffa2ab6e9495bc93f5d6843ed' + + 'a65def3f5d6843eda65defbffa2ab6e9495bc93f463d8bdd009aed3f3f90f3aa6a4fd83f3f90f3aa6a4fd8bf' + + '463d8bdd009aed3f44edd5864bacd83f4fa44584c486ed3f4fa44584c486edbf44edd5864bacd83f9ce22fed' + + '5cb2e63f719ca1ead18ee63f719ca1ead18ee6bf9ce22fed5cb2e63fbaa4ccbef821693f021d6221f6ffef3f' + + '021d6221f6ffefbfbaa4ccbef821693f')); + // Sanity check (shake256 because used already): catch byte-level corruption, endianness/layout + // mistakes, or accidental regeneration through engine-dependent sin/cos results. + const rootBytes = u8f(baswap64If(Float64Array.from(roots))); + if (bytesToHex(shake256(rootBytes)) !== + 'f45a496cf56ccc6e3e3395a20209206d81d71a7905a661447bd5bc0e24e0af1e') { + throw new Error('COMPLEX_ROOTS mismatch'); + } + return roots; +})(); +// Falcon's q-field Montgomery kernel: mul() operates on Montgomery residues and returns one. +// inv() accepts a normal residue but returns its inverse in Montgomery form, so div(x, y) can stay +// `mul(x, inv(y))`; callers like toMontgomery() manage the representation boundaries. +const intField = { + mul(x, y) { + let z = Math.imul(x, y); + let w = Math.imul(Q, Math.imul(z, Q0I) & 0xffff); + z = ((z + w) >>> 16) - Q; + z += Q & (z >> 31); + return z >>> 0; + }, + inv(y) { + // y^(q-2) mod q + if (y === 0) + throw new Error('divison by zero'); + const e00 = this.mul(y, R2); // e0 = 1 + const e01 = this.mul(e00, e00); // 2 * e0 = 2 + const e02 = this.mul(e01, e00); // e1 + e0 = 3 + const e03 = this.mul(e02, e01); // e3 = e2 + e1 = 5 + const e04 = this.mul(e03, e03); // e4 = 2 * e3 = 10 + const e05 = this.mul(e04, e04); // e5 = 2 * e4 = 20 + const e06 = this.mul(e05, e05); // e6 = 2 * e5 = 40 + const e07 = this.mul(e06, e06); // e7 = 2 * e6 = 80 + const e08 = this.mul(e07, e07); // e8 = 2 * e7 = 160 + const e09 = this.mul(e08, e02); // e9 = e8 + e2 = 163 + const e10 = this.mul(e09, e08); // e10 = e9 + e8 = 323 + const e11 = this.mul(e10, e10); // e11 = 2 * e10 = 646 + const e12 = this.mul(e11, e11); // e12 = 2 * e11 = 1292 + const e13 = this.mul(e12, e09); // e13 = e12 + e9 = 1455 + const e14 = this.mul(e13, e13); // e14 = 2 * e13 = 2910 + const e15 = this.mul(e14, e14); // e15 = 2 * e14 = 5820 + const e16 = this.mul(e15, e10); // e16 = e15 + e10 = 6143 + const e17 = this.mul(e16, e16); // e17 = 2 * e16 = 12286 + const e18 = this.mul(e17, e00); // e18 = e17 + e0 = 12287 + return e18; + }, + div: (x, y) => intField.mul(x, intField.inv(y)), +}; +function getIntPoly(logn) { + const n = 1 << logn; + const newPoly = (n) => new Uint16Array(n); + const F = Number(invert(BigInt(n), QBig)); + const { mod, smod, NTT } = genCrystals({ + N: n, + Q, + F: F, + ROOT_OF_UNITY: 7, + newPoly, + isKyber: false, + brvBits: 10, + }); + // Keep Falcon source compatible with older TS parsers: avoid spelling newer + // `Uint16Array` syntax directly and cast the callee side at the boundary. + const ntt = (r) => NTT.encode(r); + const intt = (r) => NTT.decode(r); + // Falcon integer helpers mutate their first argument in place; div() also performs intt() + // before returning, so callers must treat these as owned-temporary transforms, not pure helpers. + // Centered representatives are in [-6144, 6144] for odd q = 12289, + // not a generic [-q/2, q/2] range. + const signedCoder = { + encode: (p) => Int16Array.from(p, (x) => smod(x)), + decode: (p) => Uint16Array.from(p, (x) => mod(x)), + }; + const intPoly = { + create: newPoly, + smallSqnorm(f) { + let s = 0; + let ng = 0; + for (let u = 0; u < n; u++) { + const z = f[u]; + s = (s + z * z) >>> 0; + ng |= s; + } + return (s | -(ng >>> 31)) >>> 0; + }, + isShort(s1, s2) { + let s = 0 >>> 0; + let ng = 0 >>> 0; + for (let u = 0; u < n; u++) { + let z1 = (s1[u] << 16) >> 16; + s = (s + ((z1 * z1) >>> 0)) >>> 0; + ng |= s; + let z2 = (s2[u] << 16) >> 16; + s = (s + ((z2 * z2) >>> 0)) >>> 0; + ng |= s; + } + if (ng & 0x80000000) + s = 0xffffffff; + return s <= L2BOUND[logn]; + }, + sub(a, b) { + for (let i = 0; i < n; i++) + a[i] = mod(a[i] - b[i]); + return a; + }, + ntt, + intt, + toMontgomery(d) { + for (let i = 0; i < n; i++) + d[i] = intField.mul(d[i], R2); + return d; + }, + mul(f, d) { + for (let i = 0; i < n; i++) + f[i] = intField.mul(f[i], d[i]); + return f; + }, + div(f, d) { + for (let i = 0; i < n; i++) + f[i] = intField.div(f[i], d[i]); + this.intt(f); + return f; + }, + }; + return { newPoly, intPoly, signedCoder }; +} +// Falcon's JS binary64 complex field wrapper for FFT/sampler paths. Current uses are the +// ordinary finite-number operations add/sub/neg/mul/conj/scale/magSqSum; the inherited wider API +// exists because getComplex() exposes it, not because all methods are relied on by Falcon today. +const fComplex = getComplex({ + ZERO: 0, + ONE: 1, + add: (x, y) => x + y, + sub: (x, y) => x - y, + mul: (x, y) => x * y, + div: (x, y) => x / y, + eql: (x, y) => x === y, + inv: (x) => 1 / x, + neg: (x) => -x, +}); +// Detached object copy of the exact round-3 / PQClean fpr_gm_tab payload in its original order. +const COMPLEX_ROOTS_O = ComplexArrInterleaved.decode(COMPLEX_ROOTS); +// Re-map roots into the local forward FFTCore schedule +// `{ dit: false, invertButterflies: true, brp: false }`. +// Index 0 stays intentionally unused because FFTCore's forward group counter starts at 1. +const FFTCoreRoots = {}; +// Inverse FFTCore reads roots as `N - grp`, so fill this table from the end and store `-conj(root)` +// rather than plain conjugates +// to match Falcon's split/iFFT sign convention under the local butterfly. +const FFTCoreRootsConj = {}; +for (let logn = 0; logn < 10; logn++) { + const out = new Array(1 << logn); + const outC = new Array(1 << logn); + for (let i = 0, g1 = 1, g2 = 1; i < logn; i++) { + const ng = 1 << i; + for (let k = 0; k < ng; k++) + out[g1++] = COMPLEX_ROOTS_O[(ng << 1) + k]; + const ng2 = 1 << (logn - i); + for (let k = 0; k < ng2 >> 1; k++) + outC[out.length - g2++] = fComplex.neg(fComplex.conj(COMPLEX_ROOTS_O[ng2 + k])); + } + FFTCoreRoots[logn] = out; + FFTCoreRootsConj[logn] = outC; +} +// Mixed float-poly helper surface: most methods allocate / return fresh values, +// but FFT() and iFFT() mutate their CPoly input in place. +// Flat Float64Array buffers use ComplexArr's [...re, ...im] layout. +function getFloatPoly(logn) { + const n = 1 << logn; + const N_COMPLEX = n >> 1; + const hn = Math.log2(N_COMPLEX); + const fftOpts = { N: N_COMPLEX, invertButterflies: true, skipStages: 0, brp: false }; + const inv = 1.0 / N_COMPLEX; + return { + to: (f) => ComplexArr.decode(Array.from(f)), + from: (f) => new Float64Array(ComplexArr.encode(f)), + // Runtime callers also pass HashToPoint's Uint16Array output here; + // the implementation only needs a numeric typed-array shape, + // even though the local type is narrower. + convSmall: (f) => ComplexArr.decode(Array.from(f)), + add: (a, b) => a.map((i, j) => fComplex.add(i, b[j])), + sub: (a, b) => a.map((i, j) => fComplex.sub(i, b[j])), + neg: (a) => a.map((i) => fComplex.neg(i)), + mul: (a, b) => a.map((i, j) => fComplex.mul(i, b[j])), + conj: (a) => a.map((i) => fComplex.conj(i)), + mulConst: (a, x) => a.map((i) => fComplex.scale(i, x)), + scaleNorm: (a, b) => a.map((i, j) => fComplex.scale(i, b[j])), + invNorm: (a, b) => new Float64Array(a.map((i, j) => 1.0 / fComplex.magSqSum(i, b[j]))), + FFT: (f) => FFTCore(fComplex, { ...fftOpts, dit: false, roots: FFTCoreRoots[hn] })(f), + iFFT(f) { + FFTCore(fComplex, { ...fftOpts, dit: true, roots: FFTCoreRootsConj[hn] })(f); + for (let i = 0; i < f.length; i++) + f[i] = fComplex.scale(f[i], inv); + return f; + }, + }; +} +function ApproxExp(x, ccs) { + // Algorithm 13: ApproxExp(x, ccs), (Page 42) + // Require: Floating-point values x ∈ [0, ln(2)] and ccs ∈ [0, 1] + // Ensure: A floating approximation of ccs · exp(-x); berExp() applies the later 2^63 scaling. + // 1: C = [0x00000004741183A3, ...] + // 2: y ← C[0] ▷ y and z remain in {0, ..., 2⁶³ - 1} the whole algorithm. + // 3: z ← ⌊2⁶³ · x⌋ + // 4: for i = 1, ..., 12 do + // 5: y ← C[i] - (z · y) >> 63 ▷ (z · y) fits in 126 bits, but we only need the top 63 bits + // 6: z ← ⌊2⁶³ · ccs⌋ + // 7: y ← (z · y) >> 63 + // 8: return y + // FACCT / round-3 Falcon's leading 1.0 coefficient is implicit in `return ccs * (1.0 + z * y)`, + // so the decimal list below stores the remaining 12 polynomial coefficients only. + const ev = [ + 0.99999999999999489297408672428, 0.500000000000019206858326015208, + 0.166666666666984014666397229121, 0.041666666666110491190622155955, + 0.008333333327800835146903501993, 0.001388888894063186997887560103, + 0.000198412739277311890541063977, 0.000024801566833585381209939524, + 0.000002755586350219122514855659, 0.000000275607356160477811864927, + 0.000000025299506379442070029551, 0.000000002073772366009083061987, + ]; + const y = -x; + let z = ev[ev.length - 1]; + for (let i = ev.length - 2; i >= 0; i--) + z = z * y + ev[i]; + return ccs * (1.0 + z * y); +} +function genFalcon(opts) { + const { N } = opts; + const logn = Math.log2(N); + const id = (n) => n; + const { newPoly, intPoly, signedCoder } = getIntPoly(logn); + const floatPoly = getFloatPoly(logn); + // Kinda like FFT Sampler: single function, but a lot of private deps and internal rng stake + class NTRU { + logn; + shake; + constructor(logn, seed) { + this.logn = logn; + this.shake = shake256.create().update(seed); + } + gaussSingle() { + const g = 1 << (10 - this.logn); + let val = 0; + for (let i = 0; i < g; i++) { + const r128 = bytesToNumberLE(this.shake.xof(16)); + const r1 = r128 & 0x7fffffffffffffffn; + const r2 = (r128 >> 64n) & 0x7fffffffffffffffn; + const sign = Number((r128 >> 63n) & 1n); + let f = r1 < gauss_1024_12289[0] ? 1 : 0; + let v = 0; + for (let k = 1; k < gauss_1024_12289.length; k++) { + const tBit = r2 >= gauss_1024_12289[k] ? 1 : 0; + v |= k & -(tBit & (f ^ 1)); + f |= tBit; + } + val += sign === 1 ? -v : v; + } + return val; + } + polyGauss() { + const n = 1 << this.logn; + let mod2 = 0; // xor sum of previous elements + const f = new Int8Array(n); + for (let u = 0; u < n; u++) { + let s; + while (true) { + s = this.gaussSingle(); + if (s < -127 || s > 127) + continue; + if (u === n - 1) + if ((mod2 ^ (s & 1)) === 0) + continue; + break; + } + if (u < n - 1) + mod2 ^= s & 1; + f[u] = s; + } + return f; + } + galoisNorm(logn, a) { + const n = 1 << logn; + const d = new Array(n >> 1); + for (let k = 0; k < n; k += 2) { + let s = 0n; + for (let i = 0; i <= k; i += 2) + s += a[i] * a[k - i]; + for (let i = k + 2; i < n; i += 2) + s -= a[i] * a[k + n - i]; + d[k >>> 1] = s; + } + for (let k = 0; k < n; k += 2) { + let s = 0n; + for (let i = 1; i < k; i += 2) + s += a[i] * a[k - i]; + for (let i = k + 1; i < n; i += 2) + s -= a[i] * a[k + n - i]; + d[k >>> 1] -= s; + } + return d; + } + mulConjD(logn, d, a, b) { + const n = 1 << logn; + for (let k = 0; k < n; k++) { + let s = 0n; + for (let i = 0; i <= k; i += 2) + s += b[i >>> 1] * a[k - i]; + for (let i = k + 2 - (k & 1); i < n; i += 2) + s -= b[i >>> 1] * a[k + n - i]; + if ((k & 1) === 0) + d[k] = s; + else + d[k] = -s; + } + return d; + } + subMul(logn, a, b, c, e) { + const n = 1 << logn; + for (let k = 0; k < n; k++) { + let s = 0n; + for (let i = 0; i <= k; i++) + s += b[i] * c[k - i]; + for (let i = k + 1; i < n; i++) + s -= b[i] * c[k + n - i]; + a[k] -= s << e; + } + return a; + } + reduce(logn, f, g, F, G, logn_top) { + // Algorithm 7: Reduce(f, g, F, G) + // (Page 35) + // Require: Polynomials f, g, F, G ∈ Z[x]/(φ) + // Ensure: (F, G) is reduced with respect to (f, g) + // 1: do + // 2: k ← ⌊(Ff*+Gg*)/(ff*+gg*)⌋ ▷ (Ff*+Gg*)/(ff*+gg*) ∈ Q[x]/(φ) and k ∈ Z[x]/(φ) + // 3: F ← F - kf + // 4: G ← G - kg + // 5: while k ≠ 0 + // ▷ Multiple iterations may be needed, e.g. if k is computed in small precision. + const n = 1 << logn; + const depth = logn_top - logn; + const floatPoly = getFloatPoly(logn); + const slen = MAX_BL_SMALL[depth]; + const llen = MAX_BL_LARGE[depth]; + let maxFGBits = BigInt(31 * llen); + let FGlen = BigInt(llen); + const scalefg = BigInt(31 * (slen - 10)); + const fgMaxBits = BITLENGTH[depth].avg + 6 * BITLENGTH[depth].std; + const fgMinBits = BITLENGTH[depth].avg - 6 * BITLENGTH[depth].std; + let scaleK = BigInt(Math.round(31 * llen - fgMinBits)); + let fx = new Float64Array(n); + let gx = new Float64Array(n); + for (let i = 0; i < n; i++) { + fx[i] = Number(f[i] >> scalefg); + gx[i] = Number(g[i] >> scalefg); + } + const rt3 = floatPoly.conj(floatPoly.FFT(floatPoly.to(fx))); + const rt4 = floatPoly.conj(floatPoly.FFT(floatPoly.to(gx))); + const rt5 = floatPoly.invNorm(rt3, rt4); + const Fx = new Float64Array(n); + const Gx = new Float64Array(n); + const k = new Array(n); + while (true) { + let scaleFG = 31n * (FGlen - 10n); + for (let i = 0; i < n; i++) { + Fx[i] = Number(F[i] >> scaleFG); + Gx[i] = Number(G[i] >> scaleFG); + } + const rt2 = floatPoly.mul(floatPoly.FFT(floatPoly.to(Gx)), rt4); + const rt1 = floatPoly.mul(floatPoly.FFT(floatPoly.to(Fx)), rt3); + // convert to float64array + const rt2f = floatPoly.from(floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.add(rt2, rt1), rt5))); + const pdc = 2 ** Number(scaleFG - scalefg - scaleK); + for (let i = 0; i < n; i++) { + const BOUND = 2147483647.0; + const val = rt2f[i] * pdc; + if (val <= -BOUND || val >= BOUND) + return false; + k[i] = BigInt(Math.round(val)); + } + F = this.subMul(logn, F, f, k, scaleK); // 3: F ← F - kf + G = this.subMul(logn, G, g, k, scaleK); // 4: G ← G - kg + const maxfgNew = scaleK + BigInt(Math.round(fgMaxBits)) + 10n; + if (maxfgNew < maxFGBits) + maxFGBits = maxfgNew; + if (FGlen > 1n && FGlen * 31n >= maxFGBits + 31n) + FGlen--; + if (scaleK <= 0n) + break; + scaleK -= 25n; + if (scaleK < 0n) + scaleK = 0n; + } + return true; + } + // This is recursive thing that goes from logn to 0 + solveBranch(logn, f, g, F, G, logn_top) { + // Algorithm 6: NTRUSolve_{n,q}(f, g), (Page 35) + // Require: f, g ∈ Z[x]/(xⁿ + 1) with n a power of two + // Ensure: Polynomials F, G such that (3.15) is verified + // 1: if n = 1 then + // 2: Compute u, v ∈ Z such that uf - vg = gcd(f, g) ▷ Using the extended GCD + // 3: if gcd(f, g) ≠ 1 then + // 4: abort and return ⊥ + // 5: (F, G) ← (vq, uq) + // 6: return (F, G) + // 7: else + // 8: f' ← N(f) ▷ f', g', F', G' ∈ Z[x]/(x^{n/2} + 1) + // 9: g' ← N(g) ▷ N as defined in either (3.25) or (3.26) + // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') ▷ Recursive call + // 11: F ← F'(x²)g(-x) ▷ F, G ∈ Z[x]/(xⁿ + 1) + // 12: G ← G'(x²)f(-x) + // 13: Reduce(f, g, F, G) ▷ (F, G) is reduced with respect to (f, g) + // 14: return (F, G) + if (logn === 0) { + // // 1: if n = 1 then + const xf = f[0]; + const xg = g[0]; + // We can rely on 'invert' to throw if they are not coprime. + if (xf <= 0n || xg <= 0n) + return false; + try { + const u1 = invert(xf, xg); // if gcd(f, g) ≠ 1 then + const v1 = (1n - u1 * xf) / xg; + F[0] = -v1 * QBig; // 5: (F, G) ← (vq, uq) + G[0] = u1 * QBig; + return true; + } + catch (e) { + return false; + } + } + if (logn_top === undefined) + logn_top = logn; + const n = 1 << logn; + const hn = n >>> 1; + if (!f || f.length < n || !g || g.length < n) + return false; + const fp = this.galoisNorm(logn, f); // 8: f' ← N(f) + const gp = this.galoisNorm(logn, g); // 9: g' ← N(g) + const Fp = new Array(hn); // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') + const Gp = new Array(hn); + // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') + // ▷ Recursive call + if (!this.solveBranch(logn - 1, fp, gp, Fp, Gp, logn_top)) + return false; + F = this.mulConjD(logn, F, g, Fp); // 11: F ← F'(x²)g(-x) + G = this.mulConjD(logn, G, f, Gp); // 12: G ← G'(x²)f(-x) + // 13: Reduce(f, g, F, G) + // ▷ (F, G) is reduced with respect to (f, g) + return this.reduce(logn, f, g, F, G, logn_top); + } + solve(f, g) { + // Algorithm 5: NTRUGen(φ, q) + // (Page 34) + // Require: A monic polynomial φ ∈ Z[x] of degree n, a modulus q + // Ensure: Polynomials f, g, F, G + // 1: σ{f,g} ← 1.17√q/2n ▷ σ{f,g} is chosen so that E[||(f, g)||] = 1.17√q + // 2: for i from 0 to n-1 do + // 3: fᵢ ← DZ,σ{f,g},0 ▷ See also (3.29) + // 4: gᵢ ← DZ,σ{f,g},0 + // 5: f ← Σᵢ fᵢxⁱ ▷ f ∈ Z[x]/(φ) + // 6: g ← Σᵢ gᵢxⁱ ▷ g ∈ Z[x]/(φ) + // 7: if NTT(f) contains 0 as a coefficient then ▷ Check that f is invertible mod q + // 8: restart + // 9: γ ← max{||(g, -f)||, ||( (qf*)/(ff*+gg*), (qg*)/(ff*+gg*) )||} + // ▷ Using (3.9) with (3.8) or (3.10) + // 10: if γ > 1.17√q then ▷ Check that γ = ||B||_GS is short + // 11: restart + // 12: F, G ← NTRUSolve_{n,q}(f, g) ▷ Computing F, G such that fG - gF = q mod φ + // 13: if (F, G) = ⊥ then + // 14: restart + // 15: return f, g, F, G + const n = 1 << logn; + const bf = Array.from(f).map(BigInt); + const bg = Array.from(g).map(BigInt); + const bF = new Array(n); + const bG = new Array(n); + // 12: F, G ← NTRUSolve_{n,q}(f, g) + // ▷ Computing F, G such that fG - gF = q mod φ + if (!this.solveBranch(logn, bf, bg, bF, bG)) + return false; + const F = new Int8Array(n); + const G = new Int8Array(n); + for (let i = 0; i < n; i++) { + const x = bF[i]; + const y = bG[i]; + if (x < -127 || x > +127 || y < -127 || y > +127) + return false; + F[i] = Number(x); + G[i] = Number(y); + } + return [F, G]; + } + generate() { + // Algorithm 4: Keygen(φ, q) + // (Page 33) + // Require: A monic polynomial φ ∈ Z[x], a modulus q + // Ensure: A secret key sk, a public key pk + // 1: f, g, F, G ← NTRUGen(φ, q) ▷ Solving the NTRU equation + // 2: B ← [ g -f ; G -F ] + // 3: B̂ ← FFT(B) ▷ Compute the FFT for each of the 4 components {g, -f, G, -F} + // 4: G ← B̂ × B̂* + // 5: T ← ffLDL*(G) ▷ Computing the LDL* tree + // 6: for each leaf leaf of T do + // 7: leaf.value ← σ/√leaf.value ▷ Normalization step + // 8: sk ← (B̂, T) + // 9: h ← gf⁻¹ mod q + // 10: pk ← h + // 11: return sk, pk + let max = 1_000_000; + let curr = 0; + while (true) { + if (curr++ === max) + throw new Error("can't generate key"); + const f = this.polyGauss(); + const g = this.polyGauss(); + let lim = 1 << (opts.fgBits - 1); + for (let u = 0; u < N; u++) { + if (f[u] >= lim || f[u] <= -lim || g[u] >= lim || g[u] <= -lim) { + lim = -1; + break; + } + } + if (lim < 0) + continue; + const normf = intPoly.smallSqnorm(f); + const normg = intPoly.smallSqnorm(g); + const norm = (normf + normg) | -((normf | normg) >>> 31); + // Cheap integer prefilter for the same 1.17^2*q Gram-Schmidt bound; + // ceil(BNORM_MAX) = 16823. + if (norm >= 16823) + continue; + let rt1 = floatPoly.FFT(floatPoly.convSmall(f)); + let rt2 = floatPoly.FFT(floatPoly.convSmall(g)); + const rt3 = floatPoly.invNorm(rt1, rt2); + rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q), rt3)); + rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q), rt3)); + // Separate reals and then imaginary to enforce numerical stability + let bnorm = 0; + for (let u = 0; u < rt1.length; u++) { + bnorm += rt1[u].re * rt1[u].re; + bnorm += rt2[u].re * rt2[u].re; + } + for (let u = 0; u < rt1.length; u++) { + bnorm += rt1[u].im * rt1[u].im; + bnorm += rt2[u].im * rt2[u].im; + } + if (!(bnorm < BNORM_MAX)) + continue; + let pub; + try { + pub = computePublic(f, g); + } + catch (_) { + continue; + } + const solved = this.solve(f, g); + if (solved === false) + continue; + return [f, g, solved[0], solved[1], pub]; // f g F G h + } + } + } + // same as ml-dsa id, but MSB bits :( + const modqCoder = () => { + const coder = bitsCoderMSB(newPoly, N, 14, { + encode: id, + decode: id, + }); + return { + bytesLen: coder.bytesLen, + encode(poly) { + // Keep these raw checks in sync with Q: + // Falcon public-key coefficients must stay in [0, q - 1]. + for (let i = 0; i < poly.length; i++) + if (poly[i] >= 12289) + throw new Error('public key coeff out of range'); + return coder.encode(poly); + }, + decode(bytes) { + // Round-3 Falcon requires exact body length here; + // otherwise truncated keys decode as zero-padded + // and overlong keys silently ignore the tail in this generic bit decoder. + if (bytes.length !== coder.bytesLen) + throw new Error('wrong public key length'); + const poly = coder.decode(bytes); + // Keep these raw checks in sync with Q: + // Falcon public-key coefficients must stay in [0, q - 1]. + for (let i = 0; i < poly.length; i++) + if (poly[i] >= 12289) + throw new Error('public key coeff out of range'); + const normalized = coder.encode(poly); + if (normalized.length !== bytes.length) + throw new Error('wrong public key length'); + for (let i = 0; i < bytes.length; i++) + if (bytes[i] !== normalized[i]) + throw new Error('wrong public key encoding'); + return poly; + }, + }; + }; + const trimI8Coder = (bits) => { + const shift = 32 - bits; + const coder = bitsCoderMSB((len) => new Int8Array(len), N, bits, { + encode: (v) => v & ((1 << bits) - 1), + decode: (w) => ((w & getMask(bits)) << shift) >> shift, + }); + return { + bytesLen: coder.bytesLen, + encode(poly) { + // Secret-key trim encodings keep a symmetric signed range and reserve the most-negative + // value as a non-canonical sentinel, + // so encode() and decode() intentionally use different bounds. + const max = (1 << (bits - 1)) - 1; + const min = -max; + for (let i = 0; i < poly.length; i++) + if (poly[i] < min || poly[i] > max) + throw new Error('private key coeff out of range'); + return coder.encode(poly); + }, + decode(bytes) { + const poly = coder.decode(bytes); + const min = -(1 << (bits - 1)); + for (let i = 0; i < poly.length; i++) + if (poly[i] === min) + throw new Error('forbidden private key coeff'); + return poly; + }, + }; + }; + const fgCoder = trimI8Coder(opts.fgBits); + const FGCoder = trimI8Coder(opts.FGBits); + // Current utils.splitCoder requires a label first; + // without it Falcon key/sig encodings drift and KATs fail. + // 0x50 + logn || f || g || F + const secretKeyCoder = headerCoder(0x50 + logn, splitCoder('falcon.secretKey', fgCoder, fgCoder, FGCoder)); + const publicKeyCoder = headerCoder(0x00 + logn, modqCoder()); + const decodePaddedSig = (s2) => { + // The fixed padded form accepts only a canonical compressed payload + // followed by an all-zero tail. + const normalized = compCoder(N).encode(compCoder(N).decode(s2)); + for (let i = normalized.length; i < s2.length; i++) + if (s2[i] !== 0) + throw new Error('non-zero padding'); + return normalized; + }; + const decodeUnpaddedSig = (s2) => { + // Unpadded attached and detached signatures require the compressed payload to use its exact + // canonical bitlength. Appending a zero tail and adjusting the outer container length must + // still be rejected. + const normalized = compCoder(N).encode(compCoder(N).decode(s2)); + if (normalized.length !== s2.length) + throw new Error('wrong signature length'); + return s2; + }; + const decodeSig = opts.padded ? decodePaddedSig : decodeUnpaddedSig; + // Unpadded: [ 2B sig_len ] [ 40B nonce ] [ message ] [ 1B header ] [ compressed_sig ] + // Padded [ 1B header ] [ 40B nonce ] [ compressed_sig ] [ padding ] | [ message ] + const SignatureCoderBasic = (logn) => { + const TYPE_BYTE = 0x20 + logn; + return { + encode({ msg, nonce, s2 }) { + let compressed = s2; + const payloadLen = 1 + compressed.length; + const totalLen = 2 + NONCELEN + msg.length + payloadLen; + const out = new Uint8Array(totalLen); + let i = 0; + out[i++] = (payloadLen >> 8) & 0xff; + out[i++] = payloadLen & 0xff; + out.set(nonce, i); + i += NONCELEN; + out.set(msg, i); + i += msg.length; + out[i++] = TYPE_BYTE; + out.set(compressed, i); + return out; + }, + decode(data) { + if (!data || data.length < NONCELEN + 3) + throw new Error('signature coder: wrong length'); + const len = (data[0] << 8) | data[1]; + const s2Len = len - 1; + const msgLen = data.length - NONCELEN - 3 - s2Len; + if (msgLen < 0) + throw new Error('signature coder: wrong msg length'); + const typeByte = data[2 + NONCELEN + msgLen]; + if (typeByte !== TYPE_BYTE) + throw new Error('signature coder: wrong type byte'); + const nonce = data.subarray(2, 2 + NONCELEN); + const msg = data.subarray(2 + NONCELEN, 2 + NONCELEN + msgLen); + const s2 = decodeUnpaddedSig(data.subarray(2 + NONCELEN + msgLen + 1)); + if (s2.length !== s2Len) + throw new Error('signature coder: wrong s2 length'); + return { msg, nonce, s2 }; + }, + }; + }; + const SignatureCoderPadded = (logn) => { + const sigLen = opts.paddedLen; + return { + encode({ msg, nonce, s2 }) { + return headerCoder(0x30 + logn, splitCoder('falcon.signature', NONCELEN, sigLen, msg.length)).encode([nonce, pad(sigLen).encode(s2), msg]); + }, + decode(data) { + const msgLen = data.length - NONCELEN - sigLen - 1; + const [nonce, s2, msg] = headerCoder(0x30 + logn, splitCoder('falcon.signature', NONCELEN, sigLen, msgLen)).decode(data); + return { nonce, s2: decodeSig(s2), msg }; + }, + }; + }; + // [ 1B header ] [ 40B nonce ] [ compressed_sig ] + const SignatureCoderDetached = (logn) => { + const sigLen = opts.padded ? opts.sigLen - 1 - NONCELEN : opts.detachedLen; + const getSigLen = (s2) => (opts.padded ? sigLen : s2.length); + return { + encode({ nonce, s2 }) { + return headerCoder(0x30 + logn, splitCoder('falcon.detachedSignature', NONCELEN, getSigLen(s2))).encode([nonce, opts.padded ? pad(sigLen).encode(s2) : s2]); + }, + decode(data) { + const [nonce, raw] = headerCoder(0x30 + logn, splitCoder('falcon.detachedSignature', NONCELEN, data.length - NONCELEN - 1)).decode(data); + const s2 = decodeSig(raw); + return { nonce, s2 }; + }, + }; + }; + const SignatureCoder = (opts.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn); + // Round-3 Falcon rejects non-invertible f before division; + // otherwise malformed secret keys leak a raw arithmetic error. + // Returns NTT(f) after the nonzero-lane check; + // callers still apply f^{-1} via coefficient-wise division. + const invertF = (f) => { + const tt = intPoly.ntt(signedCoder.decode(f)); + for (let u = 0; u < N; u++) + if (tt[u] === 0) + throw new Error('invalid secretKey: non-invertible f'); + return tt; + }; + function computePublic(f, g) { + const tt = invertF(f); + const h = intPoly.ntt(signedCoder.decode(g)); + // intPoly.div() returns to coefficient form via intt(), so public keys are encoded from the + // canonical polynomial h = g/f and verifyRaw() re-enters the NTT domain later. + const res = intPoly.div(h, tt); // h = g/f + cleanBytes(tt); + return res; + } + // Reconstruct the omitted secret-key limb G as g*F/f mod q, then mirror round-3 Falcon's centered + // reduction and small-coefficient check before using the completed basis for signing. + function completePrivate(f, g, F) { + let t1 = intPoly.toMontgomery(intPoly.ntt(signedCoder.decode(g))); + const t2 = intPoly.ntt(signedCoder.decode(F)); + const tt = invertF(f); + t1 = intPoly.div(intPoly.mul(t1, t2), tt); + const G = new Int8Array(N); + for (let u = 0; u < N; u++) { + let w = t1[u]; + // This mirrors round-3 Falcon's secret-key G reconstruction, not a generic centered reduction + // helper: + // the threshold is floor(q/2), and w = Qhalf maps to -Qhalf - 1 here on purpose. + w -= Q & ~-((w - Qhalf) >>> 31); + const gi = w | 0; + if (gi < -127 || gi > 127) { + cleanBytes(t1, t2, tt, G); + throw new Error('Coefficient out of bounds'); + } + G[u] = gi; + } + cleanBytes(t1, t2, tt); + return G; + } + function HashToPoint(nonce, msg) { + // Algorithm 3: HashToPoint(str, q, n) + // (Page 31) + // Require: A string str, a modulus q ≤ 2¹⁶, a degree n ∈ N* + // Ensure: An polynomial c = Σᵢ cᵢxⁱ in Zq[x] + // 1: k ← ⌈2¹⁶/q⌉ + // 2: ctx ← SHAKE-256-Init() + // 3: SHAKE-256-Inject(ctx, str) + // 4: i ← 0 + // 5: while i < n do + // 6: t ← SHAKE-256-Extract(ctx, 16) + // 7: if t < kq then + // 8: cᵢ ← t mod q + // 9: i ← i + 1 + // 10: return c + const h = shake256.create().update(nonce).update(msg); // 3: SHAKE-256-Inject(ctx, str) + const c = new Uint16Array(N); + // Round-3 Falcon keeps 16-bit draws only in 0..61444, i.e. below 61445 = 5*q, the largest + // 16-bit multiple of q below 2^16; a literal ceil(2^16/q)*q would accept every sample. + const kQ = 5 * Q; + for (let i = 0; i < N;) { + const tmp = h.xof(2); // 6: t ← SHAKE-256-Extract(ctx, 16) + let w = (tmp[0] << 8) | tmp[1]; + if (w < kQ) + c[i++] = w % Q; // 8: cᵢ ← t mod q + } + return c; + } + // This is basically one sampling routine, + // but it carries a lot of internal state and gets complex quickly. + class FFSampler { + logn; + // Shake + shake; + shakeBuf; + ctrView; + // ChaCha + ctr = 0n; + buf; + buf32; + pos; + key; + nonce32; + curBlock; + curBlock32; + view; + // Sampler + b01; + b11; + g00; + g01; + g11; + constructor(logn, seed, b00, b01, b10, b11) { + this.logn = logn; + // Shake + this.shake = shake256.create().update(seed); + this.shakeBuf = new Uint8Array(56); + this.key = this.shakeBuf.subarray(0, 32); + this.nonce32 = u32(this.shakeBuf.subarray(32, 48)); // 4 u32s + this.ctrView = createView(this.shakeBuf.subarray(48, 56)); + // Signle chacha20 instance buffer + this.curBlock = new Uint8Array(64); + this.curBlock32 = u32(this.curBlock); + // whole rng buffer + this.buf = new Uint8Array(8 * this.curBlock.length); + this.buf32 = u32(this.buf); + this.pos = this.buf.length; // not filled yet! + this.view = createView(this.buf); + // Sampler + this.b01 = b01; + this.b11 = b11; + const { g00, g01, g11 } = this.gramFFT(b00, b10); + this.g00 = g00; + this.g01 = g01; + this.g11 = g11; + } + destroy() { + this.shake.destroy(); + cleanBytes(this.shakeBuf, this.curBlock, this.buf); + cleanCPoly(this.b01, this.b11, this.g00, this.g01, this.g11); + } + refill(minBytes) { + if (this.buf.length - this.pos >= minBytes) + return; + const out32 = swap32IfBE(this.buf32); + for (let i = 0; i < 8; i++, this.ctr++) { + const n = swap32IfBE(this.nonce32.slice()); // [n0, n1, n2, n3] + n[2] ^= Number(this.ctr & 0xffffffffn); + n[3] ^= Number(this.ctr >> 32n); + // chacha20() takes raw nonce bytes; on BE the word-normalized temp must be swapped back. + swap32IfBE(n.subarray(1)); + chacha20(this.key, u8(n.subarray(1)), EMPTY_CHACHA20_BLOCK, this.curBlock, n[0]); + // Interleave like Falcon's AVX2 layout (by u32 chunks from 8 parallel chacha20) + const block32 = swap32IfBE(this.curBlock32); + for (let j = 0; j < 16; j++) + out32[i + j * 8] = block32[j]; + swap32IfBE(block32); + } + swap32IfBE(out32); + this.pos = 0; + } + // Sampler + gaussian0() { + // Algorithm 12: BaseSampler() + // (Page 41) + // Require: - + // Ensure: An integer z₀ ∈ {0, ..., 18} such that z ~ χ ▷ χ is uniquely defined by (3.33) + // 1: u ← UniformBits(72) ▷ See (3.32) + // 2: z₀ ← 0 + // 3: for i = 0, ..., 17 do + // 4: z₀ ← z₀ + [u < RCDT[i]] ▷ Note that one should use RCDT, not pdt or cdt + // 5: return z₀ + this.refill(9); + const t0 = this.view.getUint32(this.pos, true); + const t1 = this.view.getUint32(this.pos + 4, true); + const t2 = this.buf[this.pos + 8]; + this.pos += 9; + const v0 = t0 & 0xffffff; + const v1 = ((t0 >>> 24) & 0xff) | ((t1 & 0xffff) << 8); + const v2 = ((t1 >>> 16) & 0xffff) | (t2 << 16); + let z = 0; + for (let i = 0; i < GAUSS0.length; i += 3) { + let cc = (v0 - GAUSS0[i + 2]) >>> 31; + cc = (((v1 - GAUSS0[i + 1]) | 0) - cc) >>> 31; + cc = (((v2 - GAUSS0[i + 0]) | 0) - cc) >>> 31; + z += cc; + } + return z; + } + berExp(x, ccs) { + // Algorithm 14: BerExp(x, ccs) (Page 43) + // Require: Floating point values x, ccs ≥ 0 + // Ensure: A single bit, equal to 1 with probability ≈ ccs · exp(-x) + // 1: s ← ⌊x/ln(2)⌋ + // ▷ Compute the unique decomposition x = s · ln(2) + r, + // with (r, s) ∈ [0, ln 2) × Z⁺ + // 2: r ← x - s · ln(2) + // 3: s ← min(s, 63) + // 4: z ← (2 · ApproxExp(r, ccs) - 1) >> s ▷ z ≈ 2⁶⁴⁻ˢ · ccs · exp(-r) = 2⁶⁴ · ccs · exp(-x) + // 5: i ← 64 + // 6: do + // 7: i ← i - 8 + // 8: w ← UniformBits(8) - ((z >> i) & 0xFF) + // ▷ This loop does not need to be done in constant-time + // 9: while ((w = 0) and (i > 0)) + // 10: return [w < 0] ▷ Return 1 with probability 2⁻⁶⁴ · z ≈ ccs · exp(-x) + let s = Math.trunc(x * 1.4426950408889633870046509401); + const r = x - s * 0.69314718055994530941723212146; + let e = ApproxExp(r, ccs); + e *= 2147483648.0; + let z1 = e | 0; + e = (e - z1) * 4294967296.0; + let z0 = e | 0; + z1 = (z1 << 1) | (z0 >>> 31); + z0 <<= 1; + s = (s | ((63 - s) >>> 26)) & 63; + const sm = -(s >>> 5) | 0; + z0 ^= sm & (z0 ^ z1); + z1 &= ~sm; + s &= 31; + z0 = (z0 >>> s) | ((z1 << (31 - s)) << 1); + z1 >>>= s; + for (let j = 0; j < 2; j++) { + for (let i = 24; i >= 0; i -= 8) { + this.refill(1); + const w = this.buf[this.pos++]; + const bz = (z1 >>> i) & 0xff; + if (w !== bz) + return w < bz; + } + z1 = z0; + } + return false; + } + samplerZ(mu, isigma) { + // Algorithm 15: SamplerZ(μ, σ'), (Page 43) + // Require: Floating-point values μ, σ' ∈ R such that σ' ∈ [σ_{min}, σ_{max}] + // Ensure: An integer z ∈ Z sampled from a distribution very close to DZ,μ,σ' + // 1: r ← μ - ⌊μ⌋ ▷ r must be in [0, 1) + // 2: ccs ← σ_{min}/σ' ▷ ccs helps to make the algorithm running time independent of σ' + // 3: while (1) do + // 4: z₀ ← BaseSampler() + // 5: b ← UniformBits(8) & 0x1 + // 6: z ← b + (2 · b - 1)z₀ + // 7: x ← ((z-r)²)/(2σ'²) + // 8: if (BerExp(x, ccs) = 1) then + // 9: return z + ⌊μ⌋ + const s = Math.floor(mu); + const r = mu - s; + const dss = isigma * isigma * 0.5; + const ccs = isigma * SIGMA_MIN[this.logn]; + for (;;) { + const z0 = this.gaussian0(); + this.refill(1); + const b = this.buf[this.pos++] & 1; + const z = (((z0 << 1) + 1) & -b) - z0; + let x = z - r; + x = x * x * dss - z0 * z0 * 0.1508650488753727203494747755; + if (this.berExp(x, ccs)) + return s + z; + } + } + ldlFFT(logn, g00t, g01t, g11t) { + // Algorithm 8: LDL*(G) + // (Page 37) + // Require: A full-rank self-adjoint matrix G = (Gᵢⱼ) ∈ FFT(Q[x]/(φ))²ˣ² + // Ensure: The LDL* decomposition G = LDL* over FFT(Q[x]/(φ)) + // Format: All polynomials are in FFT representation. + // 1: D₀₀ ← G₀₀ + // 2: L₁₀ ← G₁₀/G₀₀ + // 3: D₁₁ ← G₁₁ - L₁₀ ⊙ L₁₀* ⊙ G₀₀ + // 4: L ← [ 1 0 ; L₁₀ 1 ], D ← [ D₀₀ 0 ; 0 D₁₁ ] + // 5: return (L, D) + // Algorithm 9: ffLDL*(G) + // (Page 37) + // Require: A full-rank Gram matrix G ∈ FFT(Q[x]/(xⁿ + 1))²ˣ² + // Ensure: A binary tree T + // Format: All polynomials are in FFT representation. + // 1: (L, D) ← LDL*(G) ▷ L = [ 1 0 ; L₁₀ 1 ], D = [ D₀₀ 0 ; 0 D₁₁ ] + // 2: T.value ← L₁₀ + // 3: if (n = 2) then + // 4: T.leftchild ← D₀₀ + // 5: T.rightchild ← D₁₁ + // 6: return T + // 7: else + // 8: d₀₀, d₀₁ ← splitfft(D₀₀) ▷ dᵢⱼ ∈ FFT(Q[x]/(x^{n/2} + 1)) + // 9: d₁₀, d₁₁ ← splitfft(D₁₁) + // 10: G₀ ← [ d₀₀ d₀₁ ; d₀₁* d₀₀ ], G₁ ← [ d₁₀ d₁₁ ; d₁₁* d₁₀ ] + // ▷ Since D₀₀, D₁₁ are self-adjoint, (3.30) applies + // 11: T.leftchild ← ffLDL*(G₀) ▷ Recursive calls + // 12: T.rightchild ← ffLDL*(G₁) + // 13: return T + g00t = g00t.slice(); // can be same as g11t and everything will break! + const hn = 1 << (logn - 1); + for (let i = 0; i < hn; i++) { + const g01 = g01t[i]; + const g11 = g11t[i]; + const mu = fComplex.scale(g01, 1.0 / g00t[i].re); + g11t[i] = { re: g11.re - (mu.re * g01.re + mu.im * g01.im), im: g11.im }; + g01t[i] = fComplex.conj(mu); + } + return { g00: g00t, g01: g01t, g11: g11t }; + } + splitFFT(logn, f) { + // Algorithm 1: splitfft(FFT(f)) + // (Page 29) + // Require: FFT(f) = (f(ζ))ζ for some f ∈ Q[x]/(φ) + // Ensure: FFT(f₀) = (f₀(ζ'))ζ' and FFT(f₁) = (f₁(ζ'))ζ' for some f₀, f₁ ∈ Q[x]/(φ') + // Format: All polynomials are in FFT representation. + // 1: for ζ such that φ(ζ) = 0 and Im(ζ) > 0 do ▷ See eq. (3.19) with 0 ≤ k < n/2 + // 2: ζ' ← ζ² + // 3: f₀(ζ') ← ½ [f(ζ) + f(−ζ)] + // 4: f₁(ζ') ← (1/(2ζ)) [f(ζ) − f(−ζ)] + // 5: return (FFT(f₀), FFT(f₁)) + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) + return { f0: [{ re: f[0].re, im: 0.0 }], f1: [{ re: f[0].im, im: 0.0 }] }; + const f0t = new Array(qn); + const f1t = new Array(qn); + const ft = f; + for (let i = 0; i < qn; i++) { + const a = ft[(i << 1) + 0]; + const b = ft[(i << 1) + 1]; + f0t[i] = fComplex.scale(fComplex.add(a, b), 0.5); + f1t[i] = fComplex.scale(fComplex.mul(fComplex.sub(a, b), fComplex.conj(COMPLEX_ROOTS_O[i + hn])), 0.5); + } + return { f0: f0t, f1: f1t }; + } + splitSelfAdjFFT(logn, f) { + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) + return { f0: [{ re: f[0].re, im: 0.0 }], f1: [{ re: 0.0, im: 0.0 }] }; + const f0t = new Array(qn); + const f1t = new Array(qn); + const ft = f; + for (let i = 0; i < qn; i++) { + const a = ft[(i << 1) + 0]; + const b = ft[(i << 1) + 1]; + f0t[i] = fComplex.scale(fComplex.add(a, b), 0.5); + f1t[i] = fComplex.scale(fComplex.scale(fComplex.conj(COMPLEX_ROOTS_O[i + hn]), fComplex.sub(a, b).re), 0.5); + } + return { f0: f0t, f1: f1t }; + } + mergeFFT(logn, f0, f1) { + // Algorithm 2: mergefft(f₀, f₁) + // (Page 29) + // Require: FFT(f₀) = (f₀(ζ'))ζ' and FFT(f₁) = (f₁(ζ'))ζ' for some f₀, f₁ ∈ Q[x]/(φ') + // Ensure: FFT(f) = (f(ζ))ζ for some f ∈ Q[x]/(φ) + // Format: All polynomials are in FFT representation. + // 1: for ζ such that φ(ζ) = 0 do ▷ See eq. (3.19) + // 2: ζ' ← ζ² + // 3: f(ζ) ← f₀(ζ') + ζf₁(ζ') + // 4: return FFT(f) + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) + return [{ re: f0[0].re, im: f1[0].re }]; + const ft = new Array(2 * qn); + for (let i = 0; i < qn; i++) { + const a = f0[i]; + const c = fComplex.mul(f1[i], COMPLEX_ROOTS_O[i + hn]); + ft[(i << 1) + 0] = fComplex.add(a, c); + ft[(i << 1) + 1] = fComplex.sub(a, c); + } + return ft; + } + gramFFT(b00, b10) { + const { b01, b11 } = this; + const hn = (1 << this.logn) >> 1; + const g00 = new Array(hn); + const g01 = new Array(hn); + const g11 = new Array(hn); + for (let i = 0; i < hn; i++) { + const b00t = b00[i]; + const b01t = b01[i]; + const b10t = b10[i]; + const b11t = b11[i]; + const u = fComplex.mul(b00t, fComplex.conj(b10t)); + const v = fComplex.mul(b01t, fComplex.conj(b11t)); + g00[i] = { re: fComplex.magSqSum(b00t, b01t), im: 0.0 }; + g01[i] = fComplex.add(u, v); + g11[i] = { re: fComplex.magSqSum(b10t, b11t), im: 0.0 }; + } + return { g00, g01, g11 }; + } + ffsampRec(logn, t0, t1, g00i, g01i, g11i) { + // Algorithm 11: ffSamplingₙ(t, T) + // (Page 40) + // Require: t = (t₀, t₁) ∈ FFT(Q[x]/(xⁿ + 1))², a FALCON tree T + // Ensure: z = (z₀, z₁) ∈ FFT(Z[x]/(xⁿ + 1))² + // Format: All polynomials are in FFT representation. + // 1: if n = 1 then + // 2: σ' ← T.value ▷ It is always the case that σ' ∈ [σ_{min}, σ_{max}] + // 3: z₀ ← SamplerZ(t₀, σ') ▷ Since n=1, tᵢ = invFFT(tᵢ) ∈ Q and zᵢ = invFFT(zᵢ) ∈ Z + // 4: z₁ ← SamplerZ(t₁, σ') + // 5: return z = (z₀, z₁) + // 6: (l, T₀, T₁) ← (T.value, T.leftchild, T.rightchild) + // 7: t'₁ ← splitfft(t₁) ▷ t₀, t'₁ ∈ FFT(Q[x]/(x^{n/2} + 1))² + // 8: z'₁ ← ffSampling_{n/2}(t'₁, T₁) ▷ First recursive call to ffSampling_{n/2} + // 9: z₁ ← mergefft(z'₁) ▷ z₀, z₁ ∈ FFT(Z[x]/(x^{n/2} + 1))² + // 10: t'₀ ← t₀ + (t₁ - z₁) ⊙ l + // 11: t''₀ ← splitfft(t'₀) + // 12: z'₀ ← ffSampling_{n/2}(t''₀, T₀) ▷ Second recursive call to ffSampling_{n/2} + // 13: z₀ ← mergefft(z'₀) + // 14: return z = (z₀, z₁) + if (logn === 0) { + const leaf = Math.sqrt(g00i[0].re) * INV_SIGMA[this.logn]; + // 3: z₀ ← SamplerZ(t₀, σ') + // ▷ Since n=1, tᵢ = invFFT(tᵢ) ∈ Q and zᵢ = invFFT(zᵢ) ∈ Z + const t0re = this.samplerZ(t0[0].re, leaf); + const t1re = this.samplerZ(t1[0].re, leaf); // 4: z₁ ← SamplerZ(t₁, σ') + return { t0: [{ re: t0re, im: 0.0 }], t1: [{ re: t1re, im: 0.0 }] }; + } + // 6: (l, T₀, T₁) ← (T.value, T.leftchild, T.rightchild) + const { g00, g01, g11 } = this.ldlFFT(logn, g00i, g01i, g11i); + const { f0: g00f0, f1: g00f1 } = this.splitSelfAdjFFT(logn, g00); + const { f0: g11f0, f1: g11f1 } = this.splitSelfAdjFFT(logn, g11); + // 7: t'₁ ← splitfft(t₁) + // ▷ t₀, t'₁ ∈ FFT(Q[x]/(x^{n/2} + 1))² + const { f0: t1f0in, f1: t1f1in } = this.splitFFT(logn, t1); + const { t0: t1f0out, t1: t1f1out } = this.ffsampRec(logn - 1, t1f0in, t1f1in, g11f0, g11f1, g11f0); // 8: z'₁ ← ffSampling_{n/2}(t'₁, T₁) ▷ First recursive call to ffSampling_{n/2} + // 9: z₁ ← mergefft(z'₁) + // ▷ z₀, z₁ ∈ FFT(Z[x]/(x^{n/2} + 1))² + const t1new = this.mergeFFT(logn, t1f0out, t1f1out); + // 10: t'₀ ← t₀ + (t₁ - z₁) ⊙ l + const t0tmp = floatPoly.add(t0, floatPoly.mul(g01, floatPoly.sub(t1, t1new))); + const { f0: t0f0in, f1: t0f1in } = this.splitFFT(logn, t0tmp); // 11: t''₀ ← splitfft(t'₀) + const { t0: t0f0out, t1: t0f1out } = this.ffsampRec(logn - 1, t0f0in, t0f1in, g00f0, g00f1, g00f0); // 12: z'₀ ← ffSampling_{n/2}(t''₀, T₀) ▷ Second recursive call to ffSampling_{n/2} + const z1 = this.mergeFFT(logn, t0f0out, t0f1out); // 13: z₀ ← mergefft(z'₀) + return { t0: z1, t1: t1new }; + } + // sampling a preimage in FFT domain + sample(hm) { + const t0t = floatPoly.FFT(floatPoly.convSmall(hm)); + const t0f = floatPoly.mulConst(floatPoly.mul(t0t, this.b11), F_INV_Q); + const t1f = floatPoly.mulConst(floatPoly.mul(t0t, this.b01), F_MINUS_INV_Q); + // Set seed + this.shake.xofInto(this.shakeBuf); + this.ctr = this.ctrView.getBigUint64(0, true); + // Actual sampling + return this.ffsampRec(this.logn, t0f, t1f, this.g00, this.g01, this.g11); + } + } + const signRaw = (sk, msg, maxLen, rnd = randomBytes) => { + // Algorithm 10: Sign(m, sk, [β²]), (Page 39) + // Require: A message m, a secret key sk, a bound [β²] + // Ensure: A signature sig of m + // 1: r ← {0, 1}³²⁰ uniformly + // 2: c ← HashToPoint(r||m, q, n) + // 3: t ← ( (1/q)FFT(c) ⊙ FFT(F), (1/q)FFT(c) ⊙ FFT(f) ) ▷ t = (FFT(c), FFT(0)) · B̂⁻¹ + // 4: do + // 5: do + // 6: z ← ffSamplingₙ(t, T) + // 7: s = (t - z)B̂ + // ▷ At this point, s follows a Gaussian distribution: + // s ~ D_{(c,0)+Λ(B),σ,0} + // 8: while ||s||² > [β²] + // ▷ Since s is in FFT representation, one may use (3.8) to compute ||s||² + // 9: (s₁, s₂) ← invFFT(s) ▷ s₁ + s₂h = c mod (φ, q) + // 10: s ← Compress(s₂, 8 · sbytelen - 328) + // ▷ Remove 1 byte for the header, and 40 bytes for r + // 11: while (s = ⊥) + // 12: return sig = (r, s) + abytes(msg); + // One RNG stream drives both the public 40-byte nonce and the 48-byte sampler seed, so + // deterministic rnd hooks make signatures deterministic for fixed secretKey/message inputs. + const nonce = rnd(40); + // Keep these raw 40-byte checks in sync with NONCELEN: Falcon's r <- {0,1}^320 nonce + // feeds HashToPoint(r || m) and the public signature framing, so callback bugs must fail fast. + abytes(nonce, 40, 'nonce'); + const hm = HashToPoint(nonce, msg); // 2: c ← HashToPoint(r||m, q, n) + const seed = rnd(48); + // Falcon implementations here use a fixed 48-byte sampler seed; reject callback bugs up front. + abytes(seed, 48, 'seed'); + try { + const [f, g, F] = secretKeyCoder.decode(sk); + try { + const G = completePrivate(f, g, F); + const b00 = floatPoly.FFT(floatPoly.convSmall(g)); + const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f))); + const b10 = floatPoly.FFT(floatPoly.convSmall(G)); + const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F))); + const sampler = new FFSampler(logn, seed, b00, b01, b10, b11); + const s2 = new Int16Array(N); + try { + while (true) { + const { t0, t1 } = sampler.sample(hm); + // t2 = b00*t0 + b10*t1 + const t2 = floatPoly.add(floatPoly.mul(t0, b00), floatPoly.mul(t1, b10)); + const t3 = floatPoly.mul(t0, b01); // t3 = b01*t0 + const t4 = floatPoly.iFFT(t2); // t4 = iFFT(tx) + // t5 = iFFT(b11*t1 + ty) + const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3)); + // Traverse imaginary in exact same order to avoid numerical instability + const hn = N >> 1; + let sqn = 0; + for (let i = 0; i < hn; i++) { + sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2; + sqn += (hm[hn + i] - (Math.round(t4[i].im) | 0)) ** 2; + const z = -Math.round(t5[i].re); + sqn += z * z; + s2[i] = z & 0xffff; + const z2 = -Math.round(t5[i].im); + sqn += z2 * z2; + s2[i + hn] = z2 & 0xffff; + } + cleanCPoly(t0, t1, t2, t3, t4, t5); + if (!(sqn <= L2BOUND[logn])) + continue; + // 10: s ← Compress(s₂, 8 · sbytelen - 328) + // ▷ Remove 1 byte for the header, and 40 bytes for r + const s2comp = compCoder(N).encode(s2); + if (s2comp.length > maxLen) { + cleanBytes(s2comp); + continue; + } + return { s2: s2comp, nonce, msg }; + } + } + finally { + cleanBytes(s2); + sampler.destroy(); + cleanCPoly(b00, b01, b10, b11); + cleanBytes(G); + } + } + finally { + cleanBytes(f, g, F); + } + } + finally { + cleanBytes(seed); + } + }; + // Raw helper: malformed encodings or wrong lengths still throw here; the public verify()/open() + // wrappers decide whether to translate those failures into false or an exception. + const verifyRaw = (pk, s2comp, nonce, msg) => { + // Algorithm 16: Verify(m, sig, pk, [β²]) + // (Page 45) + // Require: A message m, a signature sig = (r, s), a public key pk = h ∈ Zq[x]/(φ), a bound [β²] + // Ensure: Accept or reject + // 1: c ← HashToPoint(r||m, q, n) + // 2: s₂ ← Decompress(s, 8 · sbytelen - 328) + // 3: if (s₂ = ⊥) then + // 4: reject ▷ Reject invalid encodings + // 5: s₁ ← c - s₂h mod q ▷ s₁ should be normalized between -q/2 and q/2 + // 6: if ||(s₁, s₂)||² < [β²] then + // 7: accept + // 8: else + // 9: reject ▷ Reject signatures that are too long + const s2 = compCoder(N).decode(s2comp); // 2: s₂ ← Decompress(s, 8 · sbytelen - 328) + const c0 = HashToPoint(nonce, msg); // 1: c ← HashToPoint(r||m, q, n) + const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk))); + const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h)); + intPoly.sub(s1, c0); // 5: s₁ ← c - s₂h mod q ▷ s₁ should be normalized between -q/2 and q/2 + return intPoly.isShort(signedCoder.encode(s1), s2); // 6: if ||(s₁, s₂)||² < [β²] then + }; + const info = Object.freeze({ type: 'falcon' }); + const keyLengths = Object.freeze({ + seed: 48, + publicKey: publicKeyCoder.bytesLen, + secretKey: secretKeyCoder.bytesLen, + }); + // Noble exposes a 48-byte sampler-seed hook, + // but Falcon still samples/encodes a separate 40-byte nonce per signature. + const getRnd = (opts = {}) => { + validateSigOpts(opts); + if (opts.context !== undefined) + throw new Error('context is not supported'); + if (opts.random !== undefined) + return opts.random; + if (opts.extraEntropy === undefined) + return randomBytes; + const seed = opts.extraEntropy === false ? new Uint8Array(48) : opts.extraEntropy; + abytes(seed, 48, 'opts.extraEntropy'); + const drbg = rngAesCtrDrbg256(seed); + return (len = 0) => drbg.randomBytes(len); + }; + const checkVerOpts = (opts = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) + throw new Error('context is not supported'); + }; + const tests = Object.freeze({ + publicKeyCoder: Object.freeze(publicKeyCoder), + privateKeyCoder: Object.freeze(secretKeyCoder), + maxS2Len: opts.maxS2Len, + }); + // `signRand` documents only the sampler-seed input length; + // detached/attached signatures still include their own 40-byte nonce. + const attachedLengths = Object.freeze({ ...keyLengths, signRand: 48 }); + const lengths = opts.padded + ? Object.freeze({ ...attachedLengths, signature: opts.sigLen }) + : attachedLengths; + const keygen = (seed) => { + const randSeed = seed === undefined; + if (randSeed) + seed = randomBytes(48); + abytes(seed, 48, 'seed'); + const [f, g, F, _G, pub] = new NTRU(logn, seed).generate(); + const sk = secretKeyCoder.encode([f, g, F]); + const pk = publicKeyCoder.encode(pub); + if (randSeed) + cleanBytes(seed); + cleanBytes(f, g, F, _G); + return { publicKey: pk, secretKey: sk }; + }; + const getPublicKey = (sk) => { + const [f, g, F] = secretKeyCoder.decode(sk); + try { + const h = computePublic(f, g); + cleanBytes(f, g, F); + return publicKeyCoder.encode(h); + } + catch (e) { + cleanBytes(f, g, F); + throw e; + } + }; + const sign = (msg, sk, sigOpts = {}) => { + const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts)); + return SignatureCoderDetached(logn).encode({ nonce, s2 }); + }; + /** Verify one detached Falcon signature. + * Returns `false` for malformed detached signature encodings, non-canonical detached signatures, + * and well-formed signatures that do not validate. Throws on malformed API argument types or + * unsupported verification options. + */ + const verify = (sig, msg, pk, verOpts = {}) => { + checkVerOpts(verOpts); + abytes(sig); + abytes(msg); + abytes(pk); + try { + const { s2, nonce } = SignatureCoderDetached(logn).decode(sig); + return verifyRaw(pk, s2, nonce, msg); + } + catch { + return false; + } + }; + const attached = Object.freeze({ + info, + lengths: attachedLengths, + keygen, + getPublicKey, + seal(msg, sk, sigOpts = {}) { + const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts)); + return SignatureCoder.encode({ msg, nonce, s2 }); + }, + open(sig, pk, verOpts = {}) { + checkVerOpts(verOpts); + const { s2, nonce, msg } = SignatureCoder.decode(sig); + // Zero-copy API: returned message aliases the caller-provided signature buffer. + // Copy it if ownership is needed. + if (verifyRaw(pk, s2, nonce, msg)) + return msg; + throw new Error('invalid signature'); + }, + }); + const res = { + info, + lengths, + attached, + keygen, + getPublicKey, + sign, + verify, + }; + res.__test = tests; + return Object.freeze(res); +} +const falcon512opts = { + N: 512, + // Table 3.3 fixed padded detached bytes, including the detached header byte and 40-byte nonce. + sigLen: 666, + fgBits: 6, + FGBits: 8, + // Compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + paddedLen: 625, + // Payload-only budget: genFalcon() adds the detached header byte and 40-byte nonce around it. + detachedLen: 690, +}; +/** + * Falcon-512 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512.sign(msg, secretKey); + * falcon512.verify(sig, msg, publicKey); + * ``` + */ +export const falcon512 = /* @__PURE__ */ (() => genFalcon({ ...falcon512opts, maxS2Len: 711 }))(); +/** + * Falcon-512 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512padded.sign(msg, secretKey); + * falcon512padded.verify(sig, msg, publicKey); + * ``` + */ +export const falcon512padded = /* @__PURE__ */ (() => genFalcon({ + ...falcon512opts, + padded: true, + maxS2Len: 625, +}))(); +const falcon1024opts = { + N: 1024, + // Table 3.3 fixed padded detached bytes, including the detached header byte and 40-byte nonce. + sigLen: 1280, + fgBits: 5, + FGBits: 8, + // Compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + paddedLen: 1239, + // Payload-only budget: genFalcon() adds the detached header byte and 40-byte nonce around it. + detachedLen: 1280, +}; +/** + * Falcon-1024 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024.sign(msg, secretKey); + * falcon1024.verify(sig, msg, publicKey); + * ``` + */ +export const falcon1024 = /* @__PURE__ */ (() => genFalcon({ + ...falcon1024opts, + maxS2Len: 1421, +}))(); +/** + * Falcon-1024 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024padded.sign(msg, secretKey); + * falcon1024padded.verify(sig, msg, publicKey); + * ``` + */ +export const falcon1024padded = /* @__PURE__ */ (() => genFalcon({ + ...falcon1024opts, + padded: true, + maxS2Len: 1239, +}))(); +// NOTE: for tests only, don't use +export const __tests = /* @__PURE__ */ (() => Object.freeze({ + BNORM_MAX, + COMPLEX_ROOTS, + Float, + INV_SIGMA, + SIGMA_MIN, + getFloatPoly, + cleanCPoly, + falcon512: falcon512.__test, + falcon512padded: falcon512padded.__test, + falcon1024: falcon1024.__test, + falcon1024padded: falcon1024padded.__test, +}))(); +//# sourceMappingURL=falcon.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/falcon.js.map b/node_modules/@noble/post-quantum/falcon.js.map new file mode 100644 index 0000000..6993dac --- /dev/null +++ b/node_modules/@noble/post-quantum/falcon.js.map @@ -0,0 +1 @@ +{"version":3,"file":"falcon.js","sourceRoot":"","sources":["src/falcon.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,4EAA4E;AAC5E,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AACzD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,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F;IAC/F,MAAM,EAAE,IAAI;IACZ,MAAM,EAAE,CAAC;IACT,MAAM,EAAE,CAAC;IACT,yFAAyF;IACzF,SAAS,EAAE,IAAI;IACf,8FAA8F;IAC9F,WAAW,EAAE,IAAI;CAClB,CAAC;AACF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,UAAU,GAAiB,eAAe,CAAC,CAAC,GAAG,EAAE,CAC5D,SAAS,CAAC;IACR,GAAG,cAAc;IACjB,QAAQ,EAAE,IAAI;CACf,CAAC,CAAC,EAAE,CAAC;AACR;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAiB,eAAe,CAAC,CAAC,GAAG,EAAE,CAClE,SAAS,CAAC;IACR,GAAG,cAAc;IACjB,MAAM,EAAE,IAAI;IACZ,QAAQ,EAAE,IAAI;CACf,CAAC,CAAC,EAAE,CAAC;AAER,kCAAkC;AAClC,MAAM,CAAC,MAAM,OAAO,GAAQ,eAAe,CAAC,CAAC,GAAG,EAAE,CAChD,MAAM,CAAC,MAAM,CAAC;IACZ,SAAS;IACT,aAAa;IACb,KAAK;IACL,SAAS;IACT,SAAS;IACT,YAAY;IACZ,UAAU;IACV,SAAS,EAAG,SAAiB,CAAC,MAAM;IACpC,eAAe,EAAG,eAAuB,CAAC,MAAM;IAChD,UAAU,EAAG,UAAkB,CAAC,MAAM;IACtC,gBAAgB,EAAG,gBAAwB,CAAC,MAAM;CACnD,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/hybrid.d.ts b/node_modules/@noble/post-quantum/hybrid.d.ts new file mode 100644 index 0000000..ed03609 --- /dev/null +++ b/node_modules/@noble/post-quantum/hybrid.d.ts @@ -0,0 +1,281 @@ +/** + * Post-Quantum Hybrid Cryptography + * + * The current implementation is flawed and likely redundant. We should offer + * a small, generic API to compose hybrid schemes instead of reimplementing + * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings. + * + * 1. Core Issues + * - sign/verify: implemented as two separate operations with different keys. + * - EC getSharedSecret: could be refactored into a proper KEM. + * - Multiple calls: keys, signatures, and shared secrets could be + * concatenated to reduce the number of API invocations. + * - Reinvention: most libraries add strange domain separations and + * encodings instead of simple byte concatenation. + * + * 2. API Goals + * - Provide primitives to build hybrids generically. + * - Avoid embedding SSH- or GPG-specific formats in the core API. + * + * 3. Edge Cases + * • Variable-length signatures: + * - DER-encoded (Weierstrass curves). + * - Falcon (unpadded). + * - Concatenation works only if length is fixed; otherwise a length + * prefix is required (but that breaks compatibility). + * + * • getSharedSecret: + * - Default: non-KEM (authenticated ECDH). + * - KEM conversion: generate a random SK to remove implicit auth. + * + * 4. Common Pitfalls + * - Seed expansion: + * • Expanding a small seed into multiple keys reduces entropy. + * • API should allow identity mapping (no expansion). + * + * - Skipping full point encoding: + * • Some omit the compression byte (parity) for WebCrypto compatibility. + * • Better: hash the raw secret; coordinate output is already non-uniform. + * • Some curves (e.g., X448) produce secrets that must be re-hashed to match + * symmetric-key lengths. + * + * - Combiner inconsistencies: + * • Different domain separations and encodings across libraries. + * • Should live at the application layer, since key lengths vary. + * + * 5. Protocol Examples + * - SSH: + * • Concatenate keys. + * • Combiner: SHA-512. + * + * - GPG: + * • Concatenate keys. + * • Combiner: + * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep)) + * + * - TLS: + * • Transcript-based derivation (HKDF). + * + * 6. Relevant Specs & Implementations + * - IETF Hybrid KEM drafts: + * • draft-irtf-cfrg-hybrid-kems + * • draft-connolly-cfrg-xwing-kem + * • draft-westerbaan-tls-xyber768d00 + * + * - PQC Libraries: + * • superdilithium (cyph/pqcrypto.js) – low adoption. + * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings. + * + * 7. Signatures + * - Ed25519: fixed-size, easy to support. + * - Variable-size: introduces custom format requirements; best left to + * higher-level code. + * + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { type EdDSA } from '@noble/curves/abstract/edwards.js'; +import { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js'; +import { type ECDSA } from '@noble/curves/abstract/weierstrass.js'; +import { type CHash, type CHashXOF } from '@noble/hashes/utils.js'; +import { type KEM, type Signer, type TArg, type TRet } from './utils.ts'; +type CurveECDH = ECDSA | MontgomeryECDH; +type CurveSign = ECDSA | EdDSA; +/** + * Wraps an ECDH-capable curve as a KEM. + * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF. + * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the + * 1-byte `0x02` / `0x03` prefix. + * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers. + * @param curve - Curve with `getSharedSecret`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns KEM wrapper over the curve. + * @throws If the curve does not expose `getSharedSecret`. {@link Error} + * @example + * Wrap an ECDH-capable curve as a generic KEM. + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * import { ecdhKem } from '@noble/post-quantum/hybrid.js'; + * const kem = ecdhKem(x25519); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export declare function ecdhKem(curve: CurveECDH, allowZeroKey?: boolean): TRet; +/** + * Wraps a curve signer as a generic `Signer`. + * Signatures stay in the wrapped curve's native byte encoding. + * This wrapper does not normalize or document which per-curve signing options are meaningful. + * @param curve - Curve with `sign` and `verify`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns Signer wrapper over the curve. + * @throws If the curve does not expose `sign` and `verify`. {@link Error} + * @example + * Wrap a curve signer as a generic signer. + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { ecSigner } from '@noble/post-quantum/hybrid.js'; + * const signer = ecSigner(ed25519); + * const sigLen = signer.lengths.signature; + * ``` + */ +export declare function ecSigner(curve: CurveSign, allowZeroKey?: boolean): TRet; +/** Seed-expansion callback used by the hybrid combiners. */ +export type ExpandSeed = (seed: TArg, len: number) => TRet; +type XOF = CHashXOF; +/** + * Adapts an XOF into an `ExpandSeed` callback. + * The returned callback interprets its second argument as an output byte length passed as `dkLen`. + * @param xof - Extendable-output hash function. + * @returns Seed expander using `dkLen`. + * @example + * Adapt an XOF into a seed expander. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * const expandSeed = expandSeedXof(shake256); + * const seed = expandSeed(new Uint8Array([1]), 4); + * ``` + */ +export declare function expandSeedXof(xof: TArg): TRet; +/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */ +export type Combiner = (publicKeys: TArg, cipherTexts: TArg, sharedSecrets: TArg) => TRet; +/** + * Combines multiple KEMs into one composite KEM. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param realMsgLen - Shared-secret length returned by `combiner`. + * @param expandSeed - Seed expander used to derive per-KEM seeds. + * @param combiner - Combines the per-KEM outputs into one shared secret. + * @param kems - KEM implementations to combine. + * @returns Composite KEM. + * @example + * Combine multiple KEMs into one composite KEM. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const hybrid = combineKEMS( + * 32, + * 32, + * expandSeedXof(shake256), + * (_pk, _ct, sharedSecrets) => sharedSecrets[0], + * ml_kem768, + * ml_kem768 + * ); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export declare function combineKEMS(realSeedLen: number | undefined, // how much bytes expandSeed expects +realMsgLen: number | undefined, // how much bytes combiner returns +expandSeed: TArg, combiner: TArg, ...kems: TArg): TRet; +/** + * Combines multiple signers into one composite signer. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param expandSeed - Seed expander used to derive per-signer seeds. + * @param signers - Signers to combine. + * @returns Composite signer. + * @example + * Combine multiple signers into one composite signer. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js'; + * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export declare function combineSigners(realSeedLen: number | undefined, expandSeed: TArg, ...signers: TArg): TRet; +/** + * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte + * SHA3-256 output, while custom `kdf` choices inherit their own digest size. + * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full + * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15). + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param kdf - Hash used for the final combiner. + * @returns Hybrid KEM. + * @example + * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * ```ts + * import { p256 } from '@noble/curves/nist.js'; + * import { sha3_256, shake256 } from '@noble/hashes/sha3.js'; + * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export declare function QSF(label: string, pqc: TArg, curveKEM: TArg, xof: TArg, kdf: CHash): TRet; +/** QSF preset combining ML-KEM-768 with P-256. */ +export declare const QSF_ml_kem768_p256: TRet; +/** QSF preset combining ML-KEM-1024 with P-384. */ +export declare const QSF_ml_kem1024_p384: TRet; +/** + * Builds the "KitchenSink" hybrid KEM combiner. + * The current builder always derives a fixed 32-byte output, + * regardless of the hash's native output size. + * Its HKDF extract step uses implicit zero salt with IKM + * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`. + * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`. + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param hash - Hash used for HKDF extraction and expansion. + * @returns Hybrid KEM. + * @example + * Build the "KitchenSink" hybrid KEM combiner. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * import { x25519 } from '@noble/curves/ed25519.js'; + * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export declare function createKitchenSink(label: string, pqc: TArg, curveKEM: TArg, xof: TArg, hash: CHash): TRet; +/** KitchenSink preset combining ML-KEM-768 with X25519. + * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed. + */ +export declare const KitchenSink_ml_kem768_x25519: TRet; +/** X25519 + ML-KEM-768 hybrid preset. + * Uses the hard-coded domain-separation label `\\.//^\\` and hashes only `ct1 || pk1` + * from the X25519 side in addition to the two component shared secrets. + */ +export declare const ml_kem768_x25519: TRet; +/** P-256 + ML-KEM-768 hybrid preset. */ +export declare const ml_kem768_p256: TRet; +/** P-384 + ML-KEM-1024 hybrid preset. */ +export declare const ml_kem1024_p384: TRet; +/** Legacy alias for `ml_kem768_x25519`. */ +export declare const XWing: TRet; +/** Legacy alias for `ml_kem768_x25519`. */ +export declare const MLKEM768X25519: TRet; +/** Legacy alias for `ml_kem768_p256`. */ +export declare const MLKEM768P256: TRet; +/** Legacy alias for `ml_kem1024_p384`. */ +export declare const MLKEM1024P384: TRet; +/** Legacy alias for `QSF_ml_kem768_p256`. */ +export declare const QSFMLKEM768P256: TRet; +/** Legacy alias for `QSF_ml_kem1024_p384`. */ +export declare const QSFMLKEM1024P384: TRet; +/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */ +export declare const KitchenSinkMLKEM768X25519: TRet; +export {}; +//# sourceMappingURL=hybrid.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/hybrid.d.ts.map b/node_modules/@noble/post-quantum/hybrid.d.ts.map new file mode 100644 index 0000000..7394c21 --- /dev/null +++ b/node_modules/@noble/post-quantum/hybrid.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"hybrid.d.ts","sourceRoot":"","sources":["src/hybrid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AACH,4EAA4E;AAC5E,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,uCAAuC,CAAC;AAanE,OAAO,EAA0B,KAAK,KAAK,EAAE,KAAK,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAE3F,OAAO,EAQL,KAAK,GAAG,EACR,KAAK,MAAM,EACX,KAAK,IAAI,EACT,KAAK,IAAI,EACV,MAAM,YAAY,CAAC;AAGpB,KAAK,SAAS,GAAG,KAAK,GAAG,cAAc,CAAC;AACxC,KAAK,SAAS,G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G,CACwB,CAAC;AAG/D,2CAA2C;AAC3C,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,GAAG,CAA8C,CAAC;AAC3E,2CAA2C;AAC3C,eAAO,MAAM,cAAc,EAAE,IAAI,CAAC,GAAG,CAA8C,CAAC;AACpF,yCAAyC;AACzC,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,GAAG,CAA4C,CAAC;AAChF,0CAA0C;AAC1C,eAAO,MAAM,aAAa,EAAE,IAAI,CAAC,GAAG,CAA6C,CAAC;AAClF,6CAA6C;AAC7C,eAAO,MAAM,eAAe,EAAE,IAAI,CAAC,GAAG,CAAgD,CAAC;AACvF,8CAA8C;AAC9C,eAAO,MAAM,gBAAgB,EAAE,IAAI,CAAC,GAAG,CAAiD,CAAC;AACzF,uDAAuD;AACvD,eAAO,MAAM,yBAAyB,EAAE,IAAI,CAAC,GAAG,CACf,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/hybrid.js b/node_modules/@noble/post-quantum/hybrid.js new file mode 100644 index 0000000..9c76a8f --- /dev/null +++ b/node_modules/@noble/post-quantum/hybrid.js @@ -0,0 +1,678 @@ +/** + * Post-Quantum Hybrid Cryptography + * + * The current implementation is flawed and likely redundant. We should offer + * a small, generic API to compose hybrid schemes instead of reimplementing + * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings. + * + * 1. Core Issues + * - sign/verify: implemented as two separate operations with different keys. + * - EC getSharedSecret: could be refactored into a proper KEM. + * - Multiple calls: keys, signatures, and shared secrets could be + * concatenated to reduce the number of API invocations. + * - Reinvention: most libraries add strange domain separations and + * encodings instead of simple byte concatenation. + * + * 2. API Goals + * - Provide primitives to build hybrids generically. + * - Avoid embedding SSH- or GPG-specific formats in the core API. + * + * 3. Edge Cases + * • Variable-length signatures: + * - DER-encoded (Weierstrass curves). + * - Falcon (unpadded). + * - Concatenation works only if length is fixed; otherwise a length + * prefix is required (but that breaks compatibility). + * + * • getSharedSecret: + * - Default: non-KEM (authenticated ECDH). + * - KEM conversion: generate a random SK to remove implicit auth. + * + * 4. Common Pitfalls + * - Seed expansion: + * • Expanding a small seed into multiple keys reduces entropy. + * • API should allow identity mapping (no expansion). + * + * - Skipping full point encoding: + * • Some omit the compression byte (parity) for WebCrypto compatibility. + * • Better: hash the raw secret; coordinate output is already non-uniform. + * • Some curves (e.g., X448) produce secrets that must be re-hashed to match + * symmetric-key lengths. + * + * - Combiner inconsistencies: + * • Different domain separations and encodings across libraries. + * • Should live at the application layer, since key lengths vary. + * + * 5. Protocol Examples + * - SSH: + * • Concatenate keys. + * • Combiner: SHA-512. + * + * - GPG: + * • Concatenate keys. + * • Combiner: + * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep)) + * + * - TLS: + * • Transcript-based derivation (HKDF). + * + * 6. Relevant Specs & Implementations + * - IETF Hybrid KEM drafts: + * • draft-irtf-cfrg-hybrid-kems + * • draft-connolly-cfrg-xwing-kem + * • draft-westerbaan-tls-xyber768d00 + * + * - PQC Libraries: + * • superdilithium (cyph/pqcrypto.js) – low adoption. + * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings. + * + * 7. Signatures + * - Ed25519: fixed-size, easy to support. + * - Variable-size: introduces custom format requirements; best left to + * higher-level code. + * + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import {} from '@noble/curves/abstract/edwards.js'; +import {} from '@noble/curves/abstract/montgomery.js'; +import {} from '@noble/curves/abstract/weierstrass.js'; +import { x25519 } from '@noble/curves/ed25519.js'; +import { p256, p384 } from '@noble/curves/nist.js'; +import { asciiToBytes, bytesToNumberBE, bytesToNumberLE, concatBytes, numberToBytesBE, } from '@noble/curves/utils.js'; +import { expand, extract } from '@noble/hashes/hkdf.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { sha3_256, shake256 } from '@noble/hashes/sha3.js'; +import { abytes, ahash, anumber } from '@noble/hashes/utils.js'; +import { ml_kem1024, ml_kem768 } from "./ml-kem.js"; +import { cleanBytes, copyBytes, randomBytes, splitCoder, validateSigOpts, validateVerOpts, } from "./utils.js"; +// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly +function ecKeygen(curve, allowZeroKey = false) { + const lengths = curve.lengths; + let keygen = curve.keygen; + if (allowZeroKey) { + // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are + // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on + // those curves would change key construction instead of just relaxing scalar range handling. + if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve)) + throw new Error('allowZeroKey requires a Weierstrass curve'); + // This legacy flag is really "skip the +1 shift" for vector matching, not "accept scalar 0". + // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into + // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid. + // This is ugly, but we need to return exact results here. + const wCurve = curve; + const Fn = wCurve.Point.Fn; + // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1. + // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to + // scalar 0 here and getPublicKey(secretKey) throws instead of "allowing zero". + keygen = (seed = randomBytes(lengths.seed)) => { + abytes(seed, lengths.seed, 'seed'); + const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed); + // Reduce directly into [0, ORDER); scalar 0 still stays invalid. + const secretKey = Fn.toBytes(Fn.create(seedScalar)); + return { + secretKey: secretKey, + publicKey: curve.getPublicKey(secretKey), + }; + }; + } + return { + lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed }, + keygen: (seed) => keygen(seed), + getPublicKey: (secretKey) => curve.getPublicKey(secretKey), + }; +} +/** + * Wraps an ECDH-capable curve as a KEM. + * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF. + * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the + * 1-byte `0x02` / `0x03` prefix. + * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers. + * @param curve - Curve with `getSharedSecret`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns KEM wrapper over the curve. + * @throws If the curve does not expose `getSharedSecret`. {@link Error} + * @example + * Wrap an ECDH-capable curve as a generic KEM. + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * import { ecdhKem } from '@noble/post-quantum/hybrid.js'; + * const kem = ecdhKem(x25519); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function ecdhKem(curve, allowZeroKey = false) { + const kg = ecKeygen(curve, allowZeroKey); + if (!curve.getSharedSecret) + throw new Error('wrong curve'); // ed25519 doesn't have one! + return { + lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey }, + keygen: kg.keygen, + getPublicKey: kg.getPublicKey, + encapsulate(publicKey, rand = randomBytes(curve.lengths.seed)) { + // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller + // randomness first so cleanBytes() only wipes wrapper-owned material. + const seed = copyBytes(rand); + let ek = undefined; + try { + ek = this.keygen(seed).secretKey; + const sharedSecret = this.decapsulate(publicKey, ek); + const cipherText = curve.getPublicKey(ek); + return { sharedSecret, cipherText }; + } + finally { + // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and + // derived ephemeral secret key even when encapsulation aborts before returning. + cleanBytes(seed); + if (ek) + cleanBytes(ek); + } + }, + decapsulate(cipherText, secretKey) { + const res = curve.getSharedSecret(secretKey, cipherText); + return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res); + }, + }; +} +/** + * Wraps a curve signer as a generic `Signer`. + * Signatures stay in the wrapped curve's native byte encoding. + * This wrapper does not normalize or document which per-curve signing options are meaningful. + * @param curve - Curve with `sign` and `verify`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns Signer wrapper over the curve. + * @throws If the curve does not expose `sign` and `verify`. {@link Error} + * @example + * Wrap a curve signer as a generic signer. + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { ecSigner } from '@noble/post-quantum/hybrid.js'; + * const signer = ecSigner(ed25519); + * const sigLen = signer.lengths.signature; + * ``` + */ +export function ecSigner(curve, allowZeroKey = false) { + const kg = ecKeygen(curve, allowZeroKey); + if (!curve.sign || !curve.verify) + throw new Error('wrong curve'); // ed25519 doesn't have one! + return { + lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 }, + keygen: kg.keygen, + getPublicKey: kg.getPublicKey, + sign: (message, secretKey, opts = {}) => { + validateSigOpts(opts); + // This generic wrapper intentionally keeps the Signer contract to message + key only. + // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded + // uniformly through combineSigners(), so callers that need them must use the curve directly. + if (opts.extraEntropy !== undefined) + throw new Error('ecSigner does not support extraEntropy; use the underlying curve directly'); + if (opts.context !== undefined) + throw new Error('ecSigner does not support context; use the underlying curve directly'); + return curve.sign(message, secretKey); + }, + /** Verify one wrapped curve signature. + * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported + * generic opts and lets wrapped-curve malformed-input errors escape unchanged. + */ + verify: (signature, message, publicKey, opts = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) + throw new Error('ecSigner does not support context; use the underlying curve directly'); + return curve.verify(signature, message, publicKey); + }, + }; +} +function splitLengths(lst, name) { + // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views. + return splitCoder(name, ...lst.map((i) => { + if (typeof i.lengths[name] !== 'number') + throw new Error('wrong length: ' + name); + return i.lengths[name]; + })); +} +// It is XOF for most cases, but can be more complex! +/** + * Adapts an XOF into an `ExpandSeed` callback. + * The returned callback interprets its second argument as an output byte length passed as `dkLen`. + * @param xof - Extendable-output hash function. + * @returns Seed expander using `dkLen`. + * @example + * Adapt an XOF into a seed expander. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * const expandSeed = expandSeedXof(shake256); + * const seed = expandSeed(new Uint8Array([1]), 4); + * ``` + */ +export function expandSeedXof(xof) { + // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this + // adapter only translates the requested byte length into the hash API's `dkLen` option. + return ((seed, seedLen) => xof(seed, { dkLen: seedLen })); +} +function combineKeys(realSeedLen, // how much bytes expandSeed expects +expandSeed_, ...ck_) { + const expandSeed = expandSeed_; + const ck = ck_; + const seedCoder = splitLengths(ck, 'seed'); + const pkCoder = splitLengths(ck, 'publicKey'); + // Allows to use identity functions for combiner/expandSeed + if (realSeedLen === undefined) + realSeedLen = seedCoder.bytesLen; + anumber(realSeedLen); + function expandDecapsulationKey(seed) { + abytes(seed, realSeedLen); + const expandedRaw = expandSeed(seed, seedCoder.bytesLen); + // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so + // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes. + const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw; + const expanded = []; + const keySecret = []; + const secretKey = []; + const publicKey = []; + let ok = false; + try { + // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child + // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any + // later cleanup wipes the shared backing bytes. + for (const part of seedCoder.decode(expandedSeed)) + expanded.push(copyBytes(part)); + for (let i = 0; i < ck.length; i++) { + const keys = ck[i].keygen(expanded[i]); + keySecret.push(keys.secretKey); + secretKey.push(copyBytes(keys.secretKey)); + publicKey.push(keys.publicKey); + } + ok = true; + return { secretKey, publicKey }; + } + finally { + // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep + // the exported copies on success, but wipe all temporary and partially built secret material + // on either path so failures do not strand derived child seeds in memory. + cleanBytes(expandedSeed, expanded, keySecret); + if (!ok) + cleanBytes(secretKey); + } + } + return { + info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } }, + getPublicKey(secretKey) { + // Composite secret keys are root seeds, so public-key derivation reruns key expansion from + // that seed instead of decoding a packed child-secret-key structure. + return this.keygen(secretKey).publicKey; + }, + keygen(seed = randomBytes(realSeedLen)) { + const { publicKey: pk, secretKey } = expandDecapsulationKey(seed); + try { + const publicKey = pkCoder.encode(pk); + return { secretKey: seed, publicKey }; + } + finally { + cleanBytes(pk); + // The exported secretKey is the caller/root seed itself; child secret keys are internal + // expansion outputs that are cleaned whether encoding succeeds or throws. + cleanBytes(secretKey); + } + }, + expandDecapsulationKey, + realSeedLen, + }; +} +// This generic function that combines multiple KEMs into single one +/** + * Combines multiple KEMs into one composite KEM. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param realMsgLen - Shared-secret length returned by `combiner`. + * @param expandSeed - Seed expander used to derive per-KEM seeds. + * @param combiner - Combines the per-KEM outputs into one shared secret. + * @param kems - KEM implementations to combine. + * @returns Composite KEM. + * @example + * Combine multiple KEMs into one composite KEM. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const hybrid = combineKEMS( + * 32, + * 32, + * expandSeedXof(shake256), + * (_pk, _ct, sharedSecrets) => sharedSecrets[0], + * ml_kem768, + * ml_kem768 + * ); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export function combineKEMS(realSeedLen, // how much bytes expandSeed expects +realMsgLen, // how much bytes combiner returns +expandSeed, combiner, ...kems) { + const rawCombiner = combiner; + const rawKems = kems; + const keys = combineKeys(realSeedLen, expandSeed, ...rawKems); + const ctCoder = splitLengths(rawKems, 'cipherText'); + const pkCoder = splitLengths(rawKems, 'publicKey'); + const msgCoder = splitLengths(rawKems, 'msg'); + if (realMsgLen === undefined) + realMsgLen = msgCoder.bytesLen; + anumber(realMsgLen); + const lengths = Object.freeze({ + ...keys.info.lengths, + msg: realMsgLen, + msgRand: msgCoder.bytesLen, + cipherText: ctCoder.bytesLen, + }); + return Object.freeze({ + lengths, + getPublicKey: keys.getPublicKey, + keygen: keys.keygen, + encapsulate(pk, randomness = randomBytes(msgCoder.bytesLen)) { + const pks = pkCoder.decode(pk); + const rand = msgCoder.decode(randomness); + const sharedSecret = []; + const cipherText = []; + try { + for (let i = 0; i < rawKems.length; i++) { + const enc = rawKems[i].encapsulate(pks[i], rand[i]); + sharedSecret.push(enc.sharedSecret); + cipherText.push(enc.cipherText); + } + return { + // Detach the combiner result before cleanup: a caller-provided combiner may alias one of + // the child sharedSecret buffers, and those child buffers are zeroized immediately below. + sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)), + cipherText: ctCoder.encode(cipherText), + }; + } + finally { + // Child encapsulation or combiner failures can happen after some components already + // returned secret material; zeroize whatever was produced before propagating the error. + cleanBytes(sharedSecret, cipherText); + } + }, + decapsulate(ct, seed) { + const cts = ctCoder.decode(ct); + const { publicKey, secretKey } = keys.expandDecapsulationKey(seed); + const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j])); + try { + // Detach the decapsulation result before cleanup: the combiner may hand back one of the + // child shared-secret buffers, and those temporary buffers are zeroized below. + return copyBytes(rawCombiner(publicKey, cts, sharedSecret)); + } + finally { + // Decapsulation only needs the expanded child secret keys and child shared secrets for this + // call; keep the caller/root seed intact, but wipe all derived material even on errors. + cleanBytes(secretKey, sharedSecret); + } + }, + }); +} +// There is no specs for this, but can be useful +// realSeedLen: how much bytes expandSeed expects. +/** + * Combines multiple signers into one composite signer. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param expandSeed - Seed expander used to derive per-signer seeds. + * @param signers - Signers to combine. + * @returns Composite signer. + * @example + * Combine multiple signers into one composite signer. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js'; + * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export function combineSigners(realSeedLen, expandSeed, ...signers) { + const rawSigners = signers; + const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners); + const sigCoder = splitLengths(rawSigners, 'signature'); + const pkCoder = splitLengths(rawSigners, 'publicKey'); + return { + lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 }, + getPublicKey: keys.getPublicKey, + keygen: keys.keygen, + sign(message, seed, opts = {}) { + validateSigOpts(opts); + // This generic wrapper intentionally keeps the composite signer contract to message + root + // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly + // across mixed backends, so callers that need them must use the underlying signer directly. + if (opts.extraEntropy !== undefined) + throw new Error('combineSigners does not support extraEntropy; use the underlying signer directly'); + if (opts.context !== undefined) + throw new Error('combineSigners does not support context; use the underlying signer directly'); + const { secretKey } = keys.expandDecapsulationKey(seed); + try { + const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j])); + return sigCoder.encode(sigs); + } + finally { + // Composite secret keys are root seeds; the per-signer child secret keys are temporary + // expansion outputs and must not stay live after the combined signature is produced. + cleanBytes(secretKey); + } + }, + /** Verify one combined signature. + * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify + * check fails. Throws on unsupported generic opts or malformed aggregate encodings. + */ + verify: (signature, message, publicKey, opts = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) + throw new Error('combineSigners does not support context; use the underlying signer directly'); + const pks = pkCoder.decode(publicKey); + const sigs = sigCoder.decode(signature); + for (let i = 0; i < rawSigners.length; i++) { + if (!rawSigners[i].verify(sigs[i], message, pks[i])) + return false; + } + return true; + }, + }; +} +/** + * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte + * SHA3-256 output, while custom `kdf` choices inherit their own digest size. + * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full + * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15). + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param kdf - Hash used for the final combiner. + * @returns Hybrid KEM. + * @example + * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * ```ts + * import { p256 } from '@noble/curves/nist.js'; + * import { sha3_256, shake256 } from '@noble/hashes/sha3.js'; + * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function QSF(label, pqc, curveKEM, xof, kdf) { + ahash(xof); + ahash(kdf); + return combineKEMS(32, kdf.outputLen, expandSeedXof(xof), (pk, ct, ss) => kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), pqc, curveKEM); +} +/** QSF preset combining ML-KEM-768 with P-256. */ +export 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))(); +/** QSF preset combining ML-KEM-1024 with P-384. */ +export 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))(); +/** + * Builds the "KitchenSink" hybrid KEM combiner. + * The current builder always derives a fixed 32-byte output, + * regardless of the hash's native output size. + * Its HKDF extract step uses implicit zero salt with IKM + * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`. + * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`. + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param hash - Hash used for HKDF extraction and expansion. + * @returns Hybrid KEM. + * @example + * Build the "KitchenSink" hybrid KEM combiner. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * import { x25519 } from '@noble/curves/ed25519.js'; + * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function createKitchenSink(label, pqc, curveKEM, xof, hash) { + ahash(xof); + ahash(hash); + return combineKEMS(32, 32, expandSeedXof(xof), (pk, ct, ss) => { + const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label)); + const len = 32; + const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage); + const prk = extract(hash, ikm); + const info = concatBytes(numberToBytesBE(len, 2), asciiToBytes('shared_secret'), asciiToBytes('')); + const res = expand(hash, prk, info, len); + cleanBytes(prk, info, ikm, preimage); + return res; + }, pqc, curveKEM); +} +// Internal alias only: this stays exactly `ecdhKem(x25519)` +// and inherits that wrapper's mutation/oracle behavior. +const x25519kem = /* @__PURE__ */ ecdhKem(x25519); +/** KitchenSink preset combining ML-KEM-768 with X25519. + * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed. + */ +export const KitchenSink_ml_kem768_x25519 = /* @__PURE__ */ (() => createKitchenSink('KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)', ml_kem768, x25519kem, shake256, sha256))(); +// Always X25519 and ML-KEM - 768, no point to export +/** X25519 + ML-KEM-768 hybrid preset. + * Uses the hard-coded domain-separation label `\\.//^\\` and hashes only `ct1 || pk1` + * from the X25519 side in addition to the two component shared secrets. + */ +export const ml_kem768_x25519 = /* @__PURE__ */ (() => combineKEMS(32, 32, expandSeedXof(shake256), +// Awesome label, so much escaping hell in a single line. +(pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\.//^\\'))), ml_kem768, x25519kem))(); +/** + * Internal SEC 1-style KEM wrapper for NIST curves. + * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar: + * current presets use `128` bytes for P-256 and `48` bytes for P-384. + * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04` + * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash + * both coordinates. + */ +function nistCurveKem(curve, scalarLen, elemLen, nseed) { + const Fn = curve.Point.Fn; + if (!Fn) + throw new Error('no Point.Fn'); + // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every + // window is zero or out of range, fail instead of silently reducing modulo `n`. + function rejectionSampling(seed) { + let sk; + for (let start = 0, end = scalarLen;; start = end, end += scalarLen) { + if (end > seed.length) + throw new Error('rejection sampling failed'); + sk = Fn.fromBytes(seed.subarray(start, end), true); + if (Fn.isValidNot0(sk)) + break; + } + const secretKey = Fn.toBytes(Fn.create(sk)); + const publicKey = curve.getPublicKey(secretKey, false); + return { secretKey, publicKey }; + } + return { + lengths: { + secretKey: scalarLen, + publicKey: elemLen, + seed: nseed, + msg: nseed, + cipherText: elemLen, + }, + keygen(seed = randomBytes(nseed)) { + abytes(seed, nseed, 'seed'); + return rejectionSampling(seed); + }, + getPublicKey(secretKey) { + return curve.getPublicKey(secretKey, false); + }, + encapsulate(publicKey, rand = randomBytes(nseed)) { + abytes(rand, nseed, 'rand'); + let ek = undefined; + try { + ek = rejectionSampling(rand).secretKey; + const sharedSecret = this.decapsulate(publicKey, ek); + const cipherText = curve.getPublicKey(ek, false); + return { sharedSecret, cipherText }; + } + finally { + // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and + // must be wiped even if peer-key validation or shared-secret derivation throws. + if (ek) + cleanBytes(ek); + } + }, + decapsulate(cipherText, secretKey) { + const full = curve.getSharedSecret(secretKey, cipherText); + return full.subarray(1); + }, + }; +} +/** + * Internal ML-KEM + NIST-curve combiner. + * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the + * 32-byte root seed and is not itself part of the exported secret-key length. + * The domain-separation `label` is used only in the final `sha3_256` combiner, not in + * `shake256(seed, { dkLen: 64 + nseed })`, + * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`. + */ +function concreteHybridKem(label, mlkem, curve, nseed) { + const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths; + if (!scalarLen || !elemLen) + throw new Error('wrong curve'); + const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed); + const mlkemSeedLen = 64; + const totalSeedLen = mlkemSeedLen + nseed; + return combineKEMS(32, 32, (seed) => { + abytes(seed, 32); + const expanded = shake256(seed, { dkLen: totalSeedLen }); + const mlkemSeed = expanded.subarray(0, mlkemSeedLen); + const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen); + return concatBytes(mlkemSeed, curveSeed); + }, (pk, ct, ss) => sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), mlkem, curveKem); +} +/** P-256 + ML-KEM-768 hybrid preset. */ +export const ml_kem768_p256 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))(); +/** P-384 + ML-KEM-1024 hybrid preset. */ +export const ml_kem1024_p384 = /* @__PURE__ */ (() => concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))(); +// Legacy aliases +/** Legacy alias for `ml_kem768_x25519`. */ +export const XWing = /* @__PURE__ */ (() => ml_kem768_x25519)(); +/** Legacy alias for `ml_kem768_x25519`. */ +export const MLKEM768X25519 = /* @__PURE__ */ (() => ml_kem768_x25519)(); +/** Legacy alias for `ml_kem768_p256`. */ +export const MLKEM768P256 = /* @__PURE__ */ (() => ml_kem768_p256)(); +/** Legacy alias for `ml_kem1024_p384`. */ +export const MLKEM1024P384 = /* @__PURE__ */ (() => ml_kem1024_p384)(); +/** Legacy alias for `QSF_ml_kem768_p256`. */ +export const QSFMLKEM768P256 = /* @__PURE__ */ (() => QSF_ml_kem768_p256)(); +/** Legacy alias for `QSF_ml_kem1024_p384`. */ +export const QSFMLKEM1024P384 = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)(); +/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */ +export const KitchenSinkMLKEM768X25519 = /* @__PURE__ */ (() => KitchenSink_ml_kem768_x25519)(); +//# sourceMappingURL=hybrid.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/hybrid.js.map b/node_modules/@noble/post-quantum/hybrid.js.map new file mode 100644 index 0000000..fd2feb2 --- /dev/null +++ b/node_modules/@noble/post-quantum/hybrid.js.map @@ -0,0 +1 @@ +{"version":3,"file":"hybrid.js","sourceRoot":"","sources":["src/hybrid.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0EG;AACH,4EAA4E;AAC5E,OAAO,EAAc,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAuB,MAAM,sCAAsC,CAAC;AAC3E,OAAO,EAAc,MAAM,uCAAuC,CAAC;AACnE,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAClD,OAAO,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;A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AAC,EAAE,CAAC;AAClF,6CAA6C;AAC7C,MAAM,CAAC,MAAM,eAAe,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,kBAAkB,CAAC,EAAE,CAAC;AACvF,8CAA8C;AAC9C,MAAM,CAAC,MAAM,gBAAgB,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,EAAE,CAAC;AACzF,uDAAuD;AACvD,MAAM,CAAC,MAAM,yBAAyB,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CACxE,4BAA4B,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/index.d.ts b/node_modules/@noble/post-quantum/index.d.ts new file mode 100644 index 0000000..e26a57a --- /dev/null +++ b/node_modules/@noble/post-quantum/index.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/index.d.ts.map b/node_modules/@noble/post-quantum/index.d.ts.map new file mode 100644 index 0000000..4e8c581 --- /dev/null +++ b/node_modules/@noble/post-quantum/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/index.js b/node_modules/@noble/post-quantum/index.js new file mode 100644 index 0000000..11ecb78 --- /dev/null +++ b/node_modules/@noble/post-quantum/index.js @@ -0,0 +1,29 @@ +/** + * Auditable & minimal JS implementation of post-quantum public-key cryptography. + * Check out individual modules. + * @module + * @example +```js +import { ml_kem512, ml_kem768, ml_kem1024 } from '@noble/post-quantum/ml-kem.js'; +import { ml_dsa44, ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa.js'; +import { + slh_dsa_sha2_128f, slh_dsa_sha2_128s, + slh_dsa_sha2_192f, slh_dsa_sha2_192s, + slh_dsa_sha2_256f, slh_dsa_sha2_256s, + slh_dsa_shake_128f, slh_dsa_shake_128s, + slh_dsa_shake_192f, slh_dsa_shake_192s, + slh_dsa_shake_256f, slh_dsa_shake_256s, +} from '@noble/post-quantum/slh-dsa.js'; +import { + falcon512, falcon512padded, falcon1024, falcon1024padded, +} from '@noble/post-quantum/falcon.js'; +import { + ml_kem768_x25519, ml_kem768_p256, ml_kem1024_p384, + KitchenSink_ml_kem768_x25519, XWing, + QSF_ml_kem768_p256, QSF_ml_kem1024_p384, +} from '@noble/post-quantum/hybrid.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/index.js.map b/node_modules/@noble/post-quantum/index.js.map new file mode 100644 index 0000000..452a869 --- /dev/null +++ b/node_modules/@noble/post-quantum/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,IAAI,KAAK,CAAC,6EAA6E,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-dsa.d.ts b/node_modules/@noble/post-quantum/ml-dsa.d.ts new file mode 100644 index 0000000..fa034ce --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-dsa.d.ts @@ -0,0 +1,54 @@ +import { type CryptoKeys, type Signer, type SigOpts, type TArg, type TRet, type VerOpts } from './utils.ts'; +/** Internal ML-DSA options. */ +export type DSAInternalOpts = { + /** + * Whether `internal.sign` / `internal.verify` receive a caller-supplied 64-byte `mu` + * instead of the usual FIPS 204 formatted message `M'` / prehash-formatted message. + * validateInternalOpts() only checks this flag; callers still must supply the right input length. + */ + externalMu?: boolean; +}; +/** ML-DSA signer surface with access to the internal message formatting mode. */ +export type DSAInternal = CryptoKeys & { + lengths: Signer['lengths']; + sign: (msg: TArg, secretKey: TArg, opts?: TArg) => TRet; + verify: (sig: TArg, msg: TArg, pubKey: TArg, opts?: TArg) => boolean; +}; +/** Public ML-DSA signer surface. */ +export type DSA = Signer & { + internal: TRet; +}; +/** Various lattice params. */ +/** Public ML-DSA parameter-set description. */ +export type DSAParam = { + /** Matrix row count. */ + K: number; + /** Matrix column count. */ + L: number; + /** Bit width used when rounding `t`. */ + D: number; + /** Bound used for the `y` sampling range. */ + GAMMA1: number; + /** Bound used during decomposition and hints. */ + GAMMA2: number; + /** Number of non-zero challenge coefficients. */ + TAU: number; + /** Centered-binomial noise parameter. */ + ETA: number; + /** Maximum number of hint bits in a signature. */ + OMEGA: number; +}; +/** Internal params for different versions of ML-DSA */ +/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5` + * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`. + * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later, + * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers. + */ +export declare const PARAMS: Record; +/** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */ +export declare const ml_dsa44: TRet; +/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */ +export declare const ml_dsa65: TRet; +/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */ +export declare const ml_dsa87: TRet; +//# sourceMappingURL=ml-dsa.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-dsa.d.ts.map b/node_modules/@noble/post-quantum/ml-dsa.d.ts.map new file mode 100644 index 0000000..5dcc3d0 --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-dsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ml-dsa.d.ts","sourceRoot":"","sources":["src/ml-dsa.ts"],"names":[],"mappings":"AAcA,OAAO,EAKL,KAAK,UAAU,EAKf,KAAK,MAAM,EACX,KAAK,OAAO,EAEZ,KAAK,IAAI,EACT,KAAK,IAAI,EAKT,KAAK,OAAO,EACb,MAAM,YAAY,CAAC;AAEpB,+BAA+B;AAC/B,MAAM,MAAM,eAAe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AE,QAAQ,CAW5B,CAAC;AAgnBjB,oFAAoF;AACpF,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,GAAG,CASxB,CAAC;AAER,oFAAoF;AACpF,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,GAAG,CASxB,CAAC;AAER,uEAAuE;AACvE,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,GAAG,CASxB,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-dsa.js b/node_modules/@noble/post-quantum/ml-dsa.js new file mode 100644 index 0000000..441518b --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-dsa.js @@ -0,0 +1,662 @@ +/** + * ML-DSA: Module Lattice-based Digital Signature Algorithm from + * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium. + * + * Has similar internals to ML-KEM, but their keys and params are different. + * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml), + * [repo](https://github.com/pq-crystals/dilithium). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { abool } from '@noble/curves/utils.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import { genCrystals, XOF128, XOF256 } from "./_crystals.js"; +import { abytes, checkHash, cleanBytes, equalBytes, getMessage, getMessagePrehash, randomBytes, splitCoder, validateOpts, validateSigOpts, validateVerOpts, vecCoder, } from "./utils.js"; +function validateInternalOpts(opts) { + validateOpts(opts); + if (opts.externalMu !== undefined) + abool(opts.externalMu, 'opts.externalMu'); +} +// Constants +// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients. +const N = 256; +// 2**23 − 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints +const Q = 8380417; +// FIPS 204 §2.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT. +const ROOT_OF_UNITY = 1753; +// f = 256**−1 mod q, pow(256, -1, q) = 8347681 (python3) +const F = 8347681; +// FIPS 204 Table 1 / §7.4 fixes d = 13 dropped low bits for Power2Round on t. +const D = 13; +// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87; +// §7.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint. +// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value. +const GAMMA2_1 = Math.floor((Q - 1) / 88) | 0; +const GAMMA2_2 = Math.floor((Q - 1) / 32) | 0; +/** Internal params for different versions of ML-DSA */ +// prettier-ignore +/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5` + * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`. + * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later, + * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers. + */ +export const PARAMS = /* @__PURE__ */ (() => Object.freeze({ + 2: Object.freeze({ + K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80 + }), + 3: Object.freeze({ + K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55 + }), + 5: Object.freeze({ + K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75 + }), +}))(); +const newPoly = (n) => new Int32Array(n); +// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal, +// and Int32Array polys because ordinary-form coefficients can be negative / centered. +const crystals = /* @__PURE__ */ genCrystals({ + N, + Q, + F, + ROOT_OF_UNITY, + newPoly, + isKyber: false, + brvBits: 8, +}); +const id = (n) => n; +// compress()/verify() must be compatible in both directions: +// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps. +// malformed-input rejection only happens through the optional verify hook. +const polyCoder = (d, compress = id, verify = id) => crystals.bitsCoder(d, { + encode: (i) => compress(verify(i)), + decode: (i) => verify(compress(i)), +}); +// Mutates `a` in place; callers must pass same-length polynomials. +const polyAdd = (a_, b_) => { + const a = a_; + const b = b_; + for (let i = 0; i < a.length; i++) + a[i] = crystals.mod(a[i] + b[i]); + return a; +}; +// Mutates `a` in place; callers must pass same-length polynomials. +const polySub = (a_, b_) => { + const a = a_; + const b = b_; + for (let i = 0; i < a.length; i++) + a[i] = crystals.mod(a[i] - b[i]); + return a; +}; +// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial. +const polyShiftl = (p_) => { + const p = p_; + for (let i = 0; i < N; i++) + p[i] <<= D; + return p; +}; +const polyChknorm = (p_, B) => { + const p = p_; + // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities. + for (let i = 0; i < N; i++) + if (Math.abs(crystals.smod(p[i])) >= B) + return true; + return false; +}; +// Both inputs must already be in NTT / `T_q` form. +const MultiplyNTTs = (a_, b_) => { + const a = a_; + const b = b_; + // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints, + // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit, + // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits). + // Barrett reduction is slower than mod :( + const c = newPoly(N); + for (let i = 0; i < a.length; i++) + c[i] = crystals.mod(a[i] * b[i]); + return c; +}; +// Return poly in NTT representation +function RejNTTPoly(xof_) { + const xof = xof_; + // Samples a polynomial ∈ Tq. xof() must return byte lengths divisible by 3. + const r = newPoly(N); + // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :( + for (let j = 0; j < N;) { + const b = xof(); + if (b.length % 3) + throw new Error('RejNTTPoly: unaligned block'); + for (let i = 0; j < N && i <= b.length - 3; i += 3) { + // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate. + const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes + if (t < Q) + r[j++] = t; + } + } + return r; +} +// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the +// Table 2 byte lengths / hash-width choices used by the public wrappers below. +function getDilithium(opts_) { + const opts = opts_; + const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts; + const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts; + if (![2, 4].includes(ETA)) + throw new Error('Wrong ETA'); + if (![1 << 17, 1 << 19].includes(GAMMA1)) + throw new Error('Wrong GAMMA1'); + if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) + throw new Error('Wrong GAMMA2'); + const BETA = TAU * ETA; + const decompose = (r) => { + // Decomposes r into (r1, r0) such that r ≡ r1(2γ2) + r0 mod q. + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0; + // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`. + if (rPlus - r0 === Q - 1) + return { r1: 0 | 0, r0: (r0 - 1) | 0 }; + const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0; + return { r1, r0 }; // r1 = HighBits, r0 = LowBits + }; + const HighBits = (r) => decompose(r).r1; + const LowBits = (r) => decompose(r).r0; + const MakeHint = (z, r) => { + // Compute hint bit indicating whether adding z to r alters the high bits of r. + // FIPS 204 §6.2 also permits the Section 5.1 alternative from [6], which uses the + // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally. + // This optimized predicate only applies to those transformed Section 5.1 inputs; it is + // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs. + // From dilithium code + const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1; + // from FIPS204: + // // const r1 = HighBits(r); + // // const v1 = HighBits(r + z); + // // const res1 = +(r1 !== v1); + // But they return different results! However, decompose is same. + // So, either there is a bug in Dilithium ref implementation or in FIPS204. + // For now, lets use dilithium one, so test vectors can be passed. + // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after + // `r0 += ct0`. + // See dilithium-py README section "Optimising decomposition and making hints". + return res0; + }; + const UseHint = (h, r) => { + // Returns the high bits of r adjusted according to hint h + const m = Math.floor((Q - 1) / (2 * GAMMA2)); + const { r1, r0 } = decompose(r); + // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m + // 4: if h = 1 and r0 ≤ 0 return (r1 − 1) mod m + if (h === 1) + return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0; + return r1 | 0; + }; + const Power2Round = (r) => { + // Decomposes r into (r1, r0) such that r ≡ r1*(2**d) + r0 mod q. + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 ** D) | 0; + return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 }; + }; + const hintCoder = { + bytesLen: OMEGA + K, + encode: (h_) => { + const h = h_; + if (h === false) + throw new Error('hint.encode: hint is false'); // should never happen + const res = new Uint8Array(OMEGA + K); + for (let i = 0, k = 0; i < K; i++) { + for (let j = 0; j < N; j++) + if (h[i][j] !== 0) + res[k++] = j; + res[OMEGA + i] = k; + } + return res; + }, + decode: (buf) => { + const h = []; + let k = 0; + for (let i = 0; i < K; i++) { + const hi = newPoly(N); + if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA) + return false; + for (let j = k; j < buf[OMEGA + i]; j++) { + if (j > k && buf[j] <= buf[j - 1]) + return false; + hi[buf[j]] = 1; + } + k = buf[OMEGA + i]; + h.push(hi); + } + for (let j = k; j < OMEGA; j++) + if (buf[j] !== 0) + return false; + return h; + }, + }; + const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => { + if (!(-ETA <= i && i <= ETA)) + throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`); + return i; + }); + const T0Coder = polyCoder(13, (i) => (1 << (D - 1)) - i); + const T1Coder = polyCoder(10); + // Requires smod. Need to fix! + const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i)); + const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4); + const W1Vec = vecCoder(W1Coder, K); + // Main structures + const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K)); + const secretCoder = splitCoder('secretKey', 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K)); + const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder); + const CoefFromHalfByte = ETA === 2 + ? (n) => (n < 15 ? 2 - (n % 5) : false) + : (n) => (n < 9 ? 4 - n : false); + // Return poly in ordinary representation. + // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply + // `NTT.encode()` later when needed. + function RejBoundedPoly(xof_) { + const xof = xof_; + // Samples an element a ∈ Rq with coeffcients in [−η, η] computed via rejection sampling from ρ. + const r = newPoly(N); + for (let j = 0; j < N;) { + const b = xof(); + for (let i = 0; j < N && i < b.length; i += 1) { + // half byte. Should be superfast with vector instructions. But very slow with js :( + const d1 = CoefFromHalfByte(b[i] & 0x0f); + const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f); + if (d1 !== false) + r[j++] = d1; + if (j < N && d2 !== false) + r[j++] = d2; + } + } + return r; + } + const SampleInBall = (seed) => { + // Samples a polynomial c ∈ Rq with coeffcients from {−1, 0, 1} and Hamming weight τ + const pre = newPoly(N); + const s = shake256.create({}).update(seed); + const buf = new Uint8Array(shake256.blockLen); + s.xofInto(buf); + // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`, + // then rejection-samples coefficient positions from the remaining XOF stream. + const masks = buf.slice(0, 8); + for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) { + let b = i + 1; + for (; b > i;) { + b = buf[pos++]; + if (pos < shake256.blockLen) + continue; + s.xofInto(buf); + pos = 0; + } + pre[i] = pre[b]; + pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1); + if (maskBit >= 8) { + maskPos++; + maskBit = 0; + } + } + return pre; + }; + const polyPowerRound = (p_) => { + const p = p_; + const res0 = newPoly(N); + const res1 = newPoly(N); + for (let i = 0; i < p.length; i++) { + const { r0, r1 } = Power2Round(p[i]); + res0[i] = r0; + res1[i] = r1; + } + return { r0: res0, r1: res1 }; + }; + const polyUseHint = (u_, h_) => { + const u = u_; + const h = h_; + // In-place on `u`: verification only needs the recovered high bits, so reuse the + // temporary `wApprox` buffer instead of allocating another polynomial. + for (let i = 0; i < N; i++) + u[i] = UseHint(h[i], u[i]); + return u; + }; + const polyMakeHint = (a_, b_) => { + const a = a_; + const b = b_; + const v = newPoly(N); + let cnt = 0; + for (let i = 0; i < N; i++) { + const h = MakeHint(a[i], b[i]); + v[i] = h; + cnt += h; + } + return { v, cnt }; + }; + const signRandBytes = 32; + const seedCoder = splitCoder('seed', 32, 64, 32); + // API & argument positions are exactly as in FIPS204. + const internal = Object.freeze({ + info: Object.freeze({ type: 'internal-ml-dsa' }), + lengths: Object.freeze({ + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + seed: 32, + signature: sigCoder.bytesLen, + signRand: signRandBytes, + }), + keygen: (seed) => { + // H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128) 2: ▷ expand seed + const seedDst = new Uint8Array(32 + 2); + const randSeed = seed === undefined; + if (randSeed) + seed = randomBytes(32); + abytes(seed, 32, 'seed'); + seedDst.set(seed); + if (randSeed) + cleanBytes(seed); + seedDst[32] = K; + seedDst[33] = L; + const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen })); + const xofPrime = XOF256(rhoPrime); + const s1 = []; + for (let i = 0; i < L; i++) + s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff))); + const s2 = []; + for (let i = L; i < L + K; i++) + s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff))); + const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice())); + const t0 = []; + const t1 = []; + const xof = XOF128(rho); + const t = newPoly(N); + for (let i = 0; i < K; i++) { + // t ← NTT−1(A*NTT(s1)) + s2 + cleanBytes(t); // don't-reallocate + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // super slow! + polyAdd(t, MultiplyNTTs(aij, s1Hat[j])); + } + crystals.NTT.decode(t); + const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) ← Power2Round(t, d) + t0.push(r0); + t1.push(r1); + } + const publicKey = publicCoder.encode([rho, t1]); // pk ← pkEncode(ρ, t1) + const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr ← H(BytesToBits(pk), 512) + // sk ← skEncode(ρ, K,tr, s1, s2, t0) + const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]); + xof.clean(); + xofPrime.clean(); + // STATS + // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 }, + // Kyber1024: { calls: 16, xofs: 48 } + // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 }, + // DSA87: { calls: 71, xofs: 71 } + cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst); + return { + publicKey: publicKey, + secretKey: secretKey, + }; + }, + getPublicKey: (secretKey) => { + // (ρ, K,tr, s1, s2, t0) ← skDecode(sk) + const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey); + const xof = XOF128(rho); + const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice())); + const t1 = []; + const tmp = newPoly(N); + for (let i = 0; i < K; i++) { + tmp.fill(0); + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT + polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j + } + crystals.NTT.decode(tmp); // NTT⁻¹ + polyAdd(tmp, s2[i]); // t_i = A·s1 + s2 + const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 ≈ t0 + t1.push(r1); + } + xof.clean(); + cleanBytes(tmp, s1Hat, _t0, s1, s2); + return publicCoder.encode([rho, t1]); + }, + // NOTE: random is optional. + sign: (msg, secretKey, opts = {}) => { + validateSigOpts(opts); + validateInternalOpts(opts); + let { extraEntropy: random, externalMu = false } = opts; + // This part can be pre-cached per secretKey, but there is only minor performance improvement, + // since we re-use a lot of variables to computation. + // (ρ, K,tr, s1, s2, t0) ← skDecode(sk) + const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey); + // Cache matrix to avoid re-compute later + const A = []; // A ← ExpandA(ρ) + const xof = XOF128(rho); + for (let i = 0; i < K; i++) { + const pv = []; + for (let j = 0; j < L; j++) + pv.push(RejNTTPoly(xof.get(j, i))); + A.push(pv); + } + xof.clean(); + for (let i = 0; i < L; i++) + crystals.NTT.encode(s1[i]); // sˆ1 ← NTT(s1) + for (let i = 0; i < K; i++) { + crystals.NTT.encode(s2[i]); // sˆ2 ← NTT(s2) + crystals.NTT.encode(t0[i]); // tˆ0 ← NTT(t0) + } + // This part is per msg + const mu = externalMu + ? msg + : // 6: µ ← H(tr||M, 512) + // ▷ Compute message representative µ + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); + // Compute private random seed + const rnd = random === false + ? new Uint8Array(32) + : random === undefined + ? randomBytes(signRandBytes) + : random; + abytes(rnd, 32, 'extraEntropy'); + const rhoprime = shake256 + .create({ dkLen: CRH_BYTES }) + .update(_K) + .update(rnd) + .update(mu) + .digest(); // ρ′← H(K||rnd||µ, 512) + abytes(rhoprime, CRH_BYTES); + const x256 = XOF256(rhoprime, ZCoder.bytesLen); + // Rejection sampling loop + main_loop: for (let kappa = 0;;) { + const y = []; + // y ← ExpandMask(ρ , κ) + for (let i = 0; i < L; i++, kappa++) + y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)())); + const z = y.map((i) => crystals.NTT.encode(i.slice())); + const w = []; + for (let i = 0; i < K; i++) { + // w ← NTT−1(A ◦ NTT(y)) + const wi = newPoly(N); + for (let j = 0; j < L; j++) + polyAdd(wi, MultiplyNTTs(A[i][j], z[j])); + crystals.NTT.decode(wi); + w.push(wi); + } + const w1 = w.map((j) => j.map(HighBits)); // w1 ← HighBits(w) + // Commitment hash: c˜ ∈{0, 1 2λ } ← H(µ||w1Encode(w1), 2λ) + const cTilde = shake256 + .create({ dkLen: C_TILDE_BYTES }) + .update(mu) + .update(W1Vec.encode(w1)) + .digest(); + // Verifer’s challenge + // c ← SampleInBall(c˜1); cˆ ← NTT(c) + const cHat = crystals.NTT.encode(SampleInBall(cTilde)); + // ⟨⟨cs1⟩⟩ ← NTT−1(cˆ◦ sˆ1) + const cs1 = s1.map((i) => MultiplyNTTs(i, cHat)); + for (let i = 0; i < L; i++) { + polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z ← y + ⟨⟨cs1⟩⟩ + if (polyChknorm(cs1[i], GAMMA1 - BETA)) + continue main_loop; // ||z||∞ ≥ γ1 − β + } + // cs1 is now z (▷ Signer’s response) + let cnt = 0; + const h = []; + for (let i = 0; i < K; i++) { + const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // ⟨⟨cs2⟩⟩ ← NTT−1(cˆ◦ sˆ2) + const r0 = polySub(w[i], cs2).map(LowBits); // r0 ← LowBits(w − ⟨⟨cs2⟩⟩) + if (polyChknorm(r0, GAMMA2 - BETA)) + continue main_loop; // ||r0||∞ ≥ γ2 − β + const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // ⟨⟨ct0⟩⟩ ← NTT−1(cˆ◦ tˆ0) + if (polyChknorm(ct0, GAMMA2)) + continue main_loop; + polyAdd(r0, ct0); + // ▷ Signer’s hint + const hint = polyMakeHint(r0, w1[i]); // h ← MakeHint(−⟨⟨ct0⟩⟩, w− ⟨⟨cs2⟩⟩ + ⟨⟨ct0⟩⟩) + h.push(hint.v); + cnt += hint.cnt; + } + if (cnt > OMEGA) + continue; // the number of 1’s in h is greater than ω + x256.clean(); + const res = sigCoder.encode([cTilde, cs1, h]); // σ ← sigEncode(c˜, z mod±q, h) + // rho, _K, tr is subarray of secretKey, cannot clean. + cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A); + // `externalMu` hands ownership of `mu` to the caller, + // so only wipe the internally derived digest form here; + // zeroizing caller memory would break the caller's own reuse / verify path. + if (!externalMu) + cleanBytes(mu); + return res; + } + // @ts-ignore + throw new Error('Unreachable code path reached, report this error'); + }, + verify: (sig, msg, publicKey, opts = {}) => { + validateInternalOpts(opts); + const { externalMu = false } = opts; + // ML-DSA.Verify(pk, M, σ): Verifes a signature σ for a message M. + const [rho, t1] = publicCoder.decode(publicKey); // (ρ, t1) ← pkDecode(pk) + const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr ← H(BytesToBits(pk), 512) + if (sig.length !== sigCoder.bytesLen) + return false; // return false instead of exception + // (c˜, z, h) ← sigDecode(σ) + // ▷ Signer’s commitment hash c ˜, response z and hint + const [cTilde, z, h] = sigCoder.decode(sig); + if (h === false) + return false; // if h = ⊥ then return false + for (let i = 0; i < L; i++) + if (polyChknorm(z[i], GAMMA1 - BETA)) + return false; + const mu = externalMu + ? msg + : // 7: µ ← H(tr||M, 512) + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); + // Compute verifer’s challenge from c˜ + const c = crystals.NTT.encode(SampleInBall(cTilde)); // c ← SampleInBall(c˜1) + const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z) + for (let i = 0; i < L; i++) + crystals.NTT.encode(zNtt[i]); + const wTick1 = []; + const xof = XOF128(rho); + for (let i = 0; i < K; i++) { + const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d) + const Az = newPoly(N); // // A * z + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace + polyAdd(Az, MultiplyNTTs(aij, zNtt[j])); + } + // wApprox = A*z - c*t1 * (2**d) + const wApprox = crystals.NTT.decode(polySub(Az, ct12d)); + // Reconstruction of signer’s commitment + wTick1.push(polyUseHint(wApprox, h[i])); // w ′ ← UseHint(h, w'approx ) + } + xof.clean(); + // c˜′← H (µ||w1Encode(w′1), 2λ), Hash it; this should match c˜ + const c2 = shake256 + .create({ dkLen: C_TILDE_BYTES }) + .update(mu) + .update(W1Vec.encode(wTick1)) + .digest(); + // Additional checks in FIPS-204: + // [[ ||z||∞ < γ1 − β ]] and [[c ˜ = c˜′]] and [[number of 1’s in h is ≤ ω]] + for (const t of h) { + const sum = t.reduce((acc, i) => acc + i, 0); + if (!(sum <= OMEGA)) + return false; + } + for (const t of z) + if (polyChknorm(t, GAMMA1 - BETA)) + return false; + return equalBytes(cTilde, c2); + }, + }); + return Object.freeze({ + info: Object.freeze({ type: 'ml-dsa' }), + internal, + securityLevel: securityLevel, + keygen: internal.keygen, + lengths: internal.lengths, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts = {}) => { + validateSigOpts(opts); + const M = getMessage(msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts = {}) => { + validateVerOpts(opts); + return internal.verify(sig, getMessage(msg, opts.context), publicKey); + }, + prehash: (hash) => { + checkHash(hash, securityLevel); + return Object.freeze({ + info: Object.freeze({ type: 'hashml-dsa' }), + securityLevel: securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts = {}) => { + validateSigOpts(opts); + const M = getMessagePrehash(hash, msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts = {}) => { + validateVerOpts(opts); + return internal.verify(sig, getMessagePrehash(hash, msg, opts.context), publicKey); + }, + }); + }, + }); +} +/** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */ +export const ml_dsa44 = /* @__PURE__ */ (() => getDilithium({ + ...PARAMS[2], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 32, + XOF128, + XOF256, + securityLevel: 128, +}))(); +/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */ +export const ml_dsa65 = /* @__PURE__ */ (() => getDilithium({ + ...PARAMS[3], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 48, + XOF128, + XOF256, + securityLevel: 192, +}))(); +/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */ +export const ml_dsa87 = /* @__PURE__ */ (() => getDilithium({ + ...PARAMS[5], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 64, + XOF128, + XOF256, + securityLevel: 256, +}))(); +//# sourceMappingURL=ml-dsa.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-dsa.js.map b/node_modules/@noble/post-quantum/ml-dsa.js.map new file mode 100644 index 0000000..a88c7d2 --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-dsa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ml-dsa.js","sourceRoot":"","sources":["src/ml-dsa.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,4EAA4E;AAC5E,OAAO,EAAE,KAAK,EAAE,MAAM,wBAAwB,CAAC;AAC/C,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,EAAE,WAAW,EAAY,MAAM,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACvE,OAAO,EACL,MAAM,EAEN,SAAS,EACT,UAAU,EAEV,UAAU,EACV,UAAU,EACV,iBAAiB,EACjB,WAAW,EAGX,UAAU,EAGV,YAAY,EACZ,eAAe,EACf,eAAe,EACf,QAAQ,GAET,MAAM,YAAY,CAAC;AAWpB,SAAS,oBAAoB,CAAC,IAA2B;IACvD,YAAY,CAAC,IAAI,CAAC,CAAC;IACnB,IAAI,IAAI,CAAC,UAAU,K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AAC;oBACtB,OAAO,QAAQ,CAAC,MAAM,CAAC,GAAG,EAAE,iBAAiB,CAAC,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,CAAC;gBACrF,CAAC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,MAAM,QAAQ,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CACvD,YAAY,CAAC;IACX,GAAG,MAAM,CAAC,CAAC,CAAC;IACZ,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;IACZ,aAAa,EAAE,EAAE;IACjB,MAAM;IACN,MAAM;IACN,aAAa,EAAE,GAAG;CACnB,CAAC,CAAC,EAAE,CAAC;AAER,oFAAoF;AACpF,MAAM,CAAC,MAAM,QAAQ,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CACvD,YAAY,CAAC;IACX,GAAG,MAAM,CAAC,CAAC,CAAC;IACZ,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;IACZ,aAAa,EAAE,EAAE;IACjB,MAAM;IACN,MAAM;IACN,aAAa,EAAE,GAAG;CACnB,CAAC,CAAC,EAAE,CAAC;AAER,uEAAuE;AACvE,MAAM,CAAC,MAAM,QAAQ,GAAc,eAAe,CAAC,CAAC,GAAG,EAAE,CACvD,YAAY,CAAC;IACX,GAAG,MAAM,CAAC,CAAC,CAAC;IACZ,SAAS,EAAE,EAAE;IACb,QAAQ,EAAE,EAAE;IACZ,aAAa,EAAE,EAAE;IACjB,MAAM;IACN,MAAM;IACN,aAAa,EAAE,GAAG;CACnB,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-kem.d.ts b/node_modules/@noble/post-quantum/ml-kem.d.ts new file mode 100644 index 0000000..25de4fe --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-kem.d.ts @@ -0,0 +1,45 @@ +import { type KEM, type TRet } from './utils.ts'; +/** FIPS 203: 7. Parameter Sets */ +/** Public ML-KEM parameter-set description. */ +export type KEMParam = { + /** Polynomial size. */ + N: number; + /** Module rank. */ + K: number; + /** Prime modulus. */ + Q: number; + /** CBD parameter used for secret-key noise. */ + ETA1: number; + /** CBD parameter used for error noise. */ + ETA2: number; + /** Compression width for the `u` vector. */ + du: number; + /** Compression width for the `v` polynomial. */ + dv: number; + /** Required strength of the randomness source in bits. */ + RBGstrength: number; +}; +/** Internal params of ML-KEM versions */ +/** Built-in ML-KEM parameter presets keyed by the public export names + * `ml_kem512` / `ml_kem768` / `ml_kem1024`. + * `RBGstrength` is Table 2's required randomness-source strength in bits, + * not a generic security label. + */ +export declare const PARAMS: Record; +/** + * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export declare const ml_kem512: TRet; +/** + * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export declare const ml_kem768: TRet; +/** + * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export declare const ml_kem1024: TRet; +export declare const __tests: any; +//# sourceMappingURL=ml-kem.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-kem.d.ts.map b/node_modules/@noble/post-quantum/ml-kem.d.ts.map new file mode 100644 index 0000000..bc51790 --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-kem.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ml-kem.d.ts","sourceRoot":"","sources":["src/ml-kem.ts"],"names":[],"mappings":"AAyBA,OAAO,EAOL,KAAK,GAAG,EAIR,KAAK,IAAI,EAEV,MAAM,YAAY,CAAC;AAqBpB,kCAAkC;AAClC,+CAA+C;AAC/C,MAAM,MAAM,QAAQ,GAAG;IACrB,uBAAuB;IACvB,CAAC,EAAE,MAAM,CAAC;IACV,mBAAmB;IACnB,CAAC,EAAE,MAAM,CAAC;IACV,qBAAqB;IACrB,CAAC,EAAE,MAAM,CAAC;IACV,+CAA+C;IAC/C,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,4CAA4C;IAC5C,EAAE,EAAE,MAAM,CAAC;IACX,gDAAgD;IAChD,EAAE,EAAE,MAAM,CAAC;IACX,0DAA0D;IAC1D,WAAW,EAAE,MAAM,CAAC;CACrB,CAAC;AACF,yCAAyC;AAEzC;;;;GAIG;AACH,eAAO,MAAM,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAK5B,CAAC;AA8WjB;;;GAGG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,GAAG,CAA6C,CAAC;AAC9E;;;GAGG;AACH,eAAO,MAAM,SAAS,EAAE,IAAI,CAAC,GAAG,CAA6C,CAAC;AAC9E;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,IAAI,CAAC,GAAG,CAA8C,CAAC;AAIhF,eAAO,MAAM,OAAO,EAAE,GAmCf,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-kem.js b/node_modules/@noble/post-quantum/ml-kem.js new file mode 100644 index 0000000..e8fb4f2 --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-kem.js @@ -0,0 +1,444 @@ +/** + * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from + * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber. + * + * Key encapsulation is similar to DH / ECDH (think X25519), with important differences: + * * Unlike in ECDH, we can't verify if it was "Bob" who've sent the shared secret + * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG). + * * Decapsulation never throws an error, even when shared secret was + * encrypted by a different public key. It will just return a different shared secret. + * + * There are some concerns with regards to security: see + * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and + * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E). + * + * Has similar internals to ML-DSA, but their keys and params are different. + * + * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml), + * [repo](https://github.com/pq-crystals/kyber), + * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js'; +import { swap32IfBE, u32 } from '@noble/hashes/utils.js'; +import { genCrystals, XOF128 } from "./_crystals.js"; +import { abytes, cleanBytes, copyBytes, equalBytes, getMask, randomBytes, splitCoder, vecCoder, } from "./utils.js"; +/** Key encapsulation mechanism interface */ +const N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256 +const Q = 3329; // 13*(2**8)+1, modulo prime +const F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203) +const ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1 +// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely. +// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal, +// and Uint16Array polys because current coefficients stay reduced modulo q. +const crystals = /* @__PURE__ */ genCrystals({ + N, + Q, + F, + ROOT_OF_UNITY, + newPoly: (n) => new Uint16Array(n), + brvBits: 7, + isKyber: true, +}); +/** Internal params of ML-KEM versions */ +// prettier-ignore +/** Built-in ML-KEM parameter presets keyed by the public export names + * `ml_kem512` / `ml_kem768` / `ml_kem1024`. + * `RBGstrength` is Table 2's required randomness-source strength in bits, + * not a generic security label. + */ +export const PARAMS = /* @__PURE__ */ (() => Object.freeze({ + 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }), + 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }), + 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }), +}))(); +// FIPS-203: compress/decompress +const compress = (d) => { + // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression. + // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key + // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095. + if (d >= 12) + return { encode: (i) => i, decode: (i) => (i >= Q ? i - Q : i) }; + // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber) + // const round = (i: number) => Math.floor(i + 0.5) | 0; + const a = 2 ** (d - 1); + return { + // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d). + encode: (i) => ((i << d) + Q / 2) / Q, + // const decompress = (i: number) => round((Q / 2 ** d) * i); + decode: (i) => (i * Q + a) >>> d, + }; +}; +// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly. +// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy +// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need +// this exact non-lossy variant instead. +const byteCoder = (d) => crystals.bitsCoder(d, d === 12 + ? { encode: (i) => i, decode: (i) => (i >= Q ? i - Q : i) } + : { encode: (i) => i, decode: (i) => i }); +// NOTE: we merge encoding and compress because it is faster, also both require same d param +// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side +// public-key modulus checks route through this helper's decode/encode roundtrip. +// Converts between bytes and d-bits compressed representation. +// Kinda like convertRadix2 from @scure/base. +// decode(encode(t)) == t, but there is loss of information on encode(decode(t)) +const polyCoder = (d) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d))); +function polyAdd(a_, b_) { + const a = a_; + const b = b_; + // Mutates `a` in place; callers must pass two N=256 polynomials. + for (let i = 0; i < N; i++) + a[i] = crystals.mod(a[i] + b[i]); // a += b +} +function polySub(a_, b_) { + const a = a_; + const b = b_; + // Mutates `a` in place; callers must pass two N=256 polynomials. + for (let i = 0; i < N; i++) + a[i] = crystals.mod(a[i] - b[i]); // a -= b +} +// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus +function BaseCaseMultiply(a0, a1, b0, b1, zeta) { + // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1). + const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0); + const c1 = crystals.mod(a0 * b1 + a1 * b0); + return { c0, c1 }; +} +// FIPS-203: Computes the product (in the ring Tq) of two NTT representations. +// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form. +function MultiplyNTTs(f_, g_) { + const f = f_; + const g = g_; + for (let i = 0; i < N / 2; i++) { + let z = crystals.nttZetas[64 + (i >> 1)]; + if (i & 1) + z = -z; + const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z); + f[2 * i + 0] = c0; + f[2 * i + 1] = c1; + } + return f; +} +// Return poly in NTT representation +function SampleNTT(xof_) { + const xof = xof_; + // The reader must already bind the Algorithm 7 seed||j||i bytes + // and return block lengths divisible by 3. + const r = new Uint16Array(N); + for (let j = 0; j < N;) { + const b = xof(); + if (b.length % 3) + throw new Error('SampleNTT: unaligned block'); + for (let i = 0; j < N && i + 3 <= b.length; i += 3) { + const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff; + const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff; + if (d1 < Q) + r[j++] = d1; + if (j < N && d2 < Q) + r[j++] = d2; + } + } + return r; +} +// Sampling from the centered binomial distribution +// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form. +// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes. +const sampleCBDBytes = (buf, eta) => { + const r = new Uint16Array(N); + // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE, + // then swap it back so callers still observe `buf` as read-only. + const b32 = u32(buf); + swap32IfBE(b32); + let len = 0; + for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) { + let b = b32[i]; + for (let j = 0; j < 32; j++) { + bb += b & 1; + b >>= 1; + len += 1; + if (len === eta) { + t0 = bb; + bb = 0; + } + else if (len === 2 * eta) { + r[p++] = crystals.mod(t0 - bb); + bb = 0; + len = 0; + } + } + } + swap32IfBE(b32); + if (len) + throw new Error(`sampleCBD: leftover bits: ${len}`); + return r; +}; +function sampleCBD(PRF_, seed, nonce, eta) { + const PRF = PRF_; + return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta); +} +// K-PKE +// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs +// come from Algorithms 13-15, and the helper mutates decoded temporary +// polynomials in place while leaving caller byte arrays unchanged. +const genKPKE = (opts_) => { + const opts = opts_; + const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts; + const poly1 = polyCoder(1); + const polyV = polyCoder(dv); + const polyU = polyCoder(du); + const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32); + const secretCoder = vecCoder(polyCoder(12), K); + const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV); + const seedCoder = splitCoder('seed', 32, 32); + return { + secretCoder, + lengths: { + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + cipherText: cipherCoder.bytesLen, + }, + keygen: (seed) => { + abytes(seed, 32, 'seed'); + const seedDst = new Uint8Array(33); + seedDst.set(seed); + // FIPS 203 Algorithm 13 appends the parameter-set byte `k` + // before `G(d || k)`, so expanding the same 32-byte seed + // under a different ML-KEM parameter set yields unrelated keys. + seedDst[32] = K; + const seedHash = HASH512(seedDst); + const [rho, sigma] = seedCoder.decode(seedHash); + const sHat = []; + const tHat = []; + for (let i = 0; i < K; i++) + sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1))); + const x = XOF(rho); + for (let i = 0; i < K; i++) { + const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1)); + for (let j = 0; j < K; j++) { + const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace + polyAdd(e, MultiplyNTTs(aji, sHat[j])); + } + tHat.push(e); // t ← A ◦ s + e + } + x.clean(); + const res = { + publicKey: publicCoder.encode([tHat, rho]), + secretKey: secretCoder.encode(sHat), + }; + cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash); + return res; + }, + encrypt: (publicKey, msg, seed) => { + const [tHat, rho] = publicCoder.decode(publicKey); + const rHat = []; + for (let i = 0; i < K; i++) + rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1))); + const x = XOF(rho); + const tmp2 = new Uint16Array(N); + const u = []; + for (let i = 0; i < K; i++) { + const e1 = sampleCBD(PRF, seed, K + i, ETA2); + const tmp = new Uint16Array(N); + for (let j = 0; j < K; j++) { + const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access + polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j] + } + polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp + u.push(e1); + polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i] + cleanBytes(tmp); + } + x.clean(); + const e2 = sampleCBD(PRF, seed, 2 * K, ETA2); + polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2 + const v = poly1.decode(msg); // encode plaintext m into polynomial v + polyAdd(v, e2); // v += e2 + cleanBytes(tHat, rHat, tmp2, e2); + return cipherCoder.encode([u, v]); + }, + decrypt: (cipherText, privateKey) => { + const [u, v] = cipherCoder.decode(cipherText); + const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE) + const tmp = new Uint16Array(N); + // tmp += sk[i] * u[i] + for (let i = 0; i < K; i++) + polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i]))); + polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp + cleanBytes(tmp, sk, u); + return poly1.encode(v); + }, + }; +}; +/** + * Public ML-KEM wrapper over the internal K-PKE subroutine. + * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map + * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20. + * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as + * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on + * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no + * constant-time guarantees for that path. + */ +function createKyber(opts) { + const rawOpts = opts; + const KPKE = genKPKE(rawOpts); + const { HASH256, HASH512, KDF } = rawOpts; + const { secretCoder: KPKESecretCoder, lengths } = KPKE; + const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32); + const msgLen = 32; + const seedLen = 64; + const kemLengths = Object.freeze({ + ...lengths, + seed: 64, + msg: msgLen, + msgRand: msgLen, + secretKey: secretCoder.bytesLen, + }); + return Object.freeze({ + info: Object.freeze({ type: 'ml-kem' }), + lengths: kemLengths, + keygen: (seed = randomBytes(seedLen)) => { + abytes(seed, seedLen, 'seed'); + const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32)); + const publicKeyHash = HASH256(publicKey); + // (dkPKE||ek||H(ek)||z) + const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]); + cleanBytes(sk, publicKeyHash); + return { + publicKey: publicKey, + secretKey: secretKey, + }; + }, + getPublicKey: (secretKey) => { + const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey); + return Uint8Array.from(publicKey); + }, + encapsulate: (publicKey, msg = randomBytes(msgLen)) => { + abytes(publicKey, lengths.publicKey, 'publicKey'); + abytes(msg, msgLen, 'message'); + // FIPS-203 includes additional verification check for modulus + const eke = publicKey.subarray(0, 384 * opts.K); + // Copy because of inplace encoding + const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke))); + // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)). + // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.) + if (!equalBytes(ek, eke)) { + cleanBytes(ek); + throw new Error('ML-KEM.encapsulate: wrong publicKey modulus'); + } + cleanBytes(ek); + // derive randomness + const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest(); + const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + cleanBytes(kr.subarray(32)); + return { + cipherText: cipherText, + sharedSecret: kr.subarray(0, 32), + }; + }, + decapsulate: (cipherText, secretKey) => { + abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96 + abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv) + // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) . + const k768 = secretCoder.bytesLen - 96; + const start = k768 + 32; + const test = HASH256(secretKey.subarray(k768 / 2, start)); + // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed. + if (!equalBytes(test, secretKey.subarray(start, start + 32))) + throw new Error('invalid secretKey: hash check failed'); + const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey); + const msg = KPKE.decrypt(cipherText, sk); + // derive randomness, Khat, rHat = G(mHat || h) + const kr = HASH512.create().update(msg).update(publicKeyHash).digest(); + const Khat = kr.subarray(0, 32); + // re-encrypt using the derived randomness + const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + // if ciphertexts do not match, “implicitly reject” + const isValid = equalBytes(cipherText, cipherText2); + const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest(); + cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar); + return (isValid ? Khat : Kbar); + }, + }); +} +// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces, +// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here. +function shakePRF(dkLen, key, nonce) { + return shake256 + .create({ dkLen }) + .update(key) + .update(new Uint8Array([nonce])) + .digest(); +} +// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call, +// and swapping any field changes the scheme rather than tuning an internal dependency. +const opts = /* @__PURE__ */ (() => ({ + HASH256: sha3_256, + HASH512: sha3_512, + KDF: shake256, + XOF: XOF128, + PRF: shakePRF, +}))(); +// Parameter-set instantiation step for the spec's "ML-KEM-x" names; current correctness relies +// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects. +const mk = (params) => createKyber({ + ...opts, + ...params, +}); +/** + * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem512 = /* @__PURE__ */ (() => mk(PARAMS[512]))(); +/** + * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))(); +/** + * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem1024 = /* @__PURE__ */ (() => mk(PARAMS[1024]))(); +// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available +// without re-implementing them in separate test code. +export const __tests = /* @__PURE__ */ (() => Object.freeze({ + Compress_d: (x, d) => { + if (d < 1 || d > 11) + throw new Error(`Compress_d: expected d in [1..11], got ${d}`); + return compress(d).encode(x) & getMask(d); + }, + Decompress_d: (y, d) => { + if (d < 1 || d > 11) + throw new Error(`Decompress_d: expected d in [1..11], got ${d}`); + return compress(d).decode(y); + }, + ByteEncode_d: (F, d) => { + if (d < 1 || d > 12) + throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`); + return byteCoder(d).encode(F); + }, + ByteDecode_d: (B, d) => { + if (d < 1 || d > 12) + throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`); + return byteCoder(d).decode(B); + }, + NTT: (f) => crystals.NTT.encode(Uint16Array.from(f)), + NTT_inv: (fHat) => crystals.NTT.decode(Uint16Array.from(fHat)), + MultiplyNTTs: (fHat, gHat) => MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)), + SamplePolyCBD: (B, eta) => { + abytes(B, 64 * eta, 'B'); + return sampleCBDBytes(B, eta); + }, + SampleNTT: (B) => { + abytes(B, 34, 'B'); + const xof = XOF128(B.subarray(0, 32)); + try { + return SampleNTT(xof.get(B[32], B[33])); + } + finally { + xof.clean(); + } + }, +}))(); +//# sourceMappingURL=ml-kem.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/ml-kem.js.map b/node_modules/@noble/post-quantum/ml-kem.js.map new file mode 100644 index 0000000..4d13760 --- /dev/null +++ b/node_modules/@noble/post-quantum/ml-kem.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ml-kem.js","sourceRoot":"","sources":["src/ml-kem.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,4EAA4E;AAC5E,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAc,UAAU,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AACrE,OAAO,EAAE,WAAW,EAAY,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC/D,OAAO,EACL,MAAM,EACN,UAAU,EAEV,SAAS,EACT,UAAU,EACV,OAAO,EAEP,WAAW,EACX,UAAU,EAGV,QAAQ,GACT,MAAM,YAAY,CAAC;AAEpB,4CAA4C;AAE5C,MAAM,CAAC,GAAG,GAAG,CAAC,CAAC,oFAAoF;AACnG,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,4BAA4B;AAC5C,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,oCAAoC;AACpD,MAAM,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C,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/package.json b/node_modules/@noble/post-quantum/package.json new file mode 100644 index 0000000..93a2d5c --- /dev/null +++ b/node_modules/@noble/post-quantum/package.json @@ -0,0 +1,86 @@ +{ + "name": "@noble/post-quantum", + "version": "0.6.1", + "description": "Auditable & minimal JS implementation of post-quantum cryptography: FIPS 203, 204, 205, Falcon", + "files": [ + "*.js", + "*.js.map", + "*.d.ts", + "*.d.ts.map", + "src" + ], + "dependencies": { + "@noble/ciphers": "~2.2.0", + "@noble/curves": "~2.2.0", + "@noble/hashes": "~2.2.0" + }, + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "@types/node": "25.3.0", + "fast-check": "4.2.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "node test/benchmark.ts", + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npm run check:readme && npm run check:treeshake && npm run check:jsdoc", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "build:clean": "rm *.{js,js.map,d.ts,d.ts.map} 2> /dev/null", + "format": "prettier --write 'src/**/*.{js,ts}' 'test/**/*.{js,ts,mjs}'", + "test": "node test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts", + "test:node20": "cd test; npx tsc; node compiled/test/index.js", + "test:slow": "SLOW_TESTS=1 node test/index.ts" + }, + "exports": { + ".": "./index.js", + "./_crystals.js": "./_crystals.js", + "./falcon.js": "./falcon.js", + "./hybrid.js": "./hybrid.js", + "./ml-dsa.js": "./ml-dsa.js", + "./ml-kem.js": "./ml-kem.js", + "./slh-dsa.js": "./slh-dsa.js", + "./utils.js": "./utils.js" + }, + "engines": { + "node": ">= 20.19.0" + }, + "keywords": [ + "ml-kem", + "ml-dsa", + "slh-dsa", + "kyber", + "dilithium", + "sphincs", + "fips203", + "fips204", + "fips205", + "falcon", + "xwing", + "kitchensink", + "pqc", + "post-quantum", + "public-key", + "crypto", + "noble", + "cryptography" + ], + "homepage": "https://paulmillr.com/noble/", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/noble-post-quantum.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@noble/post-quantum/slh-dsa.d.ts b/node_modules/@noble/post-quantum/slh-dsa.d.ts new file mode 100644 index 0000000..a251f38 --- /dev/null +++ b/node_modules/@noble/post-quantum/slh-dsa.d.ts @@ -0,0 +1,166 @@ +import { type CHash } from '@noble/hashes/utils.js'; +import { type Signer, type TArg, type TRet } from './utils.ts'; +/** + * * N: Security parameter (in bytes). W: Winternitz parameter + * * H: Hypertree height. D: Hypertree layers + * * K: FORS trees numbers. A: FORS trees height + */ +export type SphincsOpts = { + /** Security parameter in bytes. */ + N: number; + /** Winternitz parameter. */ + W: number; + /** Total hypertree height. */ + H: number; + /** Number of hypertree layers. */ + D: number; + /** Number of FORS trees. */ + K: number; + /** Height of each FORS tree. */ + A: number; + /** Target security level in bits. */ + securityLevel: number; +}; +/** Hash customization options for SLH-DSA context creation. */ +export type SphincsHashOpts = { + /** Whether to use the compressed-address variant from the standard. */ + isCompressed?: boolean; + /** Factory that binds one parameter set to one per-key hash context generator. */ + getContext: GetContext; +}; +/** Winternitz signature params. */ +/** + * Built-in SLH-DSA Table 2 subset keyed by strength/profile. + * SHA2 and SHAKE pairs share the same numeric rows here, so the hash family is chosen separately. + * `securityLevel` stores 128/192/256-bit strengths for `checkHash(...)`, + * not Table 2's category labels 1/3/5. + * Other Table 2 columns such as `m`, public-key bytes, and signature bytes + * stay derived at the export layer. + */ +export declare const PARAMS: Record; +/** Address byte array of size `ADDR_BYTES`. */ +export type ADRS = Uint8Array; +/** Hash and tweakable-hash callbacks bound to one SLH-DSA keypair context. */ +export type Context = { + /** + * Derive a PRF output for one address. + * @param addr - Address bytes. + * @returns PRF output bytes. + */ + PRFaddr: (addr: TArg) => TRet; + /** + * Derive the randomized message hash prefix. + * @param skPRF - Secret PRF seed. + * @param random - Per-signature randomness. + * @param msg - Message bytes. + * @returns PRF output bytes. + */ + PRFmsg: (skPRF: TArg, random: TArg, msg: TArg) => TRet; + /** + * Hash one randomized message transcript. + * @param R - Randomized message prefix. + * @param pk - Public key bytes. + * @param m - Message bytes. + * @param outLen - Output length in bytes. + * @returns Transcript hash bytes. + */ + Hmsg: (R: TArg, pk: TArg, m: TArg, outLen: number) => TRet; + /** + * Tweakable hash over one input block. + * @param input - Input block. + * @param addr - Address bytes. + * @returns Hash output bytes. + */ + thash1: (input: TArg, addr: TArg) => TRet; + /** + * Tweakable hash over multiple input blocks. + * @param blocks - Number of input blocks. + * @param input - Concatenated input bytes. + * @param addr - Address bytes. + * @returns Hash output bytes. + */ + thashN: (blocks: number, input: TArg, addr: TArg) => TRet; + /** Wipe any buffered hash state for the current context. */ + clean: () => void; +}; +/** Factory that creates a context generator for one SLH-DSA parameter set. */ +export type GetContext = (opts: SphincsOpts) => (pub_seed: TArg, sk_seed?: TArg) => TRet; +/** Public SLH-DSA signer with prehash customization. */ +export type SphincsSigner = Signer & { + internal: TRet; + securityLevel: number; + prehash: (hash: TArg) => TRet; +}; +/** + * SLH-DSA-SHAKE-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_128f: TRet; +/** + * SLH-DSA-SHAKE-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_128s: TRet; +/** + * SLH-DSA-SHAKE-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_192f: TRet; +/** + * SLH-DSA-SHAKE-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_192s: TRet; +/** + * SLH-DSA-SHAKE-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_256f: TRet; +/** + * SLH-DSA-SHAKE-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_shake_256s: TRet; +/** + * SLH-DSA-SHA2-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_128f: TRet; +/** + * SLH-DSA-SHA2-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_128s: TRet; +/** + * SLH-DSA-SHA2-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_192f: TRet; +/** + * SLH-DSA-SHA2-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_192s: TRet; +/** + * SLH-DSA-SHA2-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_256f: TRet; +/** + * SLH-DSA-SHA2-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export declare const slh_dsa_sha2_256s: TRet; +//# sourceMappingURL=slh-dsa.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/slh-dsa.d.ts.map b/node_modules/@noble/post-quantum/slh-dsa.d.ts.map new file mode 100644 index 0000000..62d6401 --- /dev/null +++ b/node_modules/@noble/post-quantum/slh-dsa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"slh-dsa.d.ts","sourceRoot":"","sources":["src/slh-dsa.ts"],"names":[],"mappings":"AAgCA,OAAO,EAKL,KAAK,KAAK,EACX,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAcL,KAAK,MAAM,EAEX,KAAK,IAAI,EACT,KAAK,IAAI,EAEV,MAAM,YAAY,CAAC;AAEpB;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG;IACxB,mCAAmC;IACnC,CAAC,EAAE,MAAM,CAAC;IACV,4BAA4B;IAC5B,CAAC,EAAE,MAAM,CAAC;IACV,8BAA8B;IAC9B,CAAC,EAAE,MAAM,C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C;AACxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,CACX,CAAC;AACxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,CACX,CAAC;AACxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,CACX,CAAC;AACxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,CACX,CAAC;AACxC;;;;GAIG;AACH,eAAO,MAAM,iBAAiB,EAAE,IAAI,CAAC,aAAa,CACX,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/slh-dsa.js b/node_modules/@noble/post-quantum/slh-dsa.js new file mode 100644 index 0000000..3e29d1c --- /dev/null +++ b/node_modules/@noble/post-quantum/slh-dsa.js @@ -0,0 +1,747 @@ +/** + * SLH-DSA: StateLess Hash-based Digital Signature Standard from + * [FIPS-205](https://csrc.nist.gov/pubs/fips/205/ipd). A.k.a. Sphincs+ v3.1. + * + * There are many different kinds of SLH, but basically `sha2` / `shake` indicate internal hash, + * `128` / `192` / `256` indicate security level, and `s` /`f` indicate trade-off (Small / Fast). + * + * Hashes function similarly to signatures. You hash a private key to get a public key, + * which can be used to verify the private key. However, this only works once since + * disclosing the pre-image invalidates the key. + * + * To address the "one-time" limitation, we can use a Merkle tree root hash: + * h(h(h(0) || h(1)) || h(h(2) || h(3)))) + * + * This allows us to have the same public key output from the hash, but disclosing one + * path in the tree doesn't invalidate the others. By choosing a path related to the + * message, we can "sign" it. + * + * Limitation: Only a fixed number of signatures can be made. For instance, a Merkle tree + * with depth 8 allows 256 distinct messages. Using different trees for each node can + * prevent forgeries, but the key will still degrade over time. + * + * WOTS: One-time signatures (can be forged if same key used twice). + * FORS: Forest of Random Subsets + * + * Check out [official site](https://sphincs.org) & [repo](https://github.com/sphincs/sphincsplus). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import { bytesToHex, concatBytes, createView, hexToBytes, } from '@noble/hashes/utils.js'; +import { abytes, checkHash, cleanBytes, copyBytes, equalBytes, getMask, getMessage, getMessagePrehash, randomBytes, splitCoder, validateSigOpts, validateVerOpts, vecCoder, } from "./utils.js"; +/** Winternitz signature params. */ +/** + * Built-in SLH-DSA Table 2 subset keyed by strength/profile. + * SHA2 and SHAKE pairs share the same numeric rows here, so the hash family is chosen separately. + * `securityLevel` stores 128/192/256-bit strengths for `checkHash(...)`, + * not Table 2's category labels 1/3/5. + * Other Table 2 columns such as `m`, public-key bytes, and signature bytes + * stay derived at the export layer. + */ +export const PARAMS = /* @__PURE__ */ (() => Object.freeze({ + '128f': Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }), + '128s': Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }), + '192f': Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }), + '192s': Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }), + '256f': Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }), + '256s': Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }), +}))(); +// FIPS 205 `ADRS.setTypeAndClear(...)` selectors. Local names shorten the spec labels +// (`WOTS_HASH` -> `WOTS`, `TREE` -> `HASHTREE`, `FORS_ROOTS` -> `FORSPK`), and `setAddr({ type })` +// below only writes the type word; callers still need to preserve or overwrite the trailing words. +const AddressType = { + WOTS: 0, + WOTSPK: 1, + HASHTREE: 2, + FORSTREE: 3, + FORSPK: 4, + WOTSPRF: 5, + FORSPRF: 6, +}; +function hexToNumber(hex) { + if (typeof hex !== 'string') + throw new Error('hex string expected, got ' + typeof hex); + return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian +} +// BE: Big Endian, LE: Little Endian. This is the local FIPS 205 `toInt(...)` equivalent. +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +// Local in-range FIPS 205 `toByte(x, n)` equivalent; callers must keep `n < 256^len`. +function numberToBytesBE(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} +// Local FIPS 205 Algorithm 4 `base_2^b(...)` implementation. Bits are consumed in big-endian +// order within each input byte, and callers must provide at least `ceil(outLen * b / 8)` bytes; +// short inputs are not rejected and would zero-extend implicitly. +const base2b = (outLen, b) => { + const mask = getMask(b); + return (bytes) => { + const baseB = new Uint32Array(outLen); + for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) { + while (bits < b) { + total = (total << 8) | bytes[pos++]; + bits += 8; + } + bits -= b; + baseB[out] = (total >>> bits) & mask; + } + return baseB; + }; +}; +function getMaskBig(bits) { + return (1n << BigInt(bits)) - 1n; // 4 -> 0b1111 +} +/** One parameter/hash instantiation of the public SLH-DSA API. + * `keygen(seed)` is a deterministic 3N-byte library hook around the internal keygen flow, + * and `getPublicKey(secretKey)` only extracts the embedded public key + * instead of recomputing `PK.root`. + */ +function gen(opts, hashOpts_) { + const hashOpts = hashOpts_; + const { N, W, H, D, K, A, securityLevel: securityLevel } = opts; + const getContext = hashOpts.getContext(opts); + if (W !== 16) + throw new Error('Unsupported Winternitz parameter'); + const WOTS_LOGW = 4; + const WOTS_LEN1 = Math.floor((8 * N) / WOTS_LOGW); + const WOTS_LEN2 = N <= 8 ? 2 : N <= 136 ? 3 : 4; + const TREE_HEIGHT = Math.floor(H / D); + const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2; + let ADDR_BYTES = 22; + let OFFSET_LAYER = 0; + let OFFSET_TREE = 1; + let OFFSET_TYPE = 9; + let OFFSET_KP_ADDR2 = 12; + let OFFSET_KP_ADDR1 = 13; + let OFFSET_CHAIN_ADDR = 17; + let OFFSET_TREE_INDEX = 18; + let OFFSET_HASH_ADDR = 21; + if (!hashOpts.isCompressed) { + ADDR_BYTES = 32; + OFFSET_LAYER += 3; + OFFSET_TREE += 7; + OFFSET_TYPE += 10; + OFFSET_KP_ADDR2 += 10; + OFFSET_KP_ADDR1 += 10; + OFFSET_CHAIN_ADDR += 10; + OFFSET_TREE_INDEX += 10; + OFFSET_HASH_ADDR += 10; + } + // Mutates and returns `addr` in place. For the built-in parameter sets, the layer / chain / + // hash / height / keypair values fit in the low byte(s), and the tree value fits in 64 bits, + // so the untouched leading bytes in the wider FIPS 205 ADRS / ADRS_c fields stay zero. + // `height` / `chain` and `index` / `hash` share the same spec words, so callers must use the + // address-type-specific combinations instead of mixing both meanings in one call. + const setAddr = (opts, addr = new Uint8Array(ADDR_BYTES)) => { + const { type, height, tree, layer, index, chain, hash, keypair } = opts; + const { subtreeAddr, keypairAddr } = opts; + const v = createView(addr); + if (height !== undefined) + addr[OFFSET_CHAIN_ADDR] = height; + if (layer !== undefined) + addr[OFFSET_LAYER] = layer; + if (type !== undefined) + addr[OFFSET_TYPE] = type; + if (chain !== undefined) + addr[OFFSET_CHAIN_ADDR] = chain; + if (hash !== undefined) + addr[OFFSET_HASH_ADDR] = hash; + if (index !== undefined) + v.setUint32(OFFSET_TREE_INDEX, index, false); + if (subtreeAddr) + addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8)); + if (tree !== undefined) + v.setBigUint64(OFFSET_TREE, tree, false); + if (keypair !== undefined) { + addr[OFFSET_KP_ADDR1] = keypair; + if (TREE_HEIGHT > 8) + addr[OFFSET_KP_ADDR2] = keypair >>> 8; + } + if (keypairAddr) { + addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8)); + addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1]; + if (TREE_HEIGHT > 8) + addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2]; + } + return addr; + }; + const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW); + const chainLengths = (msg) => { + const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg); + let csum = 0; + for (let i = 0; i < W1.length; i++) + csum += W - 1 - W1[i]; // ▷ Compute checksum + // csum ← csum ≪ ((8 − ((len2 · lg(w)) mod 8)) mod 8 + csum <<= (8 - ((WOTS_LEN2 * WOTS_LOGW) % 8)) % 8; + // Checksum to base(LOG_W) + const W2 = chainCoder(numberToBytesBE(csum, Math.ceil((WOTS_LEN2 * WOTS_LOGW) / 8))); + // W1 || W2 (concatBytes cannot concat TypedArrays) + const lengths = new Uint32Array(WOTS_LEN); + lengths.set(W1); + lengths.set(W2, W1.length); + return lengths; + }; + const messageToIndices = base2b(K, A); + const TREE_BITS = TREE_HEIGHT * (D - 1); + const LEAF_BITS = TREE_HEIGHT; + const hashMsgCoder = splitCoder('hashedMessage', Math.ceil((A * K) / 8), Math.ceil(TREE_BITS / 8), Math.ceil(TREE_HEIGHT / 8)); + // `pkSeed` is the full public key byte string `PK.seed || PK.root`; after splitting `Hmsg`, + // mask away any spare high bits so `idx_tree` / `idx_leaf` match the spec's final mod-2^k steps. + const hashMessage = (R, pkSeed, msg, context) => { + const rawContext = context; + // digest ← Hmsg(R, PK.seed, PK.root, M) + const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen); + const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest); + const tree = bytesToNumberBE(tmpIdxTree) & getMaskBig(TREE_BITS); + const leafIdx = Number(bytesToNumberBE(tmpIdxLeaf)) & getMask(LEAF_BITS); + return { tree, leafIdx, md }; + }; + // Iterative `xmss_node` / `xmss_sign` core: mutate `treeAddr` in place, collapse completed + // sibling pairs on `stack`, and record the sibling whenever the current subtree is the auth-path + // neighbor of the target leaf at that height. + const treehash = (height, fn) => function treehash_i(context, leafIdx, idxOffset, treeAddr, info) { + const rawContext = context; + const leafFn = fn; + const maxIdx = (1 << height) - 1; + const stack = new Uint8Array(height * N); + const authPath = new Uint8Array(height * N); + for (let idx = 0;; idx++) { + const current = new Uint8Array(2 * N); + const cur0 = current.subarray(0, N); + const cur1 = current.subarray(N); + const addrOffset = idx + idxOffset; + cur1.set(leafFn(leafIdx, addrOffset, rawContext, info)); + let h = 0; + for (let i = idx, o = idxOffset, l = leafIdx;; h++, i >>>= 1, l >>>= 1, o >>>= 1) { + if (h === height) + return { root: cur1, authPath }; // Returns from here + if ((i ^ l) === 1) + authPath.subarray(h * N).set(cur1); // authPath.push(cur1) + if ((i & 1) === 0 && idx < maxIdx) + break; + setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr); + cur0.set(stack.subarray(h * N).subarray(0, N)); + cur1.set(rawContext.thashN(2, current, treeAddr)); + } + stack.subarray(h * N).set(cur1); // stack.push(cur1) + } + // @ts-ignore + throw new Error('Unreachable code path reached, report this error'); + }; + const wotsTreehash = treehash(TREE_HEIGHT, (leafIdx, addrOffset, context, info) => { + const rawContext = context; + const wotsPk = new Uint8Array(WOTS_LEN * N); + // `keygen()` passes `leafIdx = ~0 >>> 0`, so no real XMSS leaf matches and this suppresses + // WOTS signature capture while still hashing every chain to its public-key endpoint. + const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0; + setAddr({ keypair: addrOffset }, info.leafAddr); + setAddr({ keypair: addrOffset }, info.pkAddr); + for (let i = 0; i < WOTS_LEN; i++) { + const wotsK = info.wotsSteps[i] | wotsKmask; + const pk = wotsPk.subarray(i * N, (i + 1) * N); + setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr); + pk.set(rawContext.PRFaddr(info.leafAddr)); + setAddr({ type: AddressType.WOTS }, info.leafAddr); + for (let k = 0;; k++) { + if (k === wotsK) + info.wotsSig.subarray(i * N).set(pk); //wotsSig.push() + if (k === W - 1) + break; + setAddr({ hash: k }, info.leafAddr); + pk.set(rawContext.thash1(pk, info.leafAddr)); + } + } + return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr); + }); + const forsTreehash = treehash(A, (_, addrOffset, context, forsLeafAddr) => { + const rawContext = context; + setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr); + const prf = rawContext.PRFaddr(forsLeafAddr); + setAddr({ type: AddressType.FORSTREE }, forsLeafAddr); + return rawContext.thash1(prf, forsLeafAddr); + }); + // Fuse `xmss_sign` with the subtree-root computation needed by `ht_sign`, so one tree walk + // yields both the WOTS/auth-path signature and the root that the next hypertree layer signs. + const merkleSign = (context, wotsAddr, treeAddr, leafIdx, prevRoot = new Uint8Array(N)) => { + setAddr({ type: AddressType.HASHTREE }, treeAddr); + // State variables + const info = { + wotsSig: new Uint8Array(wotsCoder.bytesLen), + wotsSteps: chainLengths(prevRoot), + leafAddr: setAddr({ subtreeAddr: wotsAddr }), + pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }), + }; + const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info); + return { + root, + sigWots: info.wotsSig.subarray(0, WOTS_LEN * N), + sigAuth: authPath, + }; + }; + const computeRoot = (leaf, leafIdx, idxOffset, authPath, treeHeight, context, addr) => { + const rawContext = context; + const buffer = new Uint8Array(2 * N); + const b0 = buffer.subarray(0, N); + const b1 = buffer.subarray(N, 2 * N); + // Algorithm 11 hashes `node || AUTH[k]` for even nodes and `AUTH[k] || node` for odd ones, + // so reuse one `2N` buffer and just swap which half receives the sibling at each level. + // `idxOffset` carries the subtree base for the shared FORS path, so `leafIdx + idxOffset` + // tracks the same tree-global index updates that Algorithms 11 and 17 apply to ADRS. + // First iter + if ((leafIdx & 1) !== 0) { + b1.set(leaf.subarray(0, N)); + b0.set(authPath.subarray(0, N)); + } + else { + b0.set(leaf.subarray(0, N)); + b1.set(authPath.subarray(0, N)); + } + leafIdx >>>= 1; + idxOffset >>>= 1; + // Rest + for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) { + setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr); + const a = authPath.subarray((i + 1) * N, (i + 2) * N); + if ((leafIdx & 1) !== 0) { + b1.set(rawContext.thashN(2, buffer, addr)); + b0.set(a); + } + else { + buffer.set(rawContext.thashN(2, buffer, addr)); + b1.set(a); + } + } + // Root + setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr); + return rawContext.thashN(2, buffer, addr); + }; + const seedCoder = splitCoder('seed', N, N, N); + const publicCoder = splitCoder('publicKey', N, N); + const secretCoder = splitCoder('secretKey', N, N, publicCoder.bytesLen); + const forsCoder = vecCoder(splitCoder('fors', N, N * A), K); + const wotsCoder = vecCoder(splitCoder('wots', WOTS_LEN * N, TREE_HEIGHT * N), D); + const sigCoder = splitCoder('signature', N, forsCoder, wotsCoder); // random || fors || wots + const internal = Object.freeze({ + info: Object.freeze({ type: 'internal-slh-dsa' }), + lengths: Object.freeze({ + publicKey: publicCoder.bytesLen, + secretKey: secretCoder.bytesLen, + signature: sigCoder.bytesLen, + seed: seedCoder.bytesLen, + signRand: N, + }), + keygen(seed) { + if (seed !== undefined) + abytes(seed, seedCoder.bytesLen, 'seed'); + seed = seed === undefined ? randomBytes(seedCoder.bytesLen) : copyBytes(seed); + // Set SK.seed, SK.prf, and PK.seed to random n-byte + const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed); + const context = getContext(publicSeed, secretSeed); + // ADRS.setLayerAddress(d − 1) + const topTreeAddr = setAddr({ layer: D - 1 }); + const wotsAddr = setAddr({ layer: D - 1 }); + //PK.root ←_xmss node(SK.seed, 0, h′, PK.seed, ADRS) + const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0); + const publicKey = publicCoder.encode([publicSeed, root]); + const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]); + context.clean(); + cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr); + return { + publicKey: publicKey, + secretKey: secretKey, + }; + }, + getPublicKey: (secretKey) => { + const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey); + return Uint8Array.from(pk); + }, + sign: (msg, sk, opts = {}) => { + validateSigOpts(opts); + let { extraEntropy: random } = opts; + const [skSeed, skPRF, pk] = secretCoder.decode(sk); // todo: fix + const [pkSeed, _] = publicCoder.decode(pk); + // Set opt_rand to either PK.seed or to a random n-byte string + if (random === false) + random = copyBytes(pkSeed); + else if (random === undefined) + random = randomBytes(N); + else + random = copyBytes(random); + abytes(random, N); + const context = getContext(pkSeed, skSeed); + // Generate randomizer + const R = context.PRFmsg(skPRF, random, msg); // R ← PRFmsg(SK.prf, opt_rand, M) + let { tree, leafIdx, md } = hashMessage(R, pk, msg, context); + // Create FORS signatures + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx, + }); + const roots = []; + const forsLeaf = setAddr({ keypairAddr: wotsAddr }); + const forsTreeAddr = setAddr({ keypairAddr: wotsAddr }); + const indices = messageToIndices(md); + const fors = []; + for (let i = 0; i < indices.length; i++) { + const idxOffset = i << A; + setAddr({ + type: AddressType.FORSPRF, + height: 0, + index: indices[i] + idxOffset, + }, forsTreeAddr); + const prf = context.PRFaddr(forsTreeAddr); + setAddr({ type: AddressType.FORSTREE }, forsTreeAddr); + const { root, authPath } = forsTreehash(context, indices[i], idxOffset, forsTreeAddr, forsLeaf); + roots.push(root); + fors.push([prf, authPath]); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr, + }); + const root = context.thashN(K, concatBytes(...roots), forsPkAddr); + // WOTS signatures + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wots = []; + for (let i = 0; i < D; i++, tree >>= BigInt(TREE_HEIGHT)) { + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + const { sigWots, sigAuth, root: r, } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root); + root.set(r); + cleanBytes(r); + wots.push([sigWots, sigAuth]); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + context.clean(); + const SIG = sigCoder.encode([R, fors, wots]); + cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots); + return SIG; + }, + verify: (sig, msg, publicKey) => { + const [pkSeed, pubRoot] = publicCoder.decode(publicKey); + const [random, forsVec, wotsVec] = sigCoder.decode(sig); + const pk = publicKey; + if (sig.length !== sigCoder.bytesLen) + return false; + const context = getContext(pkSeed); + let { tree, leafIdx, md } = hashMessage(random, pk, msg, context); + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx, + }); + // FORS signature + const roots = []; + const forsTreeAddr = setAddr({ + type: AddressType.FORSTREE, + keypairAddr: wotsAddr, + }); + const indices = messageToIndices(md); + for (let i = 0; i < forsVec.length; i++) { + const [prf, authPath] = forsVec[i]; + const idxOffset = i << A; + setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr); + const leaf = context.thash1(prf, forsTreeAddr); + // Compute inplace, because we need all roots in same byte array + roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr)); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr, + }); + let root = context.thashN(K, concatBytes(...roots), forsPkAddr); // root = thash() + // WOTS signature + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wotsPkAddr = setAddr({ type: AddressType.WOTSPK }); + const wotsPk = new Uint8Array(WOTS_LEN * N); + for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) { + const [wots, sigAuth] = wotsVec[i]; + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + setAddr({ keypairAddr: wotsAddr }, wotsPkAddr); + const lengths = chainLengths(root); + for (let i = 0; i < WOTS_LEN; i++) { + setAddr({ chain: i }, wotsAddr); + const steps = W - 1 - lengths[i]; + const start = lengths[i]; + const out = wotsPk.subarray(i * N); + out.set(wots.subarray(i * N, (i + 1) * N)); + for (let j = start; j < start + steps && j < W; j++) { + setAddr({ hash: j }, wotsAddr); + out.set(context.thash1(out, wotsAddr)); + } + } + const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr); + root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + return equalBytes(root, pubRoot); + }, + }); + return Object.freeze({ + info: Object.freeze({ type: 'slh-dsa' }), + internal, + securityLevel: securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts = {}) => { + validateSigOpts(opts); + const M = getMessage(msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts = {}) => { + validateVerOpts(opts); + return internal.verify(sig, getMessage(msg, opts.context), publicKey); + }, + prehash: (hash) => { + checkHash(hash, securityLevel); + const rawHash = hash; + return Object.freeze({ + info: Object.freeze({ type: 'hashslh-dsa' }), + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts = {}) => { + validateSigOpts(opts); + const M = getMessagePrehash(rawHash, msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts = {}) => { + validateVerOpts(opts); + return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey); + }, + }); + }, + }); +} +// FIPS 205 §11.1 SHAKE instantiation: this path hashes the full uncompressed address bytes, +// unlike the compressed 22-byte SHA2 path in §11.2. +const genShake = () => (opts) => (pubSeed, skSeed) => { + const { N } = opts; + const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0 }; + // §11.1 prefixes PRF/F/H/T_l with `PK.seed`, so cache that absorbed prefix once and clone it + // for each address-bound call instead of reabsorbing the same seed every time. + const h0 = shake256.create({}).update(pubSeed); + const h0tmp = h0.clone(); + const thash = (blocks, input, addr) => { + stats.thash++; + return h0 + ._cloneInto(h0tmp) + .update(addr) + .update(input.subarray(0, blocks * N)) + .xof(N); + }; + return { + PRFaddr: (addr) => { + if (!skSeed) + throw new Error('no sk seed'); + stats.prf++; + const res = h0._cloneInto(h0tmp).update(addr).update(skSeed).xof(N); + return res; + }, + PRFmsg: (skPRF, random, msg) => { + stats.gen_message_random++; + return shake256 + .create({}) + .update(skPRF) + .update(random) + .update(msg) + .digest() + .subarray(0, N); + }, + Hmsg: (R, pk, m, outLen) => { + stats.hmsg++; + return shake256.create({}).update(R.subarray(0, N)).update(pk).update(m).xof(outLen); + }, + thash1: thash.bind(null, 1), + thashN: thash, + clean: () => { + h0.destroy(); + h0tmp.destroy(); + //console.log(stats); + }, + }; +}; +const SHAKE_SIMPLE = /* @__PURE__ */ (() => ({ getContext: genShake() }))(); +/** + * SLH-DSA-SHAKE-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_128f = /* @__PURE__ */ (() => gen(PARAMS['128f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_128s = /* @__PURE__ */ (() => gen(PARAMS['128s'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_192f = /* @__PURE__ */ (() => gen(PARAMS['192f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_192s = /* @__PURE__ */ (() => gen(PARAMS['192s'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_256f = /* @__PURE__ */ (() => gen(PARAMS['256f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_256s = /* @__PURE__ */ (() => gen(PARAMS['256s'], SHAKE_SIMPLE))(); +// FIPS 205 §11.2 SHA2 instantiation. The `h0` / `h1` split is intentional: +// category-1 keeps everything on SHA-256, while category-3/5 keep `PRFaddr` / `thash1` +// on SHA-256 but switch `PRFmsg`, `Hmsg`, and multi-block `thashN` to SHA-512. +const genSha = (h0, h1) => (opts) => (pub_seed, sk_seed) => { + const { N } = opts; + /* + Perf debug stats, how much hashes we call? + 128f_simple: { prf: 8305, thash: 96_922, hmsg: 1, gen_message_random: 1, mgf1: 2 } + 256s_robust: { prf: 497_686, thash: 2_783_203, hmsg: 1, gen_message_random: 1, mgf1: 2_783_205} + 256f_simple: { prf: 36_179, thash: 309_693, hmsg: 1, gen_message_random: 1, mgf1: 2 } + */ + const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 }; + const counterB = new Uint8Array(4); + const counterV = createView(counterB); + // §11.2 prefixes SHA2 PRF/F/H/T_l with `PK.seed || toByte(0, blockLen-N)`, so cache the + // zero-padded seed block once for the SHA-256 lane and once for the SHA-512 lane. + const h0ps = h0 + .create() + .update(pub_seed) + .update(new Uint8Array(h0.blockLen - N)); + const h1ps = h1 + .create() + .update(pub_seed) + .update(new Uint8Array(h1.blockLen - N)); + const h0tmp = h0ps.clone(); + const h1tmp = h1ps.clone(); + // https://www.rfc-editor.org/rfc/rfc8017.html#appendix-B.2.1 + // This local helper is intentionally stricter than generic MGF1 reuse: current SLH-DSA callers + // only request tiny `m`-byte outputs, but the guard below rejects `length > 2^32` instead of + // RFC 8017's broader `maskLen > 2^32 * hLen` bound. + function mgf1(seed, length, hash) { + stats.mgf1++; + const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen); + // NOT 2^32-1 + if (length > 2 ** 32) + throw new Error('mask too long'); + for (let counter = 0, o = out; o.length; counter++) { + counterV.setUint32(0, counter, false); + hash.create().update(seed).update(counterB).digestInto(o); + o = o.subarray(hash.outputLen); + } + cleanBytes(out.subarray(length)); + return out.subarray(0, length); + } + const thash = (_, h, hTmp) => (blocks, input, addr) => { + stats.thash++; + const d = h + ._cloneInto(hTmp) + .update(addr) + .update(input.subarray(0, blocks * N)) + .digest(); + return d.subarray(0, N); + }; + return { + PRFaddr: (addr) => { + if (!sk_seed) + throw new Error('No sk seed'); + stats.prf++; + const res = h0ps + ._cloneInto(h0tmp) + .update(addr) + .update(sk_seed) + .digest() + .subarray(0, N); + return res; + }, + PRFmsg: (skPRF, random, msg) => { + stats.gen_message_random++; + return hmac + .create(h1, skPRF) + .update(random) + .update(msg) + .digest() + .subarray(0, N); + }, + Hmsg: (R, pk, m, outLen) => { + stats.hmsg++; + const seed = concatBytes(R.subarray(0, N), pk.subarray(0, N), h1.create().update(R.subarray(0, N)).update(pk).update(m).digest()); + return mgf1(seed, outLen, h1); + }, + thash1: thash(h0, h0ps, h0tmp).bind(null, 1), + thashN: thash(h1, h1ps, h1tmp), + clean: () => { + h0ps.destroy(); + h1ps.destroy(); + h0tmp.destroy(); + h1tmp.destroy(); + //console.log(stats); + }, + }; +}; +const SHA256_SIMPLE = /* @__PURE__ */ (() => ({ + isCompressed: true, + getContext: genSha(sha256, sha256), +}))(); +const SHA512_SIMPLE = /* @__PURE__ */ (() => ({ + isCompressed: true, + getContext: genSha(sha256, sha512), +}))(); +/** + * SLH-DSA-SHA2-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_128f = /* @__PURE__ */ (() => gen(PARAMS['128f'], SHA256_SIMPLE))(); +/** + * SLH-DSA-SHA2-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_128s = /* @__PURE__ */ (() => gen(PARAMS['128s'], SHA256_SIMPLE))(); +/** + * SLH-DSA-SHA2-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_192f = /* @__PURE__ */ (() => gen(PARAMS['192f'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_192s = /* @__PURE__ */ (() => gen(PARAMS['192s'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_256f = /* @__PURE__ */ (() => gen(PARAMS['256f'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_256s = /* @__PURE__ */ (() => gen(PARAMS['256s'], SHA512_SIMPLE))(); +//# sourceMappingURL=slh-dsa.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/slh-dsa.js.map b/node_modules/@noble/post-quantum/slh-dsa.js.map new file mode 100644 index 0000000..6355057 --- /dev/null +++ b/node_modules/@noble/post-quantum/slh-dsa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"slh-dsa.js","sourceRoot":"","sources":["src/slh-dsa.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,4EAA4E;AAC5E,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACjD,OAAO,EACL,UAAU,EACV,WAAW,EACX,UAAU,EACV,UAAU,GAEX,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,MAAM,EACN,SAAS,EACT,UAAU,EACV,SAAS,EACT,UAAU,EACV,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,WAAW,EACX,UAAU,EACV,eAAe,EACf,eAAe,EACf,QAAQ,GAMT,MAAM,YAAY,CAAC;AAgCpB,mCAAmC;AACnC;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,MAAM,GAAgC,eAAe,CAAC,CAAC,GAAG,EAAE,CACvE,MAAM,CAAC,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,EAAE,CA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ACxC;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAwB,eAAe,CAAC,CAAC,GAAG,EAAE,CAC1E,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,aAAa,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/src/_crystals.ts b/node_modules/@noble/post-quantum/src/_crystals.ts new file mode 100644 index 0000000..f6c3df3 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/_crystals.ts @@ -0,0 +1,280 @@ +/** + * Internal methods for lattice-based ML-KEM and ML-DSA. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { FFTCore, reverseBits } from '@noble/curves/abstract/fft.js'; +import { shake128, shake256 } from '@noble/hashes/sha3.js'; +import type { TypedArray } from '@noble/hashes/utils.js'; +import { + type BytesCoderLen, + cleanBytes, + type Coder, + getMask, + type TArg, + type TRet, +} from './utils.ts'; + +/** Extendable-output reader used by the CRYSTALS implementations. */ +export type XOF = ( + seed: Uint8Array, + blockLen?: number +) => { + /** + * Read diagnostic counters for the current XOF session. + * @returns Current call and XOF block counters. + */ + stats: () => { calls: number; xofs: number }; + /** + * Select one `(x, y)` coordinate pair and get a block reader for it. + * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared + * SHAKE state and invalidates older readers. + * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they + * want to retain before the next read. + * @param x - First matrix coordinate. + * @param y - Second matrix coordinate. + * @returns Lazy block reader for that coordinate pair. + */ + get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3 + /** Wipe any buffered state once the reader is no longer needed. */ + clean: () => void; +}; + +/** CRYSTALS (ml-kem, ml-dsa) options */ +/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */ +export type CrystalOpts = { + /** + * Allocate one zeroed polynomial/vector container. + * @param n - Number of coefficients to allocate. + * @returns Fresh typed container. + */ + newPoly: TypedCons; + /** Polynomial size, typically `256`. */ + N: number; + /** Prime modulus used for all coefficient arithmetic. */ + Q: number; + /** Inverse transform normalization factor: + * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber. + */ + F: number; + /** Principal root of unity for the transform domain. */ + ROOT_OF_UNITY: number; + /** Number of bits used for bit-reversal ordering. */ + brvBits: number; + /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */ + isKyber: boolean; +}; + +/** Constructor function for typed polynomial containers. */ +export type TypedCons = (n: number) => T; + +type Crystals = { + mod: (a: number, modulo?: number) => number; + smod: (a: number, modulo?: number) => number; + nttZetas: T; + NTT: { + /** Forward transform in place. Mutates and returns `r`. */ + encode: (r: T) => T; + /** Inverse transform in place. Mutates and returns `r`. */ + decode: (r: T) => T; + }; + bitsCoder: (d: number, c: Coder) => BytesCoderLen; +}; + +/** + * Creates shared modular arithmetic, NTT, and packing helpers for CRYSTALS schemes. + * @param opts - Polynomial and transform parameters. See {@link CrystalOpts}. + * @returns CRYSTALS arithmetic and encoding helpers. + * @example + * Create shared modular arithmetic and NTT helpers for a CRYSTALS parameter set. + * ```ts + * const crystals = genCrystals({ + * newPoly: (n) => new Uint16Array(n), + * N: 256, + * Q: 3329, + * F: 3303, + * ROOT_OF_UNITY: 17, + * brvBits: 7, + * isKyber: true, + * }); + * const reduced = crystals.mod(-1); + * ``` + */ +export const genCrystals = (opts: CrystalOpts): TRet> => { + // isKyber: true means Kyber, false means Dilithium + const { newPoly, N, Q, F, ROOT_OF_UNITY, brvBits, isKyber } = opts; + // Normalize JS `%` into the canonical Z_m representative `[0, modulo-1]` expected by + // FIPS 203 §2.3 / FIPS 204 §2.3 before downstream mod-q arithmetic. + const mod = (a: number, modulo = Q): number => { + const result = a % modulo | 0; + return (result >= 0 ? result | 0 : (modulo + result) | 0) | 0; + }; + // FIPS 204 §7.4 uses the centered `mod ±` representative for low bits, keeping the + // positive midpoint when `modulo` is even. + // Center to `[-floor((modulo-1)/2), floor(modulo/2)]`. + const smod = (a: number, modulo = Q): number => { + const r = mod(a, modulo) | 0; + return (r > modulo >> 1 ? (r - modulo) | 0 : r) | 0; + }; + // Kyber uses the FIPS 203 Appendix A `BitRev_7` table here via the first 128 entries, while + // Dilithium uses the FIPS 204 §7.5 / Appendix B `BitRev_8` zetas table over all 256 entries. + function getZettas() { + const out = newPoly(N); + for (let i = 0; i < N; i++) { + const b = reverseBits(i, brvBits); + const p = BigInt(ROOT_OF_UNITY) ** BigInt(b) % BigInt(Q); + out[i] = Number(p) | 0; + } + return out; + } + const nttZetas = getZettas(); + + // Number-Theoretic Transform + // Explained: https://electricdusk.com/ntt.html + + // Kyber has slightly different params, since there is no 512th primitive root of unity mod q, + // only 256th primitive root of unity mod. Which also complicates MultiplyNTT. + + const field = { + add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0, + sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0, + mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0, + inv: (_a: number) => { + throw new Error('not implemented'); + }, + }; + const nttOpts = { + N, + roots: nttZetas as any, + invertButterflies: true, + skipStages: isKyber ? 1 : 0, + brp: false, + }; + const dif = FFTCore(field, { dit: false, ...nttOpts }); + const dit = FFTCore(field, { dit: true, ...nttOpts }); + const NTT = { + encode: (r: T): T => { + return dif(r) as any; + }, + decode: (r: T): T => { + dit(r as any); + // The inverse-NTT normalization factor is family-specific: FIPS 203 Algorithm 10 line 14 + // uses `128^-1 mod q` for Kyber, while FIPS 204 Algorithm 42 lines 21-23 use `256^-1 mod q`. + // kyber uses 128 here, because brv && stuff + for (let i = 0; i < r.length; i++) r[i] = mod(F * r[i]); + return r; + }, + }; + // Pack one little-endian `d`-bit word per coefficient, matching FIPS 203 ByteEncode / + // ByteDecode and the FIPS 204 BitsToBytes-based polynomial packing helpers. + const bitsCoder = (d: number, c: Coder): TRet> => { + const mask = getMask(d); + const bytesLen = d * (N / 8); + return { + bytesLen, + encode: (poly_: TArg): TRet => { + const poly = poly_ as T; + const r = new Uint8Array(bytesLen); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { + buf |= (c.encode(poly[i]) & mask) << bufLen; + bufLen += d; + for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen); + } + return r as TRet; + }, + decode: (bytes: TArg): TRet => { + const r = newPoly(N); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { + buf |= bytes[i] << bufLen; + bufLen += 8; + for (; bufLen >= d; bufLen -= d, buf >>= d) r[pos++] = c.decode(buf & mask); + } + return r as TRet; + }, + } as TRet>; + }; + + return { + mod, + smod, + nttZetas: nttZetas as TRet, + NTT: { + encode: (r: TArg): TRet => NTT.encode(r as T) as TRet, + decode: (r: TArg): TRet => NTT.decode(r as T) as TRet, + }, + bitsCoder: bitsCoder as TRet>['bitsCoder'], + }; +}; + +const createXofShake = + (shake: typeof shake128): TRet => + (seed: TArg, blockLen?: number) => { + if (!blockLen) blockLen = shake.blockLen; + // Optimizations that won't mater: + // - cached seed update (two .update(), on start and on the end) + // - another cache which cloned into working copy + + // Faster than multiple updates, since seed less than blockLen + const _seed = new Uint8Array(seed.length + 2); + _seed.set(seed); + const seedLen = seed.length; + const buf = new Uint8Array(blockLen); // == shake128.blockLen + let h = shake.create({}); + let calls = 0; + let xofs = 0; + return { + stats: () => ({ calls, xofs }), + get: (x: number, y: number) => { + // Rebind to `seed || x || y` so callers can implement the spec's per-coordinate + // SHAKE inputs like `rho || j || i` and `rho || IntegerToBytes(counter, 2)`. + _seed[seedLen + 0] = x; + _seed[seedLen + 1] = y; + h.destroy(); + h = shake.create({}).update(_seed); + calls++; + return () => { + xofs++; + return h.xofInto(buf) as TRet; + }; + }, + clean: () => { + h.destroy(); + cleanBytes(buf, _seed); + }, + }; + }; + +/** + * SHAKE128-based extendable-output reader factory used by ML-KEM. + * `get(x, y)` selects one coordinate pair at a time; calling it again invalidates previously + * returned readers, and each squeeze reuses one mutable internal output buffer. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-KEM SHAKE128 matrix expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF128 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF128(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export const XOF128: TRet = /* @__PURE__ */ createXofShake(shake128); +/** + * SHAKE256-based extendable-output reader factory used by ML-DSA. + * `get(x, y)` appends raw one-byte coordinates to the seed, invalidates previously returned + * readers, and reuses one mutable internal output buffer for each squeeze. + * @param seed - Seed bytes for the reader. + * @param blockLen - Optional output block length. + * @returns Stateful XOF reader. + * @example + * Build the ML-DSA SHAKE256 coefficient expander and read one block. + * ```ts + * import { randomBytes } from '@noble/post-quantum/utils.js'; + * import { XOF256 } from '@noble/post-quantum/_crystals.js'; + * const reader = XOF256(randomBytes(32)); + * const block = reader.get(0, 0)(); + * ``` + */ +export const XOF256: TRet = /* @__PURE__ */ createXofShake(shake256); diff --git a/node_modules/@noble/post-quantum/src/falcon.ts b/node_modules/@noble/post-quantum/src/falcon.ts new file mode 100644 index 0000000..43c8724 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/falcon.ts @@ -0,0 +1,2503 @@ +/** + * Falcon pq-friendly signature algorithm. + * Will change in backwards-incompatible way once FIPS-206 gets finalized. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { rngAesCtrDrbg256 } from '@noble/ciphers/aes.js'; +import { chacha20 } from '@noble/ciphers/chacha.js'; +import { FFTCore } from '@noble/curves/abstract/fft.js'; +import type { IField } from '@noble/curves/abstract/modular.js'; +import { invert } from '@noble/curves/abstract/modular.js'; +import { bytesToNumberLE, numberToHexUnpadded } from '@noble/curves/utils.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import { + abytes, + bytesToHex, + createView, + hexToBytes, + randomBytes, + swap32IfBE, + type TypedArray, + u32, + u8, +} from '@noble/hashes/utils.js'; +import { genCrystals, type TypedCons } from './_crystals.ts'; +import { + baswap64If, + type BytesCoderLen, + cleanBytes, + type Coder, + type CryptoKeys, + getMask, + type Signer, + type SigOpts, + splitCoder, + type TArg, + type TRet, + validateSigOpts, + validateVerOpts, + type VerOpts, +} from './utils.ts'; +/* +FIPS-206 would likely improve the situation with spec. + +Falcon (non-FIPS) spec is terrible. Two main issues: non-deterministic keys & floats. + +## Summary + +- NIST round3 KATs pass +- No interop with other JS libraries, because they are incorrect +- No recoverPublicKey: it requires s1, which is calculated from public+s2. Sig only has s2. +- Code has verify_recover, but it's unused +- Mediocre code quality, primarily because it follows implementation-specific (C lib) tidbits +- Samplers are fragile + +## Non-deterministic keys + +Falcon spec doesn't provide enough data to re-create keys from KAT vectors. Spec mentions: +> This process reduces the maximum sizes of coefficients of F and G +> by about 30 bits at each iteration +While actual implementation reduces them by 25 bits (scale_k), which is very important detail. + +There are also various implementation checks not mentioned in spec, like +> let's skip this perfectly valid key, because it doesn't fit into our bigint implementation + +Without these, it's hard to produce correct keys. This means that, +unless NIST specifies full process with all operations, +**all keys are implementation-specific**. + +Which means, we cannot use any key derivation schemes here: same seed will return +different keys in different implementations. + +This also complicates testing a lot. If a key succesfully signs a message and other implementations +confirm it, there is still zero assurance with regards to quality / entropy of the key. +One can create a valid key, which nevertheless doesn't have enough entropy. + +## Floats + +Partially fixed by "fixed point" primitive. Falcon basically impelements floats on top of u64. + +It's more constant-time, but in JS there is no **fast** u64: + +- Using bigint backend would drop const-timeness +- Using u32 {hi, low} tuples means unnecessary allocations / jit deopt, + and is still 4 times slower than Floats + +Then, there are rounding issues. This is implementation specific. +This matters more for C, since 'double' is not neccesarily binary64. +In js, floats guaranteed to be IEEE-754 binary64. + +In theory floats are nice, but since fixed point format is not specified in spec +(other that "it is binary64"), this is even more fragile, since it doesn't implement exact +full spec of binary64 (two zeros/subnomarls/nans/etc). Those parts should not be used inside falcon, +but may cause some differences. + +Lack of specification is also hard to debug, brings precision loss (a+b+c !== a+c+b): +there are no serialized floats, all float arithmetic happens inside of an algorithm, so +we can produce same results (small differences rounded at the end). + +For byte-to-byte result in falcon, one needs to copy implementation-specific details, unspecced. + +## CSPRNG + +NIST KATs randomness situation is bad: + +1. aes-drbg generates seed +2. The seed passes CSPRNG into sign, which uses shake256 to produce another seed and nonce +3. Then a separate rejection sampling chacha20 CSPRNG is created, based on that seed. + +## Detached vs non-detached + +The API is different between detached / non-detached signatures, +however only non-detached (sm) is included in KAT, so we implement them +(crypto_sign_open instead of crypto_sign_verify). +*/ + +// Utils +// MSB first. Current Falcon uses are byte-aligned only, and outer wrappers must still enforce +// exact body lengths / canonical padding because this helper neither flushes nor rejects a final +// partial field on its own. +const bitsCoderMSB = ( + newPoly: TypedCons, + N: number, + d: number, + c: Coder +): TRet> => { + const mask = getMask(d); + const bytesLen = d * (N / 8); + return { + bytesLen, + encode: (poly: TArg): TRet => { + if (poly.length !== N) throw new Error(`wrong length: expected ${N}, got ${poly.length}`); + const r = new Uint8Array(bytesLen); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { + buf = (buf << d) | (c.encode(poly[i]) & mask); + bufLen += d; + for (; bufLen >= 8; bufLen -= 8) r[pos++] = (buf >>> (bufLen - 8)) & 0xff; + } + return r as TRet; + }, + decode: (bytes: TArg): TRet => { + const r = newPoly(N); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { + buf = (buf << 8) | bytes[i]; + bufLen += 8; + for (; bufLen >= d; bufLen -= d) r[pos++] = c.decode((buf >>> (bufLen - d)) & mask); + } + return r as TRet; + }, + } as TRet>; +}; +// Adds a single leading tag byte. Exact body validation is delegated to `restCoder.decode()`. +// encode() zeroizes the temporary encoded body after copying, so wrapped encoders must return +// owned scratch bytes rather than caller-owned buffers. +const headerCoder = (tag: number, restCoder: TArg>): TRet> => { + const coder = restCoder as BytesCoderLen; + return { + bytesLen: 1 + coder.bytesLen, + encode(value: TArg): TRet { + const body = coder.encode(value as T); + const out = new Uint8Array(1 + body.length); + out[0] = tag; + out.set(body, 1); + cleanBytes(body); + return out as TRet; + }, + decode(data: TArg): TRet { + if (data[0] !== tag) throw new Error(`wrong tag: expected ${tag}, got 0x${data[0]}`); + return coder.decode(data.subarray(1)) as TRet; + }, + } as TRet>; +}; + +// Fun, but overengineered. Hoping FIPS would fix this. +// Falcon-specific Golomb-Rice compressed format: +// Vec<[1bit sign, 7 bit low, array(1 terminated).length==high <<7]>. +// decode() returns only coefficients, so callers must still enforce exact consumed length / +// canonical framing around the payload. +const compCoder = (n: number) => { + const LIMIT = 2047; + return { + encode(data: TArg): TRet { + // Algorithm 17: Compress(s, slen) (Page 47) + // Require: A polynomial s = Σ sᵢxⁱ ∈ Z[x] of degree < n, a string bitlength slen + // Ensure: A compressed representation str of s of slen bits, or ⊥ + // 1: str ← {} ▷ str is the empty string + // 2: for i from 0 to n-1 do ▷ At each step, str ← (str||strᵢ), where strᵢ encodes sᵢ + // 3: str ← (str||b), where b = 1 if sᵢ < 0, b = 0 otherwise ▷ Encode the sign of sᵢ + // 4: str ← (str||b₆b₅...b₀), where bⱼ = (|sᵢ| >> j) & 0x1 + // ▷ Encode in binary the low bits of |sᵢ| + // 5: k ← |sᵢ| >> 7 + // 6: str ← (str||0ᵏ1) ▷ Encode in unary the high bits of |sᵢ| + // 7: if |str| > slen then + // 8: str ← ⊥ ▷ Abort if str is too long + // 9: else + // 10: str ← (str||0^{slen-|str|}) ▷ Pad str to slen bits + // 11: return str + if (data.length !== n) throw new Error('wrong length'); + const res: number[] = []; + let buf = 0; + let bufLen = 0; + const writeBits = (n: number, v: number) => { + bufLen += n; + buf = (buf << n) | v; + // flush buffer if bigger than byte + for (; bufLen >= 8; buf &= getMask(bufLen)) { + bufLen -= 8; + res.push((buf >>> bufLen) & 0xff); + } + }; + for (let i = 0; i < n; i++) { + let v = data[i]; + if (!Number.isInteger(v) || v < -LIMIT || v > LIMIT) + throw new Error(`data[${i}]=${v} out of range`); + const sign = v < 0 ? 1 : 0; + v = Math.abs(v); + writeBits(1, sign); + writeBits(7, v & 0b0111_1111); // low + writeBits((v >>> 7) + 1, 1); // high (unary) + } + if (bufLen > 0) res.push((buf << (8 - bufLen)) & 0xff); + return new Uint8Array(res) as TRet; + }, + decode(data: TArg): TRet { + // Algorithm 18: Decompress(str, slen), (Page 48) + // Require: A bitstring str = (str[i])_{i=0,...,slen-1}, a bitlength slen + // Ensure: A polynomial s = Σ sᵢxⁱ ∈ Z[x], or ⊥ + // 1: if |str| ≠ slen then ▷ Enforce fixed bitlength + // 2: return ⊥ + // 3: for i from 0 to (n-1) do + // 4: s'ᵢ ← Σ_{j=0 to 6} 2⁶⁻ʲ · str[1 + j] ▷ We recover the lowest bits of |sᵢ|. + // 5: k ← 0 + // 6: while str[8 + k] = 0 do ▷ We recover the highest bits of |sᵢ|. + // 7: k ← k + 1 + // 8: sᵢ ← (-1)^{str[0]} · (s'ᵢ + 2⁷k) ▷ We recompute sᵢ. + // 9: if (sᵢ = 0) and (str[0] = 1) then ▷ Enforce unique encoding if sᵢ = 0 + // 10: return ⊥ + // 11: str ← str with first 9 + k bits removed ▷ We remove the bits of str that encode sᵢ. + // 12: if str contains any non-zero bits then ▷ Enforce trailing bits at 0 + // 13: return ⊥ + // 14: return s = Σ_{i=0}^{n-1} sᵢxⁱ + const res = new Int16Array(n); + let buf = 0; + let bufLen = 0; + let pos = 0; + const readBits = (n: number) => { + for (; bufLen < n && pos < data.length; bufLen += 8) buf = (buf << 8) | data[pos++]; + if (bufLen < n) + throw new Error(`end of buffer: len=${bufLen} buf=${buf} lastByte=${data[pos]}`); + bufLen -= n; + const val = buf >>> bufLen; + buf &= getMask(bufLen); + return val; + }; + for (let resPos = 0; resPos < n; resPos++) { + const sign = readBits(1); + const low = readBits(7); + let high = 0; + for (; !readBits(1); high++); + const v = low | (high << 7); + if (sign && v === 0) throw new Error('negative zero encoding'); + if (v > LIMIT) throw new Error(`limit: ${v} > ${LIMIT}`); + res[resPos] = sign ? -v : v; + } + if (buf) throw new Error('non-empty accumulator'); + return res as TRet; + }, + }; +}; + +// Falcon padded-signature helper. encode() assumes `data.length <= len`; decode() strips trailing +// zero padding and returns a subarray view, so it is not a generic byte-string codec. +const pad = (len: number) => ({ + encode(data: TArg) { + const res = new Uint8Array(len); + res.set(data); + return res; + }, + decode(data: TArg) { + let end = data.length; + while (end > 0 && data[end - 1] === 0) end--; + return data.subarray(0, end); + }, +}); +// TODO: merge with noble-curves bls? +type ComplexElm = { re: T; im: T }; +// Zero complex-polynomial temporaries in place. Requires fully initialized `{ re, im }` entries. +const cleanCPoly = (...list: CPoly[]): void => { + for (const p of list) { + for (let i = 0; i < p.length; i++) { + p[i].re = 0; + p[i].im = 0; + } + } +}; +// Generic complex helper used by Falcon's FFT code. Current audited use relies on +// add/sub/mul/conj/scale/magSqSum/neg; inv() is intentionally unimplemented. +function getComplex(field: IField) { + const F = field; + return { + lift: (x: ComplexElm | T): ComplexElm => { + // Reuse existing complex objects verbatim; callers that need isolation must clone first. + if ((x as any).re !== undefined && (x as any).im !== undefined) return x as ComplexElm; + return { re: x as T, im: F.ZERO }; + }, + add: (a: ComplexElm, b: ComplexElm): ComplexElm => ({ + re: F.add(a.re, b.re), + im: F.add(a.im, b.im), + }), + sub: (a: ComplexElm, b: ComplexElm): ComplexElm => ({ + re: F.sub(a.re, b.re), + im: F.sub(a.im, b.im), + }), + mul: (a: ComplexElm, b: ComplexElm): ComplexElm => ({ + re: F.sub(F.mul(a.re, b.re), F.mul(a.im, b.im)), + im: F.add(F.mul(a.re, b.im), F.mul(a.im, b.re)), + }), + div: (a: ComplexElm, b: ComplexElm): ComplexElm => { + const denom = F.add(F.mul(b.re, b.re), F.mul(b.im, b.im)); + return { + re: F.div(F.add(F.mul(a.re, b.re), F.mul(a.im, b.im)), denom), + im: F.div(F.sub(F.mul(a.im, b.re), F.mul(a.re, b.im)), denom), + }; + }, + neg: (a: ComplexElm): ComplexElm => ({ re: F.neg(a.re), im: F.neg(a.im) }), + conj: (a: ComplexElm): ComplexElm => ({ re: a.re, im: F.neg(a.im) }), + scale: (a: ComplexElm, x: T | bigint): ComplexElm => ({ + re: F.mul(a.re, x), + im: F.mul(a.im, x), + }), + // a.re * a.re + a.im * a.im + b.re * b.re + b.im * b.im; + magSqSum: (a: ComplexElm, b: ComplexElm): T => + F.add( + F.add(F.add(F.mul(a.re, a.re), F.mul(a.im, a.im)), F.mul(b.re, b.re)), + F.mul(b.im, b.im) + ), + eql: (a: ComplexElm, b: ComplexElm): boolean => F.eql(a.re, b.re) && F.eql(a.im, b.im), + clone: (a: ComplexElm): ComplexElm => ({ re: a.re, im: a.im }), + inv: () => { + throw new Error('not implemented'); + }, + }; +} +// Falcon real-polynomial FFT layout: [...re, ...im]. Requires an even-length flat array and +// copies into fresh JS objects / arrays instead of creating views. +const ComplexArr = { + decode(lst: number[]): ComplexElm[] { + const N = lst.length; + const hn = N >> 1; + const len = lst.length; + if (len === 0) return []; + if (len % 2 !== 0) + throw new Error('Array length must be even to pair real and imaginary parts.'); + const res = []; + for (let i = 0; i < hn; i++) { + res.push({ re: lst[i], im: lst[i + hn] }); + } + return res; + }, + encode(lst: ComplexElm[]): number[] { + const re = []; + const im = []; + for (const i of lst) { + re.push(i.re); + im.push(i.im); + } + return [...re, ...im]; + }, +}; +// Precomputed root-table layout [re[0], im[0], re[1], im[1], ...]. Used for `COMPLEX_ROOTS`, +// not Falcon's packed polynomial FFT layout; encode() is currently unused. +// decode() / encode() copy between the flat root table +// and detached `{ re, im }` objects; they never create aliasing views. +const ComplexArrInterleaved = { + decode(lst: ArrayLike): ComplexElm[] { + const len = lst.length; + if (len === 0) return []; + if (len % 2 !== 0) + throw new Error('Array length must be even to pair real and imaginary parts.'); + const res: ComplexElm[] = []; + // Iterate through the list, taking two elements at a time + for (let i = 0; i < len; i += 2) { + res.push({ re: lst[i], im: lst[i + 1] }); + } + return res; + }, + encode(lst: ComplexElm[]): number[] { + const res: number[] = []; + for (const complexNum of lst) { + res.push(complexNum.re); + res.push(complexNum.im); + } + return res; + }, +}; +// Alias a Float64Array as bytes for the root-table hash pin; not a portable serialization. +const u8f = (arr: TArg): TRet => + new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet; + +// Alias bytes as Float64Array lanes. Falcon's exact binary64 tables are stored as little-endian +// payload bytes, so BE runtimes must decode lane-by-lane instead of aliasing host-endian floats. +// Copy/truncate to whole 8-byte lanes first +// so BE byte swaps cannot mutate caller-owned bytes +// or read a partial float. +const f64a = (arr: TArg): TRet => + new Float64Array( + baswap64If(Uint8Array.from(arr.subarray(0, Math.floor(arr.byteLength / 8) * 8))).buffer + ) as TRet; + +// Exact big-endian binary64 hex helper for constants. Only decode() is currently used; malformed +// inputs fail through lower-level hex / DataView checks instead of an explicit wrapper guard. +const Float = /* @__PURE__ */ Object.freeze({ + encode(n: number): string { + const bytes = new Uint8Array(8); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + view.setFloat64(0, n, false); + return bytesToHex(bytes); + }, + decode(s: string): number { + const bytes = hexToBytes(s); + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + return view.getFloat64(0, false); + }, +}); +// Decode a 64-bit bigint bit pattern into the exact binary64 value. +const f64b = (n: bigint): number => Float.decode(numberToHexUnpadded(n)); + +// Types +type SignatureRaw = { msg: Uint8Array; nonce: Uint8Array; s2: Uint8Array }; +type BPoly = bigint[]; +type FPoly = Float64Array; +type SPoly = Int8Array; // Small poly (f/g/F/G) +type IPoly = Uint16Array; // Integer poly mod Q + +// Constants +const EMPTY_CHACHA20_BLOCK = /** @__PURE__ */ new Uint8Array(64); +// Falcon's randomized hashing salt r is always 320 bits / 40 bytes, and the same width +// also drives the detached and attached signature wire formats. +const NONCELEN = 40; + +// Falcon's public modulus q = 12289 is also the NTT parameter chosen in round 3. +const Q: number = 12289; // 12 * 1024 + 1 +// Falcon's midpoint floor(q/2); the only live use is the mirrored G-reconstruction reduction below. +const Qhalf: number = Q >> 1; +const QBig = BigInt(Q); +//const R = 4091; // 2^16 mod q +// This 16-bit Montgomery kernel uses R = 2^16, so mul(x, R2) converts x into Montgomery form. +const R2 = 10952; // 2^32 mod q +// falcon.pdf page 55 says "1/q mod 2^16", +// but the reduction formula and the round-3 Falcon code both require -1/q. +const Q0I = 12287; // -1/q mod 2^16 +const F_INV_Q = 1.0 / Q; +const F_MINUS_INV_Q = -F_INV_Q; +// Round-3 bigint keygen keeps these tables coupled: MAX_BL_SMALL and MAX_BL_LARGE are measured +// 31-bit word bounds, and BITLENGTH is the measured avg/stddev heuristic. Edits must recheck the +// next-depth relation and the current 31 * wordCount headroom used by reduce(). +const MAX_BL_SMALL = [1, 1, 2, 2, 4, 7, 14, 27, 53, 106, 209]; +// Unreduced F/G word bounds for reduce(); the same round-3 source also couples this table to the +// top-10-word floating approximation there, +// so it must stay in sync with MAX_BL_SMALL and BITLENGTH. +const MAX_BL_LARGE = [2, 2, 5, 7, 12, 21, 40, 78, 157, 308]; +// Exact binary64 encoding of Falcon's Gram-Schmidt keygen bound (1.17^2) * q = 16822.4121. +const BNORM_MAX = f64b(BigInt('4670353323383631276')); +// Measured round-3 bigint-keygen heuristic, not a normative Falcon parameter table or proof bound. +const BITLENGTH = [ + { avg: 4, std: 0 }, + { avg: 11, std: 1 }, + { avg: 24, std: 1 }, + { avg: 50, std: 1 }, + { avg: 102, std: 1 }, + { avg: 202, std: 2 }, + { avg: 401, std: 4 }, + { avg: 794, std: 5 }, + { avg: 1577, std: 8 }, + { avg: 3138, std: 13 }, + { avg: 6308, std: 25 }, +]; +// First entry is P(x = 0); the remaining entries are conditional tail thresholds scaled by 2^63. +// Smaller Falcon dimensions reuse the N = 1024, q = 12289 table by summing 2^(10-logn) draws. +// The trailing 0 sentinel guarantees gaussSingle() +// always selects a tail bucket when x = 0 is missed. +const gauss_1024_12289 = [ + 1283868770400643928n, + 6416574995475331444n, + 4078260278032692663n, + 2353523259288686585n, + 1227179971273316331n, + 575931623374121527n, + 242543240509105209n, + 91437049221049666n, + 30799446349977173n, + 9255276791179340n, + 2478152334826140n, + 590642893610164n, + 125206034929641n, + 23590435911403n, + 3948334035941n, + 586753615614n, + 77391054539n, + 9056793210n, + 940121950n, + 86539696n, + 7062824n, + 510971n, + 32764n, + 1862n, + 94n, + 4n, + 0n, +]; + +// Exact binary64 1/sigma payloads from round-3 fpr.h. Nearby decimal spellings round 1 ULP low in +// JS, so keep these as decoded bit patterns and recheck the raw payloads after edits. +const INV_SIGMA = /* @__PURE__ */ Object.freeze([ + 0.0, // unused + f64b(BigInt('4574611497772390042')), + f64b(BigInt('4574501679055810265')), + f64b(BigInt('4574396282908341804')), + f64b(BigInt('4574245855758572086')), + f64b(BigInt('4574103865040221165')), + f64b(BigInt('4573969550563515544')), + f64b(BigInt('4573842244705920822')), + f64b(BigInt('4573721358406441454')), + f64b(BigInt('4573606369665796042')), + f64b(BigInt('4573496814039276259')), +]); + +// Exact binary64 sigma_min constants from round-3 fpr.h indexed by logn; despite one PQClean +// summary comment, these are sigma_min itself, not 1/sigma_min, which is why this table stays +// separate from INV_SIGMA. +const SIGMA_MIN = /* @__PURE__ */ Object.freeze([ + 0.0, // unused + f64b(BigInt('4607707126469777035')), + f64b(BigInt('4607777455861499430')), + f64b(BigInt('4607846828256951418')), + f64b(BigInt('4607949175006100261')), + f64b(BigInt('4608049571757433526')), + f64b(BigInt('4608148125896792003')), + f64b(BigInt('4608244935301382692')), + f64b(BigInt('4608340089478362016')), + f64b(BigInt('4608433670533905013')), + f64b(BigInt('4608525754002622308')), +]); + +// Falcon Table 3.1 RCDT values for chi, split into 24-bit limbs; storage is [high, mid, low], +// so gaussian0() intentionally compares them against v0, v1, v2 in reverse order. The final +// RCDT[18] = 0 row is omitted because the algorithm iterates only over i = 0..17. +const GAUSS0 = new Uint32Array([ + 10745844, 3068844, 3741698, 5559083, 1580863, 8248194, 2260429, 13669192, 2736639, 708981, + 4421575, 10046180, 169348, 7122675, 4136815, 30538, 13063405, 7650655, 4132, 14505003, 7826148, + 417, 16768101, 11363290, 31, 8444042, 8086568, 1, 12844466, 265321, 0, 1232676, 13644283, 0, + 38047, 9111839, 0, 870, 6138264, 0, 14, 12545723, 0, 0, 3104126, 0, 0, 28824, 0, 0, 198, 0, 0, 1, +]); + +// Inclusive floor(beta^2) signature-acceptance bounds indexed by logn; the Falcon PDF publishes +// only Falcon-512 and Falcon-1024 directly, while the smaller rows are mirrored from the round-3 +// NIST submission package. +const L2BOUND = [ + 0, // unused + 101498, + 208714, + 428865, + 892039, + 1852696, + 3842630, + 7959734, + 16468416, + 34034726, + 70265242, +]; + +// 32kb in hex. +// Could be 4x smaller by using 2 bytes per root. However, that would mean using sin/cos. +// Different JS engines give different sin / cos result, which means the result would be unreliable. +// See "COMPLEX ROOT GENERATION FOR FALCON" in tests. +// Those exact roots are taken from the round-3 Falcon submission, preserving its original +// bit-reversed order here and remapping it only later for FFTCore. +const COMPLEX_ROOTS = /** @__PURE__ */ (() => { + const roots = f64a( + hexToBytes( + '000000000000000000000000000000000000000000000080000000000000f03fcd3b7f669ea0e63fcd3b7f66' + + '9ea0e63fcd3b7f669ea0e6bfcd3b7f669ea0e63f468d32cf6b90ed3f63a9aea6e27dd83f63a9aea6e27dd8bf' + + '468d32cf6b90ed3f63a9aea6e27dd83f468d32cf6b90ed3f468d32cf6b90edbf63a9aea6e27dd83fb05cf7cf' + + '9762ef3f0ba6693cb8f8c83f0ba6693cb8f8c8bfb05cf7cf9762ef3fc868ae393bc7e13fa3a10e29669bea3f' + + 'a3a10e29669beabfc868ae393bc7e13fa3a10e29669bea3fc868ae393bc7e13fc868ae393bc7e1bfa3a10e29' + + '669bea3f0ba6693cb8f8c83fb05cf7cf9762ef3fb05cf7cf9762efbf0ba6693cb8f8c83f2625d1a38dd8ef3f' + + '2cb429bca617b93f2cb429bca617b9bf2625d1a38dd8ef3fd61d0925f34ce43f4117156b80bce83f4117156b' + + '80bce8bfd61d0925f34ce43fb1bd80f1b238ec3f3bf606385d2bde3f3bf606385d2bdebfb1bd80f1b238ec3f' + + '069fd52e0694d23fda2dc656419fee3fda2dc656419feebf069fd52e0694d23fda2dc656419fee3f069fd52e' + + '0694d23f069fd52e0694d2bfda2dc656419fee3f3bf606385d2bde3fb1bd80f1b238ec3fb1bd80f1b238ecbf' + + '3bf606385d2bde3f4117156b80bce83fd61d0925f34ce43fd61d0925f34ce4bf4117156b80bce83f2cb429bc' + + 'a617b93f2625d1a38dd8ef3f2625d1a38dd8efbf2cb429bca617b93f7e6d79e321f6ef3f14d80df1651fa93f' + + '14d80df1651fa9bf7e6d79e321f6ef3fa0ec8c34697de53fafaf6a22dfb5e73fafaf6a22dfb5e7bfa0ec8c34' + + '697de53f73c73cf47aedec3fc05ce109105ddb3fc05ce109105ddbbf73c73cf47aedec3fdd1fab759a8fd53f' + + 'e586f6042121ee3fe586f6042121eebfdd1fab759a8fd53fd73092fb7e0aef3f1b5f217bf919cf3f1b5f217b' + + 'f919cfbfd73092fb7e0aef3feeff22998773e03f3e6e19458372eb3f3e6e19458372ebbfeeff22998773e03f' + + '4187f347e0b3e93f3570e1fcf70fe33f3570e1fcf70fe3bf4187f347e0b3e93f3a618e6e10c8c23f17a5087f' + + '55a7ef3f17a5087f55a7efbf3a618e6e10c8c23f17a5087f55a7ef3f3a618e6e10c8c23f3a618e6e10c8c2bf' + + '17a5087f55a7ef3f3570e1fcf70fe33f4187f347e0b3e93f4187f347e0b3e9bf3570e1fcf70fe33f3e6e1945' + + '8372eb3feeff22998773e03feeff22998773e0bf3e6e19458372eb3f1b5f217bf919cf3fd73092fb7e0aef3f' + + 'd73092fb7e0aefbf1b5f217bf919cf3fe586f6042121ee3fdd1fab759a8fd53fdd1fab759a8fd5bfe586f604' + + '2121ee3fc05ce109105ddb3f73c73cf47aedec3f73c73cf47aedecbfc05ce109105ddb3fafaf6a22dfb5e73f' + + 'a0ec8c34697de53fa0ec8c34697de5bfafaf6a22dfb5e73f14d80df1651fa93f7e6d79e321f6ef3f7e6d79e3' + + '21f6efbf14d80df1651fa93f0dcd846088fdef3f7e66a3f75521993f7e66a3f7552199bf0dcd846088fdef3f' + + 'df2c1d55b710e63f96ffef37082de73f96ffef37082de7bfdf2c1d55b710e63f3ac94dd13441ed3f8aeda843' + + '79efd93f8aeda84379efd9bf3ac94dd13441ed3f9f45fa308508d73f3cc2ccb613dbed3f3cc2ccb613dbedbf' + + '9f45fa308508d73f89e564acf338ef3f634f7e6a820bcc3f634f7e6a820bccbf89e564acf338ef3f234b1b54' + + 'b31ee13f000215580a09eb3f000215580a09ebbf234b1b54b31ee13f822746a0a729ea3fdf12dd4c056de23f' + + 'df12dd4c056de2bf822746a0a729ea3fc63f8b4414e2c53fa94b71fa6487ef3fa94b71fa6487efbfc63f8b44' + + '14e2c53fd39fe17064c2ef3f0e73a9564e56bf3f0e73a9564e56bfbfd39fe17064c2ef3fb9502029faafe33f' + + 'fb639249223ae93ffb639249223ae9bfb9502029faafe33f2a956facc0d7eb3fba9af8dba48bdf3fba9af8db' + + 'a48bdfbf2a956facc0d7eb3f77f6b162d211d13f634968e740d7ee3f634968e740d7eebf77f6b162d211d13f' + + '12e148ec8862ee3f016617945c13d43f016617945c13d4bf12e148ec8862ee3f5ec431996ec6dc3ff5113421' + + '4b95ec3ff51134214b95ecbf5ec431996ec6dc3f6e97ff0b0e3be83fe9e5e3bbcae6e43fe9e5e3bbcae6e4bf' + + '6e97ff0b0e3be83ff619ce9220d5b23f3a8801adcde9ef3f3a8801adcde9efbff619ce9220d5b23f3a8801ad' + + 'cde9ef3ff619ce9220d5b23ff619ce9220d5b2bf3a8801adcde9ef3fe9e5e3bbcae6e43f6e97ff0b0e3be83f' + + '6e97ff0b0e3be8bfe9e5e3bbcae6e43ff51134214b95ec3f5ec431996ec6dc3f5ec431996ec6dcbff5113421' + + '4b95ec3f016617945c13d43f12e148ec8862ee3f12e148ec8862eebf016617945c13d43f634968e740d7ee3f' + + '77f6b162d211d13f77f6b162d211d1bf634968e740d7ee3fba9af8dba48bdf3f2a956facc0d7eb3f2a956fac' + + 'c0d7ebbfba9af8dba48bdf3ffb639249223ae93fb9502029faafe33fb9502029faafe3bffb639249223ae93f' + + '0e73a9564e56bf3fd39fe17064c2ef3fd39fe17064c2efbf0e73a9564e56bf3fa94b71fa6487ef3fc63f8b44' + + '14e2c53fc63f8b4414e2c5bfa94b71fa6487ef3fdf12dd4c056de23f822746a0a729ea3f822746a0a729eabf' + + 'df12dd4c056de23f000215580a09eb3f234b1b54b31ee13f234b1b54b31ee1bf000215580a09eb3f634f7e6a' + + '820bcc3f89e564acf338ef3f89e564acf338efbf634f7e6a820bcc3f3cc2ccb613dbed3f9f45fa308508d73f' + + '9f45fa308508d7bf3cc2ccb613dbed3f8aeda84379efd93f3ac94dd13441ed3f3ac94dd13441edbf8aeda843' + + '79efd93f96ffef37082de73fdf2c1d55b710e63fdf2c1d55b710e6bf96ffef37082de73f7e66a3f75521993f' + + '0dcd846088fdef3f0dcd846088fdefbf7e66a3f75521993fdb929b1662ffef3f84c7defcd121893f84c7defc' + + 'd12189bfdb929b1662ffef3f3d78f0251959e63fafa8ea5444e7e63fafa8ea5444e7e6bf3d78f0251959e63f' + + '8be6c9736169ed3fd793bc632a37d93fd793bc632a37d9bf8be6c9736169ed3fe7cc1d31a9c3d73f9ba03862' + + '52b6ed3f9ba0386252b6edbfe7cc1d31a9c3d73f2d2f0b3b604eef3f5104b025a082ca3f5104b025a082cabf' + + '2d2f0b3b604eef3f49dbde634d73e13f11d5219ebcd2ea3f11d5219ebcd2eabf49dbde634d73e13fe2fa021b' + + '0963ea3f59eb3399791ae23f59eb3399791ae2bfe2fa021b0963ea3f31bf50ded96dc73f7720a1a39975ef3f' + + '7720a1a39975efbf31bf50ded96dc73f7ba66dfd15ceef3fd5c29ec78537bc3fd5c29ec78537bcbf7ba66dfd' + + '15ceef3fd4564553d9fee33f0d94efa3ccfbe83f0d94efa3ccfbe8bfd4564553d9fee33f49557226c408ec3f' + + 'd678ef5219dcde3fd678ef5219dcdebf49557226c408ec3f3edb4c3f44d3d13f740bdfc8d8bbee3f740bdfc8' + + 'd8bbeebf3edb4c3f44d3d13f0dd14cab7b81ee3f5281e1c21054d33f5281e1c21054d3bf0dd14cab7b81ee3f' + + '89e3865b7779dd3f9b7388348b67ec3f9b7388348b67ecbf89e3865b7779dd3fbf2eba0f407ce83f39099b9b' + + '449ae43f39099b9b449ae4bfbf2eba0f407ce83f19a49a0ad0f6b53f095bbdfccae1ef3f095bbdfccae1efbf' + + '19a49a0ad0f6b53fad718e6595f0ef3fe020f8796e65af3fe020f8796e65afbfad718e6595f0ef3f9655a392' + + '8232e53f711757e3ecf8e73f711757e3ecf8e7bf9655a3928232e53f5cfcfcf3f0c1ec3fe71e01d84912dc3f' + + 'e71e01d84912dcbf5cfcfcf3f0c1ec3f6ae77842e2d1d43f7ec12b4b6a42ee3f7ec12b4b6a42eebf6ae77842' + + 'e2d1d43fc273e4a378f1ee3faefd370eb84fd03faefd370eb84fd0bfc273e4a378f1ee3fb73e4c87fc1ce03f' + + 'd2903567aaa5eb3fd2903567aaa5ebbfb73e4c87fc1ce03f42d7c7f47e77e93ff35906b15860e33ff35906b1' + + '5860e3bf42d7c7f47e77e93f77f5dacef039c13f41d7957179b5ef3f41d7957179b5efbf77f5dacef039c13f' + + '9b09c924f997ef3f5a3e29b17655c43f5a3e29b17655c4bf9b09c924f997ef3feaf3fa25dbbee23f94af29ef' + + '43efe93f94af29ef43efe9bfeaf3fa25dbbee23f1257f53e4d3eeb3f8f895d4d70c9e03f8f895d4d70c9e0bf' + + '1257f53e4d3eeb3f114345e54f93cd3fda3a76f75222ef3fda3a76f75222efbf114345e54f93cd3f2bbe2d62' + + 'aefeed3fc6273fdd7d4cd63fc6273fdd7d4cd6bf2bbe2d62aefeed3fca3f6d2bc8a6da3fdc353e74e717ed3f' + + 'dc353e74e717edbfca3f6d2bc8a6da3f6172035fe771e73f8c0165be7bc7e53f8c0165be7bc7e5bf6172035f' + + 'e771e73fcd55947565d8a23f5df7feef72faef3f5df7feef72faefbfcd55947565d8a23f5df7feef72faef3f' + + 'cd55947565d8a23fcd55947565d8a2bf5df7feef72faef3f8c0165be7bc7e53f6172035fe771e73f6172035f' + + 'e771e7bf8c0165be7bc7e53fdc353e74e717ed3fca3f6d2bc8a6da3fca3f6d2bc8a6dabfdc353e74e717ed3f' + + 'c6273fdd7d4cd63f2bbe2d62aefeed3f2bbe2d62aefeedbfc6273fdd7d4cd63fda3a76f75222ef3f114345e5' + + '4f93cd3f114345e54f93cdbfda3a76f75222ef3f8f895d4d70c9e03f1257f53e4d3eeb3f1257f53e4d3eebbf' + + '8f895d4d70c9e03f94af29ef43efe93feaf3fa25dbbee23feaf3fa25dbbee2bf94af29ef43efe93f5a3e29b1' + + '7655c43f9b09c924f997ef3f9b09c924f997efbf5a3e29b17655c43f41d7957179b5ef3f77f5dacef039c13f' + + '77f5dacef039c1bf41d7957179b5ef3ff35906b15860e33f42d7c7f47e77e93f42d7c7f47e77e9bff35906b1' + + '5860e33fd2903567aaa5eb3fb73e4c87fc1ce03fb73e4c87fc1ce0bfd2903567aaa5eb3faefd370eb84fd03f' + + 'c273e4a378f1ee3fc273e4a378f1eebfaefd370eb84fd03f7ec12b4b6a42ee3f6ae77842e2d1d43f6ae77842' + + 'e2d1d4bf7ec12b4b6a42ee3fe71e01d84912dc3f5cfcfcf3f0c1ec3f5cfcfcf3f0c1ecbfe71e01d84912dc3f' + + '711757e3ecf8e73f9655a3928232e53f9655a3928232e5bf711757e3ecf8e73fe020f8796e65af3fad718e65' + + '95f0ef3fad718e6595f0efbfe020f8796e65af3f095bbdfccae1ef3f19a49a0ad0f6b53f19a49a0ad0f6b5bf' + + '095bbdfccae1ef3f39099b9b449ae43fbf2eba0f407ce83fbf2eba0f407ce8bf39099b9b449ae43f9b738834' + + '8b67ec3f89e3865b7779dd3f89e3865b7779ddbf9b7388348b67ec3f5281e1c21054d33f0dd14cab7b81ee3f' + + '0dd14cab7b81eebf5281e1c21054d33f740bdfc8d8bbee3f3edb4c3f44d3d13f3edb4c3f44d3d1bf740bdfc8' + + 'd8bbee3fd678ef5219dcde3f49557226c408ec3f49557226c408ecbfd678ef5219dcde3f0d94efa3ccfbe83f' + + 'd4564553d9fee33fd4564553d9fee3bf0d94efa3ccfbe83fd5c29ec78537bc3f7ba66dfd15ceef3f7ba66dfd' + + '15ceefbfd5c29ec78537bc3f7720a1a39975ef3f31bf50ded96dc73f31bf50ded96dc7bf7720a1a39975ef3f' + + '59eb3399791ae23fe2fa021b0963ea3fe2fa021b0963eabf59eb3399791ae23f11d5219ebcd2ea3f49dbde63' + + '4d73e13f49dbde634d73e1bf11d5219ebcd2ea3f5104b025a082ca3f2d2f0b3b604eef3f2d2f0b3b604eefbf' + + '5104b025a082ca3f9ba0386252b6ed3fe7cc1d31a9c3d73fe7cc1d31a9c3d7bf9ba0386252b6ed3fd793bc63' + + '2a37d93f8be6c9736169ed3f8be6c9736169edbfd793bc632a37d93fafa8ea5444e7e63f3d78f0251959e63f' + + '3d78f0251959e6bfafa8ea5444e7e63f84c7defcd121893fdb929b1662ffef3fdb929b1662ffefbf84c7defc' + + 'd121893f928a8e85d8ffef3f710067fef021793f710067fef02179bf928a8e85d8ffef3f10af9184f77ce63f' + + '7582c1730dc4e63f7582c1730dc4e6bf10af9184f77ce63ff9ecb8020b7ded3fb0a4c82ea5dad83fb0a4c82e' + + 'a5dad8bff9ecb8020b7ded3fc4aa4eb0e320d83f888966a983a3ed3f888966a983a3edbfc4aa4eb0e320d83f' + + '849e78b1a258ef3f6643dcf2cbbdc93f6643dcf2cbbdc9bf849e78b1a258ef3fb8b9f2095a9de13fd4c01659' + + '32b7ea3fd4c0165932b7eabfb8b9f2095a9de13f9de69f52587fea3f1b86bc8bf0f0e13f1b86bc8bf0f0e1bf' + + '9de69f52587fea3fc6649ce86633c83fb7bbf57d3f6cef3fb7bbf57d3f6cefbfc6649ce86633c83f840b2214' + + '79d3ef3f035c4924b7a7ba3f035c4924b7a7babf840b221479d3ef3fb16b8e17ff25e43fcc98163345dce83f' + + 'cc98163345dce8bfb16b8e17ff25e43fb071a93fde20ec3f1451f8eae083de3f1451f8eae083debfb071a93f' + + 'de20ec3f71bbc3abbb33d23f8ea8e7e8b2adee3f8ea8e7e8b2adeebf71bbc3abbb33d23ff2f71d368490ee3f' + + '8703ecda22f4d23f8703ecda22f4d2bff2f71d368490ee3f58cc81148fd2dd3f07692b014250ec3f07692b01' + + '4250ecbf58cc81148fd2dd3faad44d9a7e9ce83f4773981bb573e43f4773981bb573e4bfaad44d9a7e9ce83f' + + '215b5d6a5887b73f56f4f19f53ddef3f56f4f19f53ddefbf215b5d6a5887b73f5c578d0f83f3ef3fe3d7c012' + + '8d42ac3fe3d7c0128d42acbf5c578d0f83f3ef3f375197381058e53fb23dc36c83d7e73fb23dc36c83d7e7bf' + + '375197381058e53ff6328b89d9d7ec3f01bd0423cfb7db3f01bd0423cfb7dbbff6328b89d9d7ec3f243caf80' + + 'd830d53f25ce70e8ea31ee3f25ce70e8ea31eebf243caf80d830d53fec950b0c22feee3ff9eddf1adcdccf3f' + + 'f9eddf1adcdccfbfec950b0c22feee3f1a22ae265648e03fe90475d2388ceb3fe90475d2388cebbf1a22ae26' + + '5648e03f220dd82ecf95e93f578e0c0d4038e33f578e0c0d4038e3bf220dd82ecf95e93fcf7becd41601c23f' + + 'bbcf468e8eaeef3fbbcf468e8eaeefbfcf7becd41601c23fc8b2ad55ce9fef3f148dcdb0db8ec33f148dcdb0' + + 'db8ec3bfc8b2ad55ce9fef3f17eae8e380e7e23fd580eaf5b1d1e93fd580eaf5b1d1e9bf17eae8e380e7e23f' + + '051492fe8958eb3fe1c51774909ee03fe1c51774909ee0bf051492fe8958eb3f1b1a101eca56ce3f5d20f753' + + '8f16ef3f5d20f7538f16efbf1b1a101eca56ce3fac8029ca0c10ee3f93a69e3727eed53f93a69e3727eed5bf' + + 'ac8029ca0c10ee3f09407f6c0d02db3f92bdb2fed402ed3f92bdb2fed402edbf09407f6c0d02db3fe5554f57' + + '0094e73f50725d2a8da2e53f50725d2a8da2e5bfe5554f570094e73f43cd90d200fca53fdf81dbda71f8ef3f' + + 'df81dbda71f8efbf43cd90d200fca53ff8d3f11d25fcef3f01cfd13137699f3f01cfd13137699fbff8d3f11d' + + '25fcef3f7470839534ece53f8dd2a88d944fe73f8dd2a88d944fe7bf7470839534ece53f9fefe020b22ced3f' + + 'e5a1de27414bda3fe5a1de27414bdabf9fefe020b22ced3f177ec77d9daad63fda47def705eded3fda47def7' + + '05ededbf177ec77d9daad63f9d9a08c9c92def3f86b212b38ccfcc3f86b212b38ccfccbf9d9a08c9c92def3f' + + '7e8e2abb26f4e03fb4130047cd23eb3fb4130047cd23ebbf7e8e2abb26f4e03f37f9baea950cea3fa89c6227' + + '0796e23fa89c62270796e2bf37f9baea950cea3ff2c59785df1bc53fdb41aeffd58fef3fdb41aeffd58fefbf' + + 'f2c59785df1bc53f8641e41716bcef3f1d83ba47a072c03f1d83ba47a072c0bf8641e41716bcef3f22ebdf85' + + '4188e33fd76d8ee4ef58e93fd76d8ee4ef58e9bf22ebdf854188e33fea8093c4d7beeb3f1012e74bf6e2df3f' + + '1012e74bf6e2dfbfea8093c4d7beeb3f90dbdbcfd9b0d03fbc9d5ae282e4ee3fbc9d5ae282e4eebf90dbdbcf' + + 'd9b0d03ffc9f72049f52ee3f541057a5b872d43f541057a5b872d4bffc9f72049f52ee3f0b0097497f6cdc3f' + + '00b9a069c1abec3f00b9a069c1abecbf0b0097497f6cdc3fcc7ab5331b1ae83f9ba0599fc00ce53f9ba0599f' + + 'c00ce5bfcc7ab5331b1ae83fb309d7340144b13fc473b6ec58edef3fc473b6ec58edefbfb309d7340144b13f' + + '40392eaff3e5ef3f962027791166b43f962027791166b4bf40392eaff3e5ef3f0400ec45a1c0e43fcc58e91a' + + 'c55be83fcc58e91ac55be8bf0400ec45a1c0e43ff33c23528e7eec3f5bdbe9e81620dd3f5bdbe9e81620ddbf' + + 'f33c23528e7eec3fb71404faceb3d33f44976adb2772ee3f44976adb2772eebfb71404faceb3d33f84bfc3d3' + + 'b2c9ee3f775176d7a072d13f775176d7a072d1bf84bfc3d3b2c9ee3f67d03f960534df3fdd7753e164f0eb3f' + + 'dd7753e164f0ebbf67d03f960534df3fa29dd46f161be93f4483c53882d7e33f4483c53882d7e3bfa29dd46f' + + '161be93fc99faecb0ec7bd3f21b7fe6c64c8ef3f21b7fe6c64c8efbfc99faecb0ec7bd3f6e3de629a67eef3f' + + 'b24af60413a8c63fb24af60413a8c6bf6e3de629a67eef3f1fac98fbd543e23fc89a11c87846ea3fc89a11c8' + + '7846eabf1fac98fbd543e23f74143cb404eeea3feb6c33af1549e13feb6c33af1549e1bf74143cb404eeea3f' + + '22673def3247cb3fdd92ff85d043ef3fdd92ff85d043efbf22673def3247cb3f600241cbd7c8ed3ff618240f' + + '3466d73ff618240f3466d7bf600241cbd7c8ed3fffbd41617193d93fb13ee9526f55ed3fb13ee9526f55edbf' + + 'ffbd41617193d93f7a6d17b3420ae73fe91b1ca30335e63fe91b1ca30335e6bf7a6d17b3420ae73ffd0ee3bb' + + '36d9923fa1514bb49cfeef3fa1514bb49cfeefbffd0ee3bb36d9923fa1514bb49cfeef3ffd0ee3bb36d9923f' + + 'fd0ee3bb36d992bfa1514bb49cfeef3fe91b1ca30335e63f7a6d17b3420ae73f7a6d17b3420ae7bfe91b1ca3' + + '0335e63fb13ee9526f55ed3fffbd41617193d93fffbd41617193d9bfb13ee9526f55ed3ff618240f3466d73f' + + '600241cbd7c8ed3f600241cbd7c8edbff618240f3466d73fdd92ff85d043ef3f22673def3247cb3f22673def' + + '3247cbbfdd92ff85d043ef3feb6c33af1549e13f74143cb404eeea3f74143cb404eeeabfeb6c33af1549e13f' + + 'c89a11c87846ea3f1fac98fbd543e23f1fac98fbd543e2bfc89a11c87846ea3fb24af60413a8c63f6e3de629' + + 'a67eef3f6e3de629a67eefbfb24af60413a8c63f21b7fe6c64c8ef3fc99faecb0ec7bd3fc99faecb0ec7bdbf' + + '21b7fe6c64c8ef3f4483c53882d7e33fa29dd46f161be93fa29dd46f161be9bf4483c53882d7e33fdd7753e1' + + '64f0eb3f67d03f960534df3f67d03f960534dfbfdd7753e164f0eb3f775176d7a072d13f84bfc3d3b2c9ee3f' + + '84bfc3d3b2c9eebf775176d7a072d13f44976adb2772ee3fb71404faceb3d33fb71404faceb3d3bf44976adb' + + '2772ee3f5bdbe9e81620dd3ff33c23528e7eec3ff33c23528e7eecbf5bdbe9e81620dd3fcc58e91ac55be83f' + + '0400ec45a1c0e43f0400ec45a1c0e4bfcc58e91ac55be83f962027791166b43f40392eaff3e5ef3f40392eaf' + + 'f3e5efbf962027791166b43fc473b6ec58edef3fb309d7340144b13fb309d7340144b1bfc473b6ec58edef3f' + + '9ba0599fc00ce53fcc7ab5331b1ae83fcc7ab5331b1ae8bf9ba0599fc00ce53f00b9a069c1abec3f0b009749' + + '7f6cdc3f0b0097497f6cdcbf00b9a069c1abec3f541057a5b872d43ffc9f72049f52ee3ffc9f72049f52eebf' + + '541057a5b872d43fbc9d5ae282e4ee3f90dbdbcfd9b0d03f90dbdbcfd9b0d0bfbc9d5ae282e4ee3f1012e74b' + + 'f6e2df3fea8093c4d7beeb3fea8093c4d7beebbf1012e74bf6e2df3fd76d8ee4ef58e93f22ebdf854188e33f' + + '22ebdf854188e3bfd76d8ee4ef58e93f1d83ba47a072c03f8641e41716bcef3f8641e41716bcefbf1d83ba47' + + 'a072c03fdb41aeffd58fef3ff2c59785df1bc53ff2c59785df1bc5bfdb41aeffd58fef3fa89c62270796e23f' + + '37f9baea950cea3f37f9baea950ceabfa89c62270796e23fb4130047cd23eb3f7e8e2abb26f4e03f7e8e2abb' + + '26f4e0bfb4130047cd23eb3f86b212b38ccfcc3f9d9a08c9c92def3f9d9a08c9c92defbf86b212b38ccfcc3f' + + 'da47def705eded3f177ec77d9daad63f177ec77d9daad6bfda47def705eded3fe5a1de27414bda3f9fefe020' + + 'b22ced3f9fefe020b22cedbfe5a1de27414bda3f8dd2a88d944fe73f7470839534ece53f7470839534ece5bf' + + '8dd2a88d944fe73f01cfd13137699f3ff8d3f11d25fcef3ff8d3f11d25fcefbf01cfd13137699f3fdf81dbda' + + '71f8ef3f43cd90d200fca53f43cd90d200fca5bfdf81dbda71f8ef3f50725d2a8da2e53fe5554f570094e73f' + + 'e5554f570094e7bf50725d2a8da2e53f92bdb2fed402ed3f09407f6c0d02db3f09407f6c0d02dbbf92bdb2fe' + + 'd402ed3f93a69e3727eed53fac8029ca0c10ee3fac8029ca0c10eebf93a69e3727eed53f5d20f7538f16ef3f' + + '1b1a101eca56ce3f1b1a101eca56cebf5d20f7538f16ef3fe1c51774909ee03f051492fe8958eb3f051492fe' + + '8958ebbfe1c51774909ee03fd580eaf5b1d1e93f17eae8e380e7e23f17eae8e380e7e2bfd580eaf5b1d1e93f' + + '148dcdb0db8ec33fc8b2ad55ce9fef3fc8b2ad55ce9fefbf148dcdb0db8ec33fbbcf468e8eaeef3fcf7becd4' + + '1601c23fcf7becd41601c2bfbbcf468e8eaeef3f578e0c0d4038e33f220dd82ecf95e93f220dd82ecf95e9bf' + + '578e0c0d4038e33fe90475d2388ceb3f1a22ae265648e03f1a22ae265648e0bfe90475d2388ceb3ff9eddf1a' + + 'dcdccf3fec950b0c22feee3fec950b0c22feeebff9eddf1adcdccf3f25ce70e8ea31ee3f243caf80d830d53f' + + '243caf80d830d5bf25ce70e8ea31ee3f01bd0423cfb7db3ff6328b89d9d7ec3ff6328b89d9d7ecbf01bd0423' + + 'cfb7db3fb23dc36c83d7e73f375197381058e53f375197381058e5bfb23dc36c83d7e73fe3d7c0128d42ac3f' + + '5c578d0f83f3ef3f5c578d0f83f3efbfe3d7c0128d42ac3f56f4f19f53ddef3f215b5d6a5887b73f215b5d6a' + + '5887b7bf56f4f19f53ddef3f4773981bb573e43faad44d9a7e9ce83faad44d9a7e9ce8bf4773981bb573e43f' + + '07692b014250ec3f58cc81148fd2dd3f58cc81148fd2ddbf07692b014250ec3f8703ecda22f4d23ff2f71d36' + + '8490ee3ff2f71d368490eebf8703ecda22f4d23f8ea8e7e8b2adee3f71bbc3abbb33d23f71bbc3abbb33d2bf' + + '8ea8e7e8b2adee3f1451f8eae083de3fb071a93fde20ec3fb071a93fde20ecbf1451f8eae083de3fcc981633' + + '45dce83fb16b8e17ff25e43fb16b8e17ff25e4bfcc98163345dce83f035c4924b7a7ba3f840b221479d3ef3f' + + '840b221479d3efbf035c4924b7a7ba3fb7bbf57d3f6cef3fc6649ce86633c83fc6649ce86633c8bfb7bbf57d' + + '3f6cef3f1b86bc8bf0f0e13f9de69f52587fea3f9de69f52587feabf1b86bc8bf0f0e13fd4c0165932b7ea3f' + + 'b8b9f2095a9de13fb8b9f2095a9de1bfd4c0165932b7ea3f6643dcf2cbbdc93f849e78b1a258ef3f849e78b1' + + 'a258efbf6643dcf2cbbdc93f888966a983a3ed3fc4aa4eb0e320d83fc4aa4eb0e320d8bf888966a983a3ed3f' + + 'b0a4c82ea5dad83ff9ecb8020b7ded3ff9ecb8020b7dedbfb0a4c82ea5dad83f7582c1730dc4e63f10af9184' + + 'f77ce63f10af9184f77ce6bf7582c1730dc4e63f710067fef021793f928a8e85d8ffef3f928a8e85d8ffefbf' + + '710067fef021793f021d6221f6ffef3fbaa4ccbef821693fbaa4ccbef82169bf021d6221f6ffef3f719ca1ea' + + 'd18ee63f9ce22fed5cb2e63f9ce22fed5cb2e6bf719ca1ead18ee63f4fa44584c486ed3f44edd5864bacd83f' + + '44edd5864bacd8bf4fa44584c486ed3f3f90f3aa6a4fd83f463d8bdd009aed3f463d8bdd009aedbf3f90f3aa' + + '6a4fd83f5d6843eda65def3ffa2ab6e9495bc93ffa2ab6e9495bc9bf5d6843eda65def3fbf73131750b2e13f' + + '8eb92c7a54a9ea3f8eb92c7a54a9eabfbf73131750b2e13fd25a546e678dea3f7248dc641bdce13f7248dc64' + + '1bdce1bfd25a546e678dea3f0418c4271796c83fee3c88567567ef3fee3c88567567efbf0418c4271796c83f' + + '9e5ca72d0dd6ef3f5ca824ebb6dfb93f5ca824ebb6dfb9bf9e5ca72d0dd6ef3f80432a5b7f39e43f55461875' + + '6acce83f554618756acce8bf80432a5b7f39e43ff1e33149d12cec3f25d83c6da857de3f25d83c6da857debf' + + 'f1e33149d12cec3fba545599e663d23f0058e69383a6ee3f0058e69383a6eebfba545599e663d23f306b0136' + + 'ec97ee3f2045954e1ac4d23f2045954e1ac4d2bf306b0136ec97ee3fde41a966fffedd3f04c041318344ec3f' + + '04c041318344ecbfde41a966fffedd3f881dde1e87ace83fa2322b695a60e43fa2322b695a60e4bf881dde1e' + + '87ace83fa130c112874fb83f8c531475fadaef3f8c531475fadaefbfa130c112874fb83fd3beb154dcf4ef3f' + + '17835fbd01b1aa3f17835fbd01b1aabfd3beb154dcf4ef3f9f649751c36ae53f33d3e29cb8c6e73f33d3e29c' + + 'b8c6e7bf9f649751c36ae53f60a09927b3e2ec3f9356fd14788adb3f9356fd14788adbbf60a09927b3e2ec3f' + + 'b467f4124060d53f7a1939448f29ee3f7a1939448f29eebfb467f4124060d53f8c73cf145a04ef3f0238bd80' + + '747bcf3f0238bd80747bcfbf8c73cf145a04ef3fb7b831ecf35de03fe992e786667feb3fe992e786667febbf' + + 'b7b831ecf35de03fb2062ba4dfa4e93f1fa649ec2124e33f1fa649ec2124e3bfb2062ba4dfa4e93f0934fd4d' + + '9964c23fdcfd0ccbfbaaef3fdcfd0ccbfbaaefbf0934fd4d9964c23f91177aac9ba3ef3fa71645f97b2bc33f' + + 'a71645f97b2bc3bf91177aac9ba3ef3f1510444bc2fbe23fc275f010d1c2e93fc275f010d1c2e9bf1510444b' + + 'c2fbe23f47bcfd148f65eb3f8cb032201189e03f8cb032201189e0bf47bcfd148f65eb3f48e32d466bb8ce3f' + + '5f8f89bc9010ef3f5f8f89bc9010efbf48e32d466bb8ce3fd966dc2fa018ee3fb6b39d8be7bed53fb6b39d8b' + + 'e7bed5bfd966dc2fa018ee3f7219b31d972fdb3f7b46cee830f8ec3f7b46cee830f8ecbf7219b31d972fdb3f' + + 'd297bf07f7a4e73fdf23f7d50190e53fdf23f7d50190e5bfd297bf07f7a4e73f864687a5ba8da73f64911bbb' + + '53f7ef3f64911bbb53f7efbf864687a5ba8da73f79a6e29ce0fcef3f1d3be54c4f459c3f1d3be54c4f459cbf' + + '79a6e29ce0fcef3f106ae5bd7cfee53f4299078e553ee73f4299078e553ee7bf106ae5bd7cfee53fdcfbcb7b' + + 'fc36ed3fc00ab543651dda3fc00ab543651ddabfdcfbcb7bfc36ed3fb60c8a6398d9d63f818d6d0f16e4ed3f' + + '818d6d0f16e4edbfb60c8a6398d9d63ff0ae3a5a6833ef3fdd745d53906dcc3fdd745d53906dccbff0ae3a5a' + + '6833ef3f57a9d0487209e13ff5a24c2a7416eb3ff5a24c2a7416ebbf57a9d0487209e13f5ea7c0d2261bea3f' + + 'ba3c4def8b81e23fba3c4def8b81e2bf5ea7c0d2261bea3fdecb5486007fc53f784bcb37a78bef3f784bcb37' + + 'a78befbfdecb5486007fc53f888d0a0f47bfef3f5bb86fade80ec03f5bb86fade80ec0bf888d0a0f47bfef3f' + + '2930d6e3239ce33f6c4aace39049e93f6c4aace39049e9bf2930d6e3239ce33f27230dcb54cbeb3fded2245c' + + '57b7df3fded2245c57b7dfbf27230dcb54cbeb3fce49174e5be1d03f5186076aebddee3f5186076aebddeebf' + + 'ce49174e5be1d03fd36704559d5aee3ff03689dc1043d43ff03689dc1043d4bfd36704559d5aee3f895386c3' + + '7f99dc3f49c4b9198fa0ec3f49c4b9198fa0ecbf895386c37f99dc3fff45f5139c2ae83f86a4cc25ccf9e43f' + + '86a4cc25ccf9e4bfff45f5139c2ae83f4d44ed74960cb23f0f4130259debef3f0f4130259debefbf4d44ed74' + + '960cb23f602d4885eae7ef3f99a2c5129f9db33f99a2c5129f9db3bf602d4885eae7ef3f7f9f586dbcd3e43f' + + 'fa83af11714be83ffa83af11714be8bf7f9f586dbcd3e43f139c0287f589ec3f21cde1ae4bf3dc3f21cde1ae' + + '4bf3dcbf139c0287f589ec3f71c26ee99be3d33fa7535dc5616aee3fa7535dc5616aeebf71c26ee99be3d33f' + + '0990995e83d0ee3f7893c6ef3e42d13f7893c6ef3e42d1bf0990995e83d0ee3fa3cd56e6de5fdf3fc1541161' + + '1be4eb3fc15411611be4ebbfa3cd56e6de5fdf3f15a8c51fa42ae93f18c58149c4c3e33f18c58149c4c3e3bf' + + '15a8c51fa42ae93f3faae4fdb78ebe3ff69a7d3b6ec5ef3ff69a7d3b6ec5efbf3faae4fdb78ebe3f0cc6404a' + + '0f83ef3f0d831d831a45c63f0d831d831a45c6bf0cc6404a0f83ef3f1071bb4c7358e23fc63b594a1838ea3f' + + 'c63b594a1838eabf1071bb4c7358e23fb6579fd88ffbea3f4f25eecfe933e13f4f25eecfe933e1bfb6579fd8' + + '8ffbea3fad5df13463a9cb3f65bc1bbc6b3eef3f65bc1bbc6b3eefbfad5df13463a9cb3f5a918af3fed1ed3f' + + '921026c96337d73f921026c96337d7bf5a918af3fed1ed3ff2f90d447dc1d93f2475181b5b4bed3f2475181b' + + '5b4bedbff2f90d447dc1d93fbf410e96ac1be73fff22ec4fe422e63fff22ec4fe422e6bfbf410e96ac1be73f' + + '26b2fa214dfd953f77cb70681cfeef3f77cb70681cfeefbf26b2fa214dfd953fd13bc54309ffef3fcb97b96a' + + '296a8f3fcb97b96a296a8fbfd13bc54309ffef3f5b537f431547e63f755bc999caf8e63f755bc999caf8e6bf' + + '5b537f431547e63f7f8a8872715fed3f8f94abb75565d93f8f94abb75565d9bf7f8a8872715fed3faedf13e6' + + 'f594d73f9a7595439ebfed3f9a7595439ebfedbfaedf13e6f594d73fb4abbc062249ef3fabb9f3d5f1e4ca3f' + + 'abb9f3d5f1e4cabfb4abbc062249ef3fbce2dbe4365ee13fefec45f368e0ea3fefec45f368e0eabfbce2dbe4' + + '365ee13f23f59010c954ea3fe2132c662d2fe23fe2132c662d2fe2bf23f59010c954ea3fffc4088dfd0ac73f' + + '2a321a9c297aef3f2a321a9c297aefbfffc4088dfd0ac73f5443910347cbef3fc17d303b53ffbc3fc17d303b' + + '53ffbcbf5443910347cbef3f8006beea33ebe33ffe5e5743790be93ffe5e5743790be9bf8006beea33ebe33f' + + '47b1a1259dfceb3ffef7bf061908df3ffef7bf061908dfbf47b1a1259dfceb3f43f2e8fbf7a2d13fb2f61a4b' + + 'cfc2ee3fb2f61a4bcfc2eebf43f2e8fbf7a2d13f5a16a529db79ee3fabb653e3f583d33fabb653e3f583d3bf' + + '5a16a529db79ee3f9d60a82bd04cdd3fd7aa9e891573ec3fd7aa9e891573ecbf9d60a82bd04cdd3f95a19a1d' + + '0a6ce83ff122675179ade43ff122675179ade4bf95a19a1d0a6ce83f0a4d4d4a772eb53f86d8e92be9e3ef3f' + + '86d8e92be9e3efbf0a4d4d4a772eb53f9161820201efef3f6430464e617bb03f6430464e617bb0bf91618202' + + '01efef3fa69ad91ca81fe53ffa526e758b09e83ffa526e758b09e8bfa69ad91ca81fe53f99da000ae2b6ec3f' + + '293126476d3fdc3f293126476d3fdcbf99da000ae2b6ec3ff3821bd153a2d43f5ece81ff8d4aee3f5ece81ff' + + '8d4aeebff3821bd153a2d43f44a5504c07ebee3f1e66eb054e80d03f1e66eb054e80d0bf44a5504c07ebee3f' + + 'e1822bc84007e03f0dc4b6a049b2eb3f0dc4b6a049b2ebbfe1822bc84007e03fe17fbd423f68e93f8d7f811b' + + '5374e33f8d7f811b5374e3bfe17fbd423f68e93f8667b2bc4dd6c03fb7ad668dd1b8ef3fb7ad668dd1b8efbf' + + '8667b2bc4dd6c03f08ac854ff193ef3f88fa797fb1b8c43f88fa797fb1b8c4bf08ac854ff193ef3f58eb7ae8' + + '76aae23fde4931f1f4fde93fde4931f1f4fde9bf58eb7ae876aae23ff37bf3a51531eb3fb6c44bb8d0dee03f' + + 'b6c44bb8d0dee0bff37bf3a51531eb3feebd2c4d7731cd3fce0946fc1728ef3fce0946fc1728efbfeebd2c4d' + + '7731cd3f9ca59b6ae3f5ed3fcb63ad9c947bd63fcb63ad9c947bd6bf9ca59b6ae3f5ed3f1bf3dbd30c79da3f' + + 'e1a4e5c65522ed3fe1a4e5c65522edbf1bf3dbd30c79da3f6447302cc560e73f5c343ee7ded9e53f5c343ee7' + + 'ded9e5bf6447302cc560e73f7fc142db8546a13faefd25e455fbef3faefd25e455fbefbf7fc142db8546a13f' + + '14c008427cf9ef3f7961f86f396aa43f7961f86f396aa4bf14c008427cf9ef3f48744f260bb5e53f5bb3901b' + + 'fb82e73f5bb3901bfb82e7bf48744f260bb5e53fb9d2592f670ded3f09dc5c1273d4da3f09dc5c1273d4dabf' + + 'b9d2592f670ded3f02c2885c591dd63f540f28d96607ee3f540f28d96607eebf02c2885c591dd63f084728be' + + '7a1cef3f9a09013f16f5cd3f9a09013f16f5cdbf084728be7a1cef3fec858f8705b4e03f2579de09744beb3f' + + '2579de09744bebbfec858f8705b4e03f7224b4ed82e0e93fb89b4ed333d3e23fb89b4ed333d3e2bf7224b4ed' + + '82e0e93f9348db572ff2c33f29defb7ced9bef3f29defb7ced9befbf9348db572ff2c33f4dd581c60db2ef3f' + + 'e724be40899dc13fe724be40899dc1bf4dd581c60db2ef3fe14dc152524ce33f947545f1ae86e93f947545f1' + + 'ae86e9bfe14dc152524ce33f5e15d91ffa98eb3f96bded55ae32e03f96bded55ae32e0bf5e15d91ffa98eb3f' + + 'd2fdb906181fd03fc0a31ce5d6f7ee3fc0a31ce5d6f7eebfd2fdb906181fd03f85ce75ec333aee3f487019dc' + + '6301d53f487019dc6301d5bf85ce75ec333aee3fd9c0ff1715e5db3fa0dec220eeccec3fa0dec220eeccecbf' + + 'd9c0ff1715e5db3f8636b0873fe8e73ffc9d15f54f45e53ffc9d15f54f45e5bf8636b0873fe8e73fc98e80f9' + + '06d4ad3fed31e11416f2ef3fed31e11416f2efbfc98e80f906d4ad3f0733f72299dfef3f29b1793e1bbfb63f' + + '29b1793e1bbfb6bf0733f72299dfef3fff9160300387e43fa11b48e7668ce83fa11b48e7668ce8bfff916030' + + '0387e43f5af8fe59ef5bec3fd910fa5c0ca6dd3fd910fa5c0ca6ddbf5af8fe59ef5bec3fafba38b61f24d33f' + + '2560ad5b0989ee3f2560ad5b0989eebfafba38b61f24d33f11885b51cfb4ee3fbe27d7838503d23fbe27d783' + + '8503d2bf11885b51cfb4ee3f2056f29506b0de3f575e46dcd914ec3f575e46dcd914ecbf2056f29506b0de3f' + + '496c489b10ece83f8c103d667212e43f8c103d667212e4bf496c489b10ece83f4cf638eca66fbb3f8760d858' + + 'd1d0ef3f8760d858d1d0efbf4cf638eca66fbb3fb77e4b43f670ef3f1ccbd2bba7d0c73f1ccbd2bba7d0c7bf' + + 'b77e4b43f670ef3fd66075a1ba05e23ff5609dde3871ea3ff5609dde3871eabfd66075a1ba05e23fc8fa3ebd' + + 'ffc4ea3fe5463a1f5988e13fe5463a1f5988e1bfc8fa3ebdffc4ea3fda31181b3e20ca3f072daf1f8b53ef3f' + + '072daf1f8b53efbfda31181b3e20ca3fb98ae62cf4aced3fe44173d34df2d73fe44173d34df2d7bfb98ae62c' + + 'f4aced3fd17bef81ef08d93fff0d8c503f73ed3fff0d8c503f73edbfd17bef81ef08d93fcdaf4aefafd5e63f' + + '86b3523f0f6be63f86b3523f0f6be6bfcdaf4aefafd5e63f0397500e6bd9823f4f8c972ca7ffef3f4f8c972c' + + 'a7ffefbf0397500e6bd9823f4f8c972ca7ffef3f0397500e6bd9823f0397500e6bd982bf4f8c972ca7ffef3f' + + '86b3523f0f6be63fcdaf4aefafd5e63fcdaf4aefafd5e6bf86b3523f0f6be63fff0d8c503f73ed3fd17bef81' + + 'ef08d93fd17bef81ef08d9bfff0d8c503f73ed3fe44173d34df2d73fb98ae62cf4aced3fb98ae62cf4acedbf' + + 'e44173d34df2d73f072daf1f8b53ef3fda31181b3e20ca3fda31181b3e20cabf072daf1f8b53ef3fe5463a1f' + + '5988e13fc8fa3ebdffc4ea3fc8fa3ebdffc4eabfe5463a1f5988e13ff5609dde3871ea3fd66075a1ba05e23f' + + 'd66075a1ba05e2bff5609dde3871ea3f1ccbd2bba7d0c73fb77e4b43f670ef3fb77e4b43f670efbf1ccbd2bb' + + 'a7d0c73f8760d858d1d0ef3f4cf638eca66fbb3f4cf638eca66fbbbf8760d858d1d0ef3f8c103d667212e43f' + + '496c489b10ece83f496c489b10ece8bf8c103d667212e43f575e46dcd914ec3f2056f29506b0de3f2056f295' + + '06b0debf575e46dcd914ec3fbe27d7838503d23f11885b51cfb4ee3f11885b51cfb4eebfbe27d7838503d23f' + + '2560ad5b0989ee3fafba38b61f24d33fafba38b61f24d3bf2560ad5b0989ee3fd910fa5c0ca6dd3f5af8fe59' + + 'ef5bec3f5af8fe59ef5becbfd910fa5c0ca6dd3fa11b48e7668ce83fff9160300387e43fff9160300387e4bf' + + 'a11b48e7668ce83f29b1793e1bbfb63f0733f72299dfef3f0733f72299dfefbf29b1793e1bbfb63fed31e114' + + '16f2ef3fc98e80f906d4ad3fc98e80f906d4adbfed31e11416f2ef3ffc9d15f54f45e53f8636b0873fe8e73f' + + '8636b0873fe8e7bffc9d15f54f45e53fa0dec220eeccec3fd9c0ff1715e5db3fd9c0ff1715e5dbbfa0dec220' + + 'eeccec3f487019dc6301d53f85ce75ec333aee3f85ce75ec333aeebf487019dc6301d53fc0a31ce5d6f7ee3f' + + 'd2fdb906181fd03fd2fdb906181fd0bfc0a31ce5d6f7ee3f96bded55ae32e03f5e15d91ffa98eb3f5e15d91f' + + 'fa98ebbf96bded55ae32e03f947545f1ae86e93fe14dc152524ce33fe14dc152524ce3bf947545f1ae86e93f' + + 'e724be40899dc13f4dd581c60db2ef3f4dd581c60db2efbfe724be40899dc13f29defb7ced9bef3f9348db57' + + '2ff2c33f9348db572ff2c3bf29defb7ced9bef3fb89b4ed333d3e23f7224b4ed82e0e93f7224b4ed82e0e9bf' + + 'b89b4ed333d3e23f2579de09744beb3fec858f8705b4e03fec858f8705b4e0bf2579de09744beb3f9a09013f' + + '16f5cd3f084728be7a1cef3f084728be7a1cefbf9a09013f16f5cd3f540f28d96607ee3f02c2885c591dd63f' + + '02c2885c591dd6bf540f28d96607ee3f09dc5c1273d4da3fb9d2592f670ded3fb9d2592f670dedbf09dc5c12' + + '73d4da3f5bb3901bfb82e73f48744f260bb5e53f48744f260bb5e5bf5bb3901bfb82e73f7961f86f396aa43f' + + '14c008427cf9ef3f14c008427cf9efbf7961f86f396aa43faefd25e455fbef3f7fc142db8546a13f7fc142db' + + '8546a1bfaefd25e455fbef3f5c343ee7ded9e53f6447302cc560e73f6447302cc560e7bf5c343ee7ded9e53f' + + 'e1a4e5c65522ed3f1bf3dbd30c79da3f1bf3dbd30c79dabfe1a4e5c65522ed3fcb63ad9c947bd63f9ca59b6a' + + 'e3f5ed3f9ca59b6ae3f5edbfcb63ad9c947bd63fce0946fc1728ef3feebd2c4d7731cd3feebd2c4d7731cdbf' + + 'ce0946fc1728ef3fb6c44bb8d0dee03ff37bf3a51531eb3ff37bf3a51531ebbfb6c44bb8d0dee03fde4931f1' + + 'f4fde93f58eb7ae876aae23f58eb7ae876aae2bfde4931f1f4fde93f88fa797fb1b8c43f08ac854ff193ef3f' + + '08ac854ff193efbf88fa797fb1b8c43fb7ad668dd1b8ef3f8667b2bc4dd6c03f8667b2bc4dd6c0bfb7ad668d' + + 'd1b8ef3f8d7f811b5374e33fe17fbd423f68e93fe17fbd423f68e9bf8d7f811b5374e33f0dc4b6a049b2eb3f' + + 'e1822bc84007e03fe1822bc84007e0bf0dc4b6a049b2eb3f1e66eb054e80d03f44a5504c07ebee3f44a5504c' + + '07ebeebf1e66eb054e80d03f5ece81ff8d4aee3ff3821bd153a2d43ff3821bd153a2d4bf5ece81ff8d4aee3f' + + '293126476d3fdc3f99da000ae2b6ec3f99da000ae2b6ecbf293126476d3fdc3ffa526e758b09e83fa69ad91c' + + 'a81fe53fa69ad91ca81fe5bffa526e758b09e83f6430464e617bb03f9161820201efef3f9161820201efefbf' + + '6430464e617bb03f86d8e92be9e3ef3f0a4d4d4a772eb53f0a4d4d4a772eb5bf86d8e92be9e3ef3ff1226751' + + '79ade43f95a19a1d0a6ce83f95a19a1d0a6ce8bff122675179ade43fd7aa9e891573ec3f9d60a82bd04cdd3f' + + '9d60a82bd04cddbfd7aa9e891573ec3fabb653e3f583d33f5a16a529db79ee3f5a16a529db79eebfabb653e3' + + 'f583d33fb2f61a4bcfc2ee3f43f2e8fbf7a2d13f43f2e8fbf7a2d1bfb2f61a4bcfc2ee3ffef7bf061908df3f' + + '47b1a1259dfceb3f47b1a1259dfcebbffef7bf061908df3ffe5e5743790be93f8006beea33ebe33f8006beea' + + '33ebe3bffe5e5743790be93fc17d303b53ffbc3f5443910347cbef3f5443910347cbefbfc17d303b53ffbc3f' + + '2a321a9c297aef3fffc4088dfd0ac73fffc4088dfd0ac7bf2a321a9c297aef3fe2132c662d2fe23f23f59010' + + 'c954ea3f23f59010c954eabfe2132c662d2fe23fefec45f368e0ea3fbce2dbe4365ee13fbce2dbe4365ee1bf' + + 'efec45f368e0ea3fabb9f3d5f1e4ca3fb4abbc062249ef3fb4abbc062249efbfabb9f3d5f1e4ca3f9a759543' + + '9ebfed3faedf13e6f594d73faedf13e6f594d7bf9a7595439ebfed3f8f94abb75565d93f7f8a8872715fed3f' + + '7f8a8872715fedbf8f94abb75565d93f755bc999caf8e63f5b537f431547e63f5b537f431547e6bf755bc999' + + 'caf8e63fcb97b96a296a8f3fd13bc54309ffef3fd13bc54309ffefbfcb97b96a296a8f3f77cb70681cfeef3f' + + '26b2fa214dfd953f26b2fa214dfd95bf77cb70681cfeef3fff22ec4fe422e63fbf410e96ac1be73fbf410e96' + + 'ac1be7bfff22ec4fe422e63f2475181b5b4bed3ff2f90d447dc1d93ff2f90d447dc1d9bf2475181b5b4bed3f' + + '921026c96337d73f5a918af3fed1ed3f5a918af3fed1edbf921026c96337d73f65bc1bbc6b3eef3fad5df134' + + '63a9cb3fad5df13463a9cbbf65bc1bbc6b3eef3f4f25eecfe933e13fb6579fd88ffbea3fb6579fd88ffbeabf' + + '4f25eecfe933e13fc63b594a1838ea3f1071bb4c7358e23f1071bb4c7358e2bfc63b594a1838ea3f0d831d83' + + '1a45c63f0cc6404a0f83ef3f0cc6404a0f83efbf0d831d831a45c63ff69a7d3b6ec5ef3f3faae4fdb78ebe3f' + + '3faae4fdb78ebebff69a7d3b6ec5ef3f18c58149c4c3e33f15a8c51fa42ae93f15a8c51fa42ae9bf18c58149' + + 'c4c3e33fc15411611be4eb3fa3cd56e6de5fdf3fa3cd56e6de5fdfbfc15411611be4eb3f7893c6ef3e42d13f' + + '0990995e83d0ee3f0990995e83d0eebf7893c6ef3e42d13fa7535dc5616aee3f71c26ee99be3d33f71c26ee9' + + '9be3d3bfa7535dc5616aee3f21cde1ae4bf3dc3f139c0287f589ec3f139c0287f589ecbf21cde1ae4bf3dc3f' + + 'fa83af11714be83f7f9f586dbcd3e43f7f9f586dbcd3e4bffa83af11714be83f99a2c5129f9db33f602d4885' + + 'eae7ef3f602d4885eae7efbf99a2c5129f9db33f0f4130259debef3f4d44ed74960cb23f4d44ed74960cb2bf' + + '0f4130259debef3f86a4cc25ccf9e43fff45f5139c2ae83fff45f5139c2ae8bf86a4cc25ccf9e43f49c4b919' + + '8fa0ec3f895386c37f99dc3f895386c37f99dcbf49c4b9198fa0ec3ff03689dc1043d43fd36704559d5aee3f' + + 'd36704559d5aeebff03689dc1043d43f5186076aebddee3fce49174e5be1d03fce49174e5be1d0bf5186076a' + + 'ebddee3fded2245c57b7df3f27230dcb54cbeb3f27230dcb54cbebbfded2245c57b7df3f6c4aace39049e93f' + + '2930d6e3239ce33f2930d6e3239ce3bf6c4aace39049e93f5bb86fade80ec03f888d0a0f47bfef3f888d0a0f' + + '47bfefbf5bb86fade80ec03f784bcb37a78bef3fdecb5486007fc53fdecb5486007fc5bf784bcb37a78bef3f' + + 'ba3c4def8b81e23f5ea7c0d2261bea3f5ea7c0d2261beabfba3c4def8b81e23ff5a24c2a7416eb3f57a9d048' + + '7209e13f57a9d0487209e1bff5a24c2a7416eb3fdd745d53906dcc3ff0ae3a5a6833ef3ff0ae3a5a6833efbf' + + 'dd745d53906dcc3f818d6d0f16e4ed3fb60c8a6398d9d63fb60c8a6398d9d6bf818d6d0f16e4ed3fc00ab543' + + '651dda3fdcfbcb7bfc36ed3fdcfbcb7bfc36edbfc00ab543651dda3f4299078e553ee73f106ae5bd7cfee53f' + + '106ae5bd7cfee5bf4299078e553ee73f1d3be54c4f459c3f79a6e29ce0fcef3f79a6e29ce0fcefbf1d3be54c' + + '4f459c3f64911bbb53f7ef3f864687a5ba8da73f864687a5ba8da7bf64911bbb53f7ef3fdf23f7d50190e53f' + + 'd297bf07f7a4e73fd297bf07f7a4e7bfdf23f7d50190e53f7b46cee830f8ec3f7219b31d972fdb3f7219b31d' + + '972fdbbf7b46cee830f8ec3fb6b39d8be7bed53fd966dc2fa018ee3fd966dc2fa018eebfb6b39d8be7bed53f' + + '5f8f89bc9010ef3f48e32d466bb8ce3f48e32d466bb8cebf5f8f89bc9010ef3f8cb032201189e03f47bcfd14' + + '8f65eb3f47bcfd148f65ebbf8cb032201189e03fc275f010d1c2e93f1510444bc2fbe23f1510444bc2fbe2bf' + + 'c275f010d1c2e93fa71645f97b2bc33f91177aac9ba3ef3f91177aac9ba3efbfa71645f97b2bc33fdcfd0ccb' + + 'fbaaef3f0934fd4d9964c23f0934fd4d9964c2bfdcfd0ccbfbaaef3f1fa649ec2124e33fb2062ba4dfa4e93f' + + 'b2062ba4dfa4e9bf1fa649ec2124e33fe992e786667feb3fb7b831ecf35de03fb7b831ecf35de0bfe992e786' + + '667feb3f0238bd80747bcf3f8c73cf145a04ef3f8c73cf145a04efbf0238bd80747bcf3f7a1939448f29ee3f' + + 'b467f4124060d53fb467f4124060d5bf7a1939448f29ee3f9356fd14788adb3f60a09927b3e2ec3f60a09927' + + 'b3e2ecbf9356fd14788adb3f33d3e29cb8c6e73f9f649751c36ae53f9f649751c36ae5bf33d3e29cb8c6e73f' + + '17835fbd01b1aa3fd3beb154dcf4ef3fd3beb154dcf4efbf17835fbd01b1aa3f8c531475fadaef3fa130c112' + + '874fb83fa130c112874fb8bf8c531475fadaef3fa2322b695a60e43f881dde1e87ace83f881dde1e87ace8bf' + + 'a2322b695a60e43f04c041318344ec3fde41a966fffedd3fde41a966fffeddbf04c041318344ec3f2045954e' + + '1ac4d23f306b0136ec97ee3f306b0136ec97eebf2045954e1ac4d23f0058e69383a6ee3fba545599e663d23f' + + 'ba545599e663d2bf0058e69383a6ee3f25d83c6da857de3ff1e33149d12cec3ff1e33149d12cecbf25d83c6d' + + 'a857de3f554618756acce83f80432a5b7f39e43f80432a5b7f39e4bf554618756acce83f5ca824ebb6dfb93f' + + '9e5ca72d0dd6ef3f9e5ca72d0dd6efbf5ca824ebb6dfb93fee3c88567567ef3f0418c4271796c83f0418c427' + + '1796c8bfee3c88567567ef3f7248dc641bdce13fd25a546e678dea3fd25a546e678deabf7248dc641bdce13f' + + '8eb92c7a54a9ea3fbf73131750b2e13fbf73131750b2e1bf8eb92c7a54a9ea3ffa2ab6e9495bc93f5d6843ed' + + 'a65def3f5d6843eda65defbffa2ab6e9495bc93f463d8bdd009aed3f3f90f3aa6a4fd83f3f90f3aa6a4fd8bf' + + '463d8bdd009aed3f44edd5864bacd83f4fa44584c486ed3f4fa44584c486edbf44edd5864bacd83f9ce22fed' + + '5cb2e63f719ca1ead18ee63f719ca1ead18ee6bf9ce22fed5cb2e63fbaa4ccbef821693f021d6221f6ffef3f' + + '021d6221f6ffefbfbaa4ccbef821693f' + ) + ); + + // Sanity check (shake256 because used already): catch byte-level corruption, endianness/layout + // mistakes, or accidental regeneration through engine-dependent sin/cos results. + const rootBytes = u8f(baswap64If(Float64Array.from(roots))); + if ( + bytesToHex(shake256(rootBytes)) !== + 'f45a496cf56ccc6e3e3395a20209206d81d71a7905a661447bd5bc0e24e0af1e' + ) { + throw new Error('COMPLEX_ROOTS mismatch'); + } + return roots; +})(); + +// Falcon's q-field Montgomery kernel: mul() operates on Montgomery residues and returns one. +// inv() accepts a normal residue but returns its inverse in Montgomery form, so div(x, y) can stay +// `mul(x, inv(y))`; callers like toMontgomery() manage the representation boundaries. +const intField = { + mul(x: number, y: number) { + let z = Math.imul(x, y); + let w = Math.imul(Q, Math.imul(z, Q0I) & 0xffff); + z = ((z + w) >>> 16) - Q; + z += Q & (z >> 31); + return z >>> 0; + }, + inv(y: number): number { + // y^(q-2) mod q + if (y === 0) throw new Error('divison by zero'); + const e00 = this.mul(y, R2); // e0 = 1 + const e01 = this.mul(e00, e00); // 2 * e0 = 2 + const e02 = this.mul(e01, e00); // e1 + e0 = 3 + const e03 = this.mul(e02, e01); // e3 = e2 + e1 = 5 + const e04 = this.mul(e03, e03); // e4 = 2 * e3 = 10 + const e05 = this.mul(e04, e04); // e5 = 2 * e4 = 20 + const e06 = this.mul(e05, e05); // e6 = 2 * e5 = 40 + const e07 = this.mul(e06, e06); // e7 = 2 * e6 = 80 + const e08 = this.mul(e07, e07); // e8 = 2 * e7 = 160 + const e09 = this.mul(e08, e02); // e9 = e8 + e2 = 163 + const e10 = this.mul(e09, e08); // e10 = e9 + e8 = 323 + const e11 = this.mul(e10, e10); // e11 = 2 * e10 = 646 + const e12 = this.mul(e11, e11); // e12 = 2 * e11 = 1292 + const e13 = this.mul(e12, e09); // e13 = e12 + e9 = 1455 + const e14 = this.mul(e13, e13); // e14 = 2 * e13 = 2910 + const e15 = this.mul(e14, e14); // e15 = 2 * e14 = 5820 + const e16 = this.mul(e15, e10); // e16 = e15 + e10 = 6143 + const e17 = this.mul(e16, e16); // e17 = 2 * e16 = 12286 + const e18 = this.mul(e17, e00); // e18 = e17 + e0 = 12287 + return e18; + }, + div: (x: number, y: number): number => intField.mul(x, intField.inv(y)), +}; + +function getIntPoly(logn: number) { + const n = 1 << logn; + const newPoly = (n: number) => new Uint16Array(n); + const F = Number(invert(BigInt(n), QBig)); + const { mod, smod, NTT } = genCrystals({ + N: n, + Q, + F: F, + ROOT_OF_UNITY: 7, + newPoly, + isKyber: false, + brvBits: 10, + }); + // Keep Falcon source compatible with older TS parsers: avoid spelling newer + // `Uint16Array` syntax directly and cast the callee side at the boundary. + const ntt = (r: TArg): TRet => (NTT.encode as any)(r); + const intt = (r: TArg): TRet => (NTT.decode as any)(r); + // Falcon integer helpers mutate their first argument in place; div() also performs intt() + // before returning, so callers must treat these as owned-temporary transforms, not pure helpers. + // Centered representatives are in [-6144, 6144] for odd q = 12289, + // not a generic [-q/2, q/2] range. + const signedCoder = { + encode: (p: TArg) => Int16Array.from(p, (x) => smod(x)), + decode: (p: TArg) => Uint16Array.from(p, (x) => mod(x)), + }; + const intPoly = { + create: newPoly, + smallSqnorm(f: TArg) { + let s = 0; + let ng = 0; + for (let u = 0; u < n; u++) { + const z = f[u]; + s = (s + z * z) >>> 0; + ng |= s; + } + return (s | -(ng >>> 31)) >>> 0; + }, + isShort(s1: TArg, s2: TArg) { + let s = 0 >>> 0; + let ng = 0 >>> 0; + for (let u = 0; u < n; u++) { + let z1 = (s1[u] << 16) >> 16; + s = (s + ((z1 * z1) >>> 0)) >>> 0; + ng |= s; + let z2 = (s2[u] << 16) >> 16; + s = (s + ((z2 * z2) >>> 0)) >>> 0; + ng |= s; + } + if (ng & 0x80000000) s = 0xffffffff; + return s <= L2BOUND[logn]; + }, + sub(a: TArg, b: TArg): TRet { + for (let i = 0; i < n; i++) a[i] = mod(a[i] - b[i]); + return a as TRet; + }, + ntt, + intt, + toMontgomery(d: TArg): TRet { + for (let i = 0; i < n; i++) d[i] = intField.mul(d[i], R2); + return d as TRet; + }, + mul(f: TArg, d: TArg): TRet { + for (let i = 0; i < n; i++) f[i] = intField.mul(f[i], d[i]); + return f as TRet; + }, + div(f: TArg, d: TArg): TRet { + for (let i = 0; i < n; i++) f[i] = intField.div(f[i], d[i]); + this.intt(f); + return f as TRet; + }, + }; + return { newPoly, intPoly, signedCoder }; +} + +// Falcon's JS binary64 complex field wrapper for FFT/sampler paths. Current uses are the +// ordinary finite-number operations add/sub/neg/mul/conj/scale/magSqSum; the inherited wider API +// exists because getComplex() exposes it, not because all methods are relied on by Falcon today. +const fComplex = getComplex({ + ZERO: 0, + ONE: 1, + add: (x: number, y: number) => x + y, + sub: (x: number, y: number) => x - y, + mul: (x: number, y: number) => x * y, + div: (x: number, y: number) => x / y, + eql: (x: number, y: number) => x === y, + inv: (x: number) => 1 / x, + neg: (x: number) => -x, +} as any as IField); + +// Detached object copy of the exact round-3 / PQClean fpr_gm_tab payload in its original order. +const COMPLEX_ROOTS_O = ComplexArrInterleaved.decode(COMPLEX_ROOTS); +// Re-map roots into the local forward FFTCore schedule +// `{ dit: false, invertButterflies: true, brp: false }`. +// Index 0 stays intentionally unused because FFTCore's forward group counter starts at 1. +const FFTCoreRoots: Record[]> = {}; +// Inverse FFTCore reads roots as `N - grp`, so fill this table from the end and store `-conj(root)` +// rather than plain conjugates +// to match Falcon's split/iFFT sign convention under the local butterfly. +const FFTCoreRootsConj: Record[]> = {}; +for (let logn = 0; logn < 10; logn++) { + const out = new Array(1 << logn); + const outC = new Array(1 << logn); + for (let i = 0, g1 = 1, g2 = 1; i < logn; i++) { + const ng = 1 << i; + for (let k = 0; k < ng; k++) out[g1++] = COMPLEX_ROOTS_O[(ng << 1) + k]; + const ng2 = 1 << (logn - i); + for (let k = 0; k < ng2 >> 1; k++) + outC[out.length - g2++] = fComplex.neg(fComplex.conj(COMPLEX_ROOTS_O[ng2 + k])); + } + FFTCoreRoots[logn] = out; + FFTCoreRootsConj[logn] = outC; +} + +type CPoly = ComplexElm[]; +// Mixed float-poly helper surface: most methods allocate / return fresh values, +// but FFT() and iFFT() mutate their CPoly input in place. +// Flat Float64Array buffers use ComplexArr's [...re, ...im] layout. +function getFloatPoly(logn: number) { + const n = 1 << logn; + const N_COMPLEX = n >> 1; + const hn = Math.log2(N_COMPLEX); + const fftOpts = { N: N_COMPLEX, invertButterflies: true, skipStages: 0, brp: false }; + const inv = 1.0 / N_COMPLEX; + return { + to: (f: TArg) => ComplexArr.decode(Array.from(f)), + from: (f: CPoly): TRet => new Float64Array(ComplexArr.encode(f)) as TRet, + // Runtime callers also pass HashToPoint's Uint16Array output here; + // the implementation only needs a numeric typed-array shape, + // even though the local type is narrower. + convSmall: (f: TArg): CPoly => ComplexArr.decode(Array.from(f)), + add: (a: CPoly, b: CPoly): CPoly => a.map((i, j) => fComplex.add(i, b[j])), + sub: (a: CPoly, b: CPoly): CPoly => a.map((i, j) => fComplex.sub(i, b[j])), + neg: (a: CPoly): CPoly => a.map((i) => fComplex.neg(i)), + mul: (a: CPoly, b: CPoly): CPoly => a.map((i, j) => fComplex.mul(i, b[j])), + conj: (a: CPoly): CPoly => a.map((i) => fComplex.conj(i)), + mulConst: (a: CPoly, x: number): CPoly => a.map((i) => fComplex.scale(i, x)), + scaleNorm: (a: CPoly, b: TArg): CPoly => a.map((i, j) => fComplex.scale(i, b[j])), + invNorm: (a: CPoly, b: CPoly) => + new Float64Array(a.map((i, j) => 1.0 / fComplex.magSqSum(i, b[j]))), + FFT: (f: CPoly): CPoly => + FFTCore(fComplex, { ...fftOpts, dit: false, roots: FFTCoreRoots[hn] })(f), + iFFT(f: CPoly): CPoly { + FFTCore(fComplex, { ...fftOpts, dit: true, roots: FFTCoreRootsConj[hn] })(f); + for (let i = 0; i < f.length; i++) f[i] = fComplex.scale(f[i], inv); + return f; + }, + }; +} + +function ApproxExp(x: number, ccs: number): number { + // Algorithm 13: ApproxExp(x, ccs), (Page 42) + // Require: Floating-point values x ∈ [0, ln(2)] and ccs ∈ [0, 1] + // Ensure: A floating approximation of ccs · exp(-x); berExp() applies the later 2^63 scaling. + // 1: C = [0x00000004741183A3, ...] + // 2: y ← C[0] ▷ y and z remain in {0, ..., 2⁶³ - 1} the whole algorithm. + // 3: z ← ⌊2⁶³ · x⌋ + // 4: for i = 1, ..., 12 do + // 5: y ← C[i] - (z · y) >> 63 ▷ (z · y) fits in 126 bits, but we only need the top 63 bits + // 6: z ← ⌊2⁶³ · ccs⌋ + // 7: y ← (z · y) >> 63 + // 8: return y + // FACCT / round-3 Falcon's leading 1.0 coefficient is implicit in `return ccs * (1.0 + z * y)`, + // so the decimal list below stores the remaining 12 polynomial coefficients only. + const ev = [ + 0.99999999999999489297408672428, 0.500000000000019206858326015208, + 0.166666666666984014666397229121, 0.041666666666110491190622155955, + 0.008333333327800835146903501993, 0.001388888894063186997887560103, + 0.000198412739277311890541063977, 0.000024801566833585381209939524, + 0.000002755586350219122514855659, 0.000000275607356160477811864927, + 0.000000025299506379442070029551, 0.000000002073772366009083061987, + ]; + const y = -x; + let z = ev[ev.length - 1]; + for (let i = ev.length - 2; i >= 0; i--) z = z * y + ev[i]; + return ccs * (1.0 + z * y); +} + +// Actual api +type FalconOpts = { + N: number; + // Table 3.3 total padded detached bytes; kept as reference config, not read by genFalcon() today. + // In padded mode it still drives `.lengths.signature` + // and the payload width `sigLen - 1 - NONCELEN`. + sigLen: number; + padded?: boolean; + fgBits: number; + FGBits: number; + // Compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + paddedLen: number; + // Max compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + // Reference unpadded payload ceiling only: detached encode/decode use each signature's runtime + // `s2` length, while signRaw() enforces `maxS2Len` separately. + detachedLen: number; + maxS2Len: number; +}; + +type FalconRandom = (bytesLength?: number) => TRet; +type FalconSigOpts = SigOpts & { random?: FalconRandom }; +/** Falcon attached-signature API. */ +export type FalconAttached = CryptoKeys & { + /** Key lengths plus the 48-byte sampler-seed hook for signing. */ + lengths: CryptoKeys['lengths'] & { signRand?: number }; + /** + * Signs a message and appends it to the returned attached signature. + * @param msg Message bytes to sign. + * @param secretKey Falcon secret key bytes. + * @param opts Optional Falcon signing options. + * @returns Attached signature containing both the message and signature. + */ + seal(msg: Uint8Array, secretKey: Uint8Array, opts?: FalconSigOpts): Uint8Array; + /** + * Verifies an attached signature and returns the embedded message. + * @param sig Attached Falcon signature bytes. + * @param publicKey Falcon public key bytes. + * @param opts Optional verification options. + * @returns Embedded message bytes when the signature is valid. + */ + open(sig: Uint8Array, publicKey: Uint8Array, opts?: VerOpts): Uint8Array; +}; +/** Falcon detached-signature API with an attached-signature helper. */ +export type Falcon = Signer & { + /** Attached-signature helper for the same Falcon parameter set. */ + attached: FalconAttached; +}; + +function genFalcon(opts: FalconOpts): TRet { + const { N } = opts; + const logn = Math.log2(N); + const id = (n: T): T => n; + const { newPoly, intPoly, signedCoder } = getIntPoly(logn); + const floatPoly = getFloatPoly(logn); + // Kinda like FFT Sampler: single function, but a lot of private deps and internal rng stake + class NTRU { + private logn: number; + private shake: ReturnType; + constructor(logn: number, seed: Uint8Array) { + this.logn = logn; + this.shake = shake256.create().update(seed); + } + private gaussSingle() { + const g = 1 << (10 - this.logn); + let val = 0; + for (let i = 0; i < g; i++) { + const r128 = bytesToNumberLE(this.shake.xof(16)); + const r1 = r128 & 0x7fffffffffffffffn; + const r2 = (r128 >> 64n) & 0x7fffffffffffffffn; + const sign = Number((r128 >> 63n) & 1n); + let f = r1 < gauss_1024_12289[0] ? 1 : 0; + let v = 0; + for (let k = 1; k < gauss_1024_12289.length; k++) { + const tBit = r2 >= gauss_1024_12289[k] ? 1 : 0; + v |= k & -(tBit & (f ^ 1)); + f |= tBit; + } + val += sign === 1 ? -v : v; + } + return val; + } + private polyGauss(): SPoly { + const n = 1 << this.logn; + let mod2 = 0; // xor sum of previous elements + const f = new Int8Array(n); + for (let u = 0; u < n; u++) { + let s; + while (true) { + s = this.gaussSingle(); + if (s < -127 || s > 127) continue; + if (u === n - 1) if ((mod2 ^ (s & 1)) === 0) continue; + break; + } + if (u < n - 1) mod2 ^= s & 1; + f[u] = s; + } + return f; + } + private galoisNorm(logn: number, a: BPoly): BPoly { + const n = 1 << logn; + const d = new Array(n >> 1); + for (let k = 0; k < n; k += 2) { + let s: bigint = 0n; + for (let i = 0; i <= k; i += 2) s += a[i] * a[k - i]; + for (let i = k + 2; i < n; i += 2) s -= a[i] * a[k + n - i]; + d[k >>> 1] = s; + } + for (let k = 0; k < n; k += 2) { + let s: bigint = 0n; + for (let i = 1; i < k; i += 2) s += a[i] * a[k - i]; + for (let i = k + 1; i < n; i += 2) s -= a[i] * a[k + n - i]; + d[k >>> 1] -= s; + } + return d; + } + private mulConjD(logn: number, d: BPoly, a: BPoly, b: BPoly): BPoly { + const n = 1 << logn; + for (let k = 0; k < n; k++) { + let s: bigint = 0n; + for (let i = 0; i <= k; i += 2) s += b[i >>> 1] * a[k - i]; + for (let i = k + 2 - (k & 1); i < n; i += 2) s -= b[i >>> 1] * a[k + n - i]; + if ((k & 1) === 0) d[k] = s; + else d[k] = -s; + } + return d; + } + private subMul(logn: number, a: BPoly, b: BPoly, c: BPoly, e: bigint): BPoly { + const n = 1 << logn; + for (let k = 0; k < n; k++) { + let s: bigint = 0n; + for (let i = 0; i <= k; i++) s += b[i] * c[k - i]; + for (let i = k + 1; i < n; i++) s -= b[i] * c[k + n - i]; + a[k] -= s << e; + } + return a; + } + private reduce(logn: number, f: BPoly, g: BPoly, F: BPoly, G: BPoly, logn_top: number) { + // Algorithm 7: Reduce(f, g, F, G) + // (Page 35) + // Require: Polynomials f, g, F, G ∈ Z[x]/(φ) + // Ensure: (F, G) is reduced with respect to (f, g) + // 1: do + // 2: k ← ⌊(Ff*+Gg*)/(ff*+gg*)⌋ ▷ (Ff*+Gg*)/(ff*+gg*) ∈ Q[x]/(φ) and k ∈ Z[x]/(φ) + // 3: F ← F - kf + // 4: G ← G - kg + // 5: while k ≠ 0 + // ▷ Multiple iterations may be needed, e.g. if k is computed in small precision. + const n = 1 << logn; + const depth = logn_top - logn; + const floatPoly = getFloatPoly(logn); + const slen = MAX_BL_SMALL[depth]; + const llen = MAX_BL_LARGE[depth]; + let maxFGBits = BigInt(31 * llen); + let FGlen = BigInt(llen); + const scalefg = BigInt(31 * (slen - 10)); + const fgMaxBits = BITLENGTH[depth].avg + 6 * BITLENGTH[depth].std; + const fgMinBits = BITLENGTH[depth].avg - 6 * BITLENGTH[depth].std; + let scaleK = BigInt(Math.round(31 * llen - fgMinBits)); + let fx = new Float64Array(n); + let gx = new Float64Array(n); + for (let i = 0; i < n; i++) { + fx[i] = Number(f[i] >> scalefg); + gx[i] = Number(g[i] >> scalefg); + } + const rt3 = floatPoly.conj(floatPoly.FFT(floatPoly.to(fx))); + const rt4 = floatPoly.conj(floatPoly.FFT(floatPoly.to(gx))); + const rt5 = floatPoly.invNorm(rt3, rt4); + + const Fx = new Float64Array(n); + const Gx = new Float64Array(n); + const k = new Array(n); + while (true) { + let scaleFG = 31n * (FGlen - 10n); + for (let i = 0; i < n; i++) { + Fx[i] = Number(F[i] >> scaleFG); + Gx[i] = Number(G[i] >> scaleFG); + } + const rt2 = floatPoly.mul(floatPoly.FFT(floatPoly.to(Gx)), rt4); + const rt1 = floatPoly.mul(floatPoly.FFT(floatPoly.to(Fx)), rt3); + // convert to float64array + const rt2f = floatPoly.from( + floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.add(rt2, rt1), rt5)) + ); + const pdc = 2 ** Number(scaleFG - scalefg - scaleK); + for (let i = 0; i < n; i++) { + const BOUND = 2147483647.0; + const val = rt2f[i] * pdc; + if (val <= -BOUND || val >= BOUND) return false; + k[i] = BigInt(Math.round(val)); + } + F = this.subMul(logn, F, f, k, scaleK); // 3: F ← F - kf + G = this.subMul(logn, G, g, k, scaleK); // 4: G ← G - kg + const maxfgNew = scaleK + BigInt(Math.round(fgMaxBits)) + 10n; + if (maxfgNew < maxFGBits) maxFGBits = maxfgNew; + if (FGlen > 1n && FGlen * 31n >= maxFGBits + 31n) FGlen--; + if (scaleK <= 0n) break; + scaleK -= 25n; + if (scaleK < 0n) scaleK = 0n; + } + return true; + } + // This is recursive thing that goes from logn to 0 + private solveBranch(logn: number, f: BPoly, g: BPoly, F: BPoly, G: BPoly, logn_top?: number) { + // Algorithm 6: NTRUSolve_{n,q}(f, g), (Page 35) + // Require: f, g ∈ Z[x]/(xⁿ + 1) with n a power of two + // Ensure: Polynomials F, G such that (3.15) is verified + // 1: if n = 1 then + // 2: Compute u, v ∈ Z such that uf - vg = gcd(f, g) ▷ Using the extended GCD + // 3: if gcd(f, g) ≠ 1 then + // 4: abort and return ⊥ + // 5: (F, G) ← (vq, uq) + // 6: return (F, G) + // 7: else + // 8: f' ← N(f) ▷ f', g', F', G' ∈ Z[x]/(x^{n/2} + 1) + // 9: g' ← N(g) ▷ N as defined in either (3.25) or (3.26) + // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') ▷ Recursive call + // 11: F ← F'(x²)g(-x) ▷ F, G ∈ Z[x]/(xⁿ + 1) + // 12: G ← G'(x²)f(-x) + // 13: Reduce(f, g, F, G) ▷ (F, G) is reduced with respect to (f, g) + // 14: return (F, G) + if (logn === 0) { + // // 1: if n = 1 then + const xf = f[0]; + const xg = g[0]; + // We can rely on 'invert' to throw if they are not coprime. + if (xf <= 0n || xg <= 0n) return false; + try { + const u1 = invert(xf, xg); // if gcd(f, g) ≠ 1 then + const v1 = (1n - u1 * xf) / xg; + F[0] = -v1 * QBig; // 5: (F, G) ← (vq, uq) + G[0] = u1 * QBig; + return true; + } catch (e) { + return false; + } + } + if (logn_top === undefined) logn_top = logn; + const n = 1 << logn; + const hn = n >>> 1; + if (!f || f.length < n || !g || g.length < n) return false; + const fp = this.galoisNorm(logn, f); // 8: f' ← N(f) + const gp = this.galoisNorm(logn, g); // 9: g' ← N(g) + const Fp = new Array(hn); // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') + const Gp = new Array(hn); + // 10: (F', G') ← NTRUSolve_{n/2,q}(f', g') + // ▷ Recursive call + if (!this.solveBranch(logn - 1, fp, gp, Fp, Gp, logn_top)) return false; + F = this.mulConjD(logn, F, g, Fp); // 11: F ← F'(x²)g(-x) + G = this.mulConjD(logn, G, f, Gp); // 12: G ← G'(x²)f(-x) + // 13: Reduce(f, g, F, G) + // ▷ (F, G) is reduced with respect to (f, g) + return this.reduce(logn, f, g, F, G, logn_top); + } + private solve(f: SPoly, g: SPoly) { + // Algorithm 5: NTRUGen(φ, q) + // (Page 34) + // Require: A monic polynomial φ ∈ Z[x] of degree n, a modulus q + // Ensure: Polynomials f, g, F, G + // 1: σ{f,g} ← 1.17√q/2n ▷ σ{f,g} is chosen so that E[||(f, g)||] = 1.17√q + // 2: for i from 0 to n-1 do + // 3: fᵢ ← DZ,σ{f,g},0 ▷ See also (3.29) + // 4: gᵢ ← DZ,σ{f,g},0 + // 5: f ← Σᵢ fᵢxⁱ ▷ f ∈ Z[x]/(φ) + // 6: g ← Σᵢ gᵢxⁱ ▷ g ∈ Z[x]/(φ) + // 7: if NTT(f) contains 0 as a coefficient then ▷ Check that f is invertible mod q + // 8: restart + // 9: γ ← max{||(g, -f)||, ||( (qf*)/(ff*+gg*), (qg*)/(ff*+gg*) )||} + // ▷ Using (3.9) with (3.8) or (3.10) + // 10: if γ > 1.17√q then ▷ Check that γ = ||B||_GS is short + // 11: restart + // 12: F, G ← NTRUSolve_{n,q}(f, g) ▷ Computing F, G such that fG - gF = q mod φ + // 13: if (F, G) = ⊥ then + // 14: restart + // 15: return f, g, F, G + const n = 1 << logn; + const bf = Array.from(f).map(BigInt); + const bg = Array.from(g).map(BigInt); + const bF = new Array(n); + const bG = new Array(n); + // 12: F, G ← NTRUSolve_{n,q}(f, g) + // ▷ Computing F, G such that fG - gF = q mod φ + if (!this.solveBranch(logn, bf, bg, bF, bG)) return false; + const F = new Int8Array(n); + const G = new Int8Array(n); + for (let i = 0; i < n; i++) { + const x = bF[i]; + const y = bG[i]; + if (x < -127 || x > +127 || y < -127 || y > +127) return false; + F[i] = Number(x); + G[i] = Number(y); + } + return [F, G]; + } + generate(): [SPoly, SPoly, SPoly, SPoly, IPoly] { + // Algorithm 4: Keygen(φ, q) + // (Page 33) + // Require: A monic polynomial φ ∈ Z[x], a modulus q + // Ensure: A secret key sk, a public key pk + // 1: f, g, F, G ← NTRUGen(φ, q) ▷ Solving the NTRU equation + // 2: B ← [ g -f ; G -F ] + // 3: B̂ ← FFT(B) ▷ Compute the FFT for each of the 4 components {g, -f, G, -F} + // 4: G ← B̂ × B̂* + // 5: T ← ffLDL*(G) ▷ Computing the LDL* tree + // 6: for each leaf leaf of T do + // 7: leaf.value ← σ/√leaf.value ▷ Normalization step + // 8: sk ← (B̂, T) + // 9: h ← gf⁻¹ mod q + // 10: pk ← h + // 11: return sk, pk + let max = 1_000_000; + let curr = 0; + while (true) { + if (curr++ === max) throw new Error("can't generate key"); + const f = this.polyGauss(); + const g = this.polyGauss(); + let lim = 1 << (opts.fgBits - 1); + for (let u = 0; u < N; u++) { + if (f[u] >= lim || f[u] <= -lim || g[u] >= lim || g[u] <= -lim) { + lim = -1; + break; + } + } + if (lim < 0) continue; + const normf = intPoly.smallSqnorm(f); + const normg = intPoly.smallSqnorm(g); + const norm = (normf + normg) | -((normf | normg) >>> 31); + // Cheap integer prefilter for the same 1.17^2*q Gram-Schmidt bound; + // ceil(BNORM_MAX) = 16823. + if (norm >= 16823) continue; + let rt1 = floatPoly.FFT(floatPoly.convSmall(f)); + let rt2 = floatPoly.FFT(floatPoly.convSmall(g)); + const rt3 = floatPoly.invNorm(rt1, rt2); + rt1 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt1), Q), rt3)); + rt2 = floatPoly.iFFT(floatPoly.scaleNorm(floatPoly.mulConst(floatPoly.conj(rt2), Q), rt3)); + // Separate reals and then imaginary to enforce numerical stability + let bnorm = 0; + for (let u = 0; u < rt1.length; u++) { + bnorm += rt1[u].re * rt1[u].re; + bnorm += rt2[u].re * rt2[u].re; + } + for (let u = 0; u < rt1.length; u++) { + bnorm += rt1[u].im * rt1[u].im; + bnorm += rt2[u].im * rt2[u].im; + } + if (!(bnorm < BNORM_MAX)) continue; + let pub; + try { + pub = computePublic(f, g); + } catch (_) { + continue; + } + const solved = this.solve(f, g); + if (solved === false) continue; + return [f, g, solved[0], solved[1], pub]; // f g F G h + } + } + } + // same as ml-dsa id, but MSB bits :( + const modqCoder = () => { + const coder = bitsCoderMSB(newPoly, N, 14, { + encode: id, + decode: id, + }) as BytesCoderLen; + return { + bytesLen: coder.bytesLen, + encode(poly: TArg) { + // Keep these raw checks in sync with Q: + // Falcon public-key coefficients must stay in [0, q - 1]. + for (let i = 0; i < poly.length; i++) + if (poly[i] >= 12289) throw new Error('public key coeff out of range'); + return coder.encode(poly); + }, + decode(bytes: TArg) { + // Round-3 Falcon requires exact body length here; + // otherwise truncated keys decode as zero-padded + // and overlong keys silently ignore the tail in this generic bit decoder. + if (bytes.length !== coder.bytesLen) throw new Error('wrong public key length'); + const poly = coder.decode(bytes); + // Keep these raw checks in sync with Q: + // Falcon public-key coefficients must stay in [0, q - 1]. + for (let i = 0; i < poly.length; i++) + if (poly[i] >= 12289) throw new Error('public key coeff out of range'); + const normalized = coder.encode(poly); + if (normalized.length !== bytes.length) throw new Error('wrong public key length'); + for (let i = 0; i < bytes.length; i++) + if (bytes[i] !== normalized[i]) throw new Error('wrong public key encoding'); + return poly; + }, + }; + }; + const trimI8Coder = (bits: number) => { + const shift = 32 - bits; + const coder = bitsCoderMSB((len) => new Int8Array(len), N, bits, { + encode: (v) => v & ((1 << bits) - 1), + decode: (w) => ((w & getMask(bits)) << shift) >> shift, + }) as BytesCoderLen; + return { + bytesLen: coder.bytesLen, + encode(poly: TArg) { + // Secret-key trim encodings keep a symmetric signed range and reserve the most-negative + // value as a non-canonical sentinel, + // so encode() and decode() intentionally use different bounds. + const max = (1 << (bits - 1)) - 1; + const min = -max; + for (let i = 0; i < poly.length; i++) + if (poly[i] < min || poly[i] > max) throw new Error('private key coeff out of range'); + return coder.encode(poly); + }, + decode(bytes: TArg) { + const poly = coder.decode(bytes); + const min = -(1 << (bits - 1)); + for (let i = 0; i < poly.length; i++) + if (poly[i] === min) throw new Error('forbidden private key coeff'); + return poly; + }, + }; + }; + const fgCoder = trimI8Coder(opts.fgBits); + const FGCoder = trimI8Coder(opts.FGBits); + // Current utils.splitCoder requires a label first; + // without it Falcon key/sig encodings drift and KATs fail. + // 0x50 + logn || f || g || F + const secretKeyCoder = headerCoder( + 0x50 + logn, + splitCoder('falcon.secretKey', fgCoder, fgCoder, FGCoder) + ) as BytesCoderLen<[Int8Array, Int8Array, Int8Array]>; + const publicKeyCoder = headerCoder(0x00 + logn, modqCoder()) as BytesCoderLen; + const decodePaddedSig = (s2: TArg) => { + // The fixed padded form accepts only a canonical compressed payload + // followed by an all-zero tail. + const normalized = compCoder(N).encode(compCoder(N).decode(s2)); + for (let i = normalized.length; i < s2.length; i++) + if (s2[i] !== 0) throw new Error('non-zero padding'); + return normalized; + }; + const decodeUnpaddedSig = (s2: TArg) => { + // Unpadded attached and detached signatures require the compressed payload to use its exact + // canonical bitlength. Appending a zero tail and adjusting the outer container length must + // still be rejected. + const normalized = compCoder(N).encode(compCoder(N).decode(s2)); + if (normalized.length !== s2.length) throw new Error('wrong signature length'); + return s2; + }; + const decodeSig = opts.padded ? decodePaddedSig : decodeUnpaddedSig; + // Unpadded: [ 2B sig_len ] [ 40B nonce ] [ message ] [ 1B header ] [ compressed_sig ] + // Padded [ 1B header ] [ 40B nonce ] [ compressed_sig ] [ padding ] | [ message ] + const SignatureCoderBasic = (logn: number) => { + const TYPE_BYTE = 0x20 + logn; + return { + encode({ msg, nonce, s2 }: TArg): TRet { + let compressed: Uint8Array = s2; + const payloadLen = 1 + compressed.length; + const totalLen = 2 + NONCELEN + msg.length + payloadLen; + const out = new Uint8Array(totalLen); + let i = 0; + out[i++] = (payloadLen >> 8) & 0xff; + out[i++] = payloadLen & 0xff; + out.set(nonce, i); + i += NONCELEN; + out.set(msg, i); + i += msg.length; + out[i++] = TYPE_BYTE; + out.set(compressed, i); + return out as TRet; + }, + decode(data: TArg): TRet { + if (!data || data.length < NONCELEN + 3) throw new Error('signature coder: wrong length'); + const len = (data[0] << 8) | data[1]; + const s2Len = len - 1; + const msgLen = data.length - NONCELEN - 3 - s2Len; + if (msgLen < 0) throw new Error('signature coder: wrong msg length'); + const typeByte = data[2 + NONCELEN + msgLen]; + if (typeByte !== TYPE_BYTE) throw new Error('signature coder: wrong type byte'); + const nonce = data.subarray(2, 2 + NONCELEN); + const msg = data.subarray(2 + NONCELEN, 2 + NONCELEN + msgLen); + const s2 = decodeUnpaddedSig(data.subarray(2 + NONCELEN + msgLen + 1)); + if (s2.length !== s2Len) throw new Error('signature coder: wrong s2 length'); + return { msg, nonce, s2 } as TRet; + }, + }; + }; + const SignatureCoderPadded = (logn: number) => { + const sigLen = opts.paddedLen; + return { + encode({ msg, nonce, s2 }: TArg): TRet { + return headerCoder( + 0x30 + logn, + splitCoder('falcon.signature', NONCELEN, sigLen, msg.length) + ).encode([nonce, pad(sigLen).encode(s2), msg]); + }, + decode(data: TArg): TRet { + const msgLen = data.length - NONCELEN - sigLen - 1; + const [nonce, s2, msg] = headerCoder( + 0x30 + logn, + splitCoder('falcon.signature', NONCELEN, sigLen, msgLen) + ).decode(data); + return { nonce, s2: decodeSig(s2), msg } as TRet; + }, + }; + }; + // [ 1B header ] [ 40B nonce ] [ compressed_sig ] + const SignatureCoderDetached = (logn: number) => { + const sigLen = opts.padded ? opts.sigLen - 1 - NONCELEN : opts.detachedLen; + const getSigLen = (s2: TArg) => (opts.padded ? sigLen : s2.length); + return { + encode({ nonce, s2 }: TArg<{ nonce: Uint8Array; s2: Uint8Array }>): TRet { + return headerCoder( + 0x30 + logn, + splitCoder('falcon.detachedSignature', NONCELEN, getSigLen(s2)) + ).encode([nonce, opts.padded ? pad(sigLen).encode(s2) : s2]); + }, + decode(data: TArg): TRet<{ + nonce: Uint8Array; + s2: Uint8Array; + }> { + const [nonce, raw] = headerCoder( + 0x30 + logn, + splitCoder('falcon.detachedSignature', NONCELEN, data.length - NONCELEN - 1) + ).decode(data); + const s2 = decodeSig(raw); + return { nonce, s2 } as TRet<{ nonce: Uint8Array; s2: Uint8Array }>; + }, + }; + }; + const SignatureCoder = (opts.padded ? SignatureCoderPadded : SignatureCoderBasic)(logn); + // Round-3 Falcon rejects non-invertible f before division; + // otherwise malformed secret keys leak a raw arithmetic error. + // Returns NTT(f) after the nonzero-lane check; + // callers still apply f^{-1} via coefficient-wise division. + const invertF = (f: TArg) => { + const tt = intPoly.ntt(signedCoder.decode(f)); + for (let u = 0; u < N; u++) + if (tt[u] === 0) throw new Error('invalid secretKey: non-invertible f'); + return tt; + }; + function computePublic(f: TArg, g: TArg) { + const tt = invertF(f); + const h = intPoly.ntt(signedCoder.decode(g)); + // intPoly.div() returns to coefficient form via intt(), so public keys are encoded from the + // canonical polynomial h = g/f and verifyRaw() re-enters the NTT domain later. + const res = intPoly.div(h, tt); // h = g/f + cleanBytes(tt); + return res; + } + // Reconstruct the omitted secret-key limb G as g*F/f mod q, then mirror round-3 Falcon's centered + // reduction and small-coefficient check before using the completed basis for signing. + function completePrivate(f: TArg, g: TArg, F: TArg) { + let t1 = intPoly.toMontgomery(intPoly.ntt(signedCoder.decode(g))); + const t2 = intPoly.ntt(signedCoder.decode(F)); + const tt = invertF(f); + t1 = intPoly.div(intPoly.mul(t1, t2), tt); + const G = new Int8Array(N); + for (let u = 0; u < N; u++) { + let w = t1[u]; + // This mirrors round-3 Falcon's secret-key G reconstruction, not a generic centered reduction + // helper: + // the threshold is floor(q/2), and w = Qhalf maps to -Qhalf - 1 here on purpose. + w -= Q & ~-((w - Qhalf) >>> 31); + const gi = w | 0; + if (gi < -127 || gi > 127) { + cleanBytes(t1, t2, tt, G); + throw new Error('Coefficient out of bounds'); + } + G[u] = gi; + } + cleanBytes(t1, t2, tt); + return G; + } + function HashToPoint(nonce: TArg, msg: TArg): TRet { + // Algorithm 3: HashToPoint(str, q, n) + // (Page 31) + // Require: A string str, a modulus q ≤ 2¹⁶, a degree n ∈ N* + // Ensure: An polynomial c = Σᵢ cᵢxⁱ in Zq[x] + // 1: k ← ⌈2¹⁶/q⌉ + // 2: ctx ← SHAKE-256-Init() + // 3: SHAKE-256-Inject(ctx, str) + // 4: i ← 0 + // 5: while i < n do + // 6: t ← SHAKE-256-Extract(ctx, 16) + // 7: if t < kq then + // 8: cᵢ ← t mod q + // 9: i ← i + 1 + // 10: return c + const h = shake256.create().update(nonce).update(msg); // 3: SHAKE-256-Inject(ctx, str) + const c = new Uint16Array(N); + // Round-3 Falcon keeps 16-bit draws only in 0..61444, i.e. below 61445 = 5*q, the largest + // 16-bit multiple of q below 2^16; a literal ceil(2^16/q)*q would accept every sample. + const kQ = 5 * Q; + for (let i = 0; i < N; ) { + const tmp = h.xof(2); // 6: t ← SHAKE-256-Extract(ctx, 16) + let w = (tmp[0] << 8) | tmp[1]; + if (w < kQ) c[i++] = w % Q; // 8: cᵢ ← t mod q + } + return c as TRet; + } + // This is basically one sampling routine, + // but it carries a lot of internal state and gets complex quickly. + class FFSampler { + private logn: number; + // Shake + private shake: ReturnType; + private shakeBuf: Uint8Array; + private ctrView: DataView; + // ChaCha + private ctr: bigint = 0n; + private buf: Uint8Array; + private buf32: Uint32Array; + private pos: number; + private key: Uint8Array; + private nonce32: Uint32Array; + private curBlock: Uint8Array; + private curBlock32: Uint32Array; + private view: DataView; + // Sampler + private b01: CPoly; + private b11: CPoly; + private g00: CPoly; + private g01: CPoly; + private g11: CPoly; + + constructor(logn: number, seed: Uint8Array, b00: CPoly, b01: CPoly, b10: CPoly, b11: CPoly) { + this.logn = logn; + // Shake + this.shake = shake256.create().update(seed); + this.shakeBuf = new Uint8Array(56); + this.key = this.shakeBuf.subarray(0, 32); + this.nonce32 = u32(this.shakeBuf.subarray(32, 48)); // 4 u32s + this.ctrView = createView(this.shakeBuf.subarray(48, 56)); + // Signle chacha20 instance buffer + this.curBlock = new Uint8Array(64); + this.curBlock32 = u32(this.curBlock); + // whole rng buffer + this.buf = new Uint8Array(8 * this.curBlock.length); + this.buf32 = u32(this.buf); + this.pos = this.buf.length; // not filled yet! + this.view = createView(this.buf); + // Sampler + this.b01 = b01; + this.b11 = b11; + const { g00, g01, g11 } = this.gramFFT(b00, b10); + this.g00 = g00; + this.g01 = g01; + this.g11 = g11; + } + destroy() { + this.shake.destroy(); + cleanBytes(this.shakeBuf, this.curBlock, this.buf); + cleanCPoly(this.b01, this.b11, this.g00, this.g01, this.g11); + } + private refill(minBytes: number): void { + if (this.buf.length - this.pos >= minBytes) return; + const out32 = swap32IfBE(this.buf32); + for (let i = 0; i < 8; i++, this.ctr++) { + const n = swap32IfBE(this.nonce32.slice()); // [n0, n1, n2, n3] + n[2] ^= Number(this.ctr & 0xffffffffn); + n[3] ^= Number(this.ctr >> 32n); + // chacha20() takes raw nonce bytes; on BE the word-normalized temp must be swapped back. + swap32IfBE(n.subarray(1)); + chacha20(this.key, u8(n.subarray(1)), EMPTY_CHACHA20_BLOCK, this.curBlock, n[0]); + // Interleave like Falcon's AVX2 layout (by u32 chunks from 8 parallel chacha20) + const block32 = swap32IfBE(this.curBlock32); + for (let j = 0; j < 16; j++) out32[i + j * 8] = block32[j]; + swap32IfBE(block32); + } + swap32IfBE(out32); + this.pos = 0; + } + // Sampler + private gaussian0(): number { + // Algorithm 12: BaseSampler() + // (Page 41) + // Require: - + // Ensure: An integer z₀ ∈ {0, ..., 18} such that z ~ χ ▷ χ is uniquely defined by (3.33) + // 1: u ← UniformBits(72) ▷ See (3.32) + // 2: z₀ ← 0 + // 3: for i = 0, ..., 17 do + // 4: z₀ ← z₀ + [u < RCDT[i]] ▷ Note that one should use RCDT, not pdt or cdt + // 5: return z₀ + this.refill(9); + const t0 = this.view.getUint32(this.pos, true); + const t1 = this.view.getUint32(this.pos + 4, true); + const t2 = this.buf[this.pos + 8]; + this.pos += 9; + const v0 = t0 & 0xffffff; + const v1 = ((t0 >>> 24) & 0xff) | ((t1 & 0xffff) << 8); + const v2 = ((t1 >>> 16) & 0xffff) | (t2 << 16); + let z = 0; + for (let i = 0; i < GAUSS0.length; i += 3) { + let cc = (v0 - GAUSS0[i + 2]) >>> 31; + cc = (((v1 - GAUSS0[i + 1]) | 0) - cc) >>> 31; + cc = (((v2 - GAUSS0[i + 0]) | 0) - cc) >>> 31; + z += cc; + } + return z; + } + private berExp(x: number, ccs: any) { + // Algorithm 14: BerExp(x, ccs) (Page 43) + // Require: Floating point values x, ccs ≥ 0 + // Ensure: A single bit, equal to 1 with probability ≈ ccs · exp(-x) + // 1: s ← ⌊x/ln(2)⌋ + // ▷ Compute the unique decomposition x = s · ln(2) + r, + // with (r, s) ∈ [0, ln 2) × Z⁺ + // 2: r ← x - s · ln(2) + // 3: s ← min(s, 63) + // 4: z ← (2 · ApproxExp(r, ccs) - 1) >> s ▷ z ≈ 2⁶⁴⁻ˢ · ccs · exp(-r) = 2⁶⁴ · ccs · exp(-x) + // 5: i ← 64 + // 6: do + // 7: i ← i - 8 + // 8: w ← UniformBits(8) - ((z >> i) & 0xFF) + // ▷ This loop does not need to be done in constant-time + // 9: while ((w = 0) and (i > 0)) + // 10: return [w < 0] ▷ Return 1 with probability 2⁻⁶⁴ · z ≈ ccs · exp(-x) + let s = Math.trunc(x * 1.4426950408889633870046509401); + const r = x - s * 0.69314718055994530941723212146; + let e = ApproxExp(r, ccs); + e *= 2147483648.0; + let z1 = e | 0; + e = (e - z1) * 4294967296.0; + let z0 = e | 0; + z1 = (z1 << 1) | (z0 >>> 31); + z0 <<= 1; + s = (s | ((63 - s) >>> 26)) & 63; + const sm = -(s >>> 5) | 0; + z0 ^= sm & (z0 ^ z1); + z1 &= ~sm; + s &= 31; + z0 = (z0 >>> s) | ((z1 << (31 - s)) << 1); + z1 >>>= s; + for (let j = 0; j < 2; j++) { + for (let i = 24; i >= 0; i -= 8) { + this.refill(1); + const w = this.buf[this.pos++]; + const bz = (z1 >>> i) & 0xff; + if (w !== bz) return w < bz; + } + z1 = z0; + } + return false; + } + private samplerZ(mu: number, isigma: number) { + // Algorithm 15: SamplerZ(μ, σ'), (Page 43) + // Require: Floating-point values μ, σ' ∈ R such that σ' ∈ [σ_{min}, σ_{max}] + // Ensure: An integer z ∈ Z sampled from a distribution very close to DZ,μ,σ' + // 1: r ← μ - ⌊μ⌋ ▷ r must be in [0, 1) + // 2: ccs ← σ_{min}/σ' ▷ ccs helps to make the algorithm running time independent of σ' + // 3: while (1) do + // 4: z₀ ← BaseSampler() + // 5: b ← UniformBits(8) & 0x1 + // 6: z ← b + (2 · b - 1)z₀ + // 7: x ← ((z-r)²)/(2σ'²) + // 8: if (BerExp(x, ccs) = 1) then + // 9: return z + ⌊μ⌋ + const s = Math.floor(mu); + const r = mu - s; + const dss = isigma * isigma * 0.5; + const ccs = isigma * SIGMA_MIN[this.logn]; + for (;;) { + const z0 = this.gaussian0(); + this.refill(1); + const b = this.buf[this.pos++] & 1; + const z = (((z0 << 1) + 1) & -b) - z0; + let x = z - r; + x = x * x * dss - z0 * z0 * 0.1508650488753727203494747755; + if (this.berExp(x, ccs)) return s + z; + } + } + private ldlFFT(logn: number, g00t: CPoly, g01t: CPoly, g11t: CPoly) { + // Algorithm 8: LDL*(G) + // (Page 37) + // Require: A full-rank self-adjoint matrix G = (Gᵢⱼ) ∈ FFT(Q[x]/(φ))²ˣ² + // Ensure: The LDL* decomposition G = LDL* over FFT(Q[x]/(φ)) + // Format: All polynomials are in FFT representation. + // 1: D₀₀ ← G₀₀ + // 2: L₁₀ ← G₁₀/G₀₀ + // 3: D₁₁ ← G₁₁ - L₁₀ ⊙ L₁₀* ⊙ G₀₀ + // 4: L ← [ 1 0 ; L₁₀ 1 ], D ← [ D₀₀ 0 ; 0 D₁₁ ] + // 5: return (L, D) + + // Algorithm 9: ffLDL*(G) + // (Page 37) + // Require: A full-rank Gram matrix G ∈ FFT(Q[x]/(xⁿ + 1))²ˣ² + // Ensure: A binary tree T + // Format: All polynomials are in FFT representation. + // 1: (L, D) ← LDL*(G) ▷ L = [ 1 0 ; L₁₀ 1 ], D = [ D₀₀ 0 ; 0 D₁₁ ] + // 2: T.value ← L₁₀ + // 3: if (n = 2) then + // 4: T.leftchild ← D₀₀ + // 5: T.rightchild ← D₁₁ + // 6: return T + // 7: else + // 8: d₀₀, d₀₁ ← splitfft(D₀₀) ▷ dᵢⱼ ∈ FFT(Q[x]/(x^{n/2} + 1)) + // 9: d₁₀, d₁₁ ← splitfft(D₁₁) + // 10: G₀ ← [ d₀₀ d₀₁ ; d₀₁* d₀₀ ], G₁ ← [ d₁₀ d₁₁ ; d₁₁* d₁₀ ] + // ▷ Since D₀₀, D₁₁ are self-adjoint, (3.30) applies + // 11: T.leftchild ← ffLDL*(G₀) ▷ Recursive calls + // 12: T.rightchild ← ffLDL*(G₁) + // 13: return T + g00t = g00t.slice(); // can be same as g11t and everything will break! + const hn = 1 << (logn - 1); + for (let i = 0; i < hn; i++) { + const g01 = g01t[i]; + const g11 = g11t[i]; + const mu = fComplex.scale(g01, 1.0 / g00t[i].re); + g11t[i] = { re: g11.re - (mu.re * g01.re + mu.im * g01.im), im: g11.im }; + g01t[i] = fComplex.conj(mu); + } + return { g00: g00t, g01: g01t, g11: g11t }; + } + private splitFFT(logn: number, f: CPoly) { + // Algorithm 1: splitfft(FFT(f)) + // (Page 29) + // Require: FFT(f) = (f(ζ))ζ for some f ∈ Q[x]/(φ) + // Ensure: FFT(f₀) = (f₀(ζ'))ζ' and FFT(f₁) = (f₁(ζ'))ζ' for some f₀, f₁ ∈ Q[x]/(φ') + // Format: All polynomials are in FFT representation. + // 1: for ζ such that φ(ζ) = 0 and Im(ζ) > 0 do ▷ See eq. (3.19) with 0 ≤ k < n/2 + // 2: ζ' ← ζ² + // 3: f₀(ζ') ← ½ [f(ζ) + f(−ζ)] + // 4: f₁(ζ') ← (1/(2ζ)) [f(ζ) − f(−ζ)] + // 5: return (FFT(f₀), FFT(f₁)) + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) return { f0: [{ re: f[0].re, im: 0.0 }], f1: [{ re: f[0].im, im: 0.0 }] }; + const f0t = new Array(qn); + const f1t = new Array(qn); + const ft = f; + for (let i = 0; i < qn; i++) { + const a = ft[(i << 1) + 0]; + const b = ft[(i << 1) + 1]; + f0t[i] = fComplex.scale(fComplex.add(a, b), 0.5); + f1t[i] = fComplex.scale( + fComplex.mul(fComplex.sub(a, b), fComplex.conj(COMPLEX_ROOTS_O[i + hn])), + 0.5 + ); + } + return { f0: f0t, f1: f1t }; + } + private splitSelfAdjFFT(logn: number, f: CPoly) { + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) return { f0: [{ re: f[0].re, im: 0.0 }], f1: [{ re: 0.0, im: 0.0 }] }; + const f0t = new Array(qn); + const f1t = new Array(qn); + const ft = f; + for (let i = 0; i < qn; i++) { + const a = ft[(i << 1) + 0]; + const b = ft[(i << 1) + 1]; + f0t[i] = fComplex.scale(fComplex.add(a, b), 0.5); + f1t[i] = fComplex.scale( + fComplex.scale(fComplex.conj(COMPLEX_ROOTS_O[i + hn]), fComplex.sub(a, b).re), + 0.5 + ); + } + return { f0: f0t, f1: f1t }; + } + private mergeFFT(logn: number, f0: CPoly, f1: CPoly): CPoly { + // Algorithm 2: mergefft(f₀, f₁) + // (Page 29) + // Require: FFT(f₀) = (f₀(ζ'))ζ' and FFT(f₁) = (f₁(ζ'))ζ' for some f₀, f₁ ∈ Q[x]/(φ') + // Ensure: FFT(f) = (f(ζ))ζ for some f ∈ Q[x]/(φ) + // Format: All polynomials are in FFT representation. + // 1: for ζ such that φ(ζ) = 0 do ▷ See eq. (3.19) + // 2: ζ' ← ζ² + // 3: f(ζ) ← f₀(ζ') + ζf₁(ζ') + // 4: return FFT(f) + const hn = 1 << (logn - 1); + const qn = hn >> 1; + if (logn === 1) return [{ re: f0[0].re, im: f1[0].re }]; + const ft = new Array(2 * qn); + for (let i = 0; i < qn; i++) { + const a = f0[i]; + const c = fComplex.mul(f1[i], COMPLEX_ROOTS_O[i + hn]); + ft[(i << 1) + 0] = fComplex.add(a, c); + ft[(i << 1) + 1] = fComplex.sub(a, c); + } + return ft; + } + private gramFFT(b00: CPoly, b10: CPoly) { + const { b01, b11 } = this; + const hn = (1 << this.logn) >> 1; + const g00: CPoly = new Array(hn); + const g01: CPoly = new Array(hn); + const g11: CPoly = new Array(hn); + for (let i = 0; i < hn; i++) { + const b00t = b00[i]; + const b01t = b01[i]; + const b10t = b10[i]; + const b11t = b11[i]; + const u = fComplex.mul(b00t, fComplex.conj(b10t)); + const v = fComplex.mul(b01t, fComplex.conj(b11t)); + g00[i] = { re: fComplex.magSqSum(b00t, b01t), im: 0.0 }; + g01[i] = fComplex.add(u, v); + g11[i] = { re: fComplex.magSqSum(b10t, b11t), im: 0.0 }; + } + return { g00, g01, g11 }; + } + private ffsampRec( + logn: number, + t0: CPoly, + t1: CPoly, + g00i: CPoly, + g01i: CPoly, + g11i: CPoly + ): { t0: CPoly; t1: CPoly } { + // Algorithm 11: ffSamplingₙ(t, T) + // (Page 40) + // Require: t = (t₀, t₁) ∈ FFT(Q[x]/(xⁿ + 1))², a FALCON tree T + // Ensure: z = (z₀, z₁) ∈ FFT(Z[x]/(xⁿ + 1))² + // Format: All polynomials are in FFT representation. + // 1: if n = 1 then + // 2: σ' ← T.value ▷ It is always the case that σ' ∈ [σ_{min}, σ_{max}] + // 3: z₀ ← SamplerZ(t₀, σ') ▷ Since n=1, tᵢ = invFFT(tᵢ) ∈ Q and zᵢ = invFFT(zᵢ) ∈ Z + // 4: z₁ ← SamplerZ(t₁, σ') + // 5: return z = (z₀, z₁) + // 6: (l, T₀, T₁) ← (T.value, T.leftchild, T.rightchild) + // 7: t'₁ ← splitfft(t₁) ▷ t₀, t'₁ ∈ FFT(Q[x]/(x^{n/2} + 1))² + // 8: z'₁ ← ffSampling_{n/2}(t'₁, T₁) ▷ First recursive call to ffSampling_{n/2} + // 9: z₁ ← mergefft(z'₁) ▷ z₀, z₁ ∈ FFT(Z[x]/(x^{n/2} + 1))² + // 10: t'₀ ← t₀ + (t₁ - z₁) ⊙ l + // 11: t''₀ ← splitfft(t'₀) + // 12: z'₀ ← ffSampling_{n/2}(t''₀, T₀) ▷ Second recursive call to ffSampling_{n/2} + // 13: z₀ ← mergefft(z'₀) + // 14: return z = (z₀, z₁) + if (logn === 0) { + const leaf = Math.sqrt(g00i[0].re) * INV_SIGMA[this.logn]; + // 3: z₀ ← SamplerZ(t₀, σ') + // ▷ Since n=1, tᵢ = invFFT(tᵢ) ∈ Q and zᵢ = invFFT(zᵢ) ∈ Z + const t0re = this.samplerZ(t0[0].re, leaf); + const t1re = this.samplerZ(t1[0].re, leaf); // 4: z₁ ← SamplerZ(t₁, σ') + return { t0: [{ re: t0re, im: 0.0 }], t1: [{ re: t1re, im: 0.0 }] }; + } + // 6: (l, T₀, T₁) ← (T.value, T.leftchild, T.rightchild) + const { g00, g01, g11 } = this.ldlFFT(logn, g00i, g01i, g11i); + const { f0: g00f0, f1: g00f1 } = this.splitSelfAdjFFT(logn, g00); + const { f0: g11f0, f1: g11f1 } = this.splitSelfAdjFFT(logn, g11); + // 7: t'₁ ← splitfft(t₁) + // ▷ t₀, t'₁ ∈ FFT(Q[x]/(x^{n/2} + 1))² + const { f0: t1f0in, f1: t1f1in } = this.splitFFT(logn, t1); + const { t0: t1f0out, t1: t1f1out } = this.ffsampRec( + logn - 1, + t1f0in, + t1f1in, + g11f0, + g11f1, + g11f0 + ); // 8: z'₁ ← ffSampling_{n/2}(t'₁, T₁) ▷ First recursive call to ffSampling_{n/2} + // 9: z₁ ← mergefft(z'₁) + // ▷ z₀, z₁ ∈ FFT(Z[x]/(x^{n/2} + 1))² + const t1new = this.mergeFFT(logn, t1f0out, t1f1out); + // 10: t'₀ ← t₀ + (t₁ - z₁) ⊙ l + const t0tmp = floatPoly.add(t0, floatPoly.mul(g01, floatPoly.sub(t1, t1new))); + const { f0: t0f0in, f1: t0f1in } = this.splitFFT(logn, t0tmp); // 11: t''₀ ← splitfft(t'₀) + const { t0: t0f0out, t1: t0f1out } = this.ffsampRec( + logn - 1, + t0f0in, + t0f1in, + g00f0, + g00f1, + g00f0 + ); // 12: z'₀ ← ffSampling_{n/2}(t''₀, T₀) ▷ Second recursive call to ffSampling_{n/2} + const z1 = this.mergeFFT(logn, t0f0out, t0f1out); // 13: z₀ ← mergefft(z'₀) + return { t0: z1, t1: t1new }; + } + // sampling a preimage in FFT domain + sample(hm: Uint16Array) { + const t0t = floatPoly.FFT(floatPoly.convSmall(hm as any)); + const t0f = floatPoly.mulConst(floatPoly.mul(t0t, this.b11), F_INV_Q); + const t1f = floatPoly.mulConst(floatPoly.mul(t0t, this.b01), F_MINUS_INV_Q); + // Set seed + this.shake.xofInto(this.shakeBuf); + this.ctr = this.ctrView.getBigUint64(0, true); + // Actual sampling + return this.ffsampRec(this.logn, t0f, t1f, this.g00, this.g01, this.g11); + } + } + + const signRaw = ( + sk: TArg, + msg: TArg, + maxLen: number, + rnd: TArg = randomBytes + ): TRet => { + // Algorithm 10: Sign(m, sk, [β²]), (Page 39) + // Require: A message m, a secret key sk, a bound [β²] + // Ensure: A signature sig of m + // 1: r ← {0, 1}³²⁰ uniformly + // 2: c ← HashToPoint(r||m, q, n) + // 3: t ← ( (1/q)FFT(c) ⊙ FFT(F), (1/q)FFT(c) ⊙ FFT(f) ) ▷ t = (FFT(c), FFT(0)) · B̂⁻¹ + // 4: do + // 5: do + // 6: z ← ffSamplingₙ(t, T) + // 7: s = (t - z)B̂ + // ▷ At this point, s follows a Gaussian distribution: + // s ~ D_{(c,0)+Λ(B),σ,0} + // 8: while ||s||² > [β²] + // ▷ Since s is in FFT representation, one may use (3.8) to compute ||s||² + // 9: (s₁, s₂) ← invFFT(s) ▷ s₁ + s₂h = c mod (φ, q) + // 10: s ← Compress(s₂, 8 · sbytelen - 328) + // ▷ Remove 1 byte for the header, and 40 bytes for r + // 11: while (s = ⊥) + // 12: return sig = (r, s) + abytes(msg); + // One RNG stream drives both the public 40-byte nonce and the 48-byte sampler seed, so + // deterministic rnd hooks make signatures deterministic for fixed secretKey/message inputs. + const nonce = rnd(40); + // Keep these raw 40-byte checks in sync with NONCELEN: Falcon's r <- {0,1}^320 nonce + // feeds HashToPoint(r || m) and the public signature framing, so callback bugs must fail fast. + abytes(nonce, 40, 'nonce'); + const hm = HashToPoint(nonce, msg); // 2: c ← HashToPoint(r||m, q, n) + const seed = rnd(48); + // Falcon implementations here use a fixed 48-byte sampler seed; reject callback bugs up front. + abytes(seed, 48, 'seed'); + try { + const [f, g, F] = secretKeyCoder.decode(sk); + try { + const G = completePrivate(f, g, F); + const b00 = floatPoly.FFT(floatPoly.convSmall(g)); + const b01 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(f))); + const b10 = floatPoly.FFT(floatPoly.convSmall(G)); + const b11 = floatPoly.FFT(floatPoly.neg(floatPoly.convSmall(F))); + const sampler = new FFSampler(logn, seed, b00, b01, b10, b11); + const s2 = new Int16Array(N); + try { + while (true) { + const { t0, t1 } = sampler.sample(hm); + // t2 = b00*t0 + b10*t1 + const t2 = floatPoly.add(floatPoly.mul(t0, b00), floatPoly.mul(t1, b10)); + const t3 = floatPoly.mul(t0, b01); // t3 = b01*t0 + const t4 = floatPoly.iFFT(t2); // t4 = iFFT(tx) + // t5 = iFFT(b11*t1 + ty) + const t5 = floatPoly.iFFT(floatPoly.add(floatPoly.mul(t1, b11), t3)); + // Traverse imaginary in exact same order to avoid numerical instability + const hn = N >> 1; + let sqn = 0; + for (let i = 0; i < hn; i++) { + sqn += (hm[i] - (Math.round(t4[i].re) | 0)) ** 2; + sqn += (hm[hn + i] - (Math.round(t4[i].im) | 0)) ** 2; + const z = -Math.round(t5[i].re); + sqn += z * z; + s2[i] = z & 0xffff; + const z2 = -Math.round(t5[i].im); + sqn += z2 * z2; + s2[i + hn] = z2 & 0xffff; + } + cleanCPoly(t0, t1, t2, t3, t4, t5); + if (!(sqn <= L2BOUND[logn])) continue; + // 10: s ← Compress(s₂, 8 · sbytelen - 328) + // ▷ Remove 1 byte for the header, and 40 bytes for r + const s2comp = compCoder(N).encode(s2); + if (s2comp.length > maxLen) { + cleanBytes(s2comp); + continue; + } + return { s2: s2comp, nonce, msg } as TRet; + } + } finally { + cleanBytes(s2); + sampler.destroy(); + cleanCPoly(b00, b01, b10, b11); + cleanBytes(G); + } + } finally { + cleanBytes(f, g, F); + } + } finally { + cleanBytes(seed); + } + }; + + // Raw helper: malformed encodings or wrong lengths still throw here; the public verify()/open() + // wrappers decide whether to translate those failures into false or an exception. + const verifyRaw = ( + pk: TArg, + s2comp: TArg, + nonce: TArg, + msg: TArg + ) => { + // Algorithm 16: Verify(m, sig, pk, [β²]) + // (Page 45) + // Require: A message m, a signature sig = (r, s), a public key pk = h ∈ Zq[x]/(φ), a bound [β²] + // Ensure: Accept or reject + // 1: c ← HashToPoint(r||m, q, n) + // 2: s₂ ← Decompress(s, 8 · sbytelen - 328) + // 3: if (s₂ = ⊥) then + // 4: reject ▷ Reject invalid encodings + // 5: s₁ ← c - s₂h mod q ▷ s₁ should be normalized between -q/2 and q/2 + // 6: if ||(s₁, s₂)||² < [β²] then + // 7: accept + // 8: else + // 9: reject ▷ Reject signatures that are too long + const s2 = compCoder(N).decode(s2comp); // 2: s₂ ← Decompress(s, 8 · sbytelen - 328) + const c0 = HashToPoint(nonce, msg); // 1: c ← HashToPoint(r||m, q, n) + const h = intPoly.toMontgomery(intPoly.ntt(publicKeyCoder.decode(pk))); + const s1 = intPoly.intt(intPoly.mul(intPoly.ntt(signedCoder.decode(s2)), h)); + intPoly.sub(s1, c0); // 5: s₁ ← c - s₂h mod q ▷ s₁ should be normalized between -q/2 and q/2 + return intPoly.isShort(signedCoder.encode(s1), s2); // 6: if ||(s₁, s₂)||² < [β²] then + }; + + const info = Object.freeze({ type: 'falcon' }); + const keyLengths = Object.freeze({ + seed: 48, + publicKey: publicKeyCoder.bytesLen, + secretKey: secretKeyCoder.bytesLen, + }); + // Noble exposes a 48-byte sampler-seed hook, + // but Falcon still samples/encodes a separate 40-byte nonce per signature. + const getRnd = (opts: TArg = {}): TRet => { + validateSigOpts(opts); + if (opts.context !== undefined) throw new Error('context is not supported'); + if (opts.random !== undefined) return opts.random as TRet; + if (opts.extraEntropy === undefined) return randomBytes; + const seed = opts.extraEntropy === false ? new Uint8Array(48) : opts.extraEntropy; + abytes(seed, 48, 'opts.extraEntropy'); + const drbg = rngAesCtrDrbg256(seed); + return (len = 0) => drbg.randomBytes(len) as TRet; + }; + const checkVerOpts = (opts: TArg = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) throw new Error('context is not supported'); + }; + const tests = Object.freeze({ + publicKeyCoder: Object.freeze(publicKeyCoder), + privateKeyCoder: Object.freeze(secretKeyCoder), + maxS2Len: opts.maxS2Len, + }); + // `signRand` documents only the sampler-seed input length; + // detached/attached signatures still include their own 40-byte nonce. + const attachedLengths = Object.freeze({ ...keyLengths, signRand: 48 }); + const lengths = opts.padded + ? Object.freeze({ ...attachedLengths, signature: opts.sigLen }) + : attachedLengths; + const keygen = ( + seed?: TArg + ): TRet<{ publicKey: Uint8Array; secretKey: Uint8Array }> => { + const randSeed = seed === undefined; + if (randSeed) seed = randomBytes(48); + abytes(seed!, 48, 'seed'); + const [f, g, F, _G, pub] = new NTRU(logn, seed!).generate(); + const sk = secretKeyCoder.encode([f, g, F]); + const pk = publicKeyCoder.encode(pub); + if (randSeed) cleanBytes(seed!); + cleanBytes(f, g, F, _G); + return { publicKey: pk, secretKey: sk } as TRet<{ + publicKey: Uint8Array; + secretKey: Uint8Array; + }>; + }; + const getPublicKey = (sk: TArg): TRet => { + const [f, g, F] = secretKeyCoder.decode(sk); + try { + const h = computePublic(f, g); + cleanBytes(f, g, F); + return publicKeyCoder.encode(h) as TRet; + } catch (e) { + cleanBytes(f, g, F); + throw e; + } + }; + const sign = ( + msg: TArg, + sk: TArg, + sigOpts: TArg = {} + ): TRet => { + const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts)); + return SignatureCoderDetached(logn).encode({ nonce, s2 }); + }; + /** Verify one detached Falcon signature. + * Returns `false` for malformed detached signature encodings, non-canonical detached signatures, + * and well-formed signatures that do not validate. Throws on malformed API argument types or + * unsupported verification options. + */ + const verify = ( + sig: TArg, + msg: TArg, + pk: TArg, + verOpts: TArg = {} + ) => { + checkVerOpts(verOpts); + abytes(sig); + abytes(msg); + abytes(pk); + try { + const { s2, nonce } = SignatureCoderDetached(logn).decode(sig); + return verifyRaw(pk, s2, nonce, msg); + } catch { + return false; + } + }; + const attached: TRet = Object.freeze({ + info, + lengths: attachedLengths, + keygen, + getPublicKey, + seal(msg: TArg, sk: TArg, sigOpts: TArg = {}) { + const { s2, nonce } = signRaw(sk, msg, opts.maxS2Len, getRnd(sigOpts)); + return SignatureCoder.encode({ msg, nonce, s2 }); + }, + open(sig: TArg, pk: TArg, verOpts: TArg = {}) { + checkVerOpts(verOpts); + const { s2, nonce, msg } = SignatureCoder.decode(sig); + // Zero-copy API: returned message aliases the caller-provided signature buffer. + // Copy it if ownership is needed. + if (verifyRaw(pk, s2, nonce, msg)) return msg; + throw new Error('invalid signature'); + }, + }); + const res = { + info, + lengths, + attached, + keygen, + getPublicKey, + sign, + verify, + }; + (res as any).__test = tests; + return Object.freeze(res); +} + +const falcon512opts = { + N: 512, + // Table 3.3 fixed padded detached bytes, including the detached header byte and 40-byte nonce. + sigLen: 666, + fgBits: 6, + FGBits: 8, + // Compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + paddedLen: 625, + // Payload-only budget: genFalcon() adds the detached header byte and 40-byte nonce around it. + detachedLen: 690, +}; +/** + * Falcon-512 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512.sign(msg, secretKey); + * falcon512.verify(sig, msg, publicKey); + * ``` + */ +export const falcon512: TRet = /* @__PURE__ */ (() => + genFalcon({ ...falcon512opts, maxS2Len: 711 }))(); +/** + * Falcon-512 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-512 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon512padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon512padded.sign(msg, secretKey); + * falcon512padded.verify(sig, msg, publicKey); + * ``` + */ +export const falcon512padded: TRet = /* @__PURE__ */ (() => + genFalcon({ + ...falcon512opts, + padded: true, + maxS2Len: 625, + }))(); + +const falcon1024opts = { + N: 1024, + // Table 3.3 fixed padded detached bytes, including the detached header byte and 40-byte nonce. + sigLen: 1280, + fgBits: 5, + FGBits: 8, + // Compressed-s payload bytes only, excluding the detached header byte and 40-byte nonce. + paddedLen: 1239, + // Payload-only budget: genFalcon() adds the detached header byte and 40-byte nonce around it. + detachedLen: 1280, +}; +/** + * Falcon-1024 detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024.sign(msg, secretKey); + * falcon1024.verify(sig, msg, publicKey); + * ``` + */ +export const falcon1024: TRet = /* @__PURE__ */ (() => + genFalcon({ + ...falcon1024opts, + maxS2Len: 1421, + }))(); +/** + * Falcon-1024 padded detached-signature API with the attached helper exposed as `.attached`. + * @example + * Generate a Falcon-1024 padded keypair and verify one detached signature. + * ```ts + * const { secretKey, publicKey } = falcon1024padded.keygen(); + * const msg = new Uint8Array([1, 2, 3]); + * const sig = falcon1024padded.sign(msg, secretKey); + * falcon1024padded.verify(sig, msg, publicKey); + * ``` + */ +export const falcon1024padded: TRet = /* @__PURE__ */ (() => + genFalcon({ + ...falcon1024opts, + padded: true, + maxS2Len: 1239, + }))(); + +// NOTE: for tests only, don't use +export const __tests: any = /* @__PURE__ */ (() => + Object.freeze({ + BNORM_MAX, + COMPLEX_ROOTS, + Float, + INV_SIGMA, + SIGMA_MIN, + getFloatPoly, + cleanCPoly, + falcon512: (falcon512 as any).__test, + falcon512padded: (falcon512padded as any).__test, + falcon1024: (falcon1024 as any).__test, + falcon1024padded: (falcon1024padded as any).__test, + }))(); diff --git a/node_modules/@noble/post-quantum/src/hybrid.ts b/node_modules/@noble/post-quantum/src/hybrid.ts new file mode 100644 index 0000000..de015f7 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/hybrid.ts @@ -0,0 +1,833 @@ +/** + * Post-Quantum Hybrid Cryptography + * + * The current implementation is flawed and likely redundant. We should offer + * a small, generic API to compose hybrid schemes instead of reimplementing + * protocol-specific logic (SSH, GPG, etc.) with ad hoc encodings. + * + * 1. Core Issues + * - sign/verify: implemented as two separate operations with different keys. + * - EC getSharedSecret: could be refactored into a proper KEM. + * - Multiple calls: keys, signatures, and shared secrets could be + * concatenated to reduce the number of API invocations. + * - Reinvention: most libraries add strange domain separations and + * encodings instead of simple byte concatenation. + * + * 2. API Goals + * - Provide primitives to build hybrids generically. + * - Avoid embedding SSH- or GPG-specific formats in the core API. + * + * 3. Edge Cases + * • Variable-length signatures: + * - DER-encoded (Weierstrass curves). + * - Falcon (unpadded). + * - Concatenation works only if length is fixed; otherwise a length + * prefix is required (but that breaks compatibility). + * + * • getSharedSecret: + * - Default: non-KEM (authenticated ECDH). + * - KEM conversion: generate a random SK to remove implicit auth. + * + * 4. Common Pitfalls + * - Seed expansion: + * • Expanding a small seed into multiple keys reduces entropy. + * • API should allow identity mapping (no expansion). + * + * - Skipping full point encoding: + * • Some omit the compression byte (parity) for WebCrypto compatibility. + * • Better: hash the raw secret; coordinate output is already non-uniform. + * • Some curves (e.g., X448) produce secrets that must be re-hashed to match + * symmetric-key lengths. + * + * - Combiner inconsistencies: + * • Different domain separations and encodings across libraries. + * • Should live at the application layer, since key lengths vary. + * + * 5. Protocol Examples + * - SSH: + * • Concatenate keys. + * • Combiner: SHA-512. + * + * - GPG: + * • Concatenate keys. + * • Combiner: + * SHA3-256(kemShare || ecdhShare || ciphertext || pubKey || algId || domSep || len(domSep)) + * + * - TLS: + * • Transcript-based derivation (HKDF). + * + * 6. Relevant Specs & Implementations + * - IETF Hybrid KEM drafts: + * • draft-irtf-cfrg-hybrid-kems + * • draft-connolly-cfrg-xwing-kem + * • draft-westerbaan-tls-xyber768d00 + * + * - PQC Libraries: + * • superdilithium (cyph/pqcrypto.js) – low adoption. + * • hybrid-pqc (DogeProtocol, quantumcoinproject) – complex encodings. + * + * 7. Signatures + * - Ed25519: fixed-size, easy to support. + * - Variable-size: introduces custom format requirements; best left to + * higher-level code. + * + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { type EdDSA } from '@noble/curves/abstract/edwards.js'; +import { type MontgomeryECDH } from '@noble/curves/abstract/montgomery.js'; +import { type ECDSA } from '@noble/curves/abstract/weierstrass.js'; +import { x25519 } from '@noble/curves/ed25519.js'; +import { p256, p384 } from '@noble/curves/nist.js'; +import { + asciiToBytes, + bytesToNumberBE, + bytesToNumberLE, + concatBytes, + numberToBytesBE, +} from '@noble/curves/utils.js'; +import { expand, extract } from '@noble/hashes/hkdf.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { sha3_256, shake256 } from '@noble/hashes/sha3.js'; +import { abytes, ahash, anumber, type CHash, type CHashXOF } from '@noble/hashes/utils.js'; +import { ml_kem1024, ml_kem768 } from './ml-kem.ts'; +import { + cleanBytes, + copyBytes, + randomBytes, + splitCoder, + validateSigOpts, + validateVerOpts, + type CryptoKeys, + type KEM, + type Signer, + type TArg, + type TRet, +} from './utils.ts'; + +type CurveAll = ECDSA | EdDSA | MontgomeryECDH; +type CurveECDH = ECDSA | MontgomeryECDH; +type CurveSign = ECDSA | EdDSA; + +// Can re-use if decide to signatures support, on other hand getSecretKey is specific and ugly +function ecKeygen(curve: CurveAll, allowZeroKey: boolean = false) { + const lengths = curve.lengths; + let keygen = curve.keygen; + if (allowZeroKey) { + // Only the ECDSA/Weierstrass branch uses raw scalar-byte secret keys here. Edwards seeds are + // hashed/pruned and Montgomery keys are clamped byte strings, so forcing Point.Fn semantics on + // those curves would change key construction instead of just relaxing scalar range handling. + if (!('getSharedSecret' in curve && 'sign' in curve && 'verify' in curve)) + throw new Error('allowZeroKey requires a Weierstrass curve'); + // This legacy flag is really "skip the +1 shift" for vector matching, not "accept scalar 0". + // It swaps seeded Weierstrass keygen from reduction into [1, ORDER) to direct reduction into + // [0, ORDER), which preserves exact reduced bytes but still leaves scalar 0 invalid. + // This is ugly, but we need to return exact results here. + const wCurve = curve as ECDSA; + const Fn = wCurve.Point.Fn; + // Unlike noble-curves' seeded Weierstrass keygen, this path removes the post-reduction +1. + // That is enough to match exact reduced-vector bytes, but an all-zero seed still reduces to + // scalar 0 here and getPublicKey(secretKey) throws instead of "allowing zero". + keygen = (seed: TArg = randomBytes(lengths.seed)) => { + abytes(seed, lengths.seed!, 'seed'); + const seedScalar = Fn.isLE ? bytesToNumberLE(seed) : bytesToNumberBE(seed); + // Reduce directly into [0, ORDER); scalar 0 still stays invalid. + const secretKey = Fn.toBytes(Fn.create(seedScalar)); + return { + secretKey: secretKey as TRet, + publicKey: curve.getPublicKey(secretKey) as TRet, + }; + }; + } + return { + lengths: { secretKey: lengths.secretKey, publicKey: lengths.publicKey, seed: lengths.seed }, + keygen: (seed?: TArg) => + keygen(seed) as TRet<{ + secretKey: Uint8Array; + publicKey: Uint8Array; + }>, + getPublicKey: (secretKey: TArg) => + curve.getPublicKey(secretKey) as TRet, + }; +} + +/** + * Wraps an ECDH-capable curve as a KEM. + * Shared secrets stay in the wrapped curve's raw ECDH byte format with no built-in KDF. + * On SEC 1 / Weierstrass curves, that means the compressed shared-point body without the + * 1-byte `0x02` / `0x03` prefix. + * The X25519 path also leaves RFC 7748's optional all-zero shared-secret check to callers. + * @param curve - Curve with `getSharedSecret`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns KEM wrapper over the curve. + * @throws If the curve does not expose `getSharedSecret`. {@link Error} + * @example + * Wrap an ECDH-capable curve as a generic KEM. + * ```ts + * import { x25519 } from '@noble/curves/ed25519.js'; + * import { ecdhKem } from '@noble/post-quantum/hybrid.js'; + * const kem = ecdhKem(x25519); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function ecdhKem(curve: CurveECDH, allowZeroKey: boolean = false): TRet { + const kg = ecKeygen(curve, allowZeroKey); + if (!curve.getSharedSecret) throw new Error('wrong curve'); // ed25519 doesn't have one! + return { + lengths: { ...kg.lengths, msg: kg.lengths.seed, cipherText: kg.lengths.publicKey }, + keygen: kg.keygen, + getPublicKey: kg.getPublicKey, + encapsulate( + publicKey: TArg, + rand: TArg = randomBytes(curve.lengths.seed) + ) { + // Some curve.keygen(seed) paths reuse the provided seed buffer as secretKey; detach caller + // randomness first so cleanBytes() only wipes wrapper-owned material. + const seed = copyBytes(rand); + let ek: Uint8Array | undefined = undefined; + try { + ek = this.keygen(seed).secretKey; + const sharedSecret = this.decapsulate(publicKey, ek); + const cipherText = curve.getPublicKey(ek) as TRet; + return { sharedSecret, cipherText }; + } finally { + // Invalid peer public keys can make decapsulation throw; wipe both the detached seed and + // derived ephemeral secret key even when encapsulation aborts before returning. + cleanBytes(seed); + if (ek) cleanBytes(ek); + } + }, + decapsulate(cipherText: TArg, secretKey: TArg) { + const res = curve.getSharedSecret(secretKey, cipherText); + return (curve.lengths.publicKeyHasPrefix ? res.subarray(1) : res) as TRet; + }, + }; +} + +/** + * Wraps a curve signer as a generic `Signer`. + * Signatures stay in the wrapped curve's native byte encoding. + * This wrapper does not normalize or document which per-curve signing options are meaningful. + * @param curve - Curve with `sign` and `verify`. + * @param allowZeroKey - Legacy vector-matching toggle for Weierstrass keygen. + * On Weierstrass curves this removes the usual post-reduction `+1` shift, changing seeded scalar + * reduction from `[1, ORDER)` to direct reduction into `[0, ORDER)`. It does not make scalar zero + * valid: an all-zero seed still derives scalar `0` and throws in `curve.getPublicKey(...)`. + * Only supported on Weierstrass/ECDSA curves. + * @returns Signer wrapper over the curve. + * @throws If the curve does not expose `sign` and `verify`. {@link Error} + * @example + * Wrap a curve signer as a generic signer. + * ```ts + * import { ed25519 } from '@noble/curves/ed25519.js'; + * import { ecSigner } from '@noble/post-quantum/hybrid.js'; + * const signer = ecSigner(ed25519); + * const sigLen = signer.lengths.signature; + * ``` + */ +export function ecSigner(curve: CurveSign, allowZeroKey: boolean = false): TRet { + const kg = ecKeygen(curve, allowZeroKey); + if (!curve.sign || !curve.verify) throw new Error('wrong curve'); // ed25519 doesn't have one! + return { + lengths: { ...kg.lengths, signature: curve.lengths.signature, signRand: 0 }, + keygen: kg.keygen, + getPublicKey: kg.getPublicKey, + sign: (message, secretKey, opts = {}) => { + validateSigOpts(opts); + // This generic wrapper intentionally keeps the Signer contract to message + key only. + // Backend-specific knobs like ECDSA extraEntropy or Ed25519ctx context cannot be forwarded + // uniformly through combineSigners(), so callers that need them must use the curve directly. + if (opts.extraEntropy !== undefined) + throw new Error( + 'ecSigner does not support extraEntropy; use the underlying curve directly' + ); + if (opts.context !== undefined) + throw new Error('ecSigner does not support context; use the underlying curve directly'); + return curve.sign(message, secretKey) as TRet; + }, + /** Verify one wrapped curve signature. + * Returns the wrapped curve's `verify()` result for well-formed inputs. Throws on unsupported + * generic opts and lets wrapped-curve malformed-input errors escape unchanged. + */ + verify: (signature, message, publicKey, opts = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) + throw new Error('ecSigner does not support context; use the underlying curve directly'); + return curve.verify(signature, message, publicKey); + }, + }; +} + +function splitLengths> }>( + lst: T[], + name: K +) { + // Preserve caller order exactly; raw numeric fields still decode as splitCoder() subarray views. + return splitCoder( + name, + ...lst.map((i) => { + if (typeof i.lengths[name] !== 'number') throw new Error('wrong length: ' + name); + return i.lengths[name]; + }) + ); +} + +/** Seed-expansion callback used by the hybrid combiners. */ +export type ExpandSeed = (seed: TArg, len: number) => TRet; +type XOF = CHashXOF; + +// It is XOF for most cases, but can be more complex! +/** + * Adapts an XOF into an `ExpandSeed` callback. + * The returned callback interprets its second argument as an output byte length passed as `dkLen`. + * @param xof - Extendable-output hash function. + * @returns Seed expander using `dkLen`. + * @example + * Adapt an XOF into a seed expander. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * const expandSeed = expandSeedXof(shake256); + * const seed = expandSeed(new Uint8Array([1]), 4); + * ``` + */ +export function expandSeedXof(xof: TArg): TRet { + // Forward the caller seed directly: XOFs are expected to treat inputs as read-only, and this + // adapter only translates the requested byte length into the hash API's `dkLen` option. + return ((seed: TArg, seedLen: number): TRet => + (xof as XOF)(seed, { dkLen: seedLen }) as TRet) as TRet; +} + +/** Combines public keys, ciphertexts, and shared secrets into one shared secret. */ +export type Combiner = ( + publicKeys: TArg, + cipherTexts: TArg, + sharedSecrets: TArg +) => TRet; + +function combineKeys( + realSeedLen: number | undefined, // how much bytes expandSeed expects + expandSeed_: TArg, + ...ck_: TArg +) { + const expandSeed = expandSeed_ as ExpandSeed; + const ck = ck_ as CryptoKeys[]; + const seedCoder = splitLengths(ck, 'seed'); + const pkCoder = splitLengths(ck, 'publicKey'); + // Allows to use identity functions for combiner/expandSeed + if (realSeedLen === undefined) realSeedLen = seedCoder.bytesLen; + anumber(realSeedLen); + function expandDecapsulationKey(seed: TArg): TRet<{ + secretKey: Uint8Array[]; + publicKey: Uint8Array[]; + }> { + abytes(seed, realSeedLen!); + const expandedRaw = expandSeed(seed, seedCoder.bytesLen); + // Identity/subarray expanders can hand back caller-owned seed storage. Detach those outputs so + // later cleanup can wipe the expanded schedule without mutating the caller's root seed bytes. + const expandedSeed = expandedRaw.buffer === seed.buffer ? copyBytes(expandedRaw) : expandedRaw; + const expanded: Uint8Array[] = []; + const keySecret: Uint8Array[] = []; + const secretKey: Uint8Array[] = []; + const publicKey: Uint8Array[] = []; + let ok = false; + try { + // seedCoder.decode() returns zero-copy slices into expandedSeed and can throw before child + // keygen() runs, so keep the raw expanded buffer separate and copy each child seed before any + // later cleanup wipes the shared backing bytes. + for (const part of seedCoder.decode(expandedSeed)) expanded.push(copyBytes(part)); + for (let i = 0; i < ck.length; i++) { + const keys = ck[i].keygen(expanded[i]); + keySecret.push(keys.secretKey); + secretKey.push(copyBytes(keys.secretKey)); + publicKey.push(keys.publicKey); + } + ok = true; + return { secretKey, publicKey } as TRet<{ + secretKey: Uint8Array[]; + publicKey: Uint8Array[]; + }>; + } finally { + // Child keygen() can throw after deriving only a prefix of the composite key schedule. Keep + // the exported copies on success, but wipe all temporary and partially built secret material + // on either path so failures do not strand derived child seeds in memory. + cleanBytes(expandedSeed, expanded, keySecret); + if (!ok) cleanBytes(secretKey); + } + } + return { + info: { lengths: { seed: realSeedLen, publicKey: pkCoder.bytesLen, secretKey: realSeedLen } }, + getPublicKey(secretKey: TArg) { + // Composite secret keys are root seeds, so public-key derivation reruns key expansion from + // that seed instead of decoding a packed child-secret-key structure. + return this.keygen(secretKey).publicKey as TRet; + }, + keygen(seed: TArg = randomBytes(realSeedLen)) { + const { publicKey: pk, secretKey } = expandDecapsulationKey(seed); + try { + const publicKey = pkCoder.encode(pk) as TRet; + return { secretKey: seed as TRet, publicKey }; + } finally { + cleanBytes(pk); + // The exported secretKey is the caller/root seed itself; child secret keys are internal + // expansion outputs that are cleaned whether encoding succeeds or throws. + cleanBytes(secretKey); + } + }, + expandDecapsulationKey, + realSeedLen, + }; +} + +// This generic function that combines multiple KEMs into single one +/** + * Combines multiple KEMs into one composite KEM. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param realMsgLen - Shared-secret length returned by `combiner`. + * @param expandSeed - Seed expander used to derive per-KEM seeds. + * @param combiner - Combines the per-KEM outputs into one shared secret. + * @param kems - KEM implementations to combine. + * @returns Composite KEM. + * @example + * Combine multiple KEMs into one composite KEM. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineKEMS, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const hybrid = combineKEMS( + * 32, + * 32, + * expandSeedXof(shake256), + * (_pk, _ct, sharedSecrets) => sharedSecrets[0], + * ml_kem768, + * ml_kem768 + * ); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export function combineKEMS( + realSeedLen: number | undefined, // how much bytes expandSeed expects + realMsgLen: number | undefined, // how much bytes combiner returns + expandSeed: TArg, + combiner: TArg, + ...kems: TArg +): TRet { + const rawCombiner = combiner as Combiner; + const rawKems = kems as KEM[]; + const keys = combineKeys(realSeedLen, expandSeed, ...rawKems); + const ctCoder = splitLengths(rawKems, 'cipherText'); + const pkCoder = splitLengths(rawKems, 'publicKey'); + const msgCoder = splitLengths(rawKems, 'msg'); + if (realMsgLen === undefined) realMsgLen = msgCoder.bytesLen; + anumber(realMsgLen); + const lengths = Object.freeze({ + ...keys.info.lengths, + msg: realMsgLen, + msgRand: msgCoder.bytesLen, + cipherText: ctCoder.bytesLen, + }); + return Object.freeze({ + lengths, + getPublicKey: keys.getPublicKey, + keygen: keys.keygen, + encapsulate( + pk: TArg, + randomness: TArg = randomBytes(msgCoder.bytesLen) + ) { + const pks = pkCoder.decode(pk); + const rand = msgCoder.decode(randomness); + const sharedSecret: Uint8Array[] = []; + const cipherText: Uint8Array[] = []; + try { + for (let i = 0; i < rawKems.length; i++) { + const enc = rawKems[i].encapsulate(pks[i], rand[i]); + sharedSecret.push(enc.sharedSecret); + cipherText.push(enc.cipherText); + } + return { + // Detach the combiner result before cleanup: a caller-provided combiner may alias one of + // the child sharedSecret buffers, and those child buffers are zeroized immediately below. + sharedSecret: copyBytes(rawCombiner(pks, cipherText, sharedSecret)), + cipherText: ctCoder.encode(cipherText) as TRet, + }; + } finally { + // Child encapsulation or combiner failures can happen after some components already + // returned secret material; zeroize whatever was produced before propagating the error. + cleanBytes(sharedSecret, cipherText); + } + }, + decapsulate(ct: TArg, seed: TArg) { + const cts = ctCoder.decode(ct); + const { publicKey, secretKey } = keys.expandDecapsulationKey(seed); + const sharedSecret = rawKems.map((i, j) => i.decapsulate(cts[j], secretKey[j])); + try { + // Detach the decapsulation result before cleanup: the combiner may hand back one of the + // child shared-secret buffers, and those temporary buffers are zeroized below. + return copyBytes(rawCombiner(publicKey, cts, sharedSecret)); + } finally { + // Decapsulation only needs the expanded child secret keys and child shared secrets for this + // call; keep the caller/root seed intact, but wipe all derived material even on errors. + cleanBytes(secretKey, sharedSecret); + } + }, + }); +} +// There is no specs for this, but can be useful +// realSeedLen: how much bytes expandSeed expects. +/** + * Combines multiple signers into one composite signer. + * @param realSeedLen - Input seed length expected by `expandSeed`. + * @param expandSeed - Seed expander used to derive per-signer seeds. + * @param signers - Signers to combine. + * @returns Composite signer. + * @example + * Combine multiple signers into one composite signer. + * ```ts + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { combineSigners, expandSeedXof } from '@noble/post-quantum/hybrid.js'; + * import { ml_dsa44 } from '@noble/post-quantum/ml-dsa.js'; + * const hybrid = combineSigners(32, expandSeedXof(shake256), ml_dsa44, ml_dsa44); + * const { publicKey } = hybrid.keygen(); + * ``` + */ +export function combineSigners( + realSeedLen: number | undefined, + expandSeed: TArg, + ...signers: TArg +): TRet { + const rawSigners = signers as Signer[]; + const keys = combineKeys(realSeedLen, expandSeed, ...rawSigners); + const sigCoder = splitLengths(rawSigners, 'signature'); + const pkCoder = splitLengths(rawSigners, 'publicKey'); + return { + lengths: { ...keys.info.lengths, signature: sigCoder.bytesLen, signRand: 0 }, + getPublicKey: keys.getPublicKey, + keygen: keys.keygen, + sign(message, seed, opts = {}) { + validateSigOpts(opts); + // This generic wrapper intentionally keeps the composite signer contract to message + root + // seed only. Per-signer opts like context or extraEntropy cannot be preserved uniformly + // across mixed backends, so callers that need them must use the underlying signer directly. + if (opts.extraEntropy !== undefined) + throw new Error( + 'combineSigners does not support extraEntropy; use the underlying signer directly' + ); + if (opts.context !== undefined) + throw new Error( + 'combineSigners does not support context; use the underlying signer directly' + ); + const { secretKey } = keys.expandDecapsulationKey(seed); + try { + const sigs = rawSigners.map((i, j) => i.sign(message, secretKey[j])); + return sigCoder.encode(sigs) as TRet; + } finally { + // Composite secret keys are root seeds; the per-signer child secret keys are temporary + // expansion outputs and must not stay live after the combined signature is produced. + cleanBytes(secretKey); + } + }, + /** Verify one combined signature. + * Returns `false` when the aggregate signature/publicKey decode succeeds but any child verify + * check fails. Throws on unsupported generic opts or malformed aggregate encodings. + */ + verify: (signature, message, publicKey, opts = {}) => { + validateVerOpts(opts); + if (opts.context !== undefined) + throw new Error( + 'combineSigners does not support context; use the underlying signer directly' + ); + const pks = pkCoder.decode(publicKey); + const sigs = sigCoder.decode(signature); + for (let i = 0; i < rawSigners.length; i++) { + if (!rawSigners[i].verify(sigs[i], message, pks[i])) return false; + } + return true; + }, + }; +} + +/** + * Builds a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * The combined shared-secret length follows `kdf.outputLen`; the built-in presets use 32-byte + * SHA3-256 output, while custom `kdf` choices inherit their own digest size. + * Its combiner hashes `ss0 || ss1 || ct1 || pk1 || label`, not the full + * `(c1, c2, ek1, ek2)` example input shape from SP 800-227 equation (15). + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param kdf - Hash used for the final combiner. + * @returns Hybrid KEM. + * @example + * Build a QSF hybrid KEM preset from a PQ KEM and an elliptic-curve KEM. + * ```ts + * import { p256 } from '@noble/curves/nist.js'; + * import { sha3_256, shake256 } from '@noble/hashes/sha3.js'; + * import { QSF, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * const kem = QSF('example', ml_kem768, ecdhKem(p256, true), shake256, sha3_256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function QSF( + label: string, + pqc: TArg, + curveKEM: TArg, + xof: TArg, + kdf: CHash +): TRet { + ahash(xof); + ahash(kdf); + return combineKEMS( + 32, + kdf.outputLen, + expandSeedXof(xof), + (pk: TArg, ct: TArg, ss: TArg) => + kdf(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), + pqc, + curveKEM + ); +} + +/** QSF preset combining ML-KEM-768 with P-256. */ +export const QSF_ml_kem768_p256: TRet = /* @__PURE__ */ (() => + QSF( + 'QSF-KEM(ML-KEM-768,P-256)-XOF(SHAKE256)-KDF(SHA3-256)', + ml_kem768, + ecdhKem(p256, true), + shake256, + sha3_256 + ))(); +/** QSF preset combining ML-KEM-1024 with P-384. */ +export const QSF_ml_kem1024_p384: TRet = /* @__PURE__ */ (() => + QSF( + 'QSF-KEM(ML-KEM-1024,P-384)-XOF(SHAKE256)-KDF(SHA3-256)', + ml_kem1024, + ecdhKem(p384, true), + shake256, + sha3_256 + ))(); + +/** + * Builds the "KitchenSink" hybrid KEM combiner. + * The current builder always derives a fixed 32-byte output, + * regardless of the hash's native output size. + * Its HKDF extract step uses implicit zero salt with IKM + * `hybrid_prk || ss0 || ss1 || ct0 || pk0 || ct1 || pk1 || label`. + * Its HKDF expand step fixes `info` to `len || 'shared_secret' || ''`. + * Labels are encoded with `asciiToBytes()`, so non-ASCII labels are rejected. + * @param label - Domain-separation label. + * @param pqc - Post-quantum KEM. + * @param curveKEM - Classical curve KEM. + * @param xof - XOF used for seed expansion. + * @param hash - Hash used for HKDF extraction and expansion. + * @returns Hybrid KEM. + * @example + * Build the "KitchenSink" hybrid KEM combiner. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { shake256 } from '@noble/hashes/sha3.js'; + * import { createKitchenSink, ecdhKem } from '@noble/post-quantum/hybrid.js'; + * import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + * import { x25519 } from '@noble/curves/ed25519.js'; + * const kem = createKitchenSink('example', ml_kem768, ecdhKem(x25519), shake256, sha256); + * const publicKeyLen = kem.lengths.publicKey; + * ``` + */ +export function createKitchenSink( + label: string, + pqc: TArg, + curveKEM: TArg, + xof: TArg, + hash: CHash +): TRet { + ahash(xof); + ahash(hash); + return combineKEMS( + 32, + 32, + expandSeedXof(xof), + (pk: TArg, ct: TArg, ss: TArg) => { + const preimage = concatBytes(ss[0], ss[1], ct[0], pk[0], ct[1], pk[1], asciiToBytes(label)); + const len = 32; + const ikm = concatBytes(asciiToBytes('hybrid_prk'), preimage); + const prk = extract(hash, ikm); + const info = concatBytes( + numberToBytesBE(len, 2), + asciiToBytes('shared_secret'), + asciiToBytes('') + ); + const res = expand(hash, prk, info, len); + cleanBytes(prk, info, ikm, preimage); + return res; + }, + pqc, + curveKEM + ); +} + +// Internal alias only: this stays exactly `ecdhKem(x25519)` +// and inherits that wrapper's mutation/oracle behavior. +const x25519kem = /* @__PURE__ */ ecdhKem(x25519); +/** KitchenSink preset combining ML-KEM-768 with X25519. + * Caller randomness splits into 32 ML-KEM coins plus a 32-byte X25519 ephemeral-secret seed. + */ +export const KitchenSink_ml_kem768_x25519: TRet = /* @__PURE__ */ (() => + createKitchenSink( + 'KitchenSink-KEM(ML-KEM-768,X25519)-XOF(SHAKE256)-KDF(HKDF-SHA-256)', + ml_kem768, + x25519kem, + shake256, + sha256 + ))(); + +// Always X25519 and ML-KEM - 768, no point to export +/** X25519 + ML-KEM-768 hybrid preset. + * Uses the hard-coded domain-separation label `\\.//^\\` and hashes only `ct1 || pk1` + * from the X25519 side in addition to the two component shared secrets. + */ +export const ml_kem768_x25519: TRet = /* @__PURE__ */ (() => + combineKEMS( + 32, + 32, + expandSeedXof(shake256), + // Awesome label, so much escaping hell in a single line. + (pk: TArg, ct: TArg, ss: TArg) => + sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes('\\.//^\\'))), + ml_kem768, + x25519kem + ))(); + +/** + * Internal SEC 1-style KEM wrapper for NIST curves. + * `nseed` is only the rejection-sampling byte budget for deriving one nonzero scalar: + * current presets use `128` bytes for P-256 and `48` bytes for P-384. + * `decapsulate()` returns the uncompressed shared point body `x || y` without the `0x04` + * prefix, not the SEC 1 `x_P`-only primitive output, because current hybrid combiners hash + * both coordinates. + */ +function nistCurveKem(curve: ECDSA, scalarLen: number, elemLen: number, nseed: number): TRet { + const Fn = curve.Point.Fn; + if (!Fn) throw new Error('no Point.Fn'); + // Scan scalar-sized windows until one decodes to a nonzero scalar in `[1, n-1]`; if every + // window is zero or out of range, fail instead of silently reducing modulo `n`. + function rejectionSampling(seed: TArg): TRet<{ + secretKey: Uint8Array; + publicKey: Uint8Array; + }> { + let sk: bigint; + for (let start = 0, end = scalarLen; ; start = end, end += scalarLen) { + if (end > seed.length) throw new Error('rejection sampling failed'); + sk = Fn.fromBytes(seed.subarray(start, end), true); + if (Fn.isValidNot0(sk)) break; + } + const secretKey = Fn.toBytes(Fn.create(sk)); + const publicKey = curve.getPublicKey(secretKey, false); + return { secretKey, publicKey } as TRet<{ + secretKey: Uint8Array; + publicKey: Uint8Array; + }>; + } + + return { + lengths: { + secretKey: scalarLen, + publicKey: elemLen, + seed: nseed, + msg: nseed, + cipherText: elemLen, + }, + keygen(seed: TArg = randomBytes(nseed)) { + abytes(seed, nseed, 'seed'); + return rejectionSampling(seed); + }, + getPublicKey(secretKey: TArg) { + return curve.getPublicKey(secretKey, false) as TRet; + }, + encapsulate(publicKey: TArg, rand: TArg = randomBytes(nseed)) { + abytes(rand, nseed, 'rand'); + let ek: Uint8Array | undefined = undefined; + try { + ek = rejectionSampling(rand).secretKey; + const sharedSecret = this.decapsulate(publicKey, ek); + const cipherText = curve.getPublicKey(ek, false) as TRet; + return { sharedSecret, cipherText }; + } finally { + // Rejection-sampled NIST-curve ephemeral secret keys are temporary encapsulation state and + // must be wiped even if peer-key validation or shared-secret derivation throws. + if (ek) cleanBytes(ek); + } + }, + decapsulate(cipherText: TArg, secretKey: TArg) { + const full = curve.getSharedSecret(secretKey, cipherText); + return full.subarray(1) as TRet; + }, + }; +} + +/** + * Internal ML-KEM + NIST-curve combiner. + * `nseed` controls only the curve-side rejection-sampling budget; it is expanded from the + * 32-byte root seed and is not itself part of the exported secret-key length. + * The domain-separation `label` is used only in the final `sha3_256` combiner, not in + * `shake256(seed, { dkLen: 64 + nseed })`, + * and the combiner hashes `ss0 || ss1 || ct1 || pk1 || label`. + */ +function concreteHybridKem( + label: string, + mlkem: TArg, + curve: ECDSA, + nseed: number +): TRet { + const { secretKey: scalarLen, publicKeyUncompressed: elemLen } = curve.lengths; + if (!scalarLen || !elemLen) throw new Error('wrong curve'); + const curveKem = nistCurveKem(curve, scalarLen, elemLen, nseed); + const mlkemSeedLen = 64; + const totalSeedLen = mlkemSeedLen + nseed; + + return combineKEMS( + 32, + 32, + (seed: TArg): TRet => { + abytes(seed, 32); + const expanded = shake256(seed, { dkLen: totalSeedLen }); + const mlkemSeed = expanded.subarray(0, mlkemSeedLen); + const curveSeed = expanded.subarray(mlkemSeedLen, totalSeedLen); + return concatBytes(mlkemSeed, curveSeed) as TRet; + }, + (pk: TArg, ct: TArg, ss: TArg) => + sha3_256(concatBytes(ss[0], ss[1], ct[1], pk[1], asciiToBytes(label))), + mlkem, + curveKem + ); +} + +/** P-256 + ML-KEM-768 hybrid preset. */ +export const ml_kem768_p256: TRet = /* @__PURE__ */ (() => + concreteHybridKem('MLKEM768-P256', ml_kem768, p256, 128))(); + +/** P-384 + ML-KEM-1024 hybrid preset. */ +export const ml_kem1024_p384: TRet = /* @__PURE__ */ (() => + concreteHybridKem('MLKEM1024-P384', ml_kem1024, p384, 48))(); + +// Legacy aliases +/** Legacy alias for `ml_kem768_x25519`. */ +export const XWing: TRet = /* @__PURE__ */ (() => ml_kem768_x25519)(); +/** Legacy alias for `ml_kem768_x25519`. */ +export const MLKEM768X25519: TRet = /* @__PURE__ */ (() => ml_kem768_x25519)(); +/** Legacy alias for `ml_kem768_p256`. */ +export const MLKEM768P256: TRet = /* @__PURE__ */ (() => ml_kem768_p256)(); +/** Legacy alias for `ml_kem1024_p384`. */ +export const MLKEM1024P384: TRet = /* @__PURE__ */ (() => ml_kem1024_p384)(); +/** Legacy alias for `QSF_ml_kem768_p256`. */ +export const QSFMLKEM768P256: TRet = /* @__PURE__ */ (() => QSF_ml_kem768_p256)(); +/** Legacy alias for `QSF_ml_kem1024_p384`. */ +export const QSFMLKEM1024P384: TRet = /* @__PURE__ */ (() => QSF_ml_kem1024_p384)(); +/** Legacy alias for `KitchenSink_ml_kem768_x25519`. */ +export const KitchenSinkMLKEM768X25519: TRet = /* @__PURE__ */ (() => + KitchenSink_ml_kem768_x25519)(); diff --git a/node_modules/@noble/post-quantum/src/index.ts b/node_modules/@noble/post-quantum/src/index.ts new file mode 100644 index 0000000..f4bf3f0 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/index.ts @@ -0,0 +1,27 @@ +/** + * Auditable & minimal JS implementation of post-quantum public-key cryptography. + * Check out individual modules. + * @module + * @example +```js +import { ml_kem512, ml_kem768, ml_kem1024 } from '@noble/post-quantum/ml-kem.js'; +import { ml_dsa44, ml_dsa65, ml_dsa87 } from '@noble/post-quantum/ml-dsa.js'; +import { + slh_dsa_sha2_128f, slh_dsa_sha2_128s, + slh_dsa_sha2_192f, slh_dsa_sha2_192s, + slh_dsa_sha2_256f, slh_dsa_sha2_256s, + slh_dsa_shake_128f, slh_dsa_shake_128s, + slh_dsa_shake_192f, slh_dsa_shake_192s, + slh_dsa_shake_256f, slh_dsa_shake_256s, +} from '@noble/post-quantum/slh-dsa.js'; +import { + falcon512, falcon512padded, falcon1024, falcon1024padded, +} from '@noble/post-quantum/falcon.js'; +import { + ml_kem768_x25519, ml_kem768_p256, ml_kem1024_p384, + KitchenSink_ml_kem768_x25519, XWing, + QSF_ml_kem768_p256, QSF_ml_kem1024_p384, +} from '@noble/post-quantum/hybrid.js'; +``` + */ +throw new Error('root module cannot be imported: import submodules instead. Check out README'); diff --git a/node_modules/@noble/post-quantum/src/ml-dsa.ts b/node_modules/@noble/post-quantum/src/ml-dsa.ts new file mode 100644 index 0000000..3358cc2 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/ml-dsa.ts @@ -0,0 +1,784 @@ +/** + * ML-DSA: Module Lattice-based Digital Signature Algorithm from + * [FIPS-204](https://csrc.nist.gov/pubs/fips/204/ipd). A.k.a. CRYSTALS-Dilithium. + * + * Has similar internals to ML-KEM, but their keys and params are different. + * Check out [official site](https://www.pq-crystals.org/dilithium/index.shtml), + * [repo](https://github.com/pq-crystals/dilithium). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { abool } from '@noble/curves/utils.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import type { CHash } from '@noble/hashes/utils.js'; +import { genCrystals, type XOF, XOF128, XOF256 } from './_crystals.ts'; +import { + abytes, + type BytesCoderLen, + checkHash, + cleanBytes, + type CryptoKeys, + equalBytes, + getMessage, + getMessagePrehash, + randomBytes, + type Signer, + type SigOpts, + splitCoder, + type TArg, + type TRet, + validateOpts, + validateSigOpts, + validateVerOpts, + vecCoder, + type VerOpts, +} from './utils.ts'; + +/** Internal ML-DSA options. */ +export type DSAInternalOpts = { + /** + * Whether `internal.sign` / `internal.verify` receive a caller-supplied 64-byte `mu` + * instead of the usual FIPS 204 formatted message `M'` / prehash-formatted message. + * validateInternalOpts() only checks this flag; callers still must supply the right input length. + */ + externalMu?: boolean; +}; +function validateInternalOpts(opts: TArg) { + validateOpts(opts); + if (opts.externalMu !== undefined) abool(opts.externalMu, 'opts.externalMu'); +} + +/** ML-DSA signer surface with access to the internal message formatting mode. */ +export type DSAInternal = CryptoKeys & { + lengths: Signer['lengths']; + sign: ( + msg: TArg, + secretKey: TArg, + opts?: TArg + ) => TRet; + verify: ( + sig: TArg, + msg: TArg, + pubKey: TArg, + opts?: TArg + ) => boolean; +}; +/** Public ML-DSA signer surface. */ +export type DSA = Signer & { internal: TRet }; + +// Constants +// FIPS 204 fixes ML-DSA over R = Z[X]/(X^256 + 1), so every polynomial has 256 coefficients. +const N = 256; +// 2**23 − 2**13 + 1, 23 bits: multiply will be 46. We have enough precision in JS to avoid bigints +const Q = 8380417; +// FIPS 204 §2.5 / Table 1 fixes zeta = 1753 as the 512th root of unity used by ML-DSA's NTT. +const ROOT_OF_UNITY = 1753; +// f = 256**−1 mod q, pow(256, -1, q) = 8347681 (python3) +const F = 8347681; +// FIPS 204 Table 1 / §7.4 fixes d = 13 dropped low bits for Power2Round on t. +const D = 13; +// FIPS 204 Table 1 fixes gamma2 to (q-1)/88 for ML-DSA-44 and (q-1)/32 for ML-DSA-65/87; +// §7.4 then uses alpha = 2*gamma2 for Decompose / MakeHint / UseHint. +// Dilithium is kinda parametrized over GAMMA2, but everything will break with any other value. +const GAMMA2_1 = Math.floor((Q - 1) / 88) | 0; +const GAMMA2_2 = Math.floor((Q - 1) / 32) | 0; + +type XofGet = ReturnType['get']>; + +/** Various lattice params. */ +/** Public ML-DSA parameter-set description. */ +export type DSAParam = { + /** Matrix row count. */ + K: number; + /** Matrix column count. */ + L: number; + /** Bit width used when rounding `t`. */ + D: number; + /** Bound used for the `y` sampling range. */ + GAMMA1: number; + /** Bound used during decomposition and hints. */ + GAMMA2: number; + /** Number of non-zero challenge coefficients. */ + TAU: number; + /** Centered-binomial noise parameter. */ + ETA: number; + /** Maximum number of hint bits in a signature. */ + OMEGA: number; +}; +/** Internal params for different versions of ML-DSA */ +// prettier-ignore +/** Built-in ML-DSA parameter presets keyed by security categories `2/3/5` + * for `ml_dsa44` / `ml_dsa65` / `ml_dsa87`. + * This is only the Table 1 subset used directly here: `BETA = TAU * ETA` is derived later, + * while `C_TILDE_BYTES`, `TR_BYTES`, `CRH_BYTES`, and `securityLevel` live in the preset wrappers. + */ +export const PARAMS: Record = /* @__PURE__ */ (() => + Object.freeze({ + 2: Object.freeze({ + K: 4, L: 4, D, GAMMA1: 2 ** 17, GAMMA2: GAMMA2_1, TAU: 39, ETA: 2, OMEGA: 80 + }), + 3: Object.freeze({ + K: 6, L: 5, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 49, ETA: 4, OMEGA: 55 + }), + 5: Object.freeze({ + K: 8, L: 7, D, GAMMA1: 2 ** 19, GAMMA2: GAMMA2_2, TAU: 60, ETA: 2, OMEGA: 75 + }), + } as const))(); + +// NOTE: there is a lot cases where negative numbers used (with smod instead of mod). +type Poly = Int32Array; +const newPoly = (n: number): TRet => new Int32Array(n) as TRet; + +// Shared CRYSTALS helper in the ML-DSA branch: non-Kyber mode, 8-bit bit-reversal, +// and Int32Array polys because ordinary-form coefficients can be negative / centered. +const crystals = /* @__PURE__ */ genCrystals({ + N, + Q, + F, + ROOT_OF_UNITY, + newPoly, + isKyber: false, + brvBits: 8, +}); + +const id = (n: T): T => n; +type IdNum = (n: number) => number; + +// compress()/verify() must be compatible in both directions: +// wrap the shared d-bit packer with the FIPS 204 SimpleBitPack / BitPack coefficient maps. +// malformed-input rejection only happens through the optional verify hook. +const polyCoder = (d: number, compress: IdNum = id, verify: IdNum = id) => + crystals.bitsCoder(d, { + encode: (i: number) => compress(verify(i)), + decode: (i: number) => verify(compress(i)), + }); + +// Mutates `a` in place; callers must pass same-length polynomials. +const polyAdd = (a_: TArg, b_: TArg): TRet => { + const a = a_ as Poly; + const b = b_ as Poly; + for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] + b[i]); + return a as TRet; +}; +// Mutates `a` in place; callers must pass same-length polynomials. +const polySub = (a_: TArg, b_: TArg): TRet => { + const a = a_ as Poly; + const b = b_ as Poly; + for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] - b[i]); + return a as TRet; +}; + +// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial. +const polyShiftl = (p_: TArg): TRet => { + const p = p_ as Poly; + for (let i = 0; i < N; i++) p[i] <<= D; + return p as TRet; +}; + +const polyChknorm = (p_: TArg, B: number): boolean => { + const p = p_ as Poly; + // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities. + for (let i = 0; i < N; i++) if (Math.abs(crystals.smod(p[i])) >= B) return true; + return false; +}; + +// Both inputs must already be in NTT / `T_q` form. +const MultiplyNTTs = (a_: TArg, b_: TArg): TRet => { + const a = a_ as Poly; + const b = b_ as Poly; + // NOTE: we don't use montgomery reduction in code, since it requires 64 bit ints, + // which is not available in JS. mod(a[i] * b[i]) is ok, since Q is 23 bit, + // which means a[i] * b[i] is 46 bit, which is safe to use in JS. (number is 53 bits). + // Barrett reduction is slower than mod :( + const c = newPoly(N); + for (let i = 0; i < a.length; i++) c[i] = crystals.mod(a[i] * b[i]); + return c as TRet; +}; + +// Return poly in NTT representation +function RejNTTPoly(xof_: TArg): TRet { + const xof = xof_ as XofGet; + // Samples a polynomial ∈ Tq. xof() must return byte lengths divisible by 3. + const r = newPoly(N); + // NOTE: we can represent 3xu24 as 4xu32, but it doesn't improve perf :( + for (let j = 0; j < N; ) { + const b = xof(); + if (b.length % 3) throw new Error('RejNTTPoly: unaligned block'); + for (let i = 0; j < N && i <= b.length - 3; i += 3) { + // FIPS 204 Algorithm 14 clears the top bit of b2 before forming the 23-bit candidate. + const t = (b[i + 0] | (b[i + 1] << 8) | (b[i + 2] << 16)) & 0x7fffff; // 3 bytes + if (t < Q) r[j++] = t; + } + } + return r as TRet; +} + +type DilithiumOpts = { + K: number; + L: number; + GAMMA1: number; + GAMMA2: number; + TAU: number; + ETA: number; + OMEGA: number; + C_TILDE_BYTES: number; + CRH_BYTES: number; + TR_BYTES: number; + XOF128: XOF; + XOF256: XOF; + securityLevel: number; +}; + +// Instantiate one ML-DSA parameter set from the Table 1 lattice constants plus the +// Table 2 byte lengths / hash-width choices used by the public wrappers below. +function getDilithium(opts_: TArg): TRet { + const opts = opts_ as DilithiumOpts; + const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts; + const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts; + + if (![2, 4].includes(ETA)) throw new Error('Wrong ETA'); + if (![1 << 17, 1 << 19].includes(GAMMA1)) throw new Error('Wrong GAMMA1'); + if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) throw new Error('Wrong GAMMA2'); + const BETA = TAU * ETA; + + const decompose = (r: number) => { + // Decomposes r into (r1, r0) such that r ≡ r1(2γ2) + r0 mod q. + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0; + // FIPS 204 Algorithm 36 folds the top bucket `q-1` back to `(r1, r0) = (0, r0-1)`. + if (rPlus - r0 === Q - 1) return { r1: 0 | 0, r0: (r0 - 1) | 0 }; + const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0; + return { r1, r0 }; // r1 = HighBits, r0 = LowBits + }; + + const HighBits = (r: number) => decompose(r).r1; + const LowBits = (r: number) => decompose(r).r0; + const MakeHint = (z: number, r: number) => { + // Compute hint bit indicating whether adding z to r alters the high bits of r. + // FIPS 204 §6.2 also permits the Section 5.1 alternative from [6], which uses the + // transformed low-bits/high-bits state at this call site instead of Algorithm 39 literally. + // This optimized predicate only applies to those transformed Section 5.1 inputs; it is + // not a drop-in replacement for Algorithm 39 on arbitrary `(z, r)` pairs. + + // From dilithium code + const res0 = z <= GAMMA2 || z > Q - GAMMA2 || (z === Q - GAMMA2 && r === 0) ? 0 : 1; + // from FIPS204: + // // const r1 = HighBits(r); + // // const v1 = HighBits(r + z); + // // const res1 = +(r1 !== v1); + // But they return different results! However, decompose is same. + // So, either there is a bug in Dilithium ref implementation or in FIPS204. + // For now, lets use dilithium one, so test vectors can be passed. + // The round-3 Dilithium / ML-DSA code uses the same low-bits / high-bits convention after + // `r0 += ct0`. + // See dilithium-py README section "Optimising decomposition and making hints". + return res0; + }; + + const UseHint = (h: number, r: number) => { + // Returns the high bits of r adjusted according to hint h + const m = Math.floor((Q - 1) / (2 * GAMMA2)); + const { r1, r0 } = decompose(r); + // 3: if h = 1 and r0 > 0 return (r1 + 1) mod m + // 4: if h = 1 and r0 ≤ 0 return (r1 − 1) mod m + if (h === 1) return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0; + return r1 | 0; + }; + const Power2Round = (r: number) => { + // Decomposes r into (r1, r0) such that r ≡ r1*(2**d) + r0 mod q. + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 ** D) | 0; + return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 }; + }; + + const hintCoder: BytesCoderLen = { + bytesLen: OMEGA + K, + encode: (h_: TArg): TRet => { + const h = h_ as Poly[] | false; + if (h === false) throw new Error('hint.encode: hint is false'); // should never happen + const res = new Uint8Array(OMEGA + K); + for (let i = 0, k = 0; i < K; i++) { + for (let j = 0; j < N; j++) if (h[i][j] !== 0) res[k++] = j; + res[OMEGA + i] = k; + } + return res as TRet; + }, + decode: (buf: TArg): TRet => { + const h = []; + let k = 0; + for (let i = 0; i < K; i++) { + const hi = newPoly(N); + if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA) return false as TRet; + for (let j = k; j < buf[OMEGA + i]; j++) { + if (j > k && buf[j] <= buf[j - 1]) return false as TRet; + hi[buf[j]] = 1; + } + k = buf[OMEGA + i]; + h.push(hi); + } + for (let j = k; j < OMEGA; j++) if (buf[j] !== 0) return false as TRet; + return h as TRet; + }, + }; + + const ETACoder = polyCoder( + ETA === 2 ? 3 : 4, + (i: number) => ETA - i, + (i: number) => { + if (!(-ETA <= i && i <= ETA)) + throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`); + return i; + } + ); + const T0Coder = polyCoder(13, (i: number) => (1 << (D - 1)) - i); + const T1Coder = polyCoder(10); + // Requires smod. Need to fix! + const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i: number) => crystals.smod(GAMMA1 - i)); + const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4); + const W1Vec = vecCoder(W1Coder, K); + // Main structures + const publicCoder = splitCoder('publicKey', 32, vecCoder(T1Coder, K)); + const secretCoder = splitCoder( + 'secretKey', + 32, + 32, + TR_BYTES, + vecCoder(ETACoder, L), + vecCoder(ETACoder, K), + vecCoder(T0Coder, K) + ); + const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder); + const CoefFromHalfByte = + ETA === 2 + ? (n: number) => (n < 15 ? 2 - (n % 5) : false) + : (n: number) => (n < 9 ? 4 - n : false); + + // Return poly in ordinary representation. + // This helper returns ordinary-form `[-ETA, ETA]` coefficients for ExpandS; callers apply + // `NTT.encode()` later when needed. + function RejBoundedPoly(xof_: TArg): TRet { + const xof = xof_ as XofGet; + // Samples an element a ∈ Rq with coeffcients in [−η, η] computed via rejection sampling from ρ. + const r: Poly = newPoly(N); + for (let j = 0; j < N; ) { + const b = xof(); + for (let i = 0; j < N && i < b.length; i += 1) { + // half byte. Should be superfast with vector instructions. But very slow with js :( + const d1 = CoefFromHalfByte(b[i] & 0x0f); + const d2 = CoefFromHalfByte((b[i] >> 4) & 0x0f); + if (d1 !== false) r[j++] = d1; + if (j < N && d2 !== false) r[j++] = d2; + } + } + return r as TRet; + } + + const SampleInBall = (seed: TArg): TRet => { + // Samples a polynomial c ∈ Rq with coeffcients from {−1, 0, 1} and Hamming weight τ + const pre = newPoly(N); + const s = shake256.create({}).update(seed); + const buf = new Uint8Array(shake256.blockLen); + s.xofInto(buf); + // FIPS 204 Algorithm 29 uses the first 8 squeezed bytes as the 64 sign bits `h`, + // then rejection-samples coefficient positions from the remaining XOF stream. + const masks = buf.slice(0, 8); + for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) { + let b = i + 1; + for (; b > i; ) { + b = buf[pos++]; + if (pos < shake256.blockLen) continue; + s.xofInto(buf); + pos = 0; + } + pre[i] = pre[b]; + pre[b] = 1 - (((masks[maskPos] >> maskBit++) & 1) << 1); + if (maskBit >= 8) { + maskPos++; + maskBit = 0; + } + } + return pre as TRet; + }; + + const polyPowerRound = (p_: TArg) => { + const p = p_ as Poly; + const res0 = newPoly(N); + const res1 = newPoly(N); + for (let i = 0; i < p.length; i++) { + const { r0, r1 } = Power2Round(p[i]); + res0[i] = r0; + res1[i] = r1; + } + return { r0: res0, r1: res1 }; + }; + const polyUseHint = (u_: TArg, h_: TArg): TRet => { + const u = u_ as Poly; + const h = h_ as Poly; + // In-place on `u`: verification only needs the recovered high bits, so reuse the + // temporary `wApprox` buffer instead of allocating another polynomial. + for (let i = 0; i < N; i++) u[i] = UseHint(h[i], u[i]); + return u as TRet; + }; + const polyMakeHint = (a_: TArg, b_: TArg) => { + const a = a_ as Poly; + const b = b_ as Poly; + const v = newPoly(N); + let cnt = 0; + for (let i = 0; i < N; i++) { + const h = MakeHint(a[i], b[i]); + v[i] = h; + cnt += h; + } + return { v, cnt }; + }; + + const signRandBytes = 32; + const seedCoder = splitCoder('seed', 32, 64, 32); + // API & argument positions are exactly as in FIPS204. + const internal: TRet = Object.freeze({ + info: Object.freeze({ type: 'internal-ml-dsa' }), + lengths: Object.freeze({ + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + seed: 32, + signature: sigCoder.bytesLen, + signRand: signRandBytes, + }), + keygen: (seed?: TArg) => { + // H(𝜉||IntegerToBytes(𝑘, 1)||IntegerToBytes(ℓ, 1), 128) 2: ▷ expand seed + const seedDst = new Uint8Array(32 + 2); + const randSeed = seed === undefined; + if (randSeed) seed = randomBytes(32); + abytes(seed!, 32, 'seed'); + seedDst.set(seed!); + if (randSeed) cleanBytes(seed!); + seedDst[32] = K; + seedDst[33] = L; + const [rho, rhoPrime, K_] = seedCoder.decode( + shake256(seedDst, { dkLen: seedCoder.bytesLen }) + ); + const xofPrime = XOF256(rhoPrime); + const s1 = []; + for (let i = 0; i < L; i++) s1.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff))); + const s2 = []; + for (let i = L; i < L + K; i++) + s2.push(RejBoundedPoly(xofPrime.get(i & 0xff, (i >> 8) & 0xff))); + const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice())); + const t0 = []; + const t1 = []; + const xof = XOF128(rho); + const t = newPoly(N); + for (let i = 0; i < K; i++) { + // t ← NTT−1(A*NTT(s1)) + s2 + cleanBytes(t); // don't-reallocate + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // super slow! + polyAdd(t, MultiplyNTTs(aij, s1Hat[j])); + } + crystals.NTT.decode(t); + const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); // (t1, t0) ← Power2Round(t, d) + t0.push(r0); + t1.push(r1); + } + const publicKey = publicCoder.encode([rho, t1]); // pk ← pkEncode(ρ, t1) + const tr = shake256(publicKey, { dkLen: TR_BYTES }); // tr ← H(BytesToBits(pk), 512) + // sk ← skEncode(ρ, K,tr, s1, s2, t0) + const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]); + xof.clean(); + xofPrime.clean(); + // STATS + // Kyber512: { calls: 4, xofs: 12 }, Kyber768: { calls: 9, xofs: 27 }, + // Kyber1024: { calls: 16, xofs: 48 } + // DSA44: { calls: 24, xofs: 24 }, DSA65: { calls: 41, xofs: 41 }, + // DSA87: { calls: 71, xofs: 71 } + cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst); + return { + publicKey: publicKey as TRet, + secretKey: secretKey as TRet, + }; + }, + getPublicKey: (secretKey: TArg): TRet => { + // (ρ, K,tr, s1, s2, t0) ← skDecode(sk) + const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey); + const xof = XOF128(rho); + const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice())); + const t1: Poly[] = []; + const tmp = newPoly(N); + for (let i = 0; i < K; i++) { + tmp.fill(0); + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // A_ij in NTT + polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); // += A_ij * s1_j + } + crystals.NTT.decode(tmp); // NTT⁻¹ + polyAdd(tmp, s2[i]); // t_i = A·s1 + s2 + const { r1 } = polyPowerRound(tmp); // r1 = t1, r0 ≈ t0 + t1.push(r1); + } + xof.clean(); + cleanBytes(tmp, s1Hat, _t0, s1, s2); + return publicCoder.encode([rho, t1]); + }, + // NOTE: random is optional. + sign: ( + msg: TArg, + secretKey: TArg, + opts: TArg = {} + ): TRet => { + validateSigOpts(opts); + validateInternalOpts(opts); + let { extraEntropy: random, externalMu = false } = opts; + // This part can be pre-cached per secretKey, but there is only minor performance improvement, + // since we re-use a lot of variables to computation. + // (ρ, K,tr, s1, s2, t0) ← skDecode(sk) + const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey); + // Cache matrix to avoid re-compute later + const A: Poly[][] = []; // A ← ExpandA(ρ) + const xof = XOF128(rho); + for (let i = 0; i < K; i++) { + const pv = []; + for (let j = 0; j < L; j++) pv.push(RejNTTPoly(xof.get(j, i))); + A.push(pv); + } + xof.clean(); + for (let i = 0; i < L; i++) crystals.NTT.encode(s1[i]); // sˆ1 ← NTT(s1) + for (let i = 0; i < K; i++) { + crystals.NTT.encode(s2[i]); // sˆ2 ← NTT(s2) + crystals.NTT.encode(t0[i]); // tˆ0 ← NTT(t0) + } + // This part is per msg + const mu = externalMu + ? msg + : // 6: µ ← H(tr||M, 512) + // ▷ Compute message representative µ + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); + + // Compute private random seed + const rnd = + random === false + ? new Uint8Array(32) + : random === undefined + ? randomBytes(signRandBytes) + : random; + abytes(rnd, 32, 'extraEntropy'); + const rhoprime = shake256 + .create({ dkLen: CRH_BYTES }) + .update(_K) + .update(rnd) + .update(mu) + .digest(); // ρ′← H(K||rnd||µ, 512) + + abytes(rhoprime, CRH_BYTES); + const x256 = XOF256(rhoprime, ZCoder.bytesLen); + // Rejection sampling loop + main_loop: for (let kappa = 0; ; ) { + const y = []; + // y ← ExpandMask(ρ , κ) + for (let i = 0; i < L; i++, kappa++) + y.push(ZCoder.decode(x256.get(kappa & 0xff, kappa >> 8)())); + const z = y.map((i) => crystals.NTT.encode(i.slice())); + const w = []; + for (let i = 0; i < K; i++) { + // w ← NTT−1(A ◦ NTT(y)) + const wi = newPoly(N); + for (let j = 0; j < L; j++) polyAdd(wi, MultiplyNTTs(A[i][j], z[j])); + crystals.NTT.decode(wi); + w.push(wi); + } + const w1 = w.map((j) => j.map(HighBits)); // w1 ← HighBits(w) + // Commitment hash: c˜ ∈{0, 1 2λ } ← H(µ||w1Encode(w1), 2λ) + const cTilde = shake256 + .create({ dkLen: C_TILDE_BYTES }) + .update(mu) + .update(W1Vec.encode(w1)) + .digest(); + // Verifer’s challenge + // c ← SampleInBall(c˜1); cˆ ← NTT(c) + const cHat = crystals.NTT.encode(SampleInBall(cTilde)); + // ⟨⟨cs1⟩⟩ ← NTT−1(cˆ◦ sˆ1) + const cs1 = s1.map((i) => MultiplyNTTs(i, cHat)); + for (let i = 0; i < L; i++) { + polyAdd(crystals.NTT.decode(cs1[i]), y[i]); // z ← y + ⟨⟨cs1⟩⟩ + if (polyChknorm(cs1[i], GAMMA1 - BETA)) continue main_loop; // ||z||∞ ≥ γ1 − β + } + // cs1 is now z (▷ Signer’s response) + let cnt = 0; + const h = []; + for (let i = 0; i < K; i++) { + const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); // ⟨⟨cs2⟩⟩ ← NTT−1(cˆ◦ sˆ2) + const r0 = polySub(w[i], cs2).map(LowBits); // r0 ← LowBits(w − ⟨⟨cs2⟩⟩) + if (polyChknorm(r0, GAMMA2 - BETA)) continue main_loop; // ||r0||∞ ≥ γ2 − β + const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); // ⟨⟨ct0⟩⟩ ← NTT−1(cˆ◦ tˆ0) + if (polyChknorm(ct0, GAMMA2)) continue main_loop; + polyAdd(r0, ct0); + // ▷ Signer’s hint + const hint = polyMakeHint(r0, w1[i]); // h ← MakeHint(−⟨⟨ct0⟩⟩, w− ⟨⟨cs2⟩⟩ + ⟨⟨ct0⟩⟩) + h.push(hint.v); + cnt += hint.cnt; + } + if (cnt > OMEGA) continue; // the number of 1’s in h is greater than ω + x256.clean(); + const res = sigCoder.encode([cTilde, cs1, h]); // σ ← sigEncode(c˜, z mod±q, h) + // rho, _K, tr is subarray of secretKey, cannot clean. + cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A); + // `externalMu` hands ownership of `mu` to the caller, + // so only wipe the internally derived digest form here; + // zeroizing caller memory would break the caller's own reuse / verify path. + if (!externalMu) cleanBytes(mu); + return res as TRet; + } + // @ts-ignore + throw new Error('Unreachable code path reached, report this error'); + }, + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts: TArg = {} + ) => { + validateInternalOpts(opts); + const { externalMu = false } = opts; + // ML-DSA.Verify(pk, M, σ): Verifes a signature σ for a message M. + const [rho, t1] = publicCoder.decode(publicKey); // (ρ, t1) ← pkDecode(pk) + const tr = shake256(publicKey, { dkLen: TR_BYTES }); // 6: tr ← H(BytesToBits(pk), 512) + + if (sig.length !== sigCoder.bytesLen) return false; // return false instead of exception + // (c˜, z, h) ← sigDecode(σ) + // ▷ Signer’s commitment hash c ˜, response z and hint + const [cTilde, z, h] = sigCoder.decode(sig); + if (h === false) return false; // if h = ⊥ then return false + for (let i = 0; i < L; i++) if (polyChknorm(z[i], GAMMA1 - BETA)) return false; + const mu = externalMu + ? msg + : // 7: µ ← H(tr||M, 512) + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest(); + // Compute verifer’s challenge from c˜ + const c = crystals.NTT.encode(SampleInBall(cTilde)); // c ← SampleInBall(c˜1) + const zNtt = z.map((i) => i.slice()); // zNtt = NTT(z) + for (let i = 0; i < L; i++) crystals.NTT.encode(zNtt[i]); + const wTick1 = []; + const xof = XOF128(rho); + for (let i = 0; i < K; i++) { + const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); //c * t1 * (2**d) + const Az = newPoly(N); // // A * z + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); // A[i][j] inplace + polyAdd(Az, MultiplyNTTs(aij, zNtt[j])); + } + // wApprox = A*z - c*t1 * (2**d) + const wApprox = crystals.NTT.decode(polySub(Az, ct12d)); + // Reconstruction of signer’s commitment + wTick1.push(polyUseHint(wApprox, h[i])); // w ′ ← UseHint(h, w'approx ) + } + xof.clean(); + // c˜′← H (µ||w1Encode(w′1), 2λ), Hash it; this should match c˜ + const c2 = shake256 + .create({ dkLen: C_TILDE_BYTES }) + .update(mu) + .update(W1Vec.encode(wTick1)) + .digest(); + // Additional checks in FIPS-204: + // [[ ||z||∞ < γ1 − β ]] and [[c ˜ = c˜′]] and [[number of 1’s in h is ≤ ω]] + for (const t of h) { + const sum = t.reduce((acc, i) => acc + i, 0); + if (!(sum <= OMEGA)) return false; + } + for (const t of z) if (polyChknorm(t, GAMMA1 - BETA)) return false; + return equalBytes(cTilde, c2); + }, + }); + return Object.freeze({ + info: Object.freeze({ type: 'ml-dsa' }), + internal, + securityLevel: securityLevel, + keygen: internal.keygen, + lengths: internal.lengths, + getPublicKey: internal.getPublicKey, + sign: ( + msg: TArg, + secretKey: TArg, + opts: TArg = {} + ): TRet => { + validateSigOpts(opts); + const M = getMessage(msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res as TRet; + }, + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts: TArg = {} + ) => { + validateVerOpts(opts); + return internal.verify(sig, getMessage(msg, opts.context), publicKey); + }, + prehash: (hash: CHash) => { + checkHash(hash, securityLevel); + return Object.freeze({ + info: Object.freeze({ type: 'hashml-dsa' }), + securityLevel: securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: ( + msg: TArg, + secretKey: TArg, + opts: TArg = {} + ): TRet => { + validateSigOpts(opts); + const M = getMessagePrehash(hash, msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res as TRet; + }, + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts: TArg = {} + ) => { + validateVerOpts(opts); + return internal.verify(sig, getMessagePrehash(hash, msg, opts.context), publicKey); + }, + }); + }, + }); +} + +/** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */ +export const ml_dsa44: TRet = /* @__PURE__ */ (() => + getDilithium({ + ...PARAMS[2], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 32, + XOF128, + XOF256, + securityLevel: 128, + }))(); + +/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */ +export const ml_dsa65: TRet = /* @__PURE__ */ (() => + getDilithium({ + ...PARAMS[3], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 48, + XOF128, + XOF256, + securityLevel: 192, + }))(); + +/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */ +export const ml_dsa87: TRet = /* @__PURE__ */ (() => + getDilithium({ + ...PARAMS[5], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 64, + XOF128, + XOF256, + securityLevel: 256, + }))(); diff --git a/node_modules/@noble/post-quantum/src/ml-kem.ts b/node_modules/@noble/post-quantum/src/ml-kem.ts new file mode 100644 index 0000000..80f893f --- /dev/null +++ b/node_modules/@noble/post-quantum/src/ml-kem.ts @@ -0,0 +1,511 @@ +/** + * ML-KEM: Module Lattice-based Key Encapsulation Mechanism from + * [FIPS-203](https://csrc.nist.gov/pubs/fips/203/ipd). A.k.a. CRYSTALS-Kyber. + * + * Key encapsulation is similar to DH / ECDH (think X25519), with important differences: + * * Unlike in ECDH, we can't verify if it was "Bob" who've sent the shared secret + * * Unlike ECDH, it is probabalistic and relies on quality of randomness (CSPRNG). + * * Decapsulation never throws an error, even when shared secret was + * encrypted by a different public key. It will just return a different shared secret. + * + * There are some concerns with regards to security: see + * [djb blog](https://blog.cr.yp.to/20231003-countcorrectly.html) and + * [mailing list](https://groups.google.com/a/list.nist.gov/g/pqc-forum/c/W2VOzy0wz_E). + * + * Has similar internals to ML-DSA, but their keys and params are different. + * + * Check out [official site](https://www.pq-crystals.org/kyber/resources.shtml), + * [repo](https://github.com/pq-crystals/kyber), + * [spec](https://datatracker.ietf.org/doc/draft-cfrg-schwabe-kyber/). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { sha3_256, sha3_512, shake256 } from '@noble/hashes/sha3.js'; +import { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js'; +import { genCrystals, type XOF, XOF128 } from './_crystals.ts'; +import { + abytes, + cleanBytes, + type Coder, + copyBytes, + equalBytes, + getMask, + type KEM, + randomBytes, + splitCoder, + type TArg, + type TRet, + vecCoder, +} from './utils.ts'; + +/** Key encapsulation mechanism interface */ + +const N = 256; // Kyber (not FIPS-203) supports different lengths, but all std modes were using 256 +const Q = 3329; // 13*(2**8)+1, modulo prime +const F = 3303; // 3303 ≡ 128**(−1) mod q (FIPS-203) +const ROOT_OF_UNITY = 17; // ζ = 17 ∈ Zq is a primitive 256-th root of unity modulo Q. ζ**128 ≡−1 +// treeshake: keep genCrystals behind the object so PARAMS-only bundles can drop it entirely. +// Shared CRYSTALS helper in the ML-KEM branch: Kyber mode, 7-bit bit-reversal, +// and Uint16Array polys because current coefficients stay reduced modulo q. +const crystals = /* @__PURE__ */ genCrystals({ + N, + Q, + F, + ROOT_OF_UNITY, + newPoly: (n: number): TRet => new Uint16Array(n) as TRet, + brvBits: 7, + isKyber: true, +}); + +/** FIPS 203: 7. Parameter Sets */ +/** Public ML-KEM parameter-set description. */ +export type KEMParam = { + /** Polynomial size. */ + N: number; + /** Module rank. */ + K: number; + /** Prime modulus. */ + Q: number; + /** CBD parameter used for secret-key noise. */ + ETA1: number; + /** CBD parameter used for error noise. */ + ETA2: number; + /** Compression width for the `u` vector. */ + du: number; + /** Compression width for the `v` polynomial. */ + dv: number; + /** Required strength of the randomness source in bits. */ + RBGstrength: number; +}; +/** Internal params of ML-KEM versions */ +// prettier-ignore +/** Built-in ML-KEM parameter presets keyed by the public export names + * `ml_kem512` / `ml_kem768` / `ml_kem1024`. + * `RBGstrength` is Table 2's required randomness-source strength in bits, + * not a generic security label. + */ +export const PARAMS: Record = /* @__PURE__ */ (() => + Object.freeze({ + 512: Object.freeze({ N, Q, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }), + 768: Object.freeze({ N, Q, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }), + 1024: Object.freeze({ N, Q, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }), + } as const))(); + +// FIPS-203: compress/decompress +const compress = (d: number): Coder => { + // d=12 is the ByteEncode12/ByteDecode12 path, not lossy compression. + // ByteDecode12 interprets each 12-bit word modulo q; without that reduction the public-key + // modulus check in encapsulate() becomes a no-op for malformed coefficients like 4095. + if (d >= 12) return { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }; + // Comments map to python implementation in RFC (draft-cfrg-schwabe-kyber) + // const round = (i: number) => Math.floor(i + 0.5) | 0; + const a = 2 ** (d - 1); + return { + // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d). + encode: (i: number) => ((i << d) + Q / 2) / Q, + // const decompress = (i: number) => round((Q / 2 ** d) * i); + decode: (i: number) => (i * Q + a) >>> d, + }; +}; + +// Raw ByteEncode_d / ByteDecode_d from FIPS 203 operate on d-bit words directly. +// That differs from `polyCoder(d)` for d<12, where noble folds packing together with the lossy +// ciphertext compression step used by u/v. Tests that exercise the spec's raw packing surface need +// this exact non-lossy variant instead. +const byteCoder = (d: number) => + crystals.bitsCoder( + d, + d === 12 + ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) } + : { encode: (i: number) => i, decode: (i: number) => i } + ); + +// NOTE: we merge encoding and compress because it is faster, also both require same d param +// d=12 is the ByteEncode12/ByteDecode12 path rather than compression, and caller-side +// public-key modulus checks route through this helper's decode/encode roundtrip. +// Converts between bytes and d-bits compressed representation. +// Kinda like convertRadix2 from @scure/base. +// decode(encode(t)) == t, but there is loss of information on encode(decode(t)) +const polyCoder = (d: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d))); + +// Poly is mod Q, so 12 bits +type Poly = Uint16Array; + +function polyAdd(a_: TArg, b_: TArg) { + const a = a_ as Poly; + const b = b_ as Poly; + // Mutates `a` in place; callers must pass two N=256 polynomials. + for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b +} +function polySub(a_: TArg, b_: TArg) { + const a = a_ as Poly; + const b = b_ as Poly; + // Mutates `a` in place; callers must pass two N=256 polynomials. + for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b +} + +// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus +function BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) { + // `zeta` here is Algorithm 11's γ = ζ^(2BitRev_7(i)+1). + const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0); + const c1 = crystals.mod(a0 * b1 + a1 * b0); + return { c0, c1 }; +} + +// FIPS-203: Computes the product (in the ring Tq) of two NTT representations. +// Works in place on `f`; `g` is read-only and both inputs must already be in NTT form. +function MultiplyNTTs(f_: TArg, g_: TArg): TRet { + const f = f_ as Poly; + const g = g_ as Poly; + for (let i = 0; i < N / 2; i++) { + let z = crystals.nttZetas[64 + (i >> 1)]; + if (i & 1) z = -z; + const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z); + f[2 * i + 0] = c0; + f[2 * i + 1] = c1; + } + return f as TRet; +} + +type PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array; + +type XofGet = ReturnType['get']>; + +type KyberOpts = KEMParam & { + HASH256: CHash; + HASH512: CHash; + KDF: CHash; + XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array; + PRF: PRF; +}; + +// Return poly in NTT representation +function SampleNTT(xof_: TArg): TRet { + const xof = xof_ as XofGet; + // The reader must already bind the Algorithm 7 seed||j||i bytes + // and return block lengths divisible by 3. + const r: Poly = new Uint16Array(N); + for (let j = 0; j < N; ) { + const b = xof(); + if (b.length % 3) throw new Error('SampleNTT: unaligned block'); + for (let i = 0; j < N && i + 3 <= b.length; i += 3) { + const d1 = ((b[i + 0] >> 0) | (b[i + 1] << 8)) & 0xfff; + const d2 = ((b[i + 1] >> 4) | (b[i + 2] << 4)) & 0xfff; + if (d1 < Q) r[j++] = d1; + if (j < N && d2 < Q) r[j++] = d2; + } + } + return r as TRet; +} + +// Sampling from the centered binomial distribution +// Returns poly with small coefficients (noise/errors) stored modulo q in ordinary coefficient form. +// Current callers only use Table 2 eta values {2,3} and PRF outputs of exactly 64*eta bytes. +const sampleCBDBytes = (buf: TArg, eta: number): TRet => { + const r: Poly = new Uint16Array(N); + // CBD consumes the PRF bitstream in little-endian byte order; normalize the word view on BE, + // then swap it back so callers still observe `buf` as read-only. + const b32 = u32(buf); + swap32IfBE(b32); + let len = 0; + for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) { + let b = b32[i]; + for (let j = 0; j < 32; j++) { + bb += b & 1; + b >>= 1; + len += 1; + if (len === eta) { + t0 = bb; + bb = 0; + } else if (len === 2 * eta) { + r[p++] = crystals.mod(t0 - bb); + bb = 0; + len = 0; + } + } + } + swap32IfBE(b32); + if (len) throw new Error(`sampleCBD: leftover bits: ${len}`); + return r as TRet; +}; + +function sampleCBD( + PRF_: TArg, + seed: TArg, + nonce: number, + eta: number +): TRet { + const PRF = PRF_ as PRF; + return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta); +} + +// K-PKE +// Internal ML-KEM subroutine only: exact 32-byte `seed` / `msg` inputs +// come from Algorithms 13-15, and the helper mutates decoded temporary +// polynomials in place while leaving caller byte arrays unchanged. +const genKPKE = (opts_: TArg) => { + const opts = opts_ as KyberOpts; + const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts; + const poly1 = polyCoder(1); + const polyV = polyCoder(dv); + const polyU = polyCoder(du); + const publicCoder = splitCoder('publicKey', vecCoder(polyCoder(12), K), 32); + const secretCoder = vecCoder(polyCoder(12), K); + const cipherCoder = splitCoder('ciphertext', vecCoder(polyU, K), polyV); + const seedCoder = splitCoder('seed', 32, 32); + return { + secretCoder, + lengths: { + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + cipherText: cipherCoder.bytesLen, + }, + keygen: (seed: TArg) => { + abytes(seed, 32, 'seed'); + const seedDst = new Uint8Array(33); + seedDst.set(seed); + // FIPS 203 Algorithm 13 appends the parameter-set byte `k` + // before `G(d || k)`, so expanding the same 32-byte seed + // under a different ML-KEM parameter set yields unrelated keys. + seedDst[32] = K; + const seedHash = HASH512(seedDst); + + const [rho, sigma] = seedCoder.decode(seedHash); + const sHat: Poly[] = []; + const tHat: Poly[] = []; + for (let i = 0; i < K; i++) sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i, ETA1))); + const x = XOF(rho); + for (let i = 0; i < K; i++) { + const e = crystals.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1)); + for (let j = 0; j < K; j++) { + const aji = SampleNTT(x.get(j, i)); // A[i][j], inplace + polyAdd(e, MultiplyNTTs(aji, sHat[j])); + } + tHat.push(e); // t ← A ◦ s + e + } + x.clean(); + const res = { + publicKey: publicCoder.encode([tHat, rho]), + secretKey: secretCoder.encode(sHat), + }; + cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash); + return res; + }, + encrypt: ( + publicKey: TArg, + msg: TArg, + seed: TArg + ): TRet => { + const [tHat, rho] = publicCoder.decode(publicKey); + const rHat = []; + for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1))); + const x = XOF(rho); + const tmp2 = new Uint16Array(N); + const u = []; + for (let i = 0; i < K; i++) { + const e1 = sampleCBD(PRF, seed, K + i, ETA2); + const tmp = new Uint16Array(N); + for (let j = 0; j < K; j++) { + const aij = SampleNTT(x.get(i, j)); // A[j][i], inplace transpose access + polyAdd(tmp, MultiplyNTTs(aij, rHat[j])); // t += aij * rHat[j] + } + polyAdd(e1, crystals.NTT.decode(tmp)); // e1 += tmp + u.push(e1); + polyAdd(tmp2, MultiplyNTTs(tHat[i], rHat[i])); // t2 += tHat[i] * rHat[i] + cleanBytes(tmp); + } + x.clean(); + const e2 = sampleCBD(PRF, seed, 2 * K, ETA2); + polyAdd(e2, crystals.NTT.decode(tmp2)); // e2 += tmp2 + const v = poly1.decode(msg); // encode plaintext m into polynomial v + polyAdd(v, e2); // v += e2 + cleanBytes(tHat, rHat, tmp2, e2); + return cipherCoder.encode([u, v]) as TRet; + }, + decrypt: (cipherText: TArg, privateKey: TArg): TRet => { + const [u, v] = cipherCoder.decode(cipherText); + const sk = secretCoder.decode(privateKey); // s ← ByteDecode_12(dkPKE) + const tmp = new Uint16Array(N); + // tmp += sk[i] * u[i] + for (let i = 0; i < K; i++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i]))); + polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp + cleanBytes(tmp, sk, u); + return poly1.encode(v) as TRet; + }, + }; +}; + +/** + * Public ML-KEM wrapper over the internal K-PKE subroutine. + * `keygen(seed)` and `encapsulate(publicKey, msg)` are deterministic/test-oriented hooks that map + * more directly to Algorithms 16-17 than to the pure no-input / random-internal Algorithms 19-20. + * decapsulate() tries to follow the Algorithms 18/21 implicit-reject structure as closely as + * practical here by re-encrypting, comparing ciphertexts, returning `Khat` on match or `Kbar` on + * mismatch, and zeroizing the non-returned shared-secret candidate; JS/JIT still provides no + * constant-time guarantees for that path. + */ +function createKyber(opts: TArg): TRet { + const rawOpts = opts as KyberOpts; + const KPKE = genKPKE(rawOpts); + const { HASH256, HASH512, KDF } = rawOpts; + const { secretCoder: KPKESecretCoder, lengths } = KPKE; + const secretCoder = splitCoder('secretKey', lengths.secretKey, lengths.publicKey, 32, 32); + const msgLen = 32; + const seedLen = 64; + const kemLengths = Object.freeze({ + ...lengths, + seed: 64, + msg: msgLen, + msgRand: msgLen, + secretKey: secretCoder.bytesLen, + }); + return Object.freeze({ + info: Object.freeze({ type: 'ml-kem' }), + lengths: kemLengths, + keygen: (seed: TArg = randomBytes(seedLen)) => { + abytes(seed, seedLen, 'seed'); + const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32)); + const publicKeyHash = HASH256(publicKey); + // (dkPKE||ek||H(ek)||z) + const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]); + cleanBytes(sk, publicKeyHash); + return { + publicKey: publicKey as TRet, + secretKey: secretKey as TRet, + }; + }, + getPublicKey: (secretKey: TArg): TRet => { + const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey); + return Uint8Array.from(publicKey) as TRet; + }, + encapsulate: (publicKey: TArg, msg: TArg = randomBytes(msgLen)) => { + abytes(publicKey, lengths.publicKey, 'publicKey'); + abytes(msg, msgLen, 'message'); + + // FIPS-203 includes additional verification check for modulus + const eke = publicKey.subarray(0, 384 * opts.K); + // Copy because of inplace encoding + const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke))); + // (Modulus check.) Perform the computation ek ← ByteEncode12(ByteDecode12(eke)). + // If ek = ̸ eke, the input is invalid. (See Section 4.2.1.) + if (!equalBytes(ek, eke)) { + cleanBytes(ek); + throw new Error('ML-KEM.encapsulate: wrong publicKey modulus'); + } + cleanBytes(ek); + // derive randomness + const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest(); + const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + cleanBytes(kr.subarray(32)); + return { + cipherText: cipherText as TRet, + sharedSecret: kr.subarray(0, 32) as TRet, + }; + }, + decapsulate: (cipherText: TArg, secretKey: TArg): TRet => { + abytes(secretKey, secretCoder.bytesLen, 'secretKey'); // 768*k + 96 + abytes(cipherText, lengths.cipherText, 'cipherText'); // 32(du*k + dv) + // test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) . + const k768 = secretCoder.bytesLen - 96; + const start = k768 + 32; + const test = HASH256(secretKey.subarray(k768 / 2, start)); + // If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed. + if (!equalBytes(test, secretKey.subarray(start, start + 32))) + throw new Error('invalid secretKey: hash check failed'); + const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey); + const msg = KPKE.decrypt(cipherText, sk); + // derive randomness, Khat, rHat = G(mHat || h) + const kr = HASH512.create().update(msg).update(publicKeyHash).digest(); + const Khat = kr.subarray(0, 32); + // re-encrypt using the derived randomness + const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + // if ciphertexts do not match, “implicitly reject” + const isValid = equalBytes(cipherText, cipherText2); + const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest(); + cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar); + return (isValid ? Khat : Kbar) as TRet; + }, + }); +} + +// FIPS 203's PRF_eta binding: current callers use only 32-byte keys, one-byte nonces, +// and dkLen values {128, 192}; out-of-range nonce numbers still wrap modulo 256 here. +function shakePRF(dkLen: number, key: TArg, nonce: number): TRet { + return shake256 + .create({ dkLen }) + .update(key) + .update(new Uint8Array([nonce])) + .digest() as TRet; +} + +// Fixed ML-KEM hash/XOF bindings. `KDF` here is the spec's fixed 32-byte `J` call, +// and swapping any field changes the scheme rather than tuning an internal dependency. +const opts = /* @__PURE__ */ (() => ({ + HASH256: sha3_256, + HASH512: sha3_512, + KDF: shake256, + XOF: XOF128, + PRF: shakePRF, +}))(); +// Parameter-set instantiation step for the spec's "ML-KEM-x" names; current correctness relies +// on the internal PARAMS rows rather than local validation of arbitrary KEMParam objects. +const mk = (params: KEMParam) => + createKyber({ + ...opts, + ...params, + }); + +/** + * ML-KEM-512: Table 2 row `k=2, η1=3, η2=2, du=10, dv=4`; Table 3 sizes `800/1632/768/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem512: TRet = /* @__PURE__ */ (() => mk(PARAMS[512]))(); +/** + * ML-KEM-768: Table 2 row `k=3, η1=2, η2=2, du=10, dv=4`; Table 3 sizes `1184/2400/1088/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem768: TRet = /* @__PURE__ */ (() => mk(PARAMS[768]))(); +/** + * ML-KEM-1024: Table 2 row `k=4, η1=2, η2=2, du=11, dv=5`; Table 3 sizes `1568/3168/1568/32`. + * The ASD lifecycle note here is external policy guidance, not a FIPS 203 requirement. + */ +export const ml_kem1024: TRet = /* @__PURE__ */ (() => mk(PARAMS[1024]))(); + +// NOTE: for tests only, don't use. This keeps the exact internal ML-KEM math surfaces available +// without re-implementing them in separate test code. +export const __tests: any = /* @__PURE__ */ (() => + Object.freeze({ + Compress_d: (x: number, d: number) => { + if (d < 1 || d > 11) throw new Error(`Compress_d: expected d in [1..11], got ${d}`); + return compress(d).encode(x) & getMask(d); + }, + Decompress_d: (y: number, d: number) => { + if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`); + return compress(d).decode(y); + }, + ByteEncode_d: (F: TArg, d: number) => { + if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`); + return byteCoder(d).encode(F as TRet); + }, + ByteDecode_d: (B: TArg, d: number) => { + if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`); + return byteCoder(d).decode(B); + }, + NTT: (f: TArg) => crystals.NTT.encode(Uint16Array.from(f)), + NTT_inv: (fHat: TArg) => crystals.NTT.decode(Uint16Array.from(fHat)), + MultiplyNTTs: (fHat: TArg, gHat: TArg) => + MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)), + SamplePolyCBD: (B: TArg, eta: number) => { + abytes(B, 64 * eta, 'B'); + return sampleCBDBytes(B, eta); + }, + SampleNTT: (B: TArg) => { + abytes(B, 34, 'B'); + const xof = XOF128(B.subarray(0, 32)); + try { + return SampleNTT(xof.get(B[32], B[33])); + } finally { + xof.clean(); + } + }, + }))(); diff --git a/node_modules/@noble/post-quantum/src/slh-dsa.ts b/node_modules/@noble/post-quantum/src/slh-dsa.ts new file mode 100644 index 0000000..98d5af9 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/slh-dsa.ts @@ -0,0 +1,1003 @@ +/** + * SLH-DSA: StateLess Hash-based Digital Signature Standard from + * [FIPS-205](https://csrc.nist.gov/pubs/fips/205/ipd). A.k.a. Sphincs+ v3.1. + * + * There are many different kinds of SLH, but basically `sha2` / `shake` indicate internal hash, + * `128` / `192` / `256` indicate security level, and `s` /`f` indicate trade-off (Small / Fast). + * + * Hashes function similarly to signatures. You hash a private key to get a public key, + * which can be used to verify the private key. However, this only works once since + * disclosing the pre-image invalidates the key. + * + * To address the "one-time" limitation, we can use a Merkle tree root hash: + * h(h(h(0) || h(1)) || h(h(2) || h(3)))) + * + * This allows us to have the same public key output from the hash, but disclosing one + * path in the tree doesn't invalidate the others. By choosing a path related to the + * message, we can "sign" it. + * + * Limitation: Only a fixed number of signatures can be made. For instance, a Merkle tree + * with depth 8 allows 256 distinct messages. Using different trees for each node can + * prevent forgeries, but the key will still degrade over time. + * + * WOTS: One-time signatures (can be forged if same key used twice). + * FORS: Forest of Random Subsets + * + * Check out [official site](https://sphincs.org) & [repo](https://github.com/sphincs/sphincsplus). + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { hmac } from '@noble/hashes/hmac.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { shake256 } from '@noble/hashes/sha3.js'; +import { + bytesToHex, + concatBytes, + createView, + hexToBytes, + type CHash, +} from '@noble/hashes/utils.js'; +import { + abytes, + checkHash, + cleanBytes, + copyBytes, + equalBytes, + getMask, + getMessage, + getMessagePrehash, + randomBytes, + splitCoder, + validateSigOpts, + validateVerOpts, + vecCoder, + type Signer, + type SigOpts, + type TArg, + type TRet, + type VerOpts, +} from './utils.ts'; + +/** + * * N: Security parameter (in bytes). W: Winternitz parameter + * * H: Hypertree height. D: Hypertree layers + * * K: FORS trees numbers. A: FORS trees height + */ +export type SphincsOpts = { + /** Security parameter in bytes. */ + N: number; + /** Winternitz parameter. */ + W: number; + /** Total hypertree height. */ + H: number; + /** Number of hypertree layers. */ + D: number; + /** Number of FORS trees. */ + K: number; + /** Height of each FORS tree. */ + A: number; + /** Target security level in bits. */ + securityLevel: number; +}; + +/** Hash customization options for SLH-DSA context creation. */ +export type SphincsHashOpts = { + /** Whether to use the compressed-address variant from the standard. */ + isCompressed?: boolean; + /** Factory that binds one parameter set to one per-key hash context generator. */ + getContext: GetContext; +}; + +/** Winternitz signature params. */ +/** + * Built-in SLH-DSA Table 2 subset keyed by strength/profile. + * SHA2 and SHAKE pairs share the same numeric rows here, so the hash family is chosen separately. + * `securityLevel` stores 128/192/256-bit strengths for `checkHash(...)`, + * not Table 2's category labels 1/3/5. + * Other Table 2 columns such as `m`, public-key bytes, and signature bytes + * stay derived at the export layer. + */ +export const PARAMS: Record = /* @__PURE__ */ (() => + Object.freeze({ + '128f': Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }), + '128s': Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }), + '192f': Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }), + '192s': Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }), + '256f': Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }), + '256s': Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }), + } as const))(); + +// FIPS 205 `ADRS.setTypeAndClear(...)` selectors. Local names shorten the spec labels +// (`WOTS_HASH` -> `WOTS`, `TREE` -> `HASHTREE`, `FORS_ROOTS` -> `FORSPK`), and `setAddr({ type })` +// below only writes the type word; callers still need to preserve or overwrite the trailing words. +const AddressType = { + WOTS: 0, + WOTSPK: 1, + HASHTREE: 2, + FORSTREE: 3, + FORSPK: 4, + WOTSPRF: 5, + FORSPRF: 6, +} as const; + +/** Address byte array of size `ADDR_BYTES`. */ +export type ADRS = Uint8Array; + +/** Hash and tweakable-hash callbacks bound to one SLH-DSA keypair context. */ +export type Context = { + /** + * Derive a PRF output for one address. + * @param addr - Address bytes. + * @returns PRF output bytes. + */ + PRFaddr: (addr: TArg) => TRet; + /** + * Derive the randomized message hash prefix. + * @param skPRF - Secret PRF seed. + * @param random - Per-signature randomness. + * @param msg - Message bytes. + * @returns PRF output bytes. + */ + PRFmsg: ( + skPRF: TArg, + random: TArg, + msg: TArg + ) => TRet; + /** + * Hash one randomized message transcript. + * @param R - Randomized message prefix. + * @param pk - Public key bytes. + * @param m - Message bytes. + * @param outLen - Output length in bytes. + * @returns Transcript hash bytes. + */ + Hmsg: ( + R: TArg, + pk: TArg, + m: TArg, + outLen: number + ) => TRet; + /** + * Tweakable hash over one input block. + * @param input - Input block. + * @param addr - Address bytes. + * @returns Hash output bytes. + */ + thash1: (input: TArg, addr: TArg) => TRet; + /** + * Tweakable hash over multiple input blocks. + * @param blocks - Number of input blocks. + * @param input - Concatenated input bytes. + * @param addr - Address bytes. + * @returns Hash output bytes. + */ + thashN: (blocks: number, input: TArg, addr: TArg) => TRet; + /** Wipe any buffered hash state for the current context. */ + clean: () => void; +}; +/** Factory that creates a context generator for one SLH-DSA parameter set. */ +export type GetContext = ( + opts: SphincsOpts +) => (pub_seed: TArg, sk_seed?: TArg) => TRet; + +function hexToNumber(hex: string): bigint { + if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex); + return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian +} + +// BE: Big Endian, LE: Little Endian. This is the local FIPS 205 `toInt(...)` equivalent. +function bytesToNumberBE(bytes: TArg): bigint { + return hexToNumber(bytesToHex(bytes)); +} + +// Local in-range FIPS 205 `toByte(x, n)` equivalent; callers must keep `n < 256^len`. +function numberToBytesBE(n: number | bigint, len: number): TRet { + return hexToBytes(n.toString(16).padStart(len * 2, '0')); +} + +// Local FIPS 205 Algorithm 4 `base_2^b(...)` implementation. Bits are consumed in big-endian +// order within each input byte, and callers must provide at least `ceil(outLen * b / 8)` bytes; +// short inputs are not rejected and would zero-extend implicitly. +const base2b = (outLen: number, b: number) => { + const mask = getMask(b); + return (bytes: TArg): TRet => { + const baseB = new Uint32Array(outLen); + for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) { + while (bits < b) { + total = (total << 8) | bytes[pos++]; + bits += 8; + } + bits -= b; + baseB[out] = (total >>> bits) & mask; + } + return baseB as TRet; + }; +}; + +function getMaskBig(bits: number) { + return (1n << BigInt(bits)) - 1n; // 4 -> 0b1111 +} + +/** Public SLH-DSA signer with prehash customization. */ +export type SphincsSigner = Signer & { + internal: TRet; + securityLevel: number; + prehash: (hash: TArg) => TRet; +}; + +/** One parameter/hash instantiation of the public SLH-DSA API. + * `keygen(seed)` is a deterministic 3N-byte library hook around the internal keygen flow, + * and `getPublicKey(secretKey)` only extracts the embedded public key + * instead of recomputing `PK.root`. + */ +function gen(opts: SphincsOpts, hashOpts_: TArg): TRet { + const hashOpts = hashOpts_ as SphincsHashOpts; + const { N, W, H, D, K, A, securityLevel: securityLevel } = opts; + const getContext = hashOpts.getContext(opts); + if (W !== 16) throw new Error('Unsupported Winternitz parameter'); + const WOTS_LOGW = 4; + const WOTS_LEN1 = Math.floor((8 * N) / WOTS_LOGW); + const WOTS_LEN2 = N <= 8 ? 2 : N <= 136 ? 3 : 4; + const TREE_HEIGHT = Math.floor(H / D); + const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2; + + let ADDR_BYTES = 22; + let OFFSET_LAYER = 0; + let OFFSET_TREE = 1; + let OFFSET_TYPE = 9; + let OFFSET_KP_ADDR2 = 12; + let OFFSET_KP_ADDR1 = 13; + let OFFSET_CHAIN_ADDR = 17; + let OFFSET_TREE_INDEX = 18; + let OFFSET_HASH_ADDR = 21; + if (!hashOpts.isCompressed) { + ADDR_BYTES = 32; + OFFSET_LAYER += 3; + OFFSET_TREE += 7; + OFFSET_TYPE += 10; + OFFSET_KP_ADDR2 += 10; + OFFSET_KP_ADDR1 += 10; + OFFSET_CHAIN_ADDR += 10; + OFFSET_TREE_INDEX += 10; + OFFSET_HASH_ADDR += 10; + } + + // Mutates and returns `addr` in place. For the built-in parameter sets, the layer / chain / + // hash / height / keypair values fit in the low byte(s), and the tree value fits in 64 bits, + // so the untouched leading bytes in the wider FIPS 205 ADRS / ADRS_c fields stay zero. + // `height` / `chain` and `index` / `hash` share the same spec words, so callers must use the + // address-type-specific combinations instead of mixing both meanings in one call. + const setAddr = ( + opts: TArg<{ + type?: (typeof AddressType)[keyof typeof AddressType]; + height?: number; + tree?: bigint; + index?: number; + layer?: number; + chain?: number; + hash?: number; + keypair?: number; + subtreeAddr?: ADRS; + keypairAddr?: ADRS; + }>, + addr: TArg = new Uint8Array(ADDR_BYTES) + ) => { + const { type, height, tree, layer, index, chain, hash, keypair } = opts; + const { subtreeAddr, keypairAddr } = opts; + const v = createView(addr); + + if (height !== undefined) addr[OFFSET_CHAIN_ADDR] = height; + if (layer !== undefined) addr[OFFSET_LAYER] = layer; + if (type !== undefined) addr[OFFSET_TYPE] = type; + if (chain !== undefined) addr[OFFSET_CHAIN_ADDR] = chain; + if (hash !== undefined) addr[OFFSET_HASH_ADDR] = hash; + if (index !== undefined) v.setUint32(OFFSET_TREE_INDEX, index, false); + if (subtreeAddr) addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8)); + if (tree !== undefined) v.setBigUint64(OFFSET_TREE, tree, false); + if (keypair !== undefined) { + addr[OFFSET_KP_ADDR1] = keypair; + if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypair >>> 8; + } + if (keypairAddr) { + addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8)); + addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1]; + if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2]; + } + return addr; + }; + + const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW); + const chainLengths = (msg: TArg) => { + const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg); + let csum = 0; + for (let i = 0; i < W1.length; i++) csum += W - 1 - W1[i]; // ▷ Compute checksum + // csum ← csum ≪ ((8 − ((len2 · lg(w)) mod 8)) mod 8 + csum <<= (8 - ((WOTS_LEN2 * WOTS_LOGW) % 8)) % 8; + // Checksum to base(LOG_W) + const W2 = chainCoder(numberToBytesBE(csum, Math.ceil((WOTS_LEN2 * WOTS_LOGW) / 8))); + // W1 || W2 (concatBytes cannot concat TypedArrays) + const lengths = new Uint32Array(WOTS_LEN); + lengths.set(W1); + lengths.set(W2, W1.length); + return lengths; + }; + const messageToIndices = base2b(K, A); + + const TREE_BITS = TREE_HEIGHT * (D - 1); + const LEAF_BITS = TREE_HEIGHT; + const hashMsgCoder = splitCoder( + 'hashedMessage', + Math.ceil((A * K) / 8), + Math.ceil(TREE_BITS / 8), + Math.ceil(TREE_HEIGHT / 8) + ); + // `pkSeed` is the full public key byte string `PK.seed || PK.root`; after splitting `Hmsg`, + // mask away any spare high bits so `idx_tree` / `idx_leaf` match the spec's final mod-2^k steps. + const hashMessage = ( + R: TArg, + pkSeed: TArg, + msg: TArg, + context: TArg + ) => { + const rawContext = context as Context; + // digest ← Hmsg(R, PK.seed, PK.root, M) + const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen); + const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest); + const tree = bytesToNumberBE(tmpIdxTree) & getMaskBig(TREE_BITS); + const leafIdx = Number(bytesToNumberBE(tmpIdxLeaf)) & getMask(LEAF_BITS); + return { tree, leafIdx, md }; + }; + + // Iterative `xmss_node` / `xmss_sign` core: mutate `treeAddr` in place, collapse completed + // sibling pairs on `stack`, and record the sibling whenever the current subtree is the auth-path + // neighbor of the target leaf at that height. + const treehash = ( + height: number, + fn: TArg<(leafIdx: number, addrOffset: number, context: Context, info: T) => Uint8Array> + ) => + function treehash_i( + context: TArg, + leafIdx: number, + idxOffset: number, + treeAddr: TArg, + info: T + ) { + const rawContext = context as Context; + const leafFn = fn as ( + leafIdx: number, + addrOffset: number, + context: Context, + info: T + ) => Uint8Array; + const maxIdx = (1 << height) - 1; + const stack = new Uint8Array(height * N); + const authPath = new Uint8Array(height * N); + for (let idx = 0; ; idx++) { + const current = new Uint8Array(2 * N); + const cur0 = current.subarray(0, N); + const cur1 = current.subarray(N); + const addrOffset = idx + idxOffset; + cur1.set(leafFn(leafIdx, addrOffset, rawContext, info)); + let h = 0; + for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) { + if (h === height) return { root: cur1, authPath }; // Returns from here + if ((i ^ l) === 1) authPath.subarray(h * N).set(cur1); // authPath.push(cur1) + if ((i & 1) === 0 && idx < maxIdx) break; + setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr); + cur0.set(stack.subarray(h * N).subarray(0, N)); + cur1.set(rawContext.thashN(2, current, treeAddr)); + } + stack.subarray(h * N).set(cur1); // stack.push(cur1) + } + // @ts-ignore + throw new Error('Unreachable code path reached, report this error'); + }; + + type LeafInfo = { + wotsSig: Uint8Array; + wotsSteps: Uint32Array; + leafAddr: ADRS; + pkAddr: ADRS; + }; + const wotsTreehash = treehash( + TREE_HEIGHT, + (leafIdx: number, addrOffset: number, context: TArg, info: TArg) => { + const rawContext = context as Context; + const wotsPk = new Uint8Array(WOTS_LEN * N); + // `keygen()` passes `leafIdx = ~0 >>> 0`, so no real XMSS leaf matches and this suppresses + // WOTS signature capture while still hashing every chain to its public-key endpoint. + const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0; + setAddr({ keypair: addrOffset }, info.leafAddr); + setAddr({ keypair: addrOffset }, info.pkAddr); + for (let i = 0; i < WOTS_LEN; i++) { + const wotsK = info.wotsSteps[i] | wotsKmask; + const pk = wotsPk.subarray(i * N, (i + 1) * N); + setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr); + pk.set(rawContext.PRFaddr(info.leafAddr)); + setAddr({ type: AddressType.WOTS }, info.leafAddr); + for (let k = 0; ; k++) { + if (k === wotsK) info.wotsSig.subarray(i * N).set(pk); //wotsSig.push() + if (k === W - 1) break; + setAddr({ hash: k }, info.leafAddr); + pk.set(rawContext.thash1(pk, info.leafAddr)); + } + } + return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr); + } + ); + + const forsTreehash = treehash( + A, + (_: number, addrOffset: number, context: TArg, forsLeafAddr: TArg) => { + const rawContext = context as Context; + setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr); + const prf = rawContext.PRFaddr(forsLeafAddr); + setAddr({ type: AddressType.FORSTREE }, forsLeafAddr); + return rawContext.thash1(prf, forsLeafAddr); + } + ); + + // Fuse `xmss_sign` with the subtree-root computation needed by `ht_sign`, so one tree walk + // yields both the WOTS/auth-path signature and the root that the next hypertree layer signs. + const merkleSign = ( + context: TArg, + wotsAddr: TArg, + treeAddr: TArg, + leafIdx: number, + prevRoot: TArg = new Uint8Array(N) + ): TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }> => { + setAddr({ type: AddressType.HASHTREE }, treeAddr); + // State variables + const info = { + wotsSig: new Uint8Array(wotsCoder.bytesLen), + wotsSteps: chainLengths(prevRoot), + leafAddr: setAddr({ subtreeAddr: wotsAddr }), + pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }), + }; + const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info); + return { + root, + sigWots: info.wotsSig.subarray(0, WOTS_LEN * N), + sigAuth: authPath, + } as TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }>; + }; + + type ForsLeafInfo = ADRS; + + const computeRoot = ( + leaf: TArg, + leafIdx: number, + idxOffset: number, + authPath: TArg, + treeHeight: number, + context: TArg, + addr: TArg + ) => { + const rawContext = context as Context; + const buffer = new Uint8Array(2 * N); + const b0 = buffer.subarray(0, N); + const b1 = buffer.subarray(N, 2 * N); + // Algorithm 11 hashes `node || AUTH[k]` for even nodes and `AUTH[k] || node` for odd ones, + // so reuse one `2N` buffer and just swap which half receives the sibling at each level. + // `idxOffset` carries the subtree base for the shared FORS path, so `leafIdx + idxOffset` + // tracks the same tree-global index updates that Algorithms 11 and 17 apply to ADRS. + // First iter + if ((leafIdx & 1) !== 0) { + b1.set(leaf.subarray(0, N)); + b0.set(authPath.subarray(0, N)); + } else { + b0.set(leaf.subarray(0, N)); + b1.set(authPath.subarray(0, N)); + } + leafIdx >>>= 1; + idxOffset >>>= 1; + // Rest + for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) { + setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr); + const a = authPath.subarray((i + 1) * N, (i + 2) * N); + if ((leafIdx & 1) !== 0) { + b1.set(rawContext.thashN(2, buffer, addr)); + b0.set(a); + } else { + buffer.set(rawContext.thashN(2, buffer, addr)); + b1.set(a); + } + } + // Root + setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr); + return rawContext.thashN(2, buffer, addr); + }; + + const seedCoder = splitCoder('seed', N, N, N); + const publicCoder = splitCoder('publicKey', N, N); + const secretCoder = splitCoder('secretKey', N, N, publicCoder.bytesLen); + const forsCoder = vecCoder(splitCoder('fors', N, N * A), K); + const wotsCoder = vecCoder(splitCoder('wots', WOTS_LEN * N, TREE_HEIGHT * N), D); + const sigCoder = splitCoder('signature', N, forsCoder, wotsCoder); // random || fors || wots + const internal: TRet = Object.freeze({ + info: Object.freeze({ type: 'internal-slh-dsa' }), + lengths: Object.freeze({ + publicKey: publicCoder.bytesLen, + secretKey: secretCoder.bytesLen, + signature: sigCoder.bytesLen, + seed: seedCoder.bytesLen, + signRand: N, + }), + keygen(seed?: TArg) { + if (seed !== undefined) abytes(seed, seedCoder.bytesLen, 'seed'); + seed = seed === undefined ? randomBytes(seedCoder.bytesLen) : copyBytes(seed); + // Set SK.seed, SK.prf, and PK.seed to random n-byte + const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed); + const context = getContext(publicSeed, secretSeed); + // ADRS.setLayerAddress(d − 1) + const topTreeAddr = setAddr({ layer: D - 1 }); + const wotsAddr = setAddr({ layer: D - 1 }); + //PK.root ←_xmss node(SK.seed, 0, h′, PK.seed, ADRS) + const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0); + const publicKey = publicCoder.encode([publicSeed, root]); + const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]); + context.clean(); + cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr); + return { + publicKey: publicKey as TRet, + secretKey: secretKey as TRet, + }; + }, + getPublicKey: (secretKey: TArg): TRet => { + const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey); + return Uint8Array.from(pk) as TRet; + }, + sign: (msg: TArg, sk: TArg, opts: TArg = {}) => { + validateSigOpts(opts); + let { extraEntropy: random } = opts; + const [skSeed, skPRF, pk] = secretCoder.decode(sk); // todo: fix + const [pkSeed, _] = publicCoder.decode(pk); + // Set opt_rand to either PK.seed or to a random n-byte string + if (random === false) random = copyBytes(pkSeed); + else if (random === undefined) random = randomBytes(N); + else random = copyBytes(random); + abytes(random, N); + const context = getContext(pkSeed, skSeed); + // Generate randomizer + const R = context.PRFmsg(skPRF, random, msg); // R ← PRFmsg(SK.prf, opt_rand, M) + let { tree, leafIdx, md } = hashMessage(R, pk, msg, context); + // Create FORS signatures + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx, + }); + const roots = []; + const forsLeaf = setAddr({ keypairAddr: wotsAddr }); + const forsTreeAddr = setAddr({ keypairAddr: wotsAddr }); + const indices = messageToIndices(md); + const fors: [Uint8Array, Uint8Array][] = []; + for (let i = 0; i < indices.length; i++) { + const idxOffset = i << A; + setAddr( + { + type: AddressType.FORSPRF, + height: 0, + index: indices[i] + idxOffset, + }, + forsTreeAddr + ); + const prf = context.PRFaddr(forsTreeAddr); + setAddr({ type: AddressType.FORSTREE }, forsTreeAddr); + const { root, authPath } = forsTreehash( + context, + indices[i], + idxOffset, + forsTreeAddr, + forsLeaf + ); + roots.push(root); + fors.push([prf, authPath]); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr, + }); + const root = context.thashN(K, concatBytes(...roots), forsPkAddr); + // WOTS signatures + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wots: [Uint8Array, Uint8Array][] = []; + for (let i = 0; i < D; i++, tree >>= BigInt(TREE_HEIGHT)) { + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + const { + sigWots, + sigAuth, + root: r, + } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root); + root.set(r); + cleanBytes(r); + wots.push([sigWots, sigAuth]); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + context.clean(); + const SIG = sigCoder.encode([R, fors, wots]); + cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots); + return SIG as TRet; + }, + verify: (sig: TArg, msg: TArg, publicKey: TArg) => { + const [pkSeed, pubRoot] = publicCoder.decode(publicKey); + const [random, forsVec, wotsVec] = sigCoder.decode(sig); + const pk = publicKey; + if (sig.length !== sigCoder.bytesLen) return false; + const context = getContext(pkSeed); + let { tree, leafIdx, md } = hashMessage(random, pk, msg, context); + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx, + }); + // FORS signature + const roots = []; + const forsTreeAddr = setAddr({ + type: AddressType.FORSTREE, + keypairAddr: wotsAddr, + }); + const indices = messageToIndices(md); + for (let i = 0; i < forsVec.length; i++) { + const [prf, authPath] = forsVec[i]; + const idxOffset = i << A; + setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr); + const leaf = context.thash1(prf, forsTreeAddr); + // Compute inplace, because we need all roots in same byte array + roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr)); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr, + }); + let root = context.thashN(K, concatBytes(...roots), forsPkAddr); // root = thash() + // WOTS signature + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wotsPkAddr = setAddr({ type: AddressType.WOTSPK }); + const wotsPk = new Uint8Array(WOTS_LEN * N); + for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) { + const [wots, sigAuth] = wotsVec[i]; + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + setAddr({ keypairAddr: wotsAddr }, wotsPkAddr); + const lengths = chainLengths(root); + for (let i = 0; i < WOTS_LEN; i++) { + setAddr({ chain: i }, wotsAddr); + const steps = W - 1 - lengths[i]; + const start = lengths[i]; + const out = wotsPk.subarray(i * N); + out.set(wots.subarray(i * N, (i + 1) * N)); + for (let j = start; j < start + steps && j < W; j++) { + setAddr({ hash: j }, wotsAddr); + out.set(context.thash1(out, wotsAddr)); + } + } + const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr); + root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + return equalBytes(root, pubRoot); + }, + }); + return Object.freeze({ + info: Object.freeze({ type: 'slh-dsa' }), + internal, + securityLevel: securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => { + validateSigOpts(opts); + const M = getMessage(msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res as TRet; + }, + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts: TArg = {} + ) => { + validateVerOpts(opts); + return internal.verify(sig, getMessage(msg, opts.context), publicKey); + }, + prehash: (hash: TArg): TRet => { + checkHash(hash as CHash, securityLevel); + const rawHash = hash as CHash; + return Object.freeze({ + info: Object.freeze({ type: 'hashslh-dsa' }), + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => { + validateSigOpts(opts); + const M = getMessagePrehash(rawHash, msg, opts.context); + const res = internal.sign(M, secretKey, opts); + cleanBytes(M); + return res as TRet; + }, + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts: TArg = {} + ) => { + validateVerOpts(opts); + return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey); + }, + }); + }, + }); +} + +// FIPS 205 §11.1 SHAKE instantiation: this path hashes the full uncompressed address bytes, +// unlike the compressed 22-byte SHA2 path in §11.2. +const genShake = + (): TRet => + (opts: SphincsOpts) => + (pubSeed: TArg, skSeed?: TArg): TRet => { + const { N } = opts; + const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0 }; + // §11.1 prefixes PRF/F/H/T_l with `PK.seed`, so cache that absorbed prefix once and clone it + // for each address-bound call instead of reabsorbing the same seed every time. + const h0 = shake256.create({}).update(pubSeed); + const h0tmp = h0.clone(); + const thash = (blocks: number, input: TArg, addr: TArg): TRet => { + stats.thash++; + return h0 + ._cloneInto(h0tmp) + .update(addr) + .update(input.subarray(0, blocks * N)) + .xof(N) as TRet; + }; + return { + PRFaddr: (addr: TArg): TRet => { + if (!skSeed) throw new Error('no sk seed'); + stats.prf++; + const res = h0._cloneInto(h0tmp).update(addr).update(skSeed).xof(N); + return res as TRet; + }, + PRFmsg: ( + skPRF: TArg, + random: TArg, + msg: TArg + ): TRet => { + stats.gen_message_random++; + return shake256 + .create({}) + .update(skPRF) + .update(random) + .update(msg) + .digest() + .subarray(0, N) as TRet; + }, + Hmsg: ( + R: TArg, + pk: TArg, + m: TArg, + outLen + ): TRet => { + stats.hmsg++; + return shake256.create({}).update(R.subarray(0, N)).update(pk).update(m).xof(outLen); + }, + thash1: thash.bind(null, 1), + thashN: thash, + clean: () => { + h0.destroy(); + h0tmp.destroy(); + //console.log(stats); + }, + } as TRet; + }; + +const SHAKE_SIMPLE = /* @__PURE__ */ (() => ({ getContext: genShake() }))(); + +/** + * SLH-DSA-SHAKE-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_128f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['128f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_128s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['128s'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_192f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['192f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_192s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['192s'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_256f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['256f'], SHAKE_SIMPLE))(); +/** + * SLH-DSA-SHAKE-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_shake_256s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['256s'], SHAKE_SIMPLE))(); + +type ShaType = typeof sha256 | typeof sha512; +// FIPS 205 §11.2 SHA2 instantiation. The `h0` / `h1` split is intentional: +// category-1 keeps everything on SHA-256, while category-3/5 keep `PRFaddr` / `thash1` +// on SHA-256 but switch `PRFmsg`, `Hmsg`, and multi-block `thashN` to SHA-512. +const genSha = + (h0: ShaType, h1: ShaType): TRet => + (opts) => + (pub_seed: TArg, sk_seed?: TArg): TRet => { + const { N } = opts; + /* + Perf debug stats, how much hashes we call? + 128f_simple: { prf: 8305, thash: 96_922, hmsg: 1, gen_message_random: 1, mgf1: 2 } + 256s_robust: { prf: 497_686, thash: 2_783_203, hmsg: 1, gen_message_random: 1, mgf1: 2_783_205} + 256f_simple: { prf: 36_179, thash: 309_693, hmsg: 1, gen_message_random: 1, mgf1: 2 } + */ + const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 }; + + const counterB = new Uint8Array(4); + const counterV = createView(counterB); + // §11.2 prefixes SHA2 PRF/F/H/T_l with `PK.seed || toByte(0, blockLen-N)`, so cache the + // zero-padded seed block once for the SHA-256 lane and once for the SHA-512 lane. + const h0ps = h0 + .create() + .update(pub_seed) + .update(new Uint8Array(h0.blockLen - N)); + const h1ps = h1 + .create() + .update(pub_seed) + .update(new Uint8Array(h1.blockLen - N)); + + const h0tmp = h0ps.clone(); + const h1tmp = h1ps.clone(); + + // https://www.rfc-editor.org/rfc/rfc8017.html#appendix-B.2.1 + // This local helper is intentionally stricter than generic MGF1 reuse: current SLH-DSA callers + // only request tiny `m`-byte outputs, but the guard below rejects `length > 2^32` instead of + // RFC 8017's broader `maskLen > 2^32 * hLen` bound. + function mgf1(seed: TArg, length: number, hash: ShaType): TRet { + stats.mgf1++; + const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen); + // NOT 2^32-1 + if (length > 2 ** 32) throw new Error('mask too long'); + for (let counter = 0, o = out; o.length; counter++) { + counterV.setUint32(0, counter, false); + hash.create().update(seed).update(counterB).digestInto(o); + o = o.subarray(hash.outputLen); + } + cleanBytes(out.subarray(length)); + return out.subarray(0, length) as TRet; + } + + const thash = + (_: ShaType, h: typeof h0ps, hTmp: typeof h0ps) => + (blocks: number, input: TArg, addr: TArg): TRet => { + stats.thash++; + const d = h + ._cloneInto(hTmp as any) + .update(addr) + .update(input.subarray(0, blocks * N)) + .digest(); + return d.subarray(0, N) as TRet; + }; + return { + PRFaddr: (addr: TArg): TRet => { + if (!sk_seed) throw new Error('No sk seed'); + stats.prf++; + const res = h0ps + ._cloneInto(h0tmp as any) + .update(addr) + .update(sk_seed) + .digest() + .subarray(0, N); + return res as TRet; + }, + PRFmsg: ( + skPRF: TArg, + random: TArg, + msg: TArg + ): TRet => { + stats.gen_message_random++; + return hmac + .create(h1, skPRF) + .update(random) + .update(msg) + .digest() + .subarray(0, N) as TRet; + }, + Hmsg: ( + R: TArg, + pk: TArg, + m: TArg, + outLen + ): TRet => { + stats.hmsg++; + const seed = concatBytes( + R.subarray(0, N), + pk.subarray(0, N), + h1.create().update(R.subarray(0, N)).update(pk).update(m).digest() + ); + return mgf1(seed, outLen, h1); + }, + thash1: thash(h0, h0ps, h0tmp).bind(null, 1), + thashN: thash(h1, h1ps, h1tmp), + clean: () => { + h0ps.destroy(); + h1ps.destroy(); + h0tmp.destroy(); + h1tmp.destroy(); + //console.log(stats); + }, + } as TRet; + }; + +const SHA256_SIMPLE = /* @__PURE__ */ (() => ({ + isCompressed: true, + getContext: genSha(sha256, sha256), +}))(); +const SHA512_SIMPLE = /* @__PURE__ */ (() => ({ + isCompressed: true, + getContext: genSha(sha256, sha512), +}))(); + +/** + * SLH-DSA-SHA2-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`; + * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_128f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['128f'], SHA256_SIMPLE))(); +/** + * SLH-DSA-SHA2-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`; + * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_128s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['128s'], SHA256_SIMPLE))(); +/** + * SLH-DSA-SHA2-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`; + * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_192f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['192f'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`; + * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_192s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['192s'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`; + * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_256f: TRet = /* @__PURE__ */ (() => + gen(PARAMS['256f'], SHA512_SIMPLE))(); +/** + * SLH-DSA-SHA2-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`; + * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`. + * Also exposes `.prehash(...)`. + */ +export const slh_dsa_sha2_256s: TRet = /* @__PURE__ */ (() => + gen(PARAMS['256s'], SHA512_SIMPLE))(); diff --git a/node_modules/@noble/post-quantum/src/utils.ts b/node_modules/@noble/post-quantum/src/utils.ts new file mode 100644 index 0000000..038d548 --- /dev/null +++ b/node_modules/@noble/post-quantum/src/utils.ts @@ -0,0 +1,654 @@ +/** + * Utilities for hex, bytearray and number handling. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { + type CHash, + type TypedArray, + abytes, + abytes as abytes_, + concatBytes, + isLE, + randomBytes as randb, +} from '@noble/hashes/utils.js'; +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array + ? BigInt64Array + : T extends BigUint64Array + ? BigUint64Array + : T extends Float32Array + ? Float32Array + : T extends Float64Array + ? Float64Array + : T extends Int16Array + ? Int16Array + : T extends Int32Array + ? Int32Array + : T extends Int8Array + ? Int8Array + : T extends Uint16Array + ? Uint16Array + : T extends Uint32Array + ? Uint32Array + : T extends Uint8ClampedArray + ? Uint8ClampedArray + : T extends Uint8Array + ? Uint8Array + : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array + ? ReturnType + : T extends BigUint64Array + ? ReturnType + : T extends Float32Array + ? ReturnType + : T extends Float64Array + ? ReturnType + : T extends Int16Array + ? ReturnType + : T extends Int32Array + ? ReturnType + : T extends Int8Array + ? ReturnType + : T extends Uint16Array + ? ReturnType + : T extends Uint32Array + ? ReturnType + : T extends Uint8ClampedArray + ? ReturnType + : T extends Uint8Array + ? ReturnType + : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = + | T + | ([TypedArg] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TRet }) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; + } + : T extends [infer A, ...infer R] + ? [TArg, ...{ [K in keyof R]: TArg }] + : T extends readonly [infer A, ...infer R] + ? readonly [TArg, ...{ [K in keyof R]: TArg }] + : T extends (infer A)[] + ? TArg[] + : T extends readonly (infer A)[] + ? readonly TArg[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TArg } + : T + : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown + ? T & + ([TypedRet] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TArg }) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; + } + : T extends [infer A, ...infer R] + ? [TRet, ...{ [K in keyof R]: TRet }] + : T extends readonly [infer A, ...infer R] + ? readonly [TRet, ...{ [K in keyof R]: TRet }] + : T extends (infer A)[] + ? TRet[] + : T extends readonly (infer A)[] + ? readonly TRet[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TRet } + : T + : TypedRet) + : never; +/** + * Asserts that a value is a byte array and optionally checks its length. + * Returns the original reference unchanged on success, and currently also accepts Node `Buffer` + * values through the upstream validator. + * This helper throws on malformed input, so APIs that must return `false` need to guard lengths + * before decoding or before calling it. + * @example + * Validate that a value is a byte array with the expected length. + * ```ts + * abytes(new Uint8Array([1]), 1); + * ``` + */ +const abytesDoc: typeof abytes = abytes; +export { abytesDoc as abytes }; +/** + * Concatenates byte arrays into a new `Uint8Array`. + * Zero arguments return an empty `Uint8Array`. + * Invalid segments throw before allocation because each argument is validated first. + * @example + * Concatenate two byte arrays into one result. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +const concatBytesDoc: typeof concatBytes = concatBytes; +export { concatBytesDoc as concatBytes }; +/** + * Returns cryptographically secure random bytes. + * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable. + * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation, + * so negative and fractional values both throw instead of truncating through JS `ToIndex`. + * @param bytesLength - Number of random bytes to generate. + * @returns Fresh random bytes. + * @example + * Generate a fresh random seed. + * ```ts + * const seed = randomBytes(4); + * ``` + */ +export const randomBytes: typeof randb = randb; + +/** + * Compares two byte arrays in a length-constant way for equal lengths. + * Unequal lengths return `false` immediately, and there is no runtime type validation. + * @param a - First byte array. + * @param b - Second byte array. + * @returns Whether both arrays contain the same bytes. + * @example + * Compare two byte arrays for equality. + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export function equalBytes(a: TArg, b: TArg): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i]; + return diff === 0; +} + +/** + * Copies bytes into a fresh `Uint8Array`. + * Returns a detached plain `Uint8Array` after validating that the input is real bytes. + * @param bytes - Source bytes. + * @returns Copy of the input bytes. + * @example + * Copy bytes into a fresh array. + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export function copyBytes(bytes: TArg): TRet { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)) as TRet; +} + +/** + * Byte-swaps each 64-bit lane in place. + * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need + * this boundary helper before aliasing them as host `Float64Array` lanes. + * @param arr - Byte buffer whose length is a multiple of 8. + * @returns The same buffer after in-place 64-bit lane byte swaps. + * @example + * Byte-swap one 64-bit lane in place. + * ```ts + * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export function byteSwap64(arr: T): T { + const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); + for (let i = 0; i < bytes.length; i += 8) { + const a0 = bytes[i + 0]; + const a1 = bytes[i + 1]; + const a2 = bytes[i + 2]; + const a3 = bytes[i + 3]; + bytes[i + 0] = bytes[i + 7]; + bytes[i + 1] = bytes[i + 6]; + bytes[i + 2] = bytes[i + 5]; + bytes[i + 3] = bytes[i + 4]; + bytes[i + 4] = a3; + bytes[i + 5] = a2; + bytes[i + 6] = a1; + bytes[i + 7] = a0; + } + return arr; +} +/** + * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian. + * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as + * `Float64Array` lanes on the current host. + * @param arr - Buffer to pass through or swap in place. + * @returns The same buffer, normalized for Falcon's little-endian table layout. + * @example + * Normalize one host-endian buffer for Falcon's float tables. + * ```ts + * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export const baswap64If: (arr: T) => T = isLE + ? (arr) => arr + : byteSwap64; + +/** Shared key-generation surface for signers and KEMs. */ +export type CryptoKeys = { + /** Optional metadata about the algorithm family or variant. */ + info?: { type?: string }; + /** Public byte lengths for the exported key material. */ + lengths: { seed?: number; publicKey?: number; secretKey?: number }; + /** + * Generate one secret/public keypair. + * @param seed - Optional seed bytes for deterministic key generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: TArg) => TRet; +}; + +/** Verification options shared by the signature APIs. */ +export type VerOpts = { + /** Optional application-defined context string. */ + context?: Uint8Array; +}; +/** Signing options shared by the signature APIs. */ +export type SigOpts = VerOpts & { + // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A + /** Optional extra entropy or `false` to disable randomized signing. */ + extraEntropy?: Uint8Array | false; +}; + +/** + * Validates that an options bag is a plain object. + * @param opts - Options object to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate that an options bag is a plain object. + * ```ts + * validateOpts({}); + * ``` + */ +export function validateOpts(opts: object): void { + // Arrays silently passed here before, but these call sites expect named option-bag fields. + if (Object.prototype.toString.call(opts) !== '[object Object]') + throw new TypeError('expected valid options object'); +} + +/** + * Validates common verification options. + * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support + * further after this shared plain-object gate. + * @param opts - Verification options. See {@link VerOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common verification options. + * ```ts + * validateVerOpts({ context: new Uint8Array([1]) }); + * ``` + */ +export function validateVerOpts(opts: TArg): void { + validateOpts(opts); + if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context'); +} + +/** + * Validates common signing options. + * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific + * restrictions are enforced later by callers. + * @param opts - Signing options. See {@link SigOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common signing options. + * ```ts + * validateSigOpts({ extraEntropy: new Uint8Array([1]) }); + * ``` + */ +export function validateSigOpts(opts: TArg): void { + validateVerOpts(opts); + if (opts.extraEntropy !== false && opts.extraEntropy !== undefined) + abytes(opts.extraEntropy, undefined, 'opts.extraEntropy'); +} + +/** Generic signature interface with key generation, signing, and verification. */ +export type Signer = CryptoKeys & { + /** Public byte lengths for signatures and signing randomness. */ + lengths: { signRand?: number; signature?: number }; + /** + * Sign one message. + * @param msg - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @param opts - Optional signing options. + * @returns Signature bytes. + */ + sign: ( + msg: TArg, + secretKey: TArg, + opts?: TArg + ) => TRet; + /** + * Verify one signature. + * @param sig - Signature bytes. + * @param msg - Signed message bytes. + * @param publicKey - Public key bytes. + * @param opts - Optional verification options. + * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the + * signature check does not pass. Some implementations also treat malformed signature encodings as + * a verification failure and return `false`. + * @throws On malformed API arguments or unsupported verification options. + */ + verify: ( + sig: TArg, + msg: TArg, + publicKey: TArg, + opts?: TArg + ) => boolean; +}; + +/** Generic key encapsulation mechanism interface. */ +export type KEM = CryptoKeys & { + /** Public byte lengths for ciphertexts and optional message randomness. */ + lengths: { cipherText?: number; msg?: number; msgRand?: number }; + /** + * Encapsulate one shared secret to a recipient public key. + * @param publicKey - Recipient public key bytes. + * @param msg - Optional caller-provided randomness/message seed. + * @returns Ciphertext plus shared secret. + */ + encapsulate: ( + publicKey: TArg, + msg?: TArg + ) => { + cipherText: TRet; + sharedSecret: TRet; + }; + /** + * Recover the shared secret from a ciphertext and recipient secret key. + * @param cipherText - Ciphertext bytes. + * @param secretKey - Recipient secret key bytes. + * @returns Decapsulated shared secret. + */ + decapsulate: (cipherText: TArg, secretKey: TArg) => TRet; +}; + +/** Bidirectional encoder/decoder interface. */ +export interface Coder { + /** + * Serialize one value. + * @param from - Value to encode. + * @returns Encoded representation. + */ + encode(from: F): T; + /** + * Parse one serialized value. + * @param to - Encoded representation. + * @returns Decoded value. + */ + decode(to: T): F; +} + +/** Encoder/decoder interface specialized for byte arrays. */ +export interface BytesCoder extends Coder { + /** + * Serialize one value into bytes. + * @param data - Value to encode. + * @returns Encoded bytes. + */ + encode: (data: T) => Uint8Array; + /** + * Parse one byte array into a value. + * @param bytes - Encoded bytes. + * @returns Decoded value. + */ + decode: (bytes: Uint8Array) => T; +} + +/** Fixed-length byte encoder/decoder. */ +export type BytesCoderLen = BytesCoder & { bytesLen: number }; + +// nano-packed, because struct encoding is hard. +type UnCoder = T extends BytesCoder ? U : never; +type SplitOut)[]> = { + [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder; +}; +/** + * Builds a fixed-layout coder from byte lengths and nested coders. + * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that + * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder` + * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards + * caller-owned bytes, it must do so only after detaching them into a disposable copy. + * @param label - Label used in validation errors. + * @param lengths - Field lengths or nested coders. + * @returns Composite fixed-length coder. + * @example + * Build a fixed-layout coder from byte lengths and nested coders. + * ```ts + * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]); + * ``` + */ +export function splitCoder)[]>( + label: string, + ...lengths: T +): TRet> & { bytesLen: number }> { + const getLength = (c: TArg>) => + typeof c === 'number' ? c : (c as BytesCoderLen).bytesLen; + const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0); + return { + bytesLen, + encode: (bufs: T) => { + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < lengths.length; i++) { + const c = lengths[i]; + const l = getLength(c); + const b: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]); + abytes_(b, l, label); + res.set(b, pos); + if (typeof c !== 'number') b.fill(0); // clean + pos += l; + } + return res; + }, + decode: (buf: TArg) => { + abytes_(buf, bytesLen, label); + const res = []; + for (const c of lengths) { + const l = getLength(c); + const b = buf.subarray(0, l); + res.push(typeof c === 'number' ? b : c.decode(b)); + buf = buf.subarray(l); + } + return res as SplitOut; + }, + } as any; +} +// nano-packed.array (fixed size) +/** + * Builds a fixed-length vector coder from another fixed-length coder. + * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder. + * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into + * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned + * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts + * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes. + * @param c - Element coder. + * @param vecLen - Number of elements in the vector. + * @returns Fixed-length vector coder. + * @example + * Build a fixed-length vector coder from another fixed-length coder. + * ```ts + * vecCoder( + * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 }, + * 2 + * ).encode([1, 2]); + * ``` + */ +export function vecCoder(c: TArg>, vecLen: number): TRet> { + const coder = c as BytesCoderLen; + const bytesLen = vecLen * coder.bytesLen; + return { + bytesLen, + encode: (u: TArg): TRet => { + if (u.length !== vecLen) + throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`); + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < u.length; i++) { + const b = coder.encode(u[i] as T); + res.set(b, pos); + b.fill(0); // clean + pos += b.length; + } + return res as TRet; + }, + decode: (a: TArg): TRet => { + abytes_(a, bytesLen); + const r: T[] = []; + for (let i = 0; i < a.length; i += coder.bytesLen) + r.push(coder.decode(a.subarray(i, i + coder.bytesLen))); + return r as TRet; + }, + } as any; +} + +/** + * Overwrites supported typed-array inputs with zeroes in place. + * Accepts direct typed arrays and one-level arrays of them. + * @param list - Typed arrays or one-level lists of typed arrays to clear. + * @example + * Overwrite typed arrays with zeroes. + * ```ts + * const buf = Uint8Array.of(1, 2, 3); + * cleanBytes(buf); + * ``` + */ +export function cleanBytes(...list: (TypedArray | TypedArray[])[]): void { + for (const t of list) { + if (Array.isArray(t)) for (const b of t) b.fill(0); + else t.fill(0); + } +} + +/** + * Creates a 32-bit mask with the lowest `bits` bits set. + * @param bits - Number of low bits to keep. + * @returns Bit mask with `bits` ones. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Create a low-bit mask for packed-field operations. + * ```ts + * const mask = getMask(4); + * ``` + */ +export function getMask(bits: number): number { + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new RangeError(`expected bits in [0..32], got ${bits}`); + // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask. + return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0; +} + +/** Shared empty byte array used as the default context. */ +export const EMPTY: TRet = /* @__PURE__ */ Uint8Array.of(); + +/** + * Builds the domain-separated message payload for the pure sign/verify paths. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated message payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated payload before direct signing. + * ```ts + * const payload = getMessage(new Uint8Array([1, 2])); + * ``` + */ +export function getMessage(msg: TArg, ctx: TArg = EMPTY): TRet { + abytes_(msg); + abytes_(ctx); + if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less'); + return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg); +} + +// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the +// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128, +// SHAKE256, or another approved hash/XOF under that subtree. +// 06 09 60 86 48 01 65 03 04 02 +const oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]); + +/** + * Validates that a hash exposes a NIST hash OID and enough collision resistance. + * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST + * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough. + * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend + * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes. + * @param hash - Hash function to validate. + * @param requiredStrength - Minimum required collision-resistance strength in bits. + * @throws If the hash metadata or collision resistance is insufficient. {@link Error} + * @example + * Validate that a hash exposes a NIST hash OID and enough collision resistance. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { checkHash } from '@noble/post-quantum/utils.js'; + * checkHash(sha256, 128); + * ``` + */ +export function checkHash(hash: CHash, requiredStrength: number = 0): void { + if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP)) + throw new Error('hash.oid is invalid: expected NIST hash'); + // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST + // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is + // the tighter runtime check, so enforce that lower bound here. + const collisionResistance = (hash.outputLen * 8) / 2; + if (requiredStrength > collisionResistance) { + throw new Error( + 'Pre-hash security strength too low: ' + + collisionResistance + + ', required: ' + + requiredStrength + ); + } +} + +/** + * Builds the domain-separated prehash payload for the prehash sign/verify paths. + * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper + * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param hash - Prehash function. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated prehash payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated prehash payload for external hashing. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { getMessagePrehash } from '@noble/post-quantum/utils.js'; + * getMessagePrehash(sha256, new Uint8Array([1, 2])); + * ``` + */ +export function getMessagePrehash( + hash: CHash, + msg: TArg, + ctx: TArg = EMPTY +): TRet { + abytes_(msg); + abytes_(ctx); + if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less'); + const hashed = hash(msg); + return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid!, hashed); +} diff --git a/node_modules/@noble/post-quantum/utils.d.ts b/node_modules/@noble/post-quantum/utils.d.ts new file mode 100644 index 0000000..ab09c1e --- /dev/null +++ b/node_modules/@noble/post-quantum/utils.d.ts @@ -0,0 +1,420 @@ +/** + * Utilities for hex, bytearray and number handling. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { type CHash, type TypedArray, abytes, concatBytes, randomBytes as randb } from '@noble/hashes/utils.js'; +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +/** + * Asserts that a value is a byte array and optionally checks its length. + * Returns the original reference unchanged on success, and currently also accepts Node `Buffer` + * values through the upstream validator. + * This helper throws on malformed input, so APIs that must return `false` need to guard lengths + * before decoding or before calling it. + * @example + * Validate that a value is a byte array with the expected length. + * ```ts + * abytes(new Uint8Array([1]), 1); + * ``` + */ +declare const abytesDoc: typeof abytes; +export { abytesDoc as abytes }; +/** + * Concatenates byte arrays into a new `Uint8Array`. + * Zero arguments return an empty `Uint8Array`. + * Invalid segments throw before allocation because each argument is validated first. + * @example + * Concatenate two byte arrays into one result. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +declare const concatBytesDoc: typeof concatBytes; +export { concatBytesDoc as concatBytes }; +/** + * Returns cryptographically secure random bytes. + * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable. + * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation, + * so negative and fractional values both throw instead of truncating through JS `ToIndex`. + * @param bytesLength - Number of random bytes to generate. + * @returns Fresh random bytes. + * @example + * Generate a fresh random seed. + * ```ts + * const seed = randomBytes(4); + * ``` + */ +export declare const randomBytes: typeof randb; +/** + * Compares two byte arrays in a length-constant way for equal lengths. + * Unequal lengths return `false` immediately, and there is no runtime type validation. + * @param a - First byte array. + * @param b - Second byte array. + * @returns Whether both arrays contain the same bytes. + * @example + * Compare two byte arrays for equality. + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export declare function equalBytes(a: TArg, b: TArg): boolean; +/** + * Copies bytes into a fresh `Uint8Array`. + * Returns a detached plain `Uint8Array` after validating that the input is real bytes. + * @param bytes - Source bytes. + * @returns Copy of the input bytes. + * @example + * Copy bytes into a fresh array. + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export declare function copyBytes(bytes: TArg): TRet; +/** + * Byte-swaps each 64-bit lane in place. + * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need + * this boundary helper before aliasing them as host `Float64Array` lanes. + * @param arr - Byte buffer whose length is a multiple of 8. + * @returns The same buffer after in-place 64-bit lane byte swaps. + * @example + * Byte-swap one 64-bit lane in place. + * ```ts + * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export declare function byteSwap64(arr: T): T; +/** + * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian. + * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as + * `Float64Array` lanes on the current host. + * @param arr - Buffer to pass through or swap in place. + * @returns The same buffer, normalized for Falcon's little-endian table layout. + * @example + * Normalize one host-endian buffer for Falcon's float tables. + * ```ts + * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export declare const baswap64If: (arr: T) => T; +/** Shared key-generation surface for signers and KEMs. */ +export type CryptoKeys = { + /** Optional metadata about the algorithm family or variant. */ + info?: { + type?: string; + }; + /** Public byte lengths for the exported key material. */ + lengths: { + seed?: number; + publicKey?: number; + secretKey?: number; + }; + /** + * Generate one secret/public keypair. + * @param seed - Optional seed bytes for deterministic key generation. + * @returns Fresh secret/public keypair. + */ + keygen: (seed?: TArg) => { + secretKey: TRet; + publicKey: TRet; + }; + /** + * Derive one public key from a secret key. + * @param secretKey - Secret key bytes. + * @returns Public key bytes. + */ + getPublicKey: (secretKey: TArg) => TRet; +}; +/** Verification options shared by the signature APIs. */ +export type VerOpts = { + /** Optional application-defined context string. */ + context?: Uint8Array; +}; +/** Signing options shared by the signature APIs. */ +export type SigOpts = VerOpts & { + /** Optional extra entropy or `false` to disable randomized signing. */ + extraEntropy?: Uint8Array | false; +}; +/** + * Validates that an options bag is a plain object. + * @param opts - Options object to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate that an options bag is a plain object. + * ```ts + * validateOpts({}); + * ``` + */ +export declare function validateOpts(opts: object): void; +/** + * Validates common verification options. + * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support + * further after this shared plain-object gate. + * @param opts - Verification options. See {@link VerOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common verification options. + * ```ts + * validateVerOpts({ context: new Uint8Array([1]) }); + * ``` + */ +export declare function validateVerOpts(opts: TArg): void; +/** + * Validates common signing options. + * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific + * restrictions are enforced later by callers. + * @param opts - Signing options. See {@link SigOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common signing options. + * ```ts + * validateSigOpts({ extraEntropy: new Uint8Array([1]) }); + * ``` + */ +export declare function validateSigOpts(opts: TArg): void; +/** Generic signature interface with key generation, signing, and verification. */ +export type Signer = CryptoKeys & { + /** Public byte lengths for signatures and signing randomness. */ + lengths: { + signRand?: number; + signature?: number; + }; + /** + * Sign one message. + * @param msg - Message bytes to sign. + * @param secretKey - Secret key bytes. + * @param opts - Optional signing options. + * @returns Signature bytes. + */ + sign: (msg: TArg, secretKey: TArg, opts?: TArg) => TRet; + /** + * Verify one signature. + * @param sig - Signature bytes. + * @param msg - Signed message bytes. + * @param publicKey - Public key bytes. + * @param opts - Optional verification options. + * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the + * signature check does not pass. Some implementations also treat malformed signature encodings as + * a verification failure and return `false`. + * @throws On malformed API arguments or unsupported verification options. + */ + verify: (sig: TArg, msg: TArg, publicKey: TArg, opts?: TArg) => boolean; +}; +/** Generic key encapsulation mechanism interface. */ +export type KEM = CryptoKeys & { + /** Public byte lengths for ciphertexts and optional message randomness. */ + lengths: { + cipherText?: number; + msg?: number; + msgRand?: number; + }; + /** + * Encapsulate one shared secret to a recipient public key. + * @param publicKey - Recipient public key bytes. + * @param msg - Optional caller-provided randomness/message seed. + * @returns Ciphertext plus shared secret. + */ + encapsulate: (publicKey: TArg, msg?: TArg) => { + cipherText: TRet; + sharedSecret: TRet; + }; + /** + * Recover the shared secret from a ciphertext and recipient secret key. + * @param cipherText - Ciphertext bytes. + * @param secretKey - Recipient secret key bytes. + * @returns Decapsulated shared secret. + */ + decapsulate: (cipherText: TArg, secretKey: TArg) => TRet; +}; +/** Bidirectional encoder/decoder interface. */ +export interface Coder { + /** + * Serialize one value. + * @param from - Value to encode. + * @returns Encoded representation. + */ + encode(from: F): T; + /** + * Parse one serialized value. + * @param to - Encoded representation. + * @returns Decoded value. + */ + decode(to: T): F; +} +/** Encoder/decoder interface specialized for byte arrays. */ +export interface BytesCoder extends Coder { + /** + * Serialize one value into bytes. + * @param data - Value to encode. + * @returns Encoded bytes. + */ + encode: (data: T) => Uint8Array; + /** + * Parse one byte array into a value. + * @param bytes - Encoded bytes. + * @returns Decoded value. + */ + decode: (bytes: Uint8Array) => T; +} +/** Fixed-length byte encoder/decoder. */ +export type BytesCoderLen = BytesCoder & { + bytesLen: number; +}; +type UnCoder = T extends BytesCoder ? U : never; +type SplitOut)[]> = { + [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder; +}; +/** + * Builds a fixed-layout coder from byte lengths and nested coders. + * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that + * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder` + * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards + * caller-owned bytes, it must do so only after detaching them into a disposable copy. + * @param label - Label used in validation errors. + * @param lengths - Field lengths or nested coders. + * @returns Composite fixed-length coder. + * @example + * Build a fixed-layout coder from byte lengths and nested coders. + * ```ts + * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]); + * ``` + */ +export declare function splitCoder)[]>(label: string, ...lengths: T): TRet> & { + bytesLen: number; +}>; +/** + * Builds a fixed-length vector coder from another fixed-length coder. + * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder. + * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into + * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned + * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts + * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes. + * @param c - Element coder. + * @param vecLen - Number of elements in the vector. + * @returns Fixed-length vector coder. + * @example + * Build a fixed-length vector coder from another fixed-length coder. + * ```ts + * vecCoder( + * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 }, + * 2 + * ).encode([1, 2]); + * ``` + */ +export declare function vecCoder(c: TArg>, vecLen: number): TRet>; +/** + * Overwrites supported typed-array inputs with zeroes in place. + * Accepts direct typed arrays and one-level arrays of them. + * @param list - Typed arrays or one-level lists of typed arrays to clear. + * @example + * Overwrite typed arrays with zeroes. + * ```ts + * const buf = Uint8Array.of(1, 2, 3); + * cleanBytes(buf); + * ``` + */ +export declare function cleanBytes(...list: (TypedArray | TypedArray[])[]): void; +/** + * Creates a 32-bit mask with the lowest `bits` bits set. + * @param bits - Number of low bits to keep. + * @returns Bit mask with `bits` ones. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Create a low-bit mask for packed-field operations. + * ```ts + * const mask = getMask(4); + * ``` + */ +export declare function getMask(bits: number): number; +/** Shared empty byte array used as the default context. */ +export declare const EMPTY: TRet; +/** + * Builds the domain-separated message payload for the pure sign/verify paths. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated message payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated payload before direct signing. + * ```ts + * const payload = getMessage(new Uint8Array([1, 2])); + * ``` + */ +export declare function getMessage(msg: TArg, ctx?: TArg): TRet; +/** + * Validates that a hash exposes a NIST hash OID and enough collision resistance. + * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST + * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough. + * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend + * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes. + * @param hash - Hash function to validate. + * @param requiredStrength - Minimum required collision-resistance strength in bits. + * @throws If the hash metadata or collision resistance is insufficient. {@link Error} + * @example + * Validate that a hash exposes a NIST hash OID and enough collision resistance. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { checkHash } from '@noble/post-quantum/utils.js'; + * checkHash(sha256, 128); + * ``` + */ +export declare function checkHash(hash: CHash, requiredStrength?: number): void; +/** + * Builds the domain-separated prehash payload for the prehash sign/verify paths. + * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper + * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param hash - Prehash function. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated prehash payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated prehash payload for external hashing. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { getMessagePrehash } from '@noble/post-quantum/utils.js'; + * getMessagePrehash(sha256, new Uint8Array([1, 2])); + * ``` + */ +export declare function getMessagePrehash(hash: CHash, msg: TArg, ctx?: TArg): TRet; +//# sourceMappingURL=utils.d.ts.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/utils.d.ts.map b/node_modules/@noble/post-quantum/utils.d.ts.map new file mode 100644 index 0000000..7c49a13 --- /dev/null +++ b/node_modules/@noble/post-quantum/utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,4EAA4E;AAC5E,OAAO,EACL,KAAK,KAAK,EACV,KAAK,UAAU,EACf,MAAM,EAEN,WAAW,EAEX,WAAW,IAAI,KAAK,EACrB,MAAM,wBAAwB,CAAC;AAChC;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,QAA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;;;;;;GAkBG;AACH,wBAAgB,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,aAAa,CAAC,CAAC,EAAE,CAAC,CAAC,CAyB/F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,GAAG,IAAI,EAAE,CAAC,UAAU,GAAG,UAAU,EAAE,CAAC,EAAE,GAAG,IAAI,CAKvE;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAK5C;AAED,2DAA2D;AAC3D,eAAO,MAAM,KAAK,EAAE,IAAI,CAAC,UAAU,CAAmC,CAAC;AAEvE;;;;;;;;;;;;GAYG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EAAE,GAAG,GAAE,IAAI,CAAC,UAAU,CAAS,GAAG,IAAI,CAAC,UAAU,CAAC,CAKjG;AAQD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,SAAS,CAAC,IAAI,EAAE,KAAK,EAAE,gBAAgB,GAAE,MAAU,GAAG,IAAI,CAezE;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,KAAK,EACX,GAAG,EAAE,IAAI,CAAC,UAAU,CAAC,EACrB,GAAG,GAAE,IAAI,CAAC,UAAU,CAAS,GAC5B,IAAI,CAAC,UAAU,CAAC,CAMlB"} \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/utils.js b/node_modules/@noble/post-quantum/utils.js new file mode 100644 index 0000000..999e582 --- /dev/null +++ b/node_modules/@noble/post-quantum/utils.js @@ -0,0 +1,391 @@ +/** + * Utilities for hex, bytearray and number handling. + * @module + */ +/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */ +import { abytes, abytes as abytes_, concatBytes, isLE, randomBytes as randb, } from '@noble/hashes/utils.js'; +/** + * Asserts that a value is a byte array and optionally checks its length. + * Returns the original reference unchanged on success, and currently also accepts Node `Buffer` + * values through the upstream validator. + * This helper throws on malformed input, so APIs that must return `false` need to guard lengths + * before decoding or before calling it. + * @example + * Validate that a value is a byte array with the expected length. + * ```ts + * abytes(new Uint8Array([1]), 1); + * ``` + */ +const abytesDoc = abytes; +export { abytesDoc as abytes }; +/** + * Concatenates byte arrays into a new `Uint8Array`. + * Zero arguments return an empty `Uint8Array`. + * Invalid segments throw before allocation because each argument is validated first. + * @example + * Concatenate two byte arrays into one result. + * ```ts + * concatBytes(new Uint8Array([1]), new Uint8Array([2])); + * ``` + */ +const concatBytesDoc = concatBytes; +export { concatBytesDoc as concatBytes }; +/** + * Returns cryptographically secure random bytes. + * Requires `globalThis.crypto.getRandomValues` and throws if that API is unavailable. + * `bytesLength` is validated by the upstream helper as a non-negative integer before allocation, + * so negative and fractional values both throw instead of truncating through JS `ToIndex`. + * @param bytesLength - Number of random bytes to generate. + * @returns Fresh random bytes. + * @example + * Generate a fresh random seed. + * ```ts + * const seed = randomBytes(4); + * ``` + */ +export const randomBytes = randb; +/** + * Compares two byte arrays in a length-constant way for equal lengths. + * Unequal lengths return `false` immediately, and there is no runtime type validation. + * @param a - First byte array. + * @param b - Second byte array. + * @returns Whether both arrays contain the same bytes. + * @example + * Compare two byte arrays for equality. + * ```ts + * equalBytes(new Uint8Array([1]), new Uint8Array([1])); + * ``` + */ +export function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +/** + * Copies bytes into a fresh `Uint8Array`. + * Returns a detached plain `Uint8Array` after validating that the input is real bytes. + * @param bytes - Source bytes. + * @returns Copy of the input bytes. + * @example + * Copy bytes into a fresh array. + * ```ts + * copyBytes(new Uint8Array([1, 2])); + * ``` + */ +export function copyBytes(bytes) { + // `Uint8Array.from(...)` would also accept arrays / other typed arrays. Keep this helper strict + // because callers use it at byte-validation boundaries before mutating the detached copy. + return Uint8Array.from(abytes(bytes)); +} +/** + * Byte-swaps each 64-bit lane in place. + * Falcon's exact binary64 tables are stored as little-endian byte payloads, so BE runtimes need + * this boundary helper before aliasing them as host `Float64Array` lanes. + * @param arr - Byte buffer whose length is a multiple of 8. + * @returns The same buffer after in-place 64-bit lane byte swaps. + * @example + * Byte-swap one 64-bit lane in place. + * ```ts + * byteSwap64(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export function byteSwap64(arr) { + const bytes = new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength); + for (let i = 0; i < bytes.length; i += 8) { + const a0 = bytes[i + 0]; + const a1 = bytes[i + 1]; + const a2 = bytes[i + 2]; + const a3 = bytes[i + 3]; + bytes[i + 0] = bytes[i + 7]; + bytes[i + 1] = bytes[i + 6]; + bytes[i + 2] = bytes[i + 5]; + bytes[i + 3] = bytes[i + 4]; + bytes[i + 4] = a3; + bytes[i + 5] = a2; + bytes[i + 6] = a1; + bytes[i + 7] = a0; + } + return arr; +} +/** + * Byte-swaps 64-bit lanes on big-endian runtimes and returns the input unchanged on little-endian. + * This keeps Falcon's binary64 tables in canonical little-endian order before aliasing them as + * `Float64Array` lanes on the current host. + * @param arr - Buffer to pass through or swap in place. + * @returns The same buffer, normalized for Falcon's little-endian table layout. + * @example + * Normalize one host-endian buffer for Falcon's float tables. + * ```ts + * baswap64If(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])); + * ``` + */ +export const baswap64If = isLE + ? (arr) => arr + : byteSwap64; +/** + * Validates that an options bag is a plain object. + * @param opts - Options object to validate. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate that an options bag is a plain object. + * ```ts + * validateOpts({}); + * ``` + */ +export function validateOpts(opts) { + // Arrays silently passed here before, but these call sites expect named option-bag fields. + if (Object.prototype.toString.call(opts) !== '[object Object]') + throw new TypeError('expected valid options object'); +} +/** + * Validates common verification options. + * `context` itself is validated with `abytes(...)`, and individual algorithms may narrow support + * further after this shared plain-object gate. + * @param opts - Verification options. See {@link VerOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common verification options. + * ```ts + * validateVerOpts({ context: new Uint8Array([1]) }); + * ``` + */ +export function validateVerOpts(opts) { + validateOpts(opts); + if (opts.context !== undefined) + abytes(opts.context, undefined, 'opts.context'); +} +/** + * Validates common signing options. + * `extraEntropy` is validated with `abytes(...)`; exact lengths and extra algorithm-specific + * restrictions are enforced later by callers. + * @param opts - Signing options. See {@link SigOpts}. + * @throws On wrong argument types. {@link TypeError} + * @example + * Validate common signing options. + * ```ts + * validateSigOpts({ extraEntropy: new Uint8Array([1]) }); + * ``` + */ +export function validateSigOpts(opts) { + validateVerOpts(opts); + if (opts.extraEntropy !== false && opts.extraEntropy !== undefined) + abytes(opts.extraEntropy, undefined, 'opts.extraEntropy'); +} +/** + * Builds a fixed-layout coder from byte lengths and nested coders. + * Raw-length fields decode as zero-copy `subarray(...)` views, and nested coders may preserve that + * aliasing too. Nested coder `encode(...)` results are treated as owned scratch: `splitCoder` + * copies them into the output and then zeroizes them with `fill(0)`. If a nested encoder forwards + * caller-owned bytes, it must do so only after detaching them into a disposable copy. + * @param label - Label used in validation errors. + * @param lengths - Field lengths or nested coders. + * @returns Composite fixed-length coder. + * @example + * Build a fixed-layout coder from byte lengths and nested coders. + * ```ts + * splitCoder('demo', 1, 2).encode([new Uint8Array([1]), new Uint8Array([2, 3])]); + * ``` + */ +export function splitCoder(label, ...lengths) { + const getLength = (c) => typeof c === 'number' ? c : c.bytesLen; + const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0); + return { + bytesLen, + encode: (bufs) => { + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < lengths.length; i++) { + const c = lengths[i]; + const l = getLength(c); + const b = typeof c === 'number' ? bufs[i] : c.encode(bufs[i]); + abytes_(b, l, label); + res.set(b, pos); + if (typeof c !== 'number') + b.fill(0); // clean + pos += l; + } + return res; + }, + decode: (buf) => { + abytes_(buf, bytesLen, label); + const res = []; + for (const c of lengths) { + const l = getLength(c); + const b = buf.subarray(0, l); + res.push(typeof c === 'number' ? b : c.decode(b)); + buf = buf.subarray(l); + } + return res; + }, + }; +} +// nano-packed.array (fixed size) +/** + * Builds a fixed-length vector coder from another fixed-length coder. + * Element decoding receives `subarray(...)` views, so aliasing depends on the element coder. + * Element coder `encode(...)` results are treated as owned scratch: `vecCoder` copies them into + * the output and then zeroizes them with `fill(0)`. If an element encoder forwards caller-owned + * bytes, it must do so only after detaching them into a disposable copy. `vecCoder` also trusts + * the `BytesCoderLen` contract: each encoded element must already be exactly `c.bytesLen` bytes. + * @param c - Element coder. + * @param vecLen - Number of elements in the vector. + * @returns Fixed-length vector coder. + * @example + * Build a fixed-length vector coder from another fixed-length coder. + * ```ts + * vecCoder( + * { bytesLen: 1, encode: (n: number) => Uint8Array.of(n), decode: (b: Uint8Array) => b[0] || 0 }, + * 2 + * ).encode([1, 2]); + * ``` + */ +export function vecCoder(c, vecLen) { + const coder = c; + const bytesLen = vecLen * coder.bytesLen; + return { + bytesLen, + encode: (u) => { + if (u.length !== vecLen) + throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`); + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < u.length; i++) { + const b = coder.encode(u[i]); + res.set(b, pos); + b.fill(0); // clean + pos += b.length; + } + return res; + }, + decode: (a) => { + abytes_(a, bytesLen); + const r = []; + for (let i = 0; i < a.length; i += coder.bytesLen) + r.push(coder.decode(a.subarray(i, i + coder.bytesLen))); + return r; + }, + }; +} +/** + * Overwrites supported typed-array inputs with zeroes in place. + * Accepts direct typed arrays and one-level arrays of them. + * @param list - Typed arrays or one-level lists of typed arrays to clear. + * @example + * Overwrite typed arrays with zeroes. + * ```ts + * const buf = Uint8Array.of(1, 2, 3); + * cleanBytes(buf); + * ``` + */ +export function cleanBytes(...list) { + for (const t of list) { + if (Array.isArray(t)) + for (const b of t) + b.fill(0); + else + t.fill(0); + } +} +/** + * Creates a 32-bit mask with the lowest `bits` bits set. + * @param bits - Number of low bits to keep. + * @returns Bit mask with `bits` ones. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Create a low-bit mask for packed-field operations. + * ```ts + * const mask = getMask(4); + * ``` + */ +export function getMask(bits) { + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new RangeError(`expected bits in [0..32], got ${bits}`); + // JS shifts are modulo 32, so bit 32 needs an explicit full-width mask. + return bits === 32 ? 0xffffffff : ~(-1 << bits) >>> 0; +} +/** Shared empty byte array used as the default context. */ +export const EMPTY = /* @__PURE__ */ Uint8Array.of(); +/** + * Builds the domain-separated message payload for the pure sign/verify paths. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated message payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated payload before direct signing. + * ```ts + * const payload = getMessage(new Uint8Array([1, 2])); + * ``` + */ +export function getMessage(msg, ctx = EMPTY) { + abytes_(msg); + abytes_(ctx); + if (ctx.length > 255) + throw new RangeError('context should be 255 bytes or less'); + return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg); +} +// DER tag+length plus the shared NIST hash OID arc 2.16.840.1.101.3.4.2.* used by the +// FIPS 204 / FIPS 205 pre-hash wrappers; the final byte selects SHA-256, SHA-512, SHAKE128, +// SHAKE256, or another approved hash/XOF under that subtree. +// 06 09 60 86 48 01 65 03 04 02 +const oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 0x60, 0x86, 0x48, 1, 0x65, 3, 4, 2]); +/** + * Validates that a hash exposes a NIST hash OID and enough collision resistance. + * Current accepted surface is broader than the FIPS algorithm tables: any hash/XOF under the NIST + * `2.16.840.1.101.3.4.2.*` subtree is accepted if its effective `outputLen` is strong enough. + * XOF callers must pass a callable whose `outputLen` matches the digest length they actually intend + * to sign; bare `shake128` / `shake256` defaults are too short for the stronger prehash modes. + * @param hash - Hash function to validate. + * @param requiredStrength - Minimum required collision-resistance strength in bits. + * @throws If the hash metadata or collision resistance is insufficient. {@link Error} + * @example + * Validate that a hash exposes a NIST hash OID and enough collision resistance. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { checkHash } from '@noble/post-quantum/utils.js'; + * checkHash(sha256, 128); + * ``` + */ +export function checkHash(hash, requiredStrength = 0) { + if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP)) + throw new Error('hash.oid is invalid: expected NIST hash'); + // FIPS 204 / FIPS 205 require both collision and second-preimage strength; for approved NIST + // hashes/XOFs under this OID subtree, the collision bound from the configured digest length is + // the tighter runtime check, so enforce that lower bound here. + const collisionResistance = (hash.outputLen * 8) / 2; + if (requiredStrength > collisionResistance) { + throw new Error('Pre-hash security strength too low: ' + + collisionResistance + + ', required: ' + + requiredStrength); + } +} +/** + * Builds the domain-separated prehash payload for the prehash sign/verify paths. + * Callers are expected to vet `hash.oid` first, e.g. via `checkHash(...)`; calling this helper + * directly with a hash object that lacks `oid` currently throws later inside `concatBytes(...)`. + * Context length `255` is valid; only `ctx.length > 255` is rejected. + * @param hash - Prehash function. + * @param msg - Message bytes. + * @param ctx - Optional context bytes. + * @returns Domain-separated prehash payload. + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Build the domain-separated prehash payload for external hashing. + * ```ts + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { getMessagePrehash } from '@noble/post-quantum/utils.js'; + * getMessagePrehash(sha256, new Uint8Array([1, 2])); + * ``` + */ +export function getMessagePrehash(hash, msg, ctx = EMPTY) { + abytes_(msg); + abytes_(ctx); + if (ctx.length > 255) + throw new RangeError('context should be 255 bytes or less'); + const hashed = hash(msg); + return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed); +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@noble/post-quantum/utils.js.map b/node_modules/@noble/post-quantum/utils.js.map new file mode 100644 index 0000000..406f14b --- /dev/null +++ b/node_modules/@noble/post-quantum/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["src/utils.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,4EAA4E;AAC5E,OAAO,EAGL,MAAM,EACN,MAAM,IAAI,OAAO,EACjB,WAAW,EACX,IAAI,EACJ,WAAW,IAAI,KAAK,GACrB,MAAM,wBAAwB,CAAC;AA0GhC;;;;;;;;;;;GAWG;AACH,MAAM,SAAS,GAAkB,MAAM,CAAC;AACxC,OAAO,EAAE,SAAS,IAAI,MAAM,EAAE,CAAC;AAC/B;;;;;;;;;GASG;AACH,MAAM,cAAc,GAAuB,WAAW,CAAC;AACvD,OAAO,EAAE,cAAc,IAAI,WAAW,EAAE,CAAC;AACzC;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,WAAW,GAAiB,KAAK,CAAC;AAE/C;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,UAAU,CAAC,CAAmB,EAAE,CAAmB;IACjE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;IACvD,OAAO,IAAI,KAAK,CAAC,CAAC;AACpB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,KAAuB;IAC/C,gGAAgG;IAChG,0FAA0F;IAC1F,OAAO,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAqB,CAAC;AAC5D,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,UAAU,CAA4B,GAAM;IAC1D,MAAM,K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qCAAqC,CAAC,CAAC;IAClF,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC;IACzB,OAAO,WAAW,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAI,EAAE,MAAM,CAAC,CAAC;AAC9E,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/base/LICENSE b/node_modules/@scure/base/LICENSE new file mode 100644 index 0000000..5b91e4c --- /dev/null +++ b/node_modules/@scure/base/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Paul Miller (https://paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/base/README.md b/node_modules/@scure/base/README.md new file mode 100644 index 0000000..c9a2edd --- /dev/null +++ b/node_modules/@scure/base/README.md @@ -0,0 +1,250 @@ +# scure-base + +Audited & minimal implementation of bech32, base64, base58, base32 & base16. + +- 🔒 [Audited](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- ✍️ Written in [functional style](#design-rationale), easily composable +- 💼 Matches specs + - [BIP173](https://en.bitcoin.it/wiki/BIP_0173), [BIP350](https://en.bitcoin.it/wiki/BIP_0350) for bech32 / bech32m + - [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648) (aka RFC 3548) for Base16, Base32, Base32Hex, Base64, Base64Url + - [Base58](https://www.ietf.org/archive/id/draft-msporny-base58-03.txt), + [Base58check](https://en.bitcoin.it/wiki/Base58Check_encoding), + [Base32 Crockford](https://www.crockford.com/base32.html) +- 🪶 4KB (gzipped) + +Check out [Projects using scure-base](#projects-using-scure-base). + +### This library belongs to _scure_ + +> **scure** — audited micro-libraries. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- Check out [homepage](https://paulmillr.com/noble/#scure) & all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer), + [sr25519](https://github.com/paulmillr/scure-sr25519), + [starknet](https://github.com/paulmillr/scure-starknet) + +## Usage + +> `npm install @scure/base` + +> `deno add jsr:@scure/base` + +We support all major platforms and runtimes. The library is hybrid ESM / Common.js package. + +```js +import { base16, base32, base64, base58 } from '@scure/base'; +// Flavors +import { + base58xmr, + base58xrp, + base32nopad, + base32hex, + base32hexnopad, + base32crockford, + base64nopad, + base64url, + base64urlnopad, +} from '@scure/base'; + +const data = Uint8Array.from([1, 2, 3]); +base64.decode(base64.encode(data)); + +// Convert utf8 string to Uint8Array +const data2 = new TextEncoder().encode('hello'); +base58.encode(data2); + +// Everything has the same API except for bech32 and base58check +base32.encode(data); +base16.encode(data); +base32hex.encode(data); +``` + +base58check is a special case: you need to pass `sha256()` function: + +> `npm install @noble/hashes` + +```js +import { createBase58check } from '@scure/base'; +import { sha256 } from '@noble/hashes/sha2.js'; + +const data = Uint8Array.from([1, 2, 3]); +createBase58check(sha256).encode(data); +``` + + +## Bech32, Bech32m and Bitcoin + +```js +import { bech32 } from '@scure/base'; + +const words = bech32.toWords(new TextEncoder().encode('hello')); +const addr = bech32.encode('test', words); +console.log(addr); // "test1w508d6qejxtdg4" + +const { prefix, words: decoded } = bech32.decode(addr); +console.log(prefix); // "test" +console.log(new TextDecoder().decode(bech32.fromWords(decoded))); // "hello" + +console.log(bech32.decodeUnsafe('invalid')); // undefined + +``` + +We provide low-level bech32 operations. +If you need high-level methods for BTC (addresses, and others), use +[scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) instead. + +Bitcoin addresses use both 5-bit words and bytes representations. +They can't be parsed using `bech32.decodeToBytes`. + +Same applies to Lightning Invoice Protocol +[BOLT-11](https://github.com/lightning/bolts/blob/master/11-payment-encoding.md). +We have many tests in `./test/bip173.test.js` that serve as minimal examples of +Bitcoin address and Lightning Invoice Protocol parsers. +Keep in mind that you'll need to verify the examples before using them in your code. + +Do something like this: + +```ts +import { bech32 } from '@scure/base'; + +const address = bech32.encode('bc', [0, ...bech32.toWords(new Uint8Array(20))]); +const decoded = bech32.decode(address); +// NOTE: words in bitcoin addresses contain version as first element, +// with actual witness program words in rest +// BIP-141: The value of the first push is called the "version byte". +// The following byte vector pushed is called the "witness program". +const [version, ...dataW] = decoded.words; +const program = bech32.fromWords(dataW); // actual witness program +``` + +## Design rationale + +The code may feel unnecessarily complicated; but actually it's much easier to reason about. +Any encoding library consists of two functions: + +``` +encode(A) -> B +decode(B) -> A + where X = decode(encode(X)) + # encode(decode(X)) can be !== X! + # because decoding can normalize input + +e.g. +base58checksum = { + encode(): { + // checksum + // radix conversion + // alphabet + }, + decode(): { + // alphabet + // radix conversion + // checksum + } +} +``` + +But instead of creating two big functions for each specific case, +we create them from tiny composable building blocks: + +``` +base58checksum = chain(checksum(), radix(), alphabet()) +``` + +Which is the same as chain/pipe/sequence function in Functional Programming, +but significantly more useful since it enforces same order of execution of encode/decode. +Basically you only define encode (in declarative way) and get correct decode for free. +So, instead of reasoning about two big functions you need only reason about primitives and encode chain. +The design revealed obvious bug in older version of the lib, +where xmr version of base58 had errors in decode's block processing. + +Besides base-encodings, we can reuse the same approach with any encode/decode function +(`bytes2number`, `bytes2u32`, etc). +For example, you can easily encode entropy to mnemonic (BIP-39): + +```ts +export function getCoder(wordlist: string[]) { + if (!Array.isArray(wordlist) || wordlist.length !== 2 ** 11 || typeof wordlist[0] !== 'string') { + throw new Error('Wordlist: expected array of 2048 strings'); + } + return mbc.chain(mbu.checksum(1, checksum), mbu.radix2(11, true), mbu.alphabet(wordlist)); +} +``` + +### base58 is O(n^2) and radixes + +`Uint8Array` is represented as big-endian number: + +``` +[1, 2, 3, 4, 5] -> 1*(256**4) + 2*(256**3) 3*(256**2) + 4*(256**1) + 5*(256**0) +where 256 = 2**8 (8 bits per byte) +``` + +which is then converted to a number in another radix/base (16/32/58/64, etc). + +However, generic conversion between bases has [quadratic O(n^2) time complexity](https://cs.stackexchange.com/q/21799). + +Which means base58 has quadratic time complexity too. Use base58 only when you have small +constant sized input, because variable length sized input from user can cause DoS. + +On the other hand, if both bases are power of same number (like `2**8 <-> 2**64`), +there is linear algorithm. For now we have implementation for power-of-two bases only (radix2). + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/scure-base/compare/2.2.0..main) +- at version 1.0.0, in Jan 2022, independently, by [cure53](https://cure53.de) + - PDFs: [online](https://cure53.de/pentest-report_hashing-libs.pdf), [offline](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography). +At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), +it was extracted to a separate package called `micro-base`. +After the audit we've decided to use `@scure` NPM namespace for security. + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there are 0 dependencies; and a few dev dependencies: + +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run build:release` will build single file + +### Projects using scure-base + +- [scure-btc-signer](https://github.com/paulmillr/scure-btc-signer) +- [prefixed-api-key](https://github.com/truestamp/prefixed-api-key) +- [coinspace](https://github.com/CoinSpace/CoinSpace) wallet and its modules: + [ada](https://github.com/CoinSpace/cs-cardano-wallet), + [btc](https://github.com/CoinSpace/cs-bitcoin-wallet) + [eos](https://github.com/CoinSpace/cs-eos-wallet), + [sol](https://github.com/CoinSpace/cs-solana-wallet), + [xmr](https://github.com/CoinSpace/cs-monero-wallet) + +## License + +MIT (c) Paul Miller [(https://paulmillr.com)](https://paulmillr.com), see LICENSE file. diff --git a/node_modules/@scure/base/index.d.ts b/node_modules/@scure/base/index.d.ts new file mode 100644 index 0000000..4cd02d7 --- /dev/null +++ b/node_modules/@scure/base/index.d.ts @@ -0,0 +1,556 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +/** Transforms values between two representations. */ +export interface Coder { + /** + * Converts a value from the input representation to the output representation. + * @param from - Value in the source representation. + * @returns Converted value. + */ + encode(from: F): T; + /** + * Converts a value from the output representation back to the input representation. + * @param to - Value in the target representation. + * @returns Converted value. + */ + decode(to: T): F; +} +/** Coder that works with byte arrays and strings. */ +export interface BytesCoder extends Coder { + /** + * Encodes bytes into a string representation. + * @param data - Bytes to encode. + * @returns Encoded string. + */ + encode: (data: Uint8Array) => string; + /** + * Decodes a string representation into raw bytes. + * @param str - Encoded string. + * @returns Decoded bytes. + */ + decode: (str: string) => Uint8Array; +} +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array ? BigInt64Array : T extends BigUint64Array ? BigUint64Array : T extends Float32Array ? Float32Array : T extends Float64Array ? Float64Array : T extends Int16Array ? Int16Array : T extends Int32Array ? Int32Array : T extends Int8Array ? Int8Array : T extends Uint16Array ? Uint16Array : T extends Uint32Array ? Uint32Array : T extends Uint8ClampedArray ? Uint8ClampedArray : T extends Uint8Array ? Uint8Array : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array ? ReturnType : T extends BigUint64Array ? ReturnType : T extends Float32Array ? ReturnType : T extends Float64Array ? ReturnType : T extends Int16Array ? ReturnType : T extends Int32Array ? ReturnType : T extends Int8Array ? ReturnType : T extends Uint16Array ? ReturnType : T extends Uint32Array ? ReturnType : T extends Uint8ClampedArray ? ReturnType : T extends Uint8Array ? ReturnType : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = T | ([TypedArg] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TRet; +}) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; +} : T extends [infer A, ...infer R] ? [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends readonly [infer A, ...infer R] ? readonly [TArg, ...{ + [K in keyof R]: TArg; +}] : T extends (infer A)[] ? TArg[] : T extends readonly (infer A)[] ? readonly TArg[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TArg; +} : T : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown ? T & ([TypedRet] extends [never] ? T extends (...args: infer A) => infer R ? ((...args: { + [K in keyof A]: TArg; +}) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; +} : T extends [infer A, ...infer R] ? [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends readonly [infer A, ...infer R] ? readonly [TRet, ...{ + [K in keyof R]: TRet; +}] : T extends (infer A)[] ? TRet[] : T extends readonly (infer A)[] ? readonly TRet[] : T extends Promise ? Promise> : T extends object ? { + [K in keyof T]: TRet; +} : T : TypedRet) : never; +type Chain = [Coder, ...Coder[]]; +type Input = F extends Coder ? T : never; +type Output = F extends Coder ? T : never; +type First = T extends [infer U, ...any[]] ? U : never; +type Last = T extends [...any[], infer U] ? U : never; +type Tail = T extends [any, ...infer U] ? U : never; +type AsChain> = { + [K in keyof C]: Coder, Input>; +}; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function chain>(...args: T): Coder>, Output>>; +/** + * Encodes integer radix representation to array of strings using alphabet and back. + * Could also be array of strings. + * @__NO_SIDE_EFFECTS__ + */ +declare function alphabet(letters: string | string[]): Coder; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function join(separator?: string): Coder; +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +declare function padding(bits: number, chr?: string): Coder; +/** + * Slow: O(n^2) time complexity + */ +declare function convertRadix(data: number[], from: number, to: number): number[]; +/** + * Implemented with numbers, because BigInt is 5x slower + */ +declare function convertRadix2(data: number[], from: number, to: number, padding: boolean): number[]; +/** + * @__NO_SIDE_EFFECTS__ + */ +declare function radix(num: number): TRet>; +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +declare function radix2(bits: number, revPadding?: boolean): TRet>; +type BytesFn = (data: TArg) => TRet; +declare function checksum(len: number, fn: TArg): TRet>; +/** + * Low-level building blocks used by the exported codecs. + * @example + * Build a radix-32 coder from the low-level helpers. + * ```ts + * import { utils } from '@scure/base'; + * utils.radix2(5).encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export declare const utils: { + alphabet: typeof alphabet; + chain: typeof chain; + checksum: typeof checksum; + convertRadix: typeof convertRadix; + convertRadix2: typeof convertRadix2; + radix: typeof radix; + radix2: typeof radix2; + join: typeof join; + padding: typeof padding; +}; +/** + * base16 encoding from RFC 4648. + * This codec uses RFC 4648 Table 5's uppercase alphabet directly. + * RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here. + * Use `hex` for case-insensitive hex decoding. + * @example + * ```js + * base16.encode(Uint8Array.from([0x12, 0xab])); + * // => '12AB' + * ``` + */ +export declare const base16: BytesCoder; +/** + * base32 encoding from RFC 4648. Has padding. + * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose + * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input. + * Use `base32nopad` for unpadded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ====' + * base32.decode('CKVQ===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base32: BytesCoder; +/** + * base32 encoding from RFC 4648. No padding. + * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input. + * Use `base32` for padded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ' + * base32nopad.decode('CKVQ'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base32nopad: BytesCoder; +/** + * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet. + * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input. + * Use `base32hexnopad` for unpadded version. + * @example + * ```js + * base32hex.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG====' + * base32hex.decode('2ALG===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base32hex: BytesCoder; +/** + * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet. + * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input. + * Use `base32hex` for padded version. + * @example + * ```js + * base32hexnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG' + * base32hexnopad.decode('2ALG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base32hexnopad: BytesCoder; +/** + * base32 encoding from RFC 4648. Doug Crockford's version. + * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}. + * @example + * ```js + * base32crockford.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ANG' + * base32crockford.decode('2ANG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base32crockford: BytesCoder; +/** + * base64 from RFC 4648. Padded. + * Use `base64nopad` for unpadded version. + * Also check out `base64url`, `base64urlnopad`. + * Falls back to built-in function, when available. + * @example + * ```js + * base64.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base64: BytesCoder; +/** + * base64 from RFC 4648. No padding. + * Use `base64` for padded version. + * @example + * ```js + * base64nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64nopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base64nopad: BytesCoder; +/** + * base64 from RFC 4648, using URL-safe alphabet. Padded. + * Use `base64urlnopad` for unpadded version. + * Falls back to built-in function, when available. + * @example + * ```js + * base64url.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64url.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base64url: BytesCoder; +/** + * base64 from RFC 4648, using URL-safe alphabet. No padding. + * Use `base64url` for padded version. + * @example + * ```js + * base64urlnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64urlnopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export declare const base64urlnopad: BytesCoder; +/** + * base58: base64 without ambigous characters +, /, 0, O, I, l. + * Quadratic (O(n^2)) - so, can't be used on large inputs. + * @example + * ```js + * const text = base58.encode(Uint8Array.from([0, 1, 2])); + * base58.decode(text); + * // => Uint8Array.from([0, 1, 2]) + * ``` + */ +export declare const base58: BytesCoder; +/** + * base58: flickr version. Check out `base58`. + * @example + * Round-trip bytes with the Flickr alphabet. + * ```ts + * const text = base58flickr.encode(Uint8Array.from([0, 1, 2])); + * base58flickr.decode(text); + * ``` + */ +export declare const base58flickr: BytesCoder; +/** + * base58: XRP version. Check out `base58`. + * @example + * Round-trip bytes with the XRP alphabet. + * ```ts + * const text = base58xrp.encode(Uint8Array.from([0, 1, 2])); + * base58xrp.decode(text); + * ``` + */ +export declare const base58xrp: BytesCoder; +/** + * base58: XMR version. Check out `base58`. + * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. + * Block encoding significantly reduces quadratic complexity of base58. + * @example + * Round-trip bytes with the Monero block codec. + * ```ts + * const text = base58xmr.encode(Uint8Array.from([0, 1, 2])); + * base58xmr.decode(text); + * ``` + */ +export declare const base58xmr: BytesCoder; +/** + * Method, which creates base58check encoder. + * Requires function, calculating sha256. + * Callers must include any version bytes in `data`; this helper only applies the + * 4-byte double-SHA256 checksum used by Bitcoin Base58Check. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Create a base58check codec from a SHA-256 implementation. + * ```ts + * import { createBase58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = createBase58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export declare const createBase58check: (sha256: TArg) => BytesCoder; +/** + * Use `createBase58check` instead. + * @deprecated Use {@link createBase58check} instead. + * Callers must include any version bytes in `data`; this alias keeps the same + * 4-byte double-SHA256 checksum behavior as `createBase58check`. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @example + * Create a base58check codec with the deprecated alias. + * ```ts + * import { base58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = base58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export declare const base58check: (sha256: TArg) => BytesCoder; +/** Result of bech32 decoding. */ +export interface Bech32Decoded { + /** Human-readable bech32 prefix. */ + prefix: Prefix; + /** Decoded 5-bit word payload. */ + words: number[]; +} +/** Result of bech32 decoding with original bytes attached. */ +export interface Bech32DecodedWithArray { + /** Human-readable bech32 prefix. */ + prefix: Prefix; + /** Decoded 5-bit word payload. */ + words: number[]; + /** Decoded payload converted back into raw bytes. */ + bytes: Uint8Array; +} +/** bech32 codec surface. */ +export interface Bech32 { + /** + * Encodes a human-readable prefix and 5-bit words into a bech32 string. + * @param prefix - Human-readable prefix. + * @param words - 5-bit words or raw bytes. + * @param limit - Maximum accepted output length, or `false` to disable the limit. + * @returns Encoded bech32 string. + */ + encode(prefix: Prefix, words: number[] | Uint8Array, limit?: number | false): `${Lowercase}1${string}`; + /** + * Decodes a bech32 string into prefix and words. + * @param str - Encoded bech32 string. + * @param limit - Maximum accepted input length, or `false` to disable the limit. + * @returns Decoded prefix and 5-bit words. + */ + decode(str: `${Prefix}1${string}`, limit?: number | false): Bech32Decoded; + decode(str: string, limit?: number | false): Bech32Decoded; + /** + * Encodes raw bytes by first converting them to 5-bit words. + * @param prefix - Human-readable prefix. + * @param bytes - Raw bytes to encode. + * @returns Encoded bech32 string. + */ + encodeFromBytes(prefix: string, bytes: Uint8Array): string; + /** + * Decodes a bech32 string and converts the payload back into bytes. + * @param str - Encoded bech32 string. + * @returns Decoded prefix, words, and bytes. + */ + decodeToBytes(str: string): Bech32DecodedWithArray; + /** + * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input. + * @param str - Encoded bech32 string. + * @param limit - Maximum accepted input length, or `false` to disable the limit. + * @returns Decoded prefix and words, or `undefined` for invalid input. + */ + decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded; + /** + * Converts 5-bit words back into raw bytes. + * @param to - 5-bit words to decode. + * @returns Decoded bytes. + */ + fromWords(to: number[]): Uint8Array; + /** + * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing. + * @param to - 5-bit words to decode. + * @returns Decoded bytes, or `undefined` for invalid input. + */ + fromWordsUnsafe(to: number[]): void | Uint8Array; + /** + * Converts raw bytes into 5-bit words for bech32 encoding. + * @param from - Raw bytes to convert. + * @returns 5-bit words. + */ + toWords(from: Uint8Array): number[]; +} +/** + * bech32 from BIP 173. Operates on words. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them, then decode back. + * ```ts + * const words = bech32.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32.encode('bc', words); + * bech32.decode(text); + * ``` + */ +export declare const bech32: TRet; +/** + * bech32m from BIP 350. Operates on words. + * It was to mitigate `bech32` weaknesses. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them with bech32m, then decode back. + * ```ts + * const words = bech32m.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32m.encode('bc', words); + * bech32m.decode(text); + * ``` + */ +export declare const bech32m: TRet; +/** + * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes. + * @example + * ```js + * const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ]) + * const str = ascii.encode(b); // "ABC" + * ``` + */ +export declare const ascii: TRet; +/** + * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and + * `decode(string)` returns bytes. + * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and + * throws on invalid UTF-8 bytes. + * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with + * lone surrogates. + * @example + * ```js + * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ]) + * const str = utf8.encode(b); // "hey" + * ``` + */ +export declare const utf8: BytesCoder; +export declare const __TESTS: { + utf8Fallback: BytesCoder; + _isWellFormedShim: (str: string) => boolean; +}; +/** + * hex string decoder. Uses built-in function, when available. + * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase. + * @example + * ```js + * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ]) + * const str = hex.encode(b); // "0102ff" + * ``` + */ +export declare const hex: BytesCoder; +/** Built-in codecs exposed through the deprecated string conversion helpers. */ +export type SomeCoders = { + /** UTF-8 string codec. */ + utf8: BytesCoder; + /** Hex codec. */ + hex: BytesCoder; + /** Uppercase RFC 4648 base16 codec. */ + base16: BytesCoder; + /** RFC 4648 base32 codec with padding. */ + base32: BytesCoder; + /** RFC 4648 base64 codec with padding. */ + base64: BytesCoder; + /** URL-safe base64 codec without `+` or `/`. */ + base64url: BytesCoder; + /** Bitcoin-style base58 codec. */ + base58: BytesCoder; + /** Monero-style base58 codec. */ + base58xmr: BytesCoder; +}; +type CoderType = keyof SomeCoders; +/** + * Encodes bytes with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.encode(bytes)`. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * bytesToString('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export declare const bytesToString: (type: CoderType, bytes: TArg) => string; +/** + * Alias for `bytesToString`. + * @deprecated Use {@link bytesToString} or the codec directly instead. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @example + * ```ts + * str('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export declare const str: (type: CoderType, bytes: TArg) => string; +/** + * Decodes a string with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.decode(text)`. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * stringToBytes('hex', '0102ff'); + * ``` + */ +export declare const stringToBytes: (type: CoderType, str: string) => TRet; +/** + * Alias for `stringToBytes`. + * @deprecated Use {@link stringToBytes} or the codec directly instead. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @example + * ```ts + * bytes('hex', '0102ff'); + * ``` + */ +export declare const bytes: (type: CoderType, str: string) => TRet; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/base/index.d.ts.map b/node_modules/@scure/base/index.d.ts.map new file mode 100644 index 0000000..769d0dd --- /dev/null +++ b/node_modules/@scure/base/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,oEAAoE;AAEpE,qDAAqD;AACrD,MAAM,WAAW,KAAK,CAAC,CAAC,EAAE,CAAC;IACzB;;;;OAIG;IACH,MAAM,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,CAAC;IACnB;;;;OAIG;IACH,MAAM,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;CAClB;AAED,qDAAqD;AACrD,MAAM,WAAW,UAAW,SAAQ,KAAK,CAAC,UAAU,EAAE,MAAM,CAAC;IAC3D;;;;OAIG;IACH,MAAM,EAAE,CAAC,IAAI,EAAE,UAAU,KAAK,MAAM,CAAC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;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,GAAI,MAAM,SAAS,EAAE,KAAK,MAAM,KAAG,IAAI,CAAC,UAAU,CAK3E,CAAC;AACF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,KAAK,EAAE,CAAC,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,KAAK,IAAI,CAAC,UAAU,CAAiB,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/base/index.js b/node_modules/@scure/base/index.js new file mode 100644 index 0000000..9af8552 --- /dev/null +++ b/node_modules/@scure/base/index.js @@ -0,0 +1,1057 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ +function isBytes(a) { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The + // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized + // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the + // fallback on byte-oriented views. + return (a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1)); +} +/** Asserts something is Uint8Array. */ +function abytes(b) { + if (!isBytes(b)) + throw new TypeError('Uint8Array expected'); +} +function isArrayOf(isString, arr) { + if (!Array.isArray(arr)) + return false; + if (arr.length === 0) + return true; + if (isString) { + return arr.every((item) => typeof item === 'string'); + } + else { + return arr.every((item) => Number.isSafeInteger(item)); + } +} +function afn(input) { + if (typeof input !== 'function') + throw new TypeError('function expected'); + return true; +} +function astr(label, input) { + if (typeof input !== 'string') + throw new TypeError(`${label}: string expected`); + return true; +} +function anumber(n) { + if (typeof n !== 'number') + throw new TypeError(`number expected, got ${typeof n}`); + if (!Number.isSafeInteger(n)) + throw new RangeError(`invalid integer: ${n}`); +} +function aArr(input) { + if (!Array.isArray(input)) + throw new TypeError('array expected'); +} +function astrArr(label, input) { + if (!isArrayOf(true, input)) + throw new TypeError(`${label}: array of strings expected`); +} +function anumArr(label, input) { + if (!isArrayOf(false, input)) + throw new TypeError(`${label}: array of numbers expected`); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain(...args) { + const id = (a) => a; + // Wrap call in closure so JIT can inline calls + const wrap = (a, b) => (c) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = args.map((x) => x.encode).reduceRight(wrap, id); + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.map((x) => x.decode).reduce(wrap, id); + return { encode, decode }; +} +/** + * Encodes integer radix representation to array of strings using alphabet and back. + * Could also be array of strings. + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(letters) { + // mapping 1 to "b" + const lettersA = typeof letters === 'string' ? letters.split('') : letters; + const len = lettersA.length; + astrArr('alphabet', lettersA); + // mapping "b" to 1 + const indexes = new Map(lettersA.map((l, i) => [l, i])); + return { + encode: (digits) => { + aArr(digits); + return digits.map((i) => { + if (!Number.isSafeInteger(i) || i < 0 || i >= len) + throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`); + return lettersA[i]; + }); + }, + decode: (input) => { + aArr(input); + return input.map((letter) => { + astr('alphabet.decode', letter); + const i = indexes.get(letter); + if (i === undefined) + throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); + return i; + }); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = '') { + astr('join', separator); + // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets. + // Multi-character tokens need a separator that cannot appear inside the chunks. + return { + encode: (from) => { + astrArr('join.decode', from); + return from.join(separator); + }, + decode: (to) => { + astr('join.decode', to); + return to.split(separator); + }, + }; +} +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits, chr = '=') { + anumber(bits); + astr('padding', chr); + return { + encode(data) { + astrArr('padding.encode', data); + // Mutates the intermediate token array in place while appending pad chars. + // utils.padding callers that need to preserve their input should pass a copy. + while ((data.length * bits) % 8) + data.push(chr); + return data; + }, + decode(input) { + astrArr('padding.decode', input); + let end = input.length; + if ((end * bits) % 8) + throw new Error('padding: invalid, string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + const last = end - 1; + const byte = last * bits; + if (byte % 8 === 0) + throw new Error('padding: invalid, string has too much padding'); + } + return input.slice(0, end); + }, + }; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn) { + afn(fn); + return { encode: (from) => from, decode: (to) => fn(to) }; +} +/** + * Slow: O(n^2) time complexity + */ +function convertRadix(data, from, to) { + // base 1 is impossible + if (from < 2) + throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`); + if (to < 2) + throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`); + aArr(data); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data, (d) => { + anumber(d); + if (d < 0 || d >= from) + throw new Error(`invalid integer: ${d}`); + return d; + }); + const dlen = digits.length; + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < dlen; i++) { + const digit = digits[i]; + const fromCarry = from * carry; + const digitBase = fromCarry + digit; + if (!Number.isSafeInteger(digitBase) || + fromCarry / from !== carry || + digitBase - digit !== fromCarry) { + throw new Error('convertRadix: carry overflow'); + } + const div = digitBase / to; + carry = digitBase % to; + const rounded = Math.floor(div); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) + continue; + else if (!rounded) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics. + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); +// Maximum carry width before the `pos` cycle repeats. +// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd). +const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); +const powers = /* @__PURE__ */ (() => { + let res = []; + for (let i = 0; i < 40; i++) + res.push(2 ** i); + return res; +})(); +/** + * Implemented with numbers, because BigInt is 5x slower + */ +function convertRadix2(data, from, to, padding) { + aArr(data); + if (from <= 0 || from > 32) + throw new RangeError(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new RangeError(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const max = powers[from]; + const mask = powers[to] - 1; + const res = []; + for (const n of data) { + anumber(n); + if (n >= max) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push(((carry >> (pos - to)) & mask) >>> 0); + const pow = powers[pos]; + if (pow === undefined) + throw new Error('invalid carry'); + carry &= pow - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + // Canonical decode paths reject leftover whole input words and non-zero pad bits. + // For Bech32 5->8 regrouping, this is the "4 bits or less, all zeroes" tail rule. + if (!padding && pos >= from) + throw new Error('Excess padding'); + if (!padding && carry > 0) + throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) + res.push(carry >>> 0); + return res; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num) { + anumber(num); + const _256 = 2 ** 8; + // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically. + return { + encode: (bytes) => { + if (!isBytes(bytes)) + throw new TypeError('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), _256, num); + }, + decode: (digits) => { + anumArr('radix.decode', digits); + return Uint8Array.from(convertRadix(digits, num, _256)); + }, + }; +} +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits, revPadding = false) { + anumber(bits); + if (bits <= 0 || bits > 32) + throw new RangeError('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new RangeError('radix2: carry overflow'); + // revPadding flips which direction allows a partial zero tail. + // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite. + return { + encode: (bytes) => { + if (!isBytes(bytes)) + throw new TypeError('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + anumArr('radix2.decode', digits); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} +function unsafeWrapper(fn) { + afn(fn); + return function (...args) { + // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`. + // Do not wrap code that needs to preserve exception details. + try { + return fn.apply(null, args); + } + catch (e) { } + }; +} +function checksum(len, fn) { + anumber(len); + // Reject degenerate zero-byte checksums up front so callers don't accidentally + // build a no-op checksum stage. + if (len <= 0) + throw new RangeError(`checksum length must be positive: ${len}`); + afn(fn); + const _fn = fn; + // Uses the first `len` bytes of fn(data) in both directions. + // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes. + return { + encode(data) { + if (!isBytes(data)) + throw new TypeError('checksum.encode: input should be Uint8Array'); + const sum = _fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(sum, data.length); + return res; + }, + decode(data) { + if (!isBytes(data)) + throw new TypeError('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const oldChecksum = data.slice(-len); + const newChecksum = _fn(payload).slice(0, len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error('Invalid checksum'); + return payload; + }, + }; +} +// prettier-ignore +/** + * Low-level building blocks used by the exported codecs. + * @example + * Build a radix-32 coder from the low-level helpers. + * ```ts + * import { utils } from '@scure/base'; + * utils.radix2(5).encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const utils = /* @__PURE__ */ Object.freeze({ + alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding, +}); +// RFC 4648 aka RFC 3548 +// --------------------- +/** + * base16 encoding from RFC 4648. + * This codec uses RFC 4648 Table 5's uppercase alphabet directly. + * RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here. + * Use `hex` for case-insensitive hex decoding. + * @example + * ```js + * base16.encode(Uint8Array.from([0x12, 0xab])); + * // => '12AB' + * ``` + */ +export const base16 = /* @__PURE__ */ Object.freeze(chain(radix2(4), alphabet('0123456789ABCDEF'), join(''))); +/** + * base32 encoding from RFC 4648. Has padding. + * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose + * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input. + * Use `base32nopad` for unpadded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ====' + * base32.decode('CKVQ===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32 = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''))); +/** + * base32 encoding from RFC 4648. No padding. + * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input. + * Use `base32` for padded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ' + * base32nopad.decode('CKVQ'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32nopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''))); +/** + * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet. + * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input. + * Use `base32hexnopad` for unpadded version. + * @example + * ```js + * base32hex.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG====' + * base32hex.decode('2ALG===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32hex = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''))); +/** + * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet. + * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input. + * Use `base32hex` for padded version. + * @example + * ```js + * base32hexnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG' + * base32hexnopad.decode('2ALG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32hexnopad = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''))); +/** + * base32 encoding from RFC 4648. Doug Crockford's version. + * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}. + * @example + * ```js + * base32crockford.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ANG' + * base32crockford.decode('2ANG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32crockford = /* @__PURE__ */ Object.freeze(chain(radix2(5), alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), join(''), normalize((s) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')))); +// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64 +// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior. +// prettier-ignore +const hasBase64Builtin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toBase64 === 'function' && + typeof Uint8Array.fromBase64 === 'function')(); +// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars. +// Reject them first so the native base64 path still follows RFC 4648 §3.3. +// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE +const ASCII_WHITESPACE = /[\t\n\f\r ]/; +const decodeBase64Builtin = (s, isUrl) => { + astr('base64', s); + const alphabet = isUrl ? 'base64url' : 'base64'; + // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace + // And checking just for whitespace makes decoding about 3x faster than a full range check. + // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical. + if (s.length > 0 && ASCII_WHITESPACE.test(s)) + throw new Error('invalid base64'); + return Uint8Array.fromBase64(s, { alphabet, lastChunkHandling: 'strict' }); +}; +/** + * base64 from RFC 4648. Padded. + * Use `base64nopad` for unpadded version. + * Also check out `base64url`, `base64urlnopad`. + * Falls back to built-in function, when available. + * @example + * ```js + * base64.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +// prettier-ignore +export const base64 = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? { + encode(b) { abytes(b); return b.toBase64(); }, + decode(s) { return decodeBase64Builtin(s, false); }, +} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), padding(6), join(''))); +/** + * base64 from RFC 4648. No padding. + * Use `base64` for padded version. + * @example + * ```js + * base64nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64nopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base64nopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), join(''))); +/** + * base64 from RFC 4648, using URL-safe alphabet. Padded. + * Use `base64urlnopad` for unpadded version. + * Falls back to built-in function, when available. + * @example + * ```js + * base64url.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64url.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +// prettier-ignore +export const base64url = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? { + encode(b) { abytes(b); return b.toBase64({ alphabet: 'base64url' }); }, + decode(s) { return decodeBase64Builtin(s, true); }, +} : chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), padding(6), join(''))); +/** + * base64 from RFC 4648, using URL-safe alphabet. No padding. + * Use `base64url` for padded version. + * @example + * ```js + * base64urlnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64urlnopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base64urlnopad = /* @__PURE__ */ Object.freeze(chain(radix2(6), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), join(''))); +// base58 code +// ----------- +const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => chain(radix(58), alphabet(abc), join('')); +/** + * base58: base64 without ambigous characters +, /, 0, O, I, l. + * Quadratic (O(n^2)) - so, can't be used on large inputs. + * @example + * ```js + * const text = base58.encode(Uint8Array.from([0, 1, 2])); + * base58.decode(text); + * // => Uint8Array.from([0, 1, 2]) + * ``` + */ +export const base58 = /* @__PURE__ */ Object.freeze(genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')); +/** + * base58: flickr version. Check out `base58`. + * @example + * Round-trip bytes with the Flickr alphabet. + * ```ts + * const text = base58flickr.encode(Uint8Array.from([0, 1, 2])); + * base58flickr.decode(text); + * ``` + */ +export const base58flickr = /* @__PURE__ */ Object.freeze(genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ')); +/** + * base58: XRP version. Check out `base58`. + * @example + * Round-trip bytes with the XRP alphabet. + * ```ts + * const text = base58xrp.encode(Uint8Array.from([0, 1, 2])); + * base58xrp.decode(text); + * ``` + */ +export const base58xrp = /* @__PURE__ */ Object.freeze(genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz')); +// Data len (index) -> encoded block len. +// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length. +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; +/** + * base58: XMR version. Check out `base58`. + * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. + * Block encoding significantly reduces quadratic complexity of base58. + * @example + * Round-trip bytes with the Monero block codec. + * ```ts + * const text = base58xmr.encode(Uint8Array.from([0, 1, 2])); + * base58xmr.decode(text); + * ``` + */ +export const base58xmr = /* @__PURE__ */ Object.freeze({ + encode(data) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length], '1'); + } + return res; + }, + decode(str) { + astr('base58xmr.decode', str); + let res = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) + throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}); +/** + * Method, which creates base58check encoder. + * Requires function, calculating sha256. + * Callers must include any version bytes in `data`; this helper only applies the + * 4-byte double-SHA256 checksum used by Bitcoin Base58Check. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Create a base58check codec from a SHA-256 implementation. + * ```ts + * import { createBase58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = createBase58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const createBase58check = (sha256) => { + // Validate the hash function at construction time so wrong inputs fail before returning a coder. + afn(sha256); + const _sha256 = sha256; + return chain(checksum(4, (data) => _sha256(_sha256(data))), base58); +}; +/** + * Use `createBase58check` instead. + * @deprecated Use {@link createBase58check} instead. + * Callers must include any version bytes in `data`; this alias keeps the same + * 4-byte double-SHA256 checksum behavior as `createBase58check`. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @example + * Create a base58check codec with the deprecated alias. + * ```ts + * import { base58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = base58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const base58check = createBase58check; +// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`. +const BECH_ALPHABET = chain(alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), join('')); +// BIP 173 `bech32_polymod` GEN coefficients. +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value. +function bech32Polymod(pre) { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) + chk ^= POLYMOD_GENERATORS[i]; + } + return chk; +} +function bechChecksum(prefix, words, encodingConst = 1) { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) + throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) + chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) + chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) + chk = bech32Polymod(chk); + // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols. + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]], 30, 5, false)); +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding) { + // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m. + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + function encode(prefix, words, limit = 90) { + astr('bech32.encode prefix', prefix); + if (isBytes(words)) + words = Array.from(words); + anumArr('bech32.encode', words); + const plen = prefix.length; + if (plen === 0) + throw new TypeError(`Invalid prefix length ${plen}`); + // Total output is hrp + `1` separator + payload words + 6 checksum chars. + const actualLength = plen + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}`; + } + function decode(str, limit = 90) { + astr('bech32.decode input', str); + const slen = str.length; + // Minimum length is 1-char hrp + `1` separator + 6-char checksum. + if (slen < 8 || (limit !== false && slen > limit)) + throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + const sepIndex = lowered.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = lowered.slice(0, sepIndex); + const data = lowered.slice(sepIndex + 1); + if (data.length < 6) + throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(data).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!data.endsWith(sum)) + throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + const decodeUnsafe = unsafeWrapper(decode); + function decodeToBytes(str) { + // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str). + const { prefix, words } = decode(str, false); + return { + prefix, + words, + bytes: fromWords(words), + }; + } + function encodeFromBytes(prefix, bytes) { + // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit). + return encode(prefix, toWords(bytes)); + } + return { + encode, + decode, + encodeFromBytes, + decodeToBytes, + decodeUnsafe, + fromWords, + fromWordsUnsafe, + toWords, + }; +} +/** + * bech32 from BIP 173. Operates on words. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them, then decode back. + * ```ts + * const words = bech32.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32.encode('bc', words); + * bech32.decode(text); + * ``` + */ +export const bech32 = /* @__PURE__ */ Object.freeze(genBech32('bech32')); +/** + * bech32m from BIP 350. Operates on words. + * It was to mitigate `bech32` weaknesses. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them with bech32m, then decode back. + * ```ts + * const words = bech32m.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32m.encode('bc', words); + * bech32m.decode(text); + * ``` + */ +export const bech32m = /* @__PURE__ */ Object.freeze(genBech32('bech32m')); +/** + * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes. + * @example + * ```js + * const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ]) + * const str = ascii.encode(b); // "ABC" + * ``` + */ +export const ascii = /* @__PURE__ */ Object.freeze({ + encode(data) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length; i++) { + const byte = data[i]; + // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to + // Latin-1/UTF-8. + if (byte > 127) + throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`); + res += String.fromCharCode(byte); + } + return res; + }, + decode(str) { + if (typeof str !== 'string') + throw new TypeError('ascii string expected, got ' + typeof str); + const res = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps + // exact error positions. + const charCode = str.charCodeAt(i); + if (charCode > 127) { + throw new RangeError(`string contains non-ASCII character "${str[i]}" with code ${charCode} at position ${i}`); + } + res[i] = charCode; + } + return res; + }, +}); +const _isWellFormedShim = (str) => { + // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native + // isWellFormed on our tests/fuzz corpus. + try { + return encodeURI(str) !== null; + } + catch { + return false; + } +}; +const _isWellFormed = /* @__PURE__ */ (() => +// Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call. +typeof ''.isWellFormed === 'function' + ? (str) => str.isWellFormed() + : _isWellFormedShim)(); +// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed +// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform +// text codecs. +const utf8Fallback = /* @__PURE__ */ Object.freeze({ + encode(data) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length;) { + const a = data[i++]; + if (a < 0b1000_0000) { + res += String.fromCharCode(a); + continue; + } + if (a < 0b1100_0010 || i >= data.length) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const b = data[i++]; + if ((b & 0b1100_0000) !== 0b1000_0000) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111); + if (a >= 0b1110_0000) { + if (i >= data.length) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const c = data[i++]; + if ((c & 0b1100_0000) !== 0b1000_0000 || + (a === 0b1110_0000 && b < 0b1010_0000) || + (a === 0xed && b >= 0b1010_0000)) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111); + if (a >= 0b1111_0000) { + if (i >= data.length) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const d = data[i++]; + if (a > 0b1111_0100 || + (d & 0b1100_0000) !== 0b1000_0000 || + (a === 0b1111_0000 && b < 0b1001_0000) || + (a === 0b1111_0100 && b >= 0b1001_0000)) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + cp = + ((a & 7) << 18) | + ((b & 0b0011_1111) << 12) | + ((c & 0b0011_1111) << 6) | + (d & 0b0011_1111); + } + } + if (cp < 0x10000) + res += String.fromCharCode(cp); + else { + cp -= 0x10000; + res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00); + } + } + return res; + }, + decode(str) { + astr('utf8', str); + if (!_isWellFormed(str)) + throw new TypeError('utf8 expected well-formed string'); + // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and + // large Node inputs. + const res = new Uint8Array(str.length * 3); + let pos = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 0b1000_0000) { + res[pos++] = c; + continue; + } + if (c >= 0xd800 && c <= 0xdfff) { + const d = str.charCodeAt(++i); + c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00; + } + if (c >= 0x10000) { + res[pos++] = (c >> 18) | 0b1111_0000; + res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000; + } + else if (c >= 0x800) + res[pos++] = (c >> 12) | 0b1110_0000; + else + res[pos++] = (c >> 6) | 0b1100_0000; + if (c >= 0x800) + res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000; + res[pos++] = (c & 0b0011_1111) | 0b1000_0000; + } + return res.subarray(0, pos); + }, +}); +/** + * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and + * `decode(string)` returns bytes. + * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and + * throws on invalid UTF-8 bytes. + * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with + * lone surrogates. + * @example + * ```js + * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ]) + * const str = utf8.encode(b); // "hey" + * ``` + */ +export const utf8 = /* @__PURE__ */ (() => { + let _utf8Encoder; + let _utf8Decoder; + const utf8Builtin = { + // ignoreBOM preserves an explicit leading U+FEFF; + // fatal rejects invalid UTF-8 bytes instead of replacing them. + encode(data) { + abytes(data); + return (_utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))).decode(data); + }, + decode(str) { + astr('utf8', str); + if (!_isWellFormed(str)) + throw new TypeError('utf8 expected well-formed string'); + return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str); + }, + }; + return Object.freeze({ + // Select each direction once at module init, since + // TextEncoder and TextDecoder can exist independently. + encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode, + decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode, + }); +})(); +// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided. +export const __TESTS = /* @__PURE__ */ Object.freeze({ + utf8Fallback: utf8Fallback, + _isWellFormedShim: _isWellFormedShim, +}); +// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex +// prettier-ignore +const hasHexBuiltin = /* @__PURE__ */ (() => +// Require both directions before enabling the native hex path so encode/decode stay symmetric. +typeof Uint8Array.from([]).toHex === 'function' && + typeof Uint8Array.fromHex === 'function')(); +// prettier-ignore +const hexBuiltin = { + // Keep local type guards so the native path preserves library-level input errors. + // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings. + encode(data) { abytes(data); return data.toHex(); }, + // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax. + decode(s) { astr('hex', s); return Uint8Array.fromHex(s); }, +}; +/** + * hex string decoder. Uses built-in function, when available. + * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase. + * @example + * ```js + * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ]) + * const str = hex.encode(b); // "0102ff" + * ``` + */ +export const hex = /* @__PURE__ */ Object.freeze(hasHexBuiltin + ? hexBuiltin + : chain(radix2(4), alphabet('0123456789abcdef'), join(''), normalize((s) => { + if (typeof s !== 'string' || s.length % 2 !== 0) + throw new TypeError(`hex.decode: expected string, got ${typeof s} with length ${s.length}`); + return s.toLowerCase(); + }))); +// prettier-ignore +// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here. +const CODERS = { + utf8, hex, base16, base32, base64, base64url, base58, base58xmr +}; +const coderTypeError = 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; +/** + * Encodes bytes with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.encode(bytes)`. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * bytesToString('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export const bytesToString = (type, bytes) => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (!isBytes(bytes)) + throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; +/** + * Alias for `bytesToString`. + * @deprecated Use {@link bytesToString} or the codec directly instead. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @example + * ```ts + * str('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export const str = bytesToString; // as in python, but for bytes only +/** + * Decodes a string with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.decode(text)`. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * stringToBytes('hex', '0102ff'); + * ``` + */ +export const stringToBytes = (type, str) => { + // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors. + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) + throw new TypeError(coderTypeError); + if (typeof str !== 'string') + throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str); +}; +/** + * Alias for `stringToBytes`. + * @deprecated Use {@link stringToBytes} or the codec directly instead. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @example + * ```ts + * bytes('hex', '0102ff'); + * ``` + */ +export const bytes = stringToBytes; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/base/index.js.map b/node_modules/@scure/base/index.js.map new file mode 100644 index 0000000..01ea643 --- /dev/null +++ b/node_modules/@scure/base/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,oEAAoE;AA4IpE,SAAS,OAAO,CAAC,CAAU;IACzB,+FAA+F;IAC/F,8EAA8E;IAC9E,mFAAmF;IACnF,mCAAmC;IACnC,OAAO,CACL,CAAC,YAAY,UAAU;QACvB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;YACpB,CAAC,CAAC,WAAW,CAAC,IAAI,KAAK,YAAY;YACnC,mBAAmB,IAAI,CAAC;YACxB,CAAC,CAAC,iBAAiB,KAAK,CAAC,CAAC,CAC7B,CAAC;AACJ,CAAC;AACD,uCAAuC;AACvC,SAAS,MAAM,CAAC,CAA+B;IAC7C,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC;QAAE,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,SAAS,CAAC,QAAiB,EAAE,GAAU;IAC9C,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC;QAAE,OAAO,KAAK,CAAC;IACtC,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAClC,IAAI,QAAQ,EAAE,CAAC;QACb,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC;IACvD,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,CAAC,KAAK,CAAC,CAAC,IAA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,MAAM,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;IAClG,IAAI,OAAO,GAAG,KAAK,QAAQ;QAAE,MAAM,IAAI,SAAS,CAAC,gCAAgC,CAAC,CAAC;IACnF,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,GAAG,CAAqB,CAAC;AACtD,CAAC,CAAC;AACF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,KAAK,GAAuD,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/base/index.ts b/node_modules/@scure/base/index.ts new file mode 100644 index 0000000..90aa7d6 --- /dev/null +++ b/node_modules/@scure/base/index.ts @@ -0,0 +1,1397 @@ +/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */ + +/** Transforms values between two representations. */ +export interface Coder { + /** + * Converts a value from the input representation to the output representation. + * @param from - Value in the source representation. + * @returns Converted value. + */ + encode(from: F): T; + /** + * Converts a value from the output representation back to the input representation. + * @param to - Value in the target representation. + * @returns Converted value. + */ + decode(to: T): F; +} + +/** Coder that works with byte arrays and strings. */ +export interface BytesCoder extends Coder { + /** + * Encodes bytes into a string representation. + * @param data - Bytes to encode. + * @returns Encoded string. + */ + encode: (data: Uint8Array) => string; + /** + * Decodes a string representation into raw bytes. + * @param str - Encoded string. + * @returns Decoded bytes. + */ + decode: (str: string) => Uint8Array; +} + +/** + * Bytes API type helpers for old + new TypeScript. + * + * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`. + * We can't use specific return type, because TS 5.6 will error. + * We can't use generic return type, because most TS 5.9 software will expect specific type. + * + * Maps typed-array input leaves to broad forms. + * These are compatibility adapters, not ownership guarantees. + * + * - `TArg` keeps byte inputs broad. + * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility. + */ +export type TypedArg = T extends BigInt64Array + ? BigInt64Array + : T extends BigUint64Array + ? BigUint64Array + : T extends Float32Array + ? Float32Array + : T extends Float64Array + ? Float64Array + : T extends Int16Array + ? Int16Array + : T extends Int32Array + ? Int32Array + : T extends Int8Array + ? Int8Array + : T extends Uint16Array + ? Uint16Array + : T extends Uint32Array + ? Uint32Array + : T extends Uint8ClampedArray + ? Uint8ClampedArray + : T extends Uint8Array + ? Uint8Array + : never; +/** Maps typed-array output leaves to narrow TS-compatible forms. */ +export type TypedRet = T extends BigInt64Array + ? ReturnType + : T extends BigUint64Array + ? ReturnType + : T extends Float32Array + ? ReturnType + : T extends Float64Array + ? ReturnType + : T extends Int16Array + ? ReturnType + : T extends Int32Array + ? ReturnType + : T extends Int8Array + ? ReturnType + : T extends Uint16Array + ? ReturnType + : T extends Uint32Array + ? ReturnType + : T extends Uint8ClampedArray + ? ReturnType + : T extends Uint8Array + ? ReturnType + : never; +/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */ +export type TArg = + | T + | ([TypedArg] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TRet }) => TArg) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg; + } + : T extends [infer A, ...infer R] + ? [TArg, ...{ [K in keyof R]: TArg }] + : T extends readonly [infer A, ...infer R] + ? readonly [TArg, ...{ [K in keyof R]: TArg }] + : T extends (infer A)[] + ? TArg[] + : T extends readonly (infer A)[] + ? readonly TArg[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TArg } + : T + : TypedArg); +/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */ +export type TRet = T extends unknown + ? T & + ([TypedRet] extends [never] + ? T extends (...args: infer A) => infer R + ? ((...args: { [K in keyof A]: TArg }) => TRet) & { + [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet; + } + : T extends [infer A, ...infer R] + ? [TRet, ...{ [K in keyof R]: TRet }] + : T extends readonly [infer A, ...infer R] + ? readonly [TRet, ...{ [K in keyof R]: TRet }] + : T extends (infer A)[] + ? TRet[] + : T extends readonly (infer A)[] + ? readonly TRet[] + : T extends Promise + ? Promise> + : T extends object + ? { [K in keyof T]: TRet } + : T + : TypedRet) + : never; + +function isBytes(a: unknown): a is Uint8Array { + // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The + // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized + // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the + // fallback on byte-oriented views. + return ( + a instanceof Uint8Array || + (ArrayBuffer.isView(a) && + a.constructor.name === 'Uint8Array' && + 'BYTES_PER_ELEMENT' in a && + a.BYTES_PER_ELEMENT === 1) + ); +} +/** Asserts something is Uint8Array. */ +function abytes(b: TArg): void { + if (!isBytes(b)) throw new TypeError('Uint8Array expected'); +} + +function isArrayOf(isString: boolean, arr: any[]) { + if (!Array.isArray(arr)) return false; + if (arr.length === 0) return true; + if (isString) { + return arr.every((item) => typeof item === 'string'); + } else { + return arr.every((item) => Number.isSafeInteger(item)); + } +} + +function afn(input: Function): input is Function { + if (typeof input !== 'function') throw new TypeError('function expected'); + return true; +} + +function astr(label: string, input: unknown): input is string { + if (typeof input !== 'string') throw new TypeError(`${label}: string expected`); + return true; +} + +function anumber(n: number): void { + if (typeof n !== 'number') throw new TypeError(`number expected, got ${typeof n}`); + if (!Number.isSafeInteger(n)) throw new RangeError(`invalid integer: ${n}`); +} + +function aArr(input: any[]) { + if (!Array.isArray(input)) throw new TypeError('array expected'); +} +function astrArr(label: string, input: string[]) { + if (!isArrayOf(true, input)) throw new TypeError(`${label}: array of strings expected`); +} +function anumArr(label: string, input: number[]) { + if (!isArrayOf(false, input)) throw new TypeError(`${label}: array of numbers expected`); +} + +// TODO: some recusive type inference so it would check correct order of input/output inside rest? +// like , , +type Chain = [Coder, ...Coder[]]; +// Extract info from Coder type +type Input = F extends Coder ? T : never; +type Output = F extends Coder ? T : never; +// Generic function for arrays +type First = T extends [infer U, ...any[]] ? U : never; +type Last = T extends [...any[], infer U] ? U : never; +type Tail = T extends [any, ...infer U] ? U : never; + +type AsChain> = { + // C[K] = Coder, Input> + [K in keyof C]: Coder, Input>; +}; + +/** + * @__NO_SIDE_EFFECTS__ + */ +function chain>(...args: T): Coder>, Output>> { + const id = (a: any) => a; + // Wrap call in closure so JIT can inline calls + const wrap = (a: any, b: any) => (c: any) => a(b(c)); + // Construct chain of args[-1].encode(args[-2].encode([...])) + const encode = args.map((x) => x.encode).reduceRight(wrap, id); + // Construct chain of args[0].decode(args[1].decode(...)) + const decode = args.map((x) => x.decode).reduce(wrap, id); + return { encode, decode }; +} + +/** + * Encodes integer radix representation to array of strings using alphabet and back. + * Could also be array of strings. + * @__NO_SIDE_EFFECTS__ + */ +function alphabet(letters: string | string[]): Coder { + // mapping 1 to "b" + const lettersA = typeof letters === 'string' ? letters.split('') : letters; + const len = lettersA.length; + astrArr('alphabet', lettersA); + + // mapping "b" to 1 + const indexes = new Map(lettersA.map((l, i) => [l, i])); + return { + encode: (digits: number[]) => { + aArr(digits); + return digits.map((i) => { + if (!Number.isSafeInteger(i) || i < 0 || i >= len) + throw new Error( + `alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}` + ); + return lettersA[i]!; + }); + }, + decode: (input: string[]): number[] => { + aArr(input); + return input.map((letter) => { + astr('alphabet.decode', letter); + const i = indexes.get(letter); + if (i === undefined) throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); + return i; + }); + }, + }; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function join(separator = ''): Coder { + astr('join', separator); + // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets. + // Multi-character tokens need a separator that cannot appear inside the chunks. + return { + encode: (from) => { + astrArr('join.decode', from); + return from.join(separator); + }, + decode: (to) => { + astr('join.decode', to); + return to.split(separator); + }, + }; +} + +/** + * Pad strings array so it has integer number of bits + * @__NO_SIDE_EFFECTS__ + */ +function padding(bits: number, chr = '='): Coder { + anumber(bits); + astr('padding', chr); + return { + encode(data: string[]): string[] { + astrArr('padding.encode', data); + // Mutates the intermediate token array in place while appending pad chars. + // utils.padding callers that need to preserve their input should pass a copy. + while ((data.length * bits) % 8) data.push(chr); + return data; + }, + decode(input: string[]): string[] { + astrArr('padding.decode', input); + let end = input.length; + if ((end * bits) % 8) + throw new Error('padding: invalid, string should have whole number of bytes'); + for (; end > 0 && input[end - 1] === chr; end--) { + const last = end - 1; + const byte = last * bits; + if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding'); + } + return input.slice(0, end); + }, + }; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function normalize(fn: (val: T) => T): Coder { + afn(fn); + return { encode: (from: T) => from, decode: (to: T) => fn(to) }; +} + +/** + * Slow: O(n^2) time complexity + */ +function convertRadix(data: number[], from: number, to: number): number[] { + // base 1 is impossible + if (from < 2) + throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`); + if (to < 2) throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`); + aArr(data); + if (!data.length) return []; + let pos = 0; + const res = []; + const digits = Array.from(data, (d) => { + anumber(d); + if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`); + return d; + }); + const dlen = digits.length; + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < dlen; i++) { + const digit = digits[i]!; + const fromCarry = from * carry; + const digitBase = fromCarry + digit; + if ( + !Number.isSafeInteger(digitBase) || + fromCarry / from !== carry || + digitBase - digit !== fromCarry + ) { + throw new Error('convertRadix: carry overflow'); + } + const div = digitBase / to; + carry = digitBase % to; + const rounded = Math.floor(div); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error('convertRadix: carry overflow'); + if (!done) continue; + else if (!rounded) pos = i; + else done = false; + } + res.push(carry); + if (done) break; + } + // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics. + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0); + return res.reverse(); +} + +const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b)); +// Maximum carry width before the `pos` cycle repeats. +// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd). +const radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) => + from + (to - gcd(from, to)); +const powers: number[] = /* @__PURE__ */ (() => { + let res = []; + for (let i = 0; i < 40; i++) res.push(2 ** i); + return res; +})(); +/** + * Implemented with numbers, because BigInt is 5x slower + */ +function convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] { + aArr(data); + if (from <= 0 || from > 32) throw new RangeError(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) throw new RangeError(`convertRadix2: wrong to=${to}`); + if (radix2carry(from, to) > 32) { + throw new Error( + `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}` + ); + } + let carry = 0; + let pos = 0; // bitwise position in current element + const max = powers[from]!; + const mask = powers[to]! - 1; + const res: number[] = []; + for (const n of data) { + anumber(n); + if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = (carry << from) | n; + if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0); + const pow = powers[pos]; + if (pow === undefined) throw new Error('invalid carry'); + carry &= pow - 1; // clean carry, otherwise it will cause overflow + } + carry = (carry << (to - pos)) & mask; + // Canonical decode paths reject leftover whole input words and non-zero pad bits. + // For Bech32 5->8 regrouping, this is the "4 bits or less, all zeroes" tail rule. + if (!padding && pos >= from) throw new Error('Excess padding'); + if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`); + if (padding && pos > 0) res.push(carry >>> 0); + return res; +} + +/** + * @__NO_SIDE_EFFECTS__ + */ +function radix(num: number): TRet> { + anumber(num); + const _256 = 2 ** 8; + // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically. + return { + encode: (bytes: TArg) => { + if (!isBytes(bytes)) throw new TypeError('radix.encode input should be Uint8Array'); + return convertRadix(Array.from(bytes), _256, num); + }, + decode: (digits: number[]) => { + anumArr('radix.decode', digits); + return Uint8Array.from(convertRadix(digits, num, _256)); + }, + }; +} + +/** + * If both bases are power of same number (like `2**8 <-> 2**64`), + * there is a linear algorithm. For now we have implementation for power-of-two bases only. + * @__NO_SIDE_EFFECTS__ + */ +function radix2(bits: number, revPadding = false): TRet> { + anumber(bits); + if (bits <= 0 || bits > 32) throw new RangeError('radix2: bits should be in (0..32]'); + if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32) + throw new RangeError('radix2: carry overflow'); + // revPadding flips which direction allows a partial zero tail. + // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite. + return { + encode: (bytes: TArg) => { + if (!isBytes(bytes)) throw new TypeError('radix2.encode input should be Uint8Array'); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits: number[]) => { + anumArr('radix2.decode', digits); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + }, + }; +} + +type ArgumentTypes = F extends (...args: infer A) => any ? A : never; +type BytesFn = (data: TArg) => TRet; +function unsafeWrapper any>(fn: T) { + afn(fn); + return function (...args: ArgumentTypes): ReturnType | void { + // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`. + // Do not wrap code that needs to preserve exception details. + try { + return fn.apply(null, args); + } catch (e) {} + }; +} + +function checksum(len: number, fn: TArg): TRet> { + anumber(len); + // Reject degenerate zero-byte checksums up front so callers don't accidentally + // build a no-op checksum stage. + if (len <= 0) throw new RangeError(`checksum length must be positive: ${len}`); + afn(fn); + const _fn = fn as BytesFn; + // Uses the first `len` bytes of fn(data) in both directions. + // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes. + return { + encode(data: TArg) { + if (!isBytes(data)) throw new TypeError('checksum.encode: input should be Uint8Array'); + const sum = _fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(sum, data.length); + return res; + }, + decode(data: TArg) { + if (!isBytes(data)) throw new TypeError('checksum.decode: input should be Uint8Array'); + const payload = data.slice(0, -len); + const oldChecksum = data.slice(-len); + const newChecksum = _fn(payload).slice(0, len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum'); + return payload; + }, + }; +} + +// prettier-ignore +/** + * Low-level building blocks used by the exported codecs. + * @example + * Build a radix-32 coder from the low-level helpers. + * ```ts + * import { utils } from '@scure/base'; + * utils.radix2(5).encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = /* @__PURE__ */ Object.freeze({ + alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding, +}); + +// RFC 4648 aka RFC 3548 +// --------------------- + +/** + * base16 encoding from RFC 4648. + * This codec uses RFC 4648 Table 5's uppercase alphabet directly. + * RFC 4648 §8 calls base16 "case-insensitive hex encoding", but we intentionally do not case-fold decode input here. + * Use `hex` for case-insensitive hex decoding. + * @example + * ```js + * base16.encode(Uint8Array.from([0x12, 0xab])); + * // => '12AB' + * ``` + */ +export const base16: BytesCoder = /* @__PURE__ */ Object.freeze( + chain(radix2(4), alphabet('0123456789ABCDEF'), join('')) +); + +/** + * base32 encoding from RFC 4648. Has padding. + * RFC 4648 §6 Table 3 uses uppercase letters, and RFC 4648 §3.4 allows applications to choose + * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input. + * Use `base32nopad` for unpadded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ====' + * base32.decode('CKVQ===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32: BytesCoder = /* @__PURE__ */ Object.freeze( + chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join('')) +); + +/** + * base32 encoding from RFC 4648. No padding. + * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input. + * Use `base32` for padded version. + * Also check out `base32hex`, `base32hexnopad`, `base32crockford`. + * @example + * ```js + * base32nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'CKVQ' + * base32nopad.decode('CKVQ'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32nopad: BytesCoder = /* @__PURE__ */ Object.freeze( + chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join('')) +); +/** + * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet. + * RFC 4648 §7 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input. + * Use `base32hexnopad` for unpadded version. + * @example + * ```js + * base32hex.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG====' + * base32hex.decode('2ALG===='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32hex: BytesCoder = /* @__PURE__ */ Object.freeze( + chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join('')) +); + +/** + * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet. + * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input. + * Use `base32hex` for padded version. + * @example + * ```js + * base32hexnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ALG' + * base32hexnopad.decode('2ALG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32hexnopad: BytesCoder = /* @__PURE__ */ Object.freeze( + chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join('')) +); +/** + * base32 encoding from RFC 4648. Doug Crockford's version. + * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}. + * @example + * ```js + * base32crockford.encode(Uint8Array.from([0x12, 0xab])); + * // => '2ANG' + * base32crockford.decode('2ANG'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base32crockford: BytesCoder = /* @__PURE__ */ Object.freeze( + chain( + radix2(5), + alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'), + join(''), + normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1')) + ) +); + +// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64 +// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior. +// prettier-ignore +const hasBase64Builtin: boolean = /* @__PURE__ */ (() => + typeof (Uint8Array as any).from([]).toBase64 === 'function' && + typeof (Uint8Array as any).fromBase64 === 'function')(); + +// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars. +// Reject them first so the native base64 path still follows RFC 4648 §3.3. +// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE +const ASCII_WHITESPACE = /[\t\n\f\r ]/; + +const decodeBase64Builtin = (s: string, isUrl: boolean) => { + astr('base64', s); + const alphabet = isUrl ? 'base64url' : 'base64'; + // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace + // And checking just for whitespace makes decoding about 3x faster than a full range check. + // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical. + if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error('invalid base64'); + return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' }); +}; + +/** + * base64 from RFC 4648. Padded. + * Use `base64nopad` for unpadded version. + * Also check out `base64url`, `base64urlnopad`. + * Falls back to built-in function, when available. + * @example + * ```js + * base64.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +// prettier-ignore +export const base64: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? { + encode(b) { abytes(b); return (b as any).toBase64(); }, + decode(s) { return decodeBase64Builtin(s, false); }, +} : chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), + padding(6), + join('') +)); +/** + * base64 from RFC 4648. No padding. + * Use `base64` for padded version. + * @example + * ```js + * base64nopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64nopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base64nopad: BytesCoder = /* @__PURE__ */ Object.freeze( + chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'), + join('') + ) +); + +/** + * base64 from RFC 4648, using URL-safe alphabet. Padded. + * Use `base64urlnopad` for unpadded version. + * Falls back to built-in function, when available. + * @example + * ```js + * base64url.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs=' + * base64url.decode('Eqs='); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +// prettier-ignore +export const base64url: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? { + encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); }, + decode(s) { return decodeBase64Builtin(s, true); }, +} : chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), + padding(6), + join('') +)); + +/** + * base64 from RFC 4648, using URL-safe alphabet. No padding. + * Use `base64url` for padded version. + * @example + * ```js + * base64urlnopad.encode(Uint8Array.from([0x12, 0xab])); + * // => 'Eqs' + * base64urlnopad.decode('Eqs'); + * // => Uint8Array.from([0x12, 0xab]) + * ``` + */ +export const base64urlnopad: BytesCoder = /* @__PURE__ */ Object.freeze( + chain( + radix2(6), + alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'), + join('') + ) +); + +// base58 code +// ----------- +const genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) => + chain(radix(58), alphabet(abc), join('')); + +/** + * base58: base64 without ambigous characters +, /, 0, O, I, l. + * Quadratic (O(n^2)) - so, can't be used on large inputs. + * @example + * ```js + * const text = base58.encode(Uint8Array.from([0, 1, 2])); + * base58.decode(text); + * // => Uint8Array.from([0, 1, 2]) + * ``` + */ +export const base58: BytesCoder = /* @__PURE__ */ Object.freeze( + genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz') +); +/** + * base58: flickr version. Check out `base58`. + * @example + * Round-trip bytes with the Flickr alphabet. + * ```ts + * const text = base58flickr.encode(Uint8Array.from([0, 1, 2])); + * base58flickr.decode(text); + * ``` + */ +export const base58flickr: BytesCoder = /* @__PURE__ */ Object.freeze( + genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ') +); +/** + * base58: XRP version. Check out `base58`. + * @example + * Round-trip bytes with the XRP alphabet. + * ```ts + * const text = base58xrp.encode(Uint8Array.from([0, 1, 2])); + * base58xrp.decode(text); + * ``` + */ +export const base58xrp: BytesCoder = /* @__PURE__ */ Object.freeze( + genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz') +); + +// Data len (index) -> encoded block len. +// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length. +const XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11]; + +/** + * base58: XMR version. Check out `base58`. + * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN. + * Block encoding significantly reduces quadratic complexity of base58. + * @example + * Round-trip bytes with the Monero block codec. + * ```ts + * const text = base58xmr.encode(Uint8Array.from([0, 1, 2])); + * base58xmr.decode(text); + * ``` + */ +export const base58xmr: BytesCoder = /* @__PURE__ */ Object.freeze({ + encode(data: TArg) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length; i += 8) { + const block = data.subarray(i, i + 8); + res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1'); + } + return res; + }, + decode(str: string) { + astr('base58xmr.decode', str); + let res: number[] = []; + for (let i = 0; i < str.length; i += 11) { + const slice = str.slice(i, i + 11); + const blockLen = XMR_BLOCK_LEN.indexOf(slice.length); + const block = base58.decode(slice); + for (let j = 0; j < block.length - blockLen; j++) { + if (block[j] !== 0) throw new Error('base58xmr: wrong padding'); + } + res = res.concat(Array.from(block.slice(block.length - blockLen))); + } + return Uint8Array.from(res); + }, +}); + +/** + * Method, which creates base58check encoder. + * Requires function, calculating sha256. + * Callers must include any version bytes in `data`; this helper only applies the + * 4-byte double-SHA256 checksum used by Bitcoin Base58Check. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * Create a base58check codec from a SHA-256 implementation. + * ```ts + * import { createBase58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = createBase58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const createBase58check = (sha256: TArg): BytesCoder => { + // Validate the hash function at construction time so wrong inputs fail before returning a coder. + afn(sha256); + const _sha256 = sha256 as BytesFn; + return chain( + checksum(4, (data: TArg) => _sha256(_sha256(data))), + base58 + ); +}; + +/** + * Use `createBase58check` instead. + * @deprecated Use {@link createBase58check} instead. + * Callers must include any version bytes in `data`; this alias keeps the same + * 4-byte double-SHA256 checksum behavior as `createBase58check`. + * @param sha256 - Function used to calculate the checksum hash. + * @returns base58check codec using 4 checksum bytes. + * @example + * Create a base58check codec with the deprecated alias. + * ```ts + * import { base58check } from '@scure/base'; + * import { sha256 } from '@noble/hashes/sha2.js'; + * const coder = base58check(sha256); + * coder.encode(Uint8Array.from([1, 2, 3])); + * ``` + */ +export const base58check: (sha256: TArg) => BytesCoder = createBase58check; + +// Bech32 code +// ----------- +/** Result of bech32 decoding. */ +export interface Bech32Decoded { + /** Human-readable bech32 prefix. */ + prefix: Prefix; + /** Decoded 5-bit word payload. */ + words: number[]; +} +/** Result of bech32 decoding with original bytes attached. */ +export interface Bech32DecodedWithArray { + /** Human-readable bech32 prefix. */ + prefix: Prefix; + /** Decoded 5-bit word payload. */ + words: number[]; + /** Decoded payload converted back into raw bytes. */ + bytes: Uint8Array; +} + +// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`. +const BECH_ALPHABET: Coder = chain( + alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'), + join('') +); + +// BIP 173 `bech32_polymod` GEN coefficients. +const POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3]; +// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value. +function bech32Polymod(pre: number): number { + const b = pre >> 25; + let chk = (pre & 0x1ffffff) << 5; + for (let i = 0; i < POLYMOD_GENERATORS.length; i++) { + if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!; + } + return chk; +} + +function bechChecksum(prefix: string, words: number[], encodingConst = 1): string { + const len = prefix.length; + let chk = 1; + for (let i = 0; i < len; i++) { + const c = prefix.charCodeAt(i); + if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`); + chk = bech32Polymod(chk) ^ (c >> 5); + } + chk = bech32Polymod(chk); + for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f); + for (let v of words) chk = bech32Polymod(chk) ^ v; + for (let i = 0; i < 6; i++) chk = bech32Polymod(chk); + // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols. + chk ^= encodingConst; + return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false)); +} + +/** bech32 codec surface. */ +export interface Bech32 { + /** + * Encodes a human-readable prefix and 5-bit words into a bech32 string. + * @param prefix - Human-readable prefix. + * @param words - 5-bit words or raw bytes. + * @param limit - Maximum accepted output length, or `false` to disable the limit. + * @returns Encoded bech32 string. + */ + encode( + prefix: Prefix, + words: number[] | Uint8Array, + limit?: number | false + ): `${Lowercase}1${string}`; + /** + * Decodes a bech32 string into prefix and words. + * @param str - Encoded bech32 string. + * @param limit - Maximum accepted input length, or `false` to disable the limit. + * @returns Decoded prefix and 5-bit words. + */ + decode( + str: `${Prefix}1${string}`, + limit?: number | false + ): Bech32Decoded; + decode(str: string, limit?: number | false): Bech32Decoded; + /** + * Encodes raw bytes by first converting them to 5-bit words. + * @param prefix - Human-readable prefix. + * @param bytes - Raw bytes to encode. + * @returns Encoded bech32 string. + */ + encodeFromBytes(prefix: string, bytes: Uint8Array): string; + /** + * Decodes a bech32 string and converts the payload back into bytes. + * @param str - Encoded bech32 string. + * @returns Decoded prefix, words, and bytes. + */ + decodeToBytes(str: string): Bech32DecodedWithArray; + /** + * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input. + * @param str - Encoded bech32 string. + * @param limit - Maximum accepted input length, or `false` to disable the limit. + * @returns Decoded prefix and words, or `undefined` for invalid input. + */ + decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded; + /** + * Converts 5-bit words back into raw bytes. + * @param to - 5-bit words to decode. + * @returns Decoded bytes. + */ + fromWords(to: number[]): Uint8Array; + /** + * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing. + * @param to - 5-bit words to decode. + * @returns Decoded bytes, or `undefined` for invalid input. + */ + fromWordsUnsafe(to: number[]): void | Uint8Array; + /** + * Converts raw bytes into 5-bit words for bech32 encoding. + * @param from - Raw bytes to convert. + * @returns 5-bit words. + */ + toWords(from: Uint8Array): number[]; +} +/** + * @__NO_SIDE_EFFECTS__ + */ +function genBech32(encoding: 'bech32' | 'bech32m'): TRet { + // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m. + const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3; + const _words = radix2(5); + const fromWords = _words.decode; + const toWords = _words.encode; + const fromWordsUnsafe = unsafeWrapper(fromWords); + + function encode( + prefix: Prefix, + words: TArg, + limit: number | false = 90 + ): `${Lowercase}1${string}` { + astr('bech32.encode prefix', prefix); + if (isBytes(words)) words = Array.from(words); + anumArr('bech32.encode', words); + const plen = prefix.length; + if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`); + // Total output is hrp + `1` separator + payload words + 6 checksum chars. + const actualLength = plen + 7 + words.length; + if (limit !== false && actualLength > limit) + throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`); + const lowered = prefix.toLowerCase(); + const sum = bechChecksum(lowered, words, ENCODING_CONST); + return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`; + } + + function decode( + str: `${Prefix}1${string}`, + limit?: number | false + ): Bech32Decoded; + function decode(str: string, limit?: number | false): Bech32Decoded; + function decode(str: string, limit: number | false = 90): Bech32Decoded { + astr('bech32.decode input', str); + const slen = str.length; + // Minimum length is 1-char hrp + `1` separator + 6-char checksum. + if (slen < 8 || (limit !== false && slen > limit)) + throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`); + // don't allow mixed case + const lowered = str.toLowerCase(); + if (str !== lowered && str !== str.toUpperCase()) + throw new Error(`String must be lowercase or uppercase`); + const sepIndex = lowered.lastIndexOf('1'); + if (sepIndex === 0 || sepIndex === -1) + throw new Error(`Letter "1" must be present between prefix and data only`); + const prefix = lowered.slice(0, sepIndex); + const data = lowered.slice(sepIndex + 1); + if (data.length < 6) throw new Error('Data must be at least 6 characters long'); + const words = BECH_ALPHABET.decode(data).slice(0, -6); + const sum = bechChecksum(prefix, words, ENCODING_CONST); + if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected "${sum}"`); + return { prefix, words }; + } + + const decodeUnsafe = unsafeWrapper(decode); + + function decodeToBytes(str: string): TRet { + // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str). + const { prefix, words } = decode(str, false); + return { + prefix, + words, + bytes: fromWords(words) as TRet, + } as TRet; + } + + function encodeFromBytes(prefix: string, bytes: TArg) { + // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit). + return encode(prefix, toWords(bytes)); + } + + return { + encode, + decode, + encodeFromBytes, + decodeToBytes, + decodeUnsafe, + fromWords, + fromWordsUnsafe, + toWords, + }; +} + +/** + * bech32 from BIP 173. Operates on words. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them, then decode back. + * ```ts + * const words = bech32.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32.encode('bc', words); + * bech32.decode(text); + * ``` + */ +export const bech32: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32')); + +/** + * bech32m from BIP 350. Operates on words. + * It was to mitigate `bech32` weaknesses. + * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}. + * @example + * Convert bytes to words, encode them with bech32m, then decode back. + * ```ts + * const words = bech32m.toWords(Uint8Array.from([1, 2, 3])); + * const text = bech32m.encode('bc', words); + * bech32m.decode(text); + * ``` + */ +export const bech32m: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32m')); + +declare const TextEncoder: any; +declare const TextDecoder: any; + +/** + * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes. + * @example + * ```js + * const b = ascii.decode("ABC"); // => new Uint8Array([ 65, 66, 67 ]) + * const str = ascii.encode(b); // "ABC" + * ``` + */ +export const ascii: TRet = /* @__PURE__ */ Object.freeze({ + encode(data: TArg) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length; i++) { + const byte = data[i]!; + // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to + // Latin-1/UTF-8. + if (byte > 127) throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`); + res += String.fromCharCode(byte); + } + return res; + }, + decode(str: string) { + if (typeof str !== 'string') throw new TypeError('ascii string expected, got ' + typeof str); + const res = new Uint8Array(str.length); + for (let i = 0; i < str.length; i++) { + // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps + // exact error positions. + const charCode = str.charCodeAt(i); + if (charCode > 127) { + throw new RangeError( + `string contains non-ASCII character "${str[i]}" with code ${charCode} at position ${i}` + ); + } + res[i] = charCode; + } + return res; + }, +}); + +const _isWellFormedShim = (str: string): boolean => { + // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native + // isWellFormed on our tests/fuzz corpus. + try { + return encodeURI(str) !== null; + } catch { + return false; + } +}; +const _isWellFormed: (str: string) => boolean = /* @__PURE__ */ (() => + // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call. + typeof ('' as any).isWellFormed === 'function' + ? (str) => (str as any).isWellFormed() + : _isWellFormedShim)(); +// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed +// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform +// text codecs. +const utf8Fallback: BytesCoder = /* @__PURE__ */ Object.freeze({ + encode(data: TArg) { + abytes(data); + let res = ''; + for (let i = 0; i < data.length; ) { + const a = data[i++]!; + if (a < 0b1000_0000) { + res += String.fromCharCode(a); + continue; + } + if (a < 0b1100_0010 || i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const b = data[i++]!; + if ((b & 0b1100_0000) !== 0b1000_0000) throw new TypeError(`invalid utf8 at byte ${i - 1}`); + let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111); + if (a >= 0b1110_0000) { + if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const c = data[i++]!; + if ( + (c & 0b1100_0000) !== 0b1000_0000 || + (a === 0b1110_0000 && b < 0b1010_0000) || + (a === 0xed && b >= 0b1010_0000) + ) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111); + if (a >= 0b1111_0000) { + if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`); + const d = data[i++]!; + if ( + a > 0b1111_0100 || + (d & 0b1100_0000) !== 0b1000_0000 || + (a === 0b1111_0000 && b < 0b1001_0000) || + (a === 0b1111_0100 && b >= 0b1001_0000) + ) + throw new TypeError(`invalid utf8 at byte ${i - 1}`); + cp = + ((a & 7) << 18) | + ((b & 0b0011_1111) << 12) | + ((c & 0b0011_1111) << 6) | + (d & 0b0011_1111); + } + } + if (cp < 0x10000) res += String.fromCharCode(cp); + else { + cp -= 0x10000; + res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00); + } + } + return res; + }, + decode(str: string) { + astr('utf8', str); + if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string'); + // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and + // large Node inputs. + const res = new Uint8Array(str.length * 3); + let pos = 0; + for (let i = 0; i < str.length; i++) { + let c = str.charCodeAt(i); + if (c < 0b1000_0000) { + res[pos++] = c; + continue; + } + if (c >= 0xd800 && c <= 0xdfff) { + const d = str.charCodeAt(++i); + c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00; + } + if (c >= 0x10000) { + res[pos++] = (c >> 18) | 0b1111_0000; + res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000; + } else if (c >= 0x800) res[pos++] = (c >> 12) | 0b1110_0000; + else res[pos++] = (c >> 6) | 0b1100_0000; + if (c >= 0x800) res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000; + res[pos++] = (c & 0b0011_1111) | 0b1000_0000; + } + return res.subarray(0, pos); + }, +}); + +/** + * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available. + * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and + * `decode(string)` returns bytes. + * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and + * throws on invalid UTF-8 bytes. + * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with + * lone surrogates. + * @example + * ```js + * const b = utf8.decode("hey"); // => new Uint8Array([ 104, 101, 121 ]) + * const str = utf8.encode(b); // "hey" + * ``` + */ +export const utf8: BytesCoder = /* @__PURE__ */ (() => { + let _utf8Encoder: any; + let _utf8Decoder: any; + const utf8Builtin: BytesCoder = { + // ignoreBOM preserves an explicit leading U+FEFF; + // fatal rejects invalid UTF-8 bytes instead of replacing them. + encode(data) { + abytes(data); + return ( + _utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true })) + ).decode(data); + }, + decode(str) { + astr('utf8', str); + if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string'); + return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str); + }, + }; + return Object.freeze({ + // Select each direction once at module init, since + // TextEncoder and TextDecoder can exist independently. + encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode, + decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode, + }); +})(); +// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided. +export const __TESTS: { + utf8Fallback: BytesCoder; + _isWellFormedShim: (str: string) => boolean; +} = /* @__PURE__ */ Object.freeze({ + utf8Fallback: utf8Fallback, + _isWellFormedShim: _isWellFormedShim, +}); + +// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex +// prettier-ignore +const hasHexBuiltin: boolean = /* @__PURE__ */ (() => + // Require both directions before enabling the native hex path so encode/decode stay symmetric. + typeof (Uint8Array as any).from([]).toHex === 'function' && + typeof (Uint8Array as any).fromHex === 'function')(); +// prettier-ignore +const hexBuiltin: BytesCoder = { + // Keep local type guards so the native path preserves library-level input errors. + // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings. + encode(data) { abytes(data); return (data as any).toHex(); }, + // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax. + decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); }, +}; +/** + * hex string decoder. Uses built-in function, when available. + * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase. + * @example + * ```js + * const b = hex.decode("0102ff"); // => new Uint8Array([ 1, 2, 255 ]) + * const str = hex.encode(b); // "0102ff" + * ``` + */ +export const hex: BytesCoder = /* @__PURE__ */ Object.freeze( + hasHexBuiltin + ? hexBuiltin + : chain( + radix2(4), + alphabet('0123456789abcdef'), + join(''), + normalize((s: string) => { + if (typeof s !== 'string' || s.length % 2 !== 0) + throw new TypeError( + `hex.decode: expected string, got ${typeof s} with length ${s.length}` + ); + return s.toLowerCase(); + }) + ) +); + +/** Built-in codecs exposed through the deprecated string conversion helpers. */ +export type SomeCoders = { + /** UTF-8 string codec. */ + utf8: BytesCoder; + /** Hex codec. */ + hex: BytesCoder; + /** Uppercase RFC 4648 base16 codec. */ + base16: BytesCoder; + /** RFC 4648 base32 codec with padding. */ + base32: BytesCoder; + /** RFC 4648 base64 codec with padding. */ + base64: BytesCoder; + /** URL-safe base64 codec without `+` or `/`. */ + base64url: BytesCoder; + /** Bitcoin-style base58 codec. */ + base58: BytesCoder; + /** Monero-style base58 codec. */ + base58xmr: BytesCoder; +}; +// prettier-ignore +// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here. +const CODERS: SomeCoders = { + utf8, hex, base16, base32, base64, base64url, base58, base58xmr +}; +type CoderType = keyof SomeCoders; +const coderTypeError = + 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr'; + +/** + * Encodes bytes with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.encode(bytes)`. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * bytesToString('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export const bytesToString = (type: CoderType, bytes: TArg): string => { + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError); + if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array'); + return CODERS[type].encode(bytes); +}; + +/** + * Alias for `bytesToString`. + * @deprecated Use {@link bytesToString} or the codec directly instead. + * @param type - Codec name. + * @param bytes - Bytes to encode. + * @returns Encoded string. + * @example + * ```ts + * str('hex', Uint8Array.from([1, 2, 255])); + * ``` + */ +export const str: (type: CoderType, bytes: TArg) => string = bytesToString; // as in python, but for bytes only + +/** + * Decodes a string with one of the built-in codecs. + * @deprecated Use the codec directly, for example `hex.decode(text)`. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @throws On wrong argument types. {@link TypeError} + * @example + * ```ts + * stringToBytes('hex', '0102ff'); + * ``` + */ +export const stringToBytes = (type: CoderType, str: string): TRet => { + // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors. + if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError); + if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string'); + return CODERS[type].decode(str) as TRet; +}; +/** + * Alias for `stringToBytes`. + * @deprecated Use {@link stringToBytes} or the codec directly instead. + * @param type - Codec name. + * @param str - Encoded string. + * @returns Decoded bytes. + * @example + * ```ts + * bytes('hex', '0102ff'); + * ``` + */ +export const bytes: (type: CoderType, str: string) => TRet = stringToBytes; diff --git a/node_modules/@scure/base/package.json b/node_modules/@scure/base/package.json new file mode 100644 index 0000000..9da56a7 --- /dev/null +++ b/node_modules/@scure/base/package.json @@ -0,0 +1,62 @@ +{ + "name": "@scure/base", + "version": "2.2.0", + "description": "Secure, audited & 0-dep implementation of base64, bech32, base58, base32 & base16", + "files": [ + "index.js", + "index.js.map", + "index.d.ts", + "index.d.ts.map", + "index.ts" + ], + "devDependencies": { + "@noble/hashes": "2.2.0", + "@paulmillr/jsbt": "0.5.0", + "@types/node": "25.3.0", + "fast-check": "4.2.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "bench": "node test/benchmark/index.ts", + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npx --no @paulmillr/jsbt check package.json", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "format": "prettier --write index.ts test/*.test.ts", + "test": "node test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts && deno test/deno.ts", + "test:node20": "cd test; npx tsc; node compiled/test/index.js" + }, + "keywords": [ + "bech32", + "bech32m", + "base64", + "base58", + "base32", + "base16", + "rfc4648", + "rfc3548", + "crockford", + "encode", + "encoder", + "base-x", + "base" + ], + "homepage": "https://paulmillr.com/noble/#scure", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/scure-base.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@scure/bip32/LICENSE b/node_modules/@scure/bip32/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/node_modules/@scure/bip32/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/bip32/README.md b/node_modules/@scure/bip32/README.md new file mode 100644 index 0000000..600a69a --- /dev/null +++ b/node_modules/@scure/bip32/README.md @@ -0,0 +1,165 @@ +# scure-bip32 + +Audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1. + +- 🔒 [Audited](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 📦 ESM +- ➰ Only 3 audited dependencies by the same author: + [noble-curves](https://github.com/paulmillr/noble-curves), + [noble-hashes](https://github.com/paulmillr/noble-hashes), + and [scure-base](https://github.com/paulmillr/scure-base) +- 🪶 18KB gzipped with all dependencies bundled + +Check out [scure-bip39](https://github.com/paulmillr/scure-bip39) if you need mnemonic phrases. +See [key-producer](https://github.com/paulmillr/micro-key-producer) if you need SLIP-0010/BIP32 ed25519 hdkey implementation. +Notice [Warnings about BIP32](#warnings-about-bip32). + +### This library belongs to _scure_ + +> **scure** — audited micro-libraries. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- Check out [homepage](https://paulmillr.com/noble/#scure) & all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer), + [sr25519](https://github.com/paulmillr/scure-sr25519), + [starknet](https://github.com/paulmillr/scure-starknet) + +## Usage + +> `npm install @scure/bip32` + +> `deno add jsr:@scure/bip32` + +This module exports a single class `HDKey`, which should be used like this: + +```ts +import { HDKey } from '@scure/bip32'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { randomBytes } from '@noble/hashes/utils.js'; + +const seed = randomBytes(32); +const root = HDKey.fromMasterSeed(seed); +const base58key = root.privateExtendedKey; +const restored = HDKey.fromExtendedKey(base58key); +const fromJson = HDKey.fromJSON({ xpriv: base58key }); +const child = fromJson.derive("m/0/2147483647'/1"); +const msgHash = sha256(new TextEncoder().encode('hello scure-bip32')); + +// props +[root.depth, root.index, root.chainCode]; +[restored.privateKey, restored.publicKey]; +const sig = child.sign(msgHash); +child.verify(msgHash, sig); +``` + +Note: `chainCode` property is essentially a private part +of a secret "master" key, it should be guarded from unauthorized access. + +The full API is: + +```ts +class HDKey { + public static HARDENED_OFFSET: number; + public static fromMasterSeed(seed: Uint8Array, versions: Versions): HDKey; + public static fromExtendedKey(base58key: string, versions: Versions): HDKey; + public static fromJSON(json: { xpriv: string }): HDKey; + + readonly versions: Versions; + readonly depth: number = 0; + readonly index: number = 0; + readonly chainCode: Uint8Array | null = null; + readonly parentFingerprint: number = 0; + + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + + derive(path: string): HDKey; + deriveChild(index: number): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; +} + +interface Versions { + private: number; + public: number; +} +``` + +The module implements [bip32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) standard: +check it out for additional documentation. + +The implementation is loosely based on cryptocoinjs/hdkey, [which has MIT License](#LICENSE). + +## Warnings about BIP32 + +BIP32 is a bad standard. It would be great if we've had something better. + +- Network IDs (different currencies) are taken from a single GitHub document + called SLIP-0044 +- There were new projects, which did not yet have SLIP. Exchanges added support of + those projects to their cold wallets. Then after the projects were added to SLIP, + the exchanges were required to re-generate their cold wallets - a complicated task +- BIP32 is unusable for many different elliptic curves. For example, ETH2 uses bls12-381 + curve, and with bip32 54% of generated keys would be invalid. So, they’re using much better + BLS-only EIP-2333 as a replacement. +- It’s easy to shoot yourself in foot with non-hardened keys, which + could allow simple de-anonimization of all addresses + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/scure-bip32/compare/2.2.0..main) +- at version 1.0.1, in Jan 2022, independently, by [cure53](https://cure53.de) + - PDFs: [online](https://cure53.de/pentest-report_hashing-libs.pdf), [offline](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - [Changes since audit](https://github.com/paulmillr/scure-bip32/compare/1.0.0..main). + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography). +At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), +it was extracted to a separate package called `micro-bip32`. +After the audit we've decided to use `@scure` NPM namespace for security. + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there are 3 dependencies; and a few dev dependencies: + +- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality +- [noble-curves](https://github.com/paulmillr/noble-curves) provides ECDSA +- [scure-base](https://github.com/paulmillr/scure-base) provides base58 +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run build:release` will build single file + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/node_modules/@scure/bip32/index.d.ts b/node_modules/@scure/bip32/index.d.ts new file mode 100644 index 0000000..b7b15dd --- /dev/null +++ b/node_modules/@scure/bip32/index.d.ts @@ -0,0 +1,75 @@ +import { type TArg, type TRet } from '@noble/hashes/utils.js'; +/** Network-specific BIP32 version bytes. */ +export interface Versions { + /** 4-byte version used when serializing private extended keys. */ + private: number; + /** 4-byte version used when serializing public extended keys. */ + public: number; +} +/** Hardened child index offset from BIP32. */ +export declare const HARDENED_OFFSET: number; +interface HDKeyOpt { + versions?: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode?: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array; +} +/** + * HDKey from BIP32 + * @param opt - Node fields used to construct one HDKey instance. + * @example + * ```js + * import { HDKey } from '@scure/bip32'; + * import { randomBytes } from '@noble/hashes/utils.js'; + * + * const seed = randomBytes(32); + * const root = HDKey.fromMasterSeed(seed); + * const account0 = root.derive("m/0/1'"); + * account0.publicKey; + * ``` + */ +export declare class HDKey { + get fingerprint(): number; + get identifier(): Uint8Array | undefined; + get pubKeyHash(): Uint8Array | undefined; + get privateKey(): Uint8Array | null; + get publicKey(): Uint8Array | null; + get privateExtendedKey(): string; + get publicExtendedKey(): string; + static fromMasterSeed(seed: Uint8Array, versions?: Versions): HDKey; + static fromExtendedKey(base58key: string, versions?: Versions): HDKey; + static fromJSON(json: { + xpriv: string; + }): HDKey; + readonly versions: Versions; + readonly depth: number; + readonly index: number; + readonly chainCode: Uint8Array | null; + readonly parentFingerprint: number; + private _privateKey?; + private _publicKey?; + private pubHash; + constructor(opt: HDKeyOpt); + derive(path: string): HDKey; + /** + * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it. + */ + deriveChild(index: number, _I?: Uint8Array): HDKey; + sign(hash: Uint8Array): Uint8Array; + verify(hash: Uint8Array, signature: Uint8Array): boolean; + wipePrivateData(): this; + toJSON(): { + xpriv: string; + xpub: string; + }; + private serialize; +} +type Tests = Readonly<{ + deriveChildWithI(key: TArg, index: number, I: TArg): TRet; +}>; +export declare const __TESTS: TRet; +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/index.d.ts.map b/node_modules/@scure/bip32/index.d.ts.map new file mode 100644 index 0000000..fa399e1 --- /dev/null +++ b/node_modules/@scure/bip32/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AA4BA,OAAO,EAAmC,KAAK,IAAI,EAAE,KAAK,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAU/F,4CAA4C;AAC5C,MAAM,WAAW,QAAQ;IACvB,kEAAkE;IAClE,OAAO,EAAE,MAAM,CAAC;IAChB,iEAAiE;IACjE,MAAM,EAAE,MAAM,CAAC;CAChB;AAGD,8CAA8C;AAC9C,eAAO,MAAM,eAAe,EAAE,MAAmB,CAAC;AAclD,UAAU,QAAQ;IAChB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,SAAS,CAAC,EAAE,UAAU,CAAC;IACvB,SAAS,CAAC,EAAE,UAAU,CAAC;IACvB,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAED;;;;;;;;;;;;;GAaG;AACH,qBAAa,KAAK;IAChB,IAAI,WAAW,IAAI,MAAM,CAKxB;IACD,IAAI,UAAU,IAAI,UAAU,GAAG,SAAS,CAEvC;IACD,IAAI,UAAU,IAAI,UAAU,GAAG,SAAS,CAEvC;IAGD,IAAI,UAAU,IAAI,UAAU,GAAG,IAAI,CAElC;IACD,IAAI,SAAS,IAAI,UAAU,GAAG,IAAI,CAEjC;IACD,IAAI,kBAAkB,IAAI,MAAM,CAQ/B;IACD,IAAI,iBAAiB,IAAI,MAAM,CAK9B;IAED,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,UAAU,EAAE,QAAQ,GAAE,QAA2B,GAAG,KA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newline at end of file diff --git a/node_modules/@scure/bip32/index.js b/node_modules/@scure/bip32/index.js new file mode 100644 index 0000000..8e49612 --- /dev/null +++ b/node_modules/@scure/bip32/index.js @@ -0,0 +1,313 @@ +/** + * BIP32 hierarchical deterministic (HD) wallets over secp256k1. + * @module + * @example + * ```js + * import { HDKey } from "@scure/bip32"; + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { randomBytes } from '@noble/hashes/utils.js'; + * const seed = randomBytes(32); + * const root = HDKey.fromMasterSeed(seed); + * const base58key = root.privateExtendedKey; + * const restored = HDKey.fromExtendedKey(base58key); + * const fromJson = HDKey.fromJSON({ xpriv: base58key }); + * const child = fromJson.derive("m/0/2147483647'/1"); + * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32')); + * + * // props + * [root.depth, root.index, root.chainCode]; + * [restored.privateKey, restored.publicKey]; + * const sig = child.sign(msgHash); + * child.verify(msgHash, sig); + * ``` + */ +/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { secp256k1 as secp } from '@noble/curves/secp256k1.js'; +import { hmac } from '@noble/hashes/hmac.js'; +import { ripemd160 } from '@noble/hashes/legacy.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes, createView } from '@noble/hashes/utils.js'; +import { createBase58check } from '@scure/base'; +const Point = /* @__PURE__ */ (() => secp.Point)(); +const Fn = /* @__PURE__ */ (() => Point.Fn)(); +const base58check = /* @__PURE__ */ createBase58check(sha256); +const MASTER_SECRET = /* @__PURE__ */ (() => { + return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0)); +})(); +const BITCOIN_VERSIONS = { private: 0x0488ade4, public: 0x0488b21e }; +/** Hardened child index offset from BIP32. */ +export const HARDENED_OFFSET = 0x80000000; +const hash160 = (data) => ripemd160(sha256(data)); +const fromU32 = (data) => createView(data).getUint32(0, false); +const toU32 = (n) => { + if (typeof n !== 'number') + throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n); + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) + throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n); + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; +/** + * HDKey from BIP32 + * @param opt - Node fields used to construct one HDKey instance. + * @example + * ```js + * import { HDKey } from '@scure/bip32'; + * import { randomBytes } from '@noble/hashes/utils.js'; + * + * const seed = randomBytes(32); + * const root = HDKey.fromMasterSeed(seed); + * const account0 = root.derive("m/0/1'"); + * account0.publicKey; + * ``` + */ +export class HDKey { + get fingerprint() { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + // Returns the live private key buffer for this instance. + // Copy it first if you need an immutable snapshot. + get privateKey() { + return this._privateKey || null; + } + get publicKey() { + return this._publicKey || null; + } + get privateExtendedKey() { + const priv = this._privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))); + } + get publicExtendedKey() { + if (!this._publicKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this._publicKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + abytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new RangeError('HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' + + seed.length); + } + const I = hmac(sha512, MASTER_SECRET, seed); + const privateKey = I.slice(0, 32); + const chainCode = I.slice(32); + return new HDKey({ versions, chainCode, privateKey }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + const keyBuffer = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } + else { + return new HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return HDKey.fromExtendedKey(json.xpriv); + } + versions; + depth = 0; + index = 0; + chainCode = null; + parentFingerprint = 0; + _privateKey; + _publicKey; + pubHash; + constructor(opt) { + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (this.depth > 255) { + throw new Error('HDKey: depth exceeds the serializable value 255'); + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidSecretKey(opt.privateKey)) + throw new Error('Invalid private key'); + // Don't alias caller-owned secret buffers. + this._privateKey = Uint8Array.from(opt.privateKey); + this._publicKey = secp.getPublicKey(this._privateKey, true); + } + else if (opt.publicKey) { + this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point + } + else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this._publicKey); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + // tslint:disable-next-line + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + const m1 = m && m[1]; + if (!m || m.length !== 3 || typeof m1 !== 'string') + throw new Error('invalid child index: ' + c); + let idx = +m1; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + // hardened key + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + /** + * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it. + */ + deriveChild(index, _I) { + if (!this._publicKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + // Hardened + const priv = this._privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + // Hardened child: 0x00 || ser256(kpar) || ser32(index) + data = concatBytes(Uint8Array.of(0), priv, data); + } + else { + // Normal child: serP(point(kpar)) || ser32(index) + data = concatBytes(this._publicKey, data); + } + const out = _I || hmac(sha512, this.chainCode, data); + abytes(out, 64); + const childTweak = out.slice(0, 32); + const chainCode = out.slice(32); + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + // Fail early instead of re-trying different index + if (opt.depth > 255) { + throw new Error('HDKey: depth exceeds the serializable value 255'); + } + try { + const ctweak = Fn.fromBytes(childTweak); + // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0. + // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity. + // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n. + if (this._privateKey) { + const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak); + if (!Fn.isValidNot0(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = Fn.toBytes(added); + } + else { + const point = Point.fromBytes(this._publicKey); + const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak)); + // Cryptographically impossible: hmac-sha512 preimage would need to be found + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toBytes(true); + } + return new HDKey(opt); + } + catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this._privateKey) { + throw new Error('No privateKey set!'); + } + abytes(hash, 32); + return secp.sign(hash, this._privateKey, { prehash: false }); + } + verify(hash, signature) { + abytes(hash, 32); + abytes(signature, 64); + if (!this._publicKey) { + throw new Error('No publicKey set!'); + } + return secp.verify(signature, hash, this._publicKey, { prehash: false }); + } + wipePrivateData() { + if (this._privateKey) { + this._privateKey.fill(0); + this._privateKey = undefined; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + abytes(key, 33); + // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +} +export const __TESTS = /* @__PURE__ */ Object.freeze({ + deriveChildWithI(key, index, I) { + // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs. + return key.deriveChild(index, I); + }, +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip32/index.js.map b/node_modules/@scure/bip32/index.js.map new file mode 100644 index 0000000..d4e31ac --- /dev/null +++ b/node_modules/@scure/bip32/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,yFAAyF;AACzF,OAAO,EAAE,SAAS,IAAI,IAAI,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AACpD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAwB,MAAM,wBAAwB,CAAC;AAC/F,OAAO,EAAE,iBAAiB,EAAE,MAAM,aA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AC;IAEO,SAAS,CAAC,OAAe,EAAE,GAAe;QAChD,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;QACtC,CAAC;QACD,MAAM,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;QAChB,+EAA+E;QAC/E,OAAO,WAAW,CAChB,KAAK,CAAC,OAAO,CAAC,EACd,IAAI,UAAU,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAC5B,KAAK,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAC7B,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EACjB,IAAI,CAAC,SAAS,EACd,GAAG,CACJ,CAAC;IACJ,CAAC;CACF;AAMD,MAAM,CAAC,MAAM,OAAO,GAAgB,eAAe,CAAC,MAAM,CAAC,MAAM,CAAC;IAChE,gBAAgB,CAAC,GAAgB,EAAE,KAAa,EAAE,CAAmB;QACnE,4FAA4F;QAC5F,OAAQ,GAAa,CAAC,WAAW,CAAC,KAAK,EAAE,CAAe,CAAgB,CAAC;IAC3E,CAAC;CACF,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@scure/bip32/index.ts b/node_modules/@scure/bip32/index.ts new file mode 100644 index 0000000..576f7d3 --- /dev/null +++ b/node_modules/@scure/bip32/index.ts @@ -0,0 +1,353 @@ +/** + * BIP32 hierarchical deterministic (HD) wallets over secp256k1. + * @module + * @example + * ```js + * import { HDKey } from "@scure/bip32"; + * import { sha256 } from '@noble/hashes/sha2.js'; + * import { randomBytes } from '@noble/hashes/utils.js'; + * const seed = randomBytes(32); + * const root = HDKey.fromMasterSeed(seed); + * const base58key = root.privateExtendedKey; + * const restored = HDKey.fromExtendedKey(base58key); + * const fromJson = HDKey.fromJSON({ xpriv: base58key }); + * const child = fromJson.derive("m/0/2147483647'/1"); + * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32')); + * + * // props + * [root.depth, root.index, root.chainCode]; + * [restored.privateKey, restored.publicKey]; + * const sig = child.sign(msgHash); + * child.verify(msgHash, sig); + * ``` + */ +/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { secp256k1 as secp } from '@noble/curves/secp256k1.js'; +import { hmac } from '@noble/hashes/hmac.js'; +import { ripemd160 } from '@noble/hashes/legacy.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, concatBytes, createView, type TArg, type TRet } from '@noble/hashes/utils.js'; +import { createBase58check } from '@scure/base'; + +const Point = /* @__PURE__ */ (() => secp.Point)(); +const Fn = /* @__PURE__ */ (() => Point.Fn)(); +const base58check = /* @__PURE__ */ createBase58check(sha256); +const MASTER_SECRET = /* @__PURE__ */ (() => { + return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0)); +})(); + +/** Network-specific BIP32 version bytes. */ +export interface Versions { + /** 4-byte version used when serializing private extended keys. */ + private: number; + /** 4-byte version used when serializing public extended keys. */ + public: number; +} + +const BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e }; +/** Hardened child index offset from BIP32. */ +export const HARDENED_OFFSET: number = 0x80000000; + +const hash160 = (data: TArg) => ripemd160(sha256(data)); +const fromU32 = (data: TArg) => createView(data).getUint32(0, false); +const toU32 = (n: number): TRet => { + if (typeof n !== 'number') + throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n); + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) + throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n); + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; + +interface HDKeyOpt { + versions?: Versions; + depth?: number; + index?: number; + parentFingerprint?: number; + chainCode?: Uint8Array; + publicKey?: Uint8Array; + privateKey?: Uint8Array; +} + +/** + * HDKey from BIP32 + * @param opt - Node fields used to construct one HDKey instance. + * @example + * ```js + * import { HDKey } from '@scure/bip32'; + * import { randomBytes } from '@noble/hashes/utils.js'; + * + * const seed = randomBytes(32); + * const root = HDKey.fromMasterSeed(seed); + * const account0 = root.derive("m/0/1'"); + * account0.publicKey; + * ``` + */ +export class HDKey { + get fingerprint(): number { + if (!this.pubHash) { + throw new Error('No publicKey set!'); + } + return fromU32(this.pubHash); + } + get identifier(): Uint8Array | undefined { + return this.pubHash; + } + get pubKeyHash(): Uint8Array | undefined { + return this.pubHash; + } + // Returns the live private key buffer for this instance. + // Copy it first if you need an immutable snapshot. + get privateKey(): Uint8Array | null { + return this._privateKey || null; + } + get publicKey(): Uint8Array | null { + return this._publicKey || null; + } + get privateExtendedKey(): string { + const priv = this._privateKey; + if (!priv) { + throw new Error('No private key'); + } + return base58check.encode( + this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv)) + ); + } + get publicExtendedKey(): string { + if (!this._publicKey) { + throw new Error('No public key'); + } + return base58check.encode(this.serialize(this.versions.public, this._publicKey)); + } + + static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey { + abytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new RangeError( + 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' + + seed.length + ); + } + const I = hmac(sha512, MASTER_SECRET, seed); + const privateKey = I.slice(0, 32); + const chainCode = I.slice(32); + return new HDKey({ versions, chainCode, privateKey }); + } + + static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey { + // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + const keyBuffer: Uint8Array = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45), + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? 'private' : 'public']) { + throw new Error('Version mismatch'); + } + if (isPriv) { + return new HDKey({ ...opt, privateKey: key.slice(1) }); + } else { + return new HDKey({ ...opt, publicKey: key }); + } + } + + public static fromJSON(json: { xpriv: string }): HDKey { + return HDKey.fromExtendedKey(json.xpriv); + } + readonly versions: Versions; + readonly depth: number = 0; + readonly index: number = 0; + readonly chainCode: Uint8Array | null = null; + readonly parentFingerprint: number = 0; + private _privateKey?: Uint8Array; + private _publicKey?: Uint8Array; + private pubHash: Uint8Array | undefined; + + constructor(opt: HDKeyOpt) { + if (!opt || typeof opt !== 'object') { + throw new Error('HDKey.constructor must not be called directly'); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error('HDKey: zero depth with non-zero index/parent fingerprint'); + } + } + if (this.depth > 255) { + throw new Error('HDKey: depth exceeds the serializable value 255'); + } + if (opt.publicKey && opt.privateKey) { + throw new Error('HDKey: publicKey and privateKey at same time.'); + } + if (opt.privateKey) { + if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key'); + // Don't alias caller-owned secret buffers. + this._privateKey = Uint8Array.from(opt.privateKey); + this._publicKey = secp.getPublicKey(this._privateKey, true); + } else if (opt.publicKey) { + this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point + } else { + throw new Error('HDKey: no public or private key provided'); + } + this.pubHash = hash160(this._publicKey); + } + + derive(path: string): HDKey { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, '').split('/'); + // tslint:disable-next-line + let child: HDKey = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + const m1 = m && m[1]; + if (!m || m.length !== 3 || typeof m1 !== 'string') + throw new Error('invalid child index: ' + c); + let idx = +m1; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error('Invalid index'); + } + // hardened key + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + + /** + * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it. + */ + deriveChild(index: number, _I?: Uint8Array): HDKey { + if (!this._publicKey || !this.chainCode) { + throw new Error('No publicKey or chainCode set'); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + // Hardened + const priv = this._privateKey; + if (!priv) { + throw new Error('Could not derive hardened child key'); + } + // Hardened child: 0x00 || ser256(kpar) || ser32(index) + data = concatBytes(Uint8Array.of(0), priv, data); + } else { + // Normal child: serP(point(kpar)) || ser32(index) + data = concatBytes(this._publicKey, data); + } + const out = _I || hmac(sha512, this.chainCode, data); + abytes(out, 64); + const childTweak = out.slice(0, 32); + const chainCode = out.slice(32); + const opt: HDKeyOpt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index, + }; + // Fail early instead of re-trying different index + if (opt.depth! > 255) { + throw new Error('HDKey: depth exceeds the serializable value 255'); + } + try { + const ctweak = Fn.fromBytes(childTweak); + // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0. + // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity. + // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n. + if (this._privateKey) { + const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak); + if (!Fn.isValidNot0(added)) { + throw new Error('The tweak was out of range or the resulted private key is invalid'); + } + opt.privateKey = Fn.toBytes(added); + } else { + const point = Point.fromBytes(this._publicKey); + const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak)); + // Cryptographically impossible: hmac-sha512 preimage would need to be found + if (added.equals(Point.ZERO)) { + throw new Error('The tweak was equal to negative P, which made the result key invalid'); + } + opt.publicKey = added.toBytes(true); + } + return new HDKey(opt); + } catch (err) { + return this.deriveChild(index + 1); + } + } + + sign(hash: Uint8Array): Uint8Array { + if (!this._privateKey) { + throw new Error('No privateKey set!'); + } + abytes(hash, 32); + return secp.sign(hash, this._privateKey, { prehash: false }); + } + + verify(hash: Uint8Array, signature: Uint8Array): boolean { + abytes(hash, 32); + abytes(signature, 64); + if (!this._publicKey) { + throw new Error('No publicKey set!'); + } + return secp.verify(signature, hash, this._publicKey, { prehash: false }); + } + + wipePrivateData(): this { + if (this._privateKey) { + this._privateKey.fill(0); + this._privateKey = undefined; + } + return this; + } + toJSON(): { xpriv: string; xpub: string } { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey, + }; + } + + private serialize(version: number, key: Uint8Array) { + if (!this.chainCode) { + throw new Error('No chainCode set'); + } + abytes(key, 33); + // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33) + return concatBytes( + toU32(version), + new Uint8Array([this.depth]), + toU32(this.parentFingerprint), + toU32(this.index), + this.chainCode, + key + ); + } +} + +type Tests = Readonly<{ + deriveChildWithI(key: TArg, index: number, I: TArg): TRet; +}>; + +export const __TESTS: TRet = /* @__PURE__ */ Object.freeze({ + deriveChildWithI(key: TArg, index: number, I: TArg): TRet { + // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs. + return (key as HDKey).deriveChild(index, I as Uint8Array) as TRet; + }, +}); diff --git a/node_modules/@scure/bip32/package.json b/node_modules/@scure/bip32/package.json new file mode 100644 index 0000000..79e26f9 --- /dev/null +++ b/node_modules/@scure/bip32/package.json @@ -0,0 +1,61 @@ +{ + "name": "@scure/bip32", + "version": "2.2.0", + "description": "Secure, audited & minimal implementation of BIP32 hierarchical deterministic (HD) wallets over secp256k1", + "files": [ + "index.js", + "index.js.map", + "index.d.ts", + "index.d.ts.map", + "index.ts" + ], + "dependencies": { + "@noble/curves": "2.2.0", + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npx --no @paulmillr/jsbt check package.json", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "format": "prettier --write 'index.ts' 'test/*.test.ts'", + "test": "node --experimental-strip-types --no-warnings test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.ts" + }, + "keywords": [ + "bip32", + "hierarchical", + "deterministic", + "hd key", + "bip0032", + "bip-32", + "bip39", + "micro", + "scure", + "mnemonic", + "phrase", + "code" + ], + "homepage": "https://paulmillr.com/noble/#scure", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/scure-bip32.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@scure/bip39/LICENSE b/node_modules/@scure/bip39/LICENSE new file mode 100644 index 0000000..68222b8 --- /dev/null +++ b/node_modules/@scure/bip39/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the “Software”), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/node_modules/@scure/bip39/README.md b/node_modules/@scure/bip39/README.md new file mode 100644 index 0000000..48433e7 --- /dev/null +++ b/node_modules/@scure/bip39/README.md @@ -0,0 +1,141 @@ +# scure-bip39 + +Audited & minimal JS implementation of [BIP39 mnemonic phrases](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). + +- 🔒 [**Audited**](#security) by an independent security firm +- 🔻 Tree-shakeable: unused code is excluded from your builds +- 🥈 Two implementations: pure JS or friendly WebCrypto wrapper +- ➰ Only 2 audited dependencies by the same author: + [noble-hashes](https://github.com/paulmillr/noble-hashes) and [scure-base](https://github.com/paulmillr/scure-base) +- 🪶 14KB (gzipped) with one wordlist, 79KB with all of them: much smaller than similar libraries + +Check out [scure-bip32](https://github.com/paulmillr/scure-bip32) if you need +hierarchical deterministic wallets ("HD Wallets"). + +### This library belongs to _scure_ + +> **scure** — audited micro-libraries. + +- Zero or minimal dependencies +- Highly readable TypeScript / JS code +- PGP-signed releases and transparent NPM builds +- Check out [homepage](https://paulmillr.com/noble/#scure) & all libraries: + [base](https://github.com/paulmillr/scure-base), + [bip32](https://github.com/paulmillr/scure-bip32), + [bip39](https://github.com/paulmillr/scure-bip39), + [btc-signer](https://github.com/paulmillr/scure-btc-signer), + [sr25519](https://github.com/paulmillr/scure-sr25519), + [starknet](https://github.com/paulmillr/scure-starknet) + +## Usage + +> `npm install @scure/bip39` + +> `deno add jsr:@scure/bip39` + +We don't provide source maps. +Wordlists are large, including source maps would double package size. + +```js +import * as bip39 from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english.js'; + +// Generate x random words. Uses Cryptographically-Secure Random Number Generator. +const mn = bip39.generateMnemonic(wordlist); +console.log(mn); + +// You can customize the strength of the generated mnemonic by passing a value between 128 and 256 as the second argument to the generateMnemonic function. +// This value must be a multiple of 32. Default is 128. +const mn256 = bip39.generateMnemonic(wordlist, 256); +console.log(mn256); + +// Reversible: Converts mnemonic string to raw entropy in form of byte array. +const ent = bip39.mnemonicToEntropy(mn, wordlist); + +// Reversible: Converts raw entropy in form of byte array to mnemonic string. +bip39.entropyToMnemonic(ent, wordlist); + +// Validates mnemonic for being 12-24 words contained in `wordlist`. +bip39.validateMnemonic(mn, wordlist); +bip39.validateMnemonic(mn256, wordlist); + +// Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. +const seed1 = await bip39.mnemonicToSeed(mn, 'password'); +const seed2 = bip39.mnemonicToSeedSync(mn, 'password'); +const seed3 = await bip39.mnemonicToSeedWebcrypto(mn, 'password'); // Native, WebCrypto version. +``` + +This submodule contains the word lists defined by BIP39 for Czech, English, French, Italian, Japanese, Korean, Portuguese, Simplified and Traditional Chinese, and Spanish. These are not imported by default, as that would increase bundle sizes too much. Instead, you should import and use them explicitly. + +```typescript +function generateMnemonic(wordlist: string[], strength?: number): string; +function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; +function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; +function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise; +function mnemonicToSeedSync(mnemonic: string, passphrase?: string): Uint8Array; +function mnemonicToSeedWebcrypto(mnemonic: string, passphrase?: string): Promise; +``` + +All wordlists (**warning: non-english wordlists are officially discouraged by bip39**): + +```typescript +import { wordlist as czech } from '@scure/bip39/wordlists/czech.js'; +import { wordlist as english } from '@scure/bip39/wordlists/english.js'; +import { wordlist as french } from '@scure/bip39/wordlists/french.js'; +import { wordlist as italian } from '@scure/bip39/wordlists/italian.js'; +import { wordlist as japanese } from '@scure/bip39/wordlists/japanese.js'; +import { wordlist as korean } from '@scure/bip39/wordlists/korean.js'; +import { wordlist as portuguese } from '@scure/bip39/wordlists/portuguese.js'; +import { wordlist as simplifiedChinese } from '@scure/bip39/wordlists/simplified-chinese.js'; +import { wordlist as spanish } from '@scure/bip39/wordlists/spanish.js'; +import { wordlist as traditionalChinese } from '@scure/bip39/wordlists/traditional-chinese.js'; +``` + +## Security + +The library has been audited: + +- at version 2.2.0, in Apr 2026, by ourselves (self-audited) + - Scope: everything + - [Changes since audit](https://github.com/paulmillr/scure-bip39/compare/2.2.0..main) +- at version 1.0.0, in Jan 2022, by [cure53](https://cure53.de) + - PDFs: [online](https://cure53.de/pentest-report_hashing-libs.pdf), [offline](./audit/2022-01-05-cure53-audit-nbl2.pdf) + - [Changes since audit](https://github.com/paulmillr/scure-bip39/compare/1.0.0..main). + - The audit has been funded by [Ethereum Foundation](https://ethereum.org/en/) with help of [Nomic Labs](https://nomiclabs.io) + +The library was initially developed for [js-ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography). +At commit [ae00e6d7](https://github.com/ethereum/js-ethereum-cryptography/commit/ae00e6d7d24fb3c76a1c7fe10039f6ecd120b77e), +it was extracted to a separate package called `micro-bip39`. +After the audit we've decided to use `@scure` NPM namespace for security. + +To audit wordlist content, run `node scripts/fetch-wordlist.js`. + +### Supply chain security + +- **Commits** are signed with PGP keys to prevent forgery. Be sure to verify the commit signatures +- **Releases** are made transparently through token-less GitHub CI and Trusted Publishing. Be sure to verify the [provenance logs](https://docs.npmjs.com/generating-provenance-statements) for authenticity. +- **Rare releasing** is practiced to minimize the need for re-audits by end-users. +- **Dependencies** are minimized and strictly pinned to reduce supply-chain risk. + - We use as few dependencies as possible. + - Version ranges are locked, and changes are checked with npm-diff. +- **Dev dependencies** are excluded from end-user installs; they’re only used for development and build steps. + +For this package, there are 2 dependencies; and a few dev dependencies: + +- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality +- [scure-base](https://github.com/paulmillr/scure-base) provides low-level wordlist utilities +- jsbt is used for benchmarking / testing / build tooling and developed by the same author +- prettier, fast-check and typescript are used for code quality / test generation / ts compilation + +## Contributing & testing + +- `npm install && npm run build && npm test` will build the code and run tests. +- `npm run lint` / `npm run format` will run linter / fix linter issues. +- `npm run build:release` will build single file + +## License + +[MIT License](./LICENSE) + +Copyright (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) diff --git a/node_modules/@scure/bip39/index.d.ts b/node_modules/@scure/bip39/index.d.ts new file mode 100644 index 0000000..70c1e66 --- /dev/null +++ b/node_modules/@scure/bip39/index.d.ts @@ -0,0 +1,130 @@ +import { type TArg, type TRet } from '@noble/hashes/utils.js'; +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist - Imported wordlist for a specific language. + * @param strength - Mnemonic strength, from 128 to 256 bits. + * @returns 12-24 word mnemonic phrase. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Generate a new English mnemonic. + * ```ts + * import { generateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnemonic = generateMnemonic(wordlist, 128); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export declare function generateMnemonic(wordlist: string[], strength?: number): string; +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns Raw entropy bytes. + * @throws If the mnemonic shape or checksum is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode a mnemonic back into its original entropy bytes. + * ```ts + * import { mnemonicToEntropy } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const entropy = mnemonicToEntropy(mnem, wordlist); + * // Produces the original 16-byte entropy payload. + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + * ``` + */ +export declare function mnemonicToEntropy(mnemonic: string, wordlist: string[]): TRet; +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy - Byte array. + * @param wordlist - Imported wordlist for a specific language. + * @returns 12-24 words. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Convert raw entropy into an English mnemonic. + * ```ts + * import { entropyToMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * const mnemonic = entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export declare function entropyToMnemonic(entropy: TArg, wordlist: string[]): string; +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns `true` when mnemonic checksum and words are valid. + * @example + * Validate one English mnemonic. + * ```ts + * import { validateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ok = validateMnemonic( + * 'legal winner thank year wave sausage worth useful legal winner thank yellow', + * wordlist + * ); + * // => true + * ``` + */ +export declare function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the async PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeed(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export declare function mnemonicToSeed(mnemonic: string, passphrase?: string): Promise>; +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the sync PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = mnemonicToSeedSync(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export declare function mnemonicToSeedSync(mnemonic: string, passphrase?: string): TRet; +/** + * Uses native, built-in functionality, provided by globalThis.crypto. + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed with the native WebCrypto PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeedWebcrypto(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export declare function mnemonicToSeedWebcrypto(mnemonic: string, passphrase?: string): Promise>; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/index.js b/node_modules/@scure/bip39/index.js new file mode 100644 index 0000000..daa93b4 --- /dev/null +++ b/node_modules/@scure/bip39/index.js @@ -0,0 +1,224 @@ +/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, anumber, randomBytes } from '@noble/hashes/utils.js'; +import { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js'; +import { utils as baseUtils } from '@scure/base'; +// Japanese wordlist +// The canonical BIP-39 Japanese wordlist starts with あいこくしん. +// Use that sentinel so generated phrases use U+3000 ideographic spaces. +const isJapanese = (wordlist) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; +// Normalization replaces equivalent sequences of characters +// so that any two texts that are equivalent will be reduced +// to the same sequence of code points, called the normal form of the original text. +// https://tonsky.me/blog/unicode/#why-is-a---- +// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences. +// It also applies NFKD to the "mnemonic" + passphrase salt. +function nfkd(str) { + if (typeof str !== 'string') + throw new TypeError('invalid mnemonic type: ' + typeof str); + return str.normalize('NFKD'); +} +// BIP-39 mnemonics are consumed in NFKD form. +// They must contain 12, 15, 18, 21, or 24 words before checksum validation. +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} +// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes. +function aentropy(ent) { + abytes(ent); + if (![16, 20, 24, 28, 32].includes(ent.length)) + throw new RangeError('invalid entropy length'); +} +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist - Imported wordlist for a specific language. + * @param strength - Mnemonic strength, from 128 to 256 bits. + * @returns 12-24 word mnemonic phrase. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Generate a new English mnemonic. + * ```ts + * import { generateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnemonic = generateMnemonic(wordlist, 128); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export function generateMnemonic(wordlist, strength = 128) { + anumber(strength); + if (strength % 32 !== 0 || strength > 256) + throw new RangeError('Invalid entropy'); + return entropyToMnemonic(randomBytes(strength / 8), wordlist); +} +const calcChecksum = (entropy) => { + // Checksum is ent.length/4 bits long + const bitsLeft = 8 - entropy.length / 4; + // Zero rightmost "bitsLeft" bits in byte + // For example: bitsLeft=4 val=10111101 -> 10110000 + return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]); +}; +function getCoder(wordlist) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new TypeError('Wordlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') + throw new TypeError('wordlist: non-string element: ' + i); + }); + // BIP-39 appends checksum bits to entropy. + // It then splits the bitstream into 11-bit indexes for a 2048-word list. + return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist)); +} +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns Raw entropy bytes. + * @throws If the mnemonic shape or checksum is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode a mnemonic back into its original entropy bytes. + * ```ts + * import { mnemonicToEntropy } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const entropy = mnemonicToEntropy(mnem, wordlist); + * // Produces the original 16-byte entropy payload. + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + * ``` + */ +export function mnemonicToEntropy(mnemonic, wordlist) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + aentropy(entropy); + return entropy; +} +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy - Byte array. + * @param wordlist - Imported wordlist for a specific language. + * @returns 12-24 words. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Convert raw entropy into an English mnemonic. + * ```ts + * import { entropyToMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * const mnemonic = entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export function entropyToMnemonic(entropy, wordlist) { + aentropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns `true` when mnemonic checksum and words are valid. + * @example + * Validate one English mnemonic. + * ```ts + * import { validateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ok = validateMnemonic( + * 'legal winner thank year wave sausage worth useful legal winner thank yellow', + * wordlist + * ); + * // => true + * ``` + */ +export function validateMnemonic(mnemonic, wordlist) { + try { + mnemonicToEntropy(mnemonic, wordlist); + } + catch (e) { + return false; + } + return true; +} +// BIP-39 salts PBKDF2 with the UTF-8 NFKD string "mnemonic" + passphrase. +const psalt = (passphrase) => nfkd('mnemonic' + passphrase); +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the async PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeed(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +// BIP-39 seed derivation is independent from mnemonic generation. +// These helpers normalize the phrase but do not verify checksum or wordlist membership. +export function mnemonicToSeed(mnemonic, passphrase = '') { + return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }); +} +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the sync PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = mnemonicToSeedSync(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export function mnemonicToSeedSync(mnemonic, passphrase = '') { + return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }); +} +/** + * Uses native, built-in functionality, provided by globalThis.crypto. + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed with the native WebCrypto PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeedWebcrypto(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') { + return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/package.json b/node_modules/@scure/bip39/package.json new file mode 100644 index 0000000..bbf2b79 --- /dev/null +++ b/node_modules/@scure/bip39/package.json @@ -0,0 +1,74 @@ +{ + "name": "@scure/bip39", + "version": "2.2.0", + "description": "Secure, audited & minimal implementation of BIP39 mnemonic phrases", + "files": [ + "index.js", + "index.d.ts", + "wordlists/*.js", + "wordlists/*.d.ts", + "src/index.ts" + ], + "dependencies": { + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "devDependencies": { + "@paulmillr/jsbt": "0.5.0", + "prettier": "3.6.2", + "typescript": "6.0.2" + }, + "scripts": { + "build": "tsc", + "build:release": "npx --no @paulmillr/jsbt esbuild test/build", + "check": "npx --no @paulmillr/jsbt check package.json", + "check:readme": "npx --no @paulmillr/jsbt readme package.json", + "check:treeshake": "npx --no @paulmillr/jsbt treeshake package.json test/build/out-treeshake", + "check:jsdoc": "npx --no @paulmillr/jsbt tsdoc package.json", + "format": "prettier --write 'src/**/*.ts' 'test/*.test.ts' 'test/scripts/*.js'", + "bench": "node test/benchmark.js", + "test": "node --experimental-strip-types --no-warnings test/index.ts", + "test:bun": "bun test/index.ts", + "test:deno": "deno --allow-env --allow-read test/index.js", + "test:node20": "cd test; npx tsc; node compiled/test/index.js", + "fetch-wordlist": "./test/scripts/fetch-wordlist.js" + }, + "exports": { + ".": "./index.js", + "./wordlists/czech.js": "./wordlists/czech.js", + "./wordlists/english.js": "./wordlists/english.js", + "./wordlists/french.js": "./wordlists/french.js", + "./wordlists/italian.js": "./wordlists/italian.js", + "./wordlists/japanese.js": "./wordlists/japanese.js", + "./wordlists/korean.js": "./wordlists/korean.js", + "./wordlists/portuguese.js": "./wordlists/portuguese.js", + "./wordlists/simplified-chinese.js": "./wordlists/simplified-chinese.js", + "./wordlists/spanish.js": "./wordlists/spanish.js", + "./wordlists/traditional-chinese.js": "./wordlists/traditional-chinese.js" + }, + "keywords": [ + "bip39", + "mnemonic", + "phrase", + "code", + "bip0039", + "bip-39", + "wordlist", + "scure", + "noble", + "bitcoin" + ], + "homepage": "https://paulmillr.com/noble/#scure", + "funding": "https://paulmillr.com/funding/", + "repository": { + "type": "git", + "url": "git+https://github.com/paulmillr/scure-bip39.git" + }, + "type": "module", + "main": "index.js", + "module": "index.js", + "types": "index.d.ts", + "sideEffects": false, + "author": "Paul Miller (https://paulmillr.com)", + "license": "MIT" +} diff --git a/node_modules/@scure/bip39/src/index.ts b/node_modules/@scure/bip39/src/index.ts new file mode 100644 index 0000000..953a78c --- /dev/null +++ b/node_modules/@scure/bip39/src/index.ts @@ -0,0 +1,238 @@ +/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */ +import { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js'; +import { sha256, sha512 } from '@noble/hashes/sha2.js'; +import { abytes, anumber, randomBytes, type TArg, type TRet } from '@noble/hashes/utils.js'; +import { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js'; +import { utils as baseUtils } from '@scure/base'; + +// Japanese wordlist +// The canonical BIP-39 Japanese wordlist starts with あいこくしん. +// Use that sentinel so generated phrases use U+3000 ideographic spaces. +const isJapanese = (wordlist: string[]) => wordlist[0] === '\u3042\u3044\u3053\u304f\u3057\u3093'; + +// Normalization replaces equivalent sequences of characters +// so that any two texts that are equivalent will be reduced +// to the same sequence of code points, called the normal form of the original text. +// https://tonsky.me/blog/unicode/#why-is-a---- +// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences. +// It also applies NFKD to the "mnemonic" + passphrase salt. +function nfkd(str: string) { + if (typeof str !== 'string') throw new TypeError('invalid mnemonic type: ' + typeof str); + return str.normalize('NFKD'); +} + +// BIP-39 mnemonics are consumed in NFKD form. +// They must contain 12, 15, 18, 21, or 24 words before checksum validation. +function normalize(str: string) { + const norm = nfkd(str); + const words = norm.split(' '); + if (![12, 15, 18, 21, 24].includes(words.length)) throw new Error('Invalid mnemonic'); + return { nfkd: norm, words }; +} + +// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes. +function aentropy(ent: TArg) { + abytes(ent); + if (![16, 20, 24, 28, 32].includes(ent.length)) throw new RangeError('invalid entropy length'); +} + +/** + * Generate x random words. Uses Cryptographically-Secure Random Number Generator. + * @param wordlist - Imported wordlist for a specific language. + * @param strength - Mnemonic strength, from 128 to 256 bits. + * @returns 12-24 word mnemonic phrase. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Generate a new English mnemonic. + * ```ts + * import { generateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnemonic = generateMnemonic(wordlist, 128); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export function generateMnemonic(wordlist: string[], strength: number = 128): string { + anumber(strength); + if (strength % 32 !== 0 || strength > 256) throw new RangeError('Invalid entropy'); + return entropyToMnemonic(randomBytes(strength / 8), wordlist); +} + +const calcChecksum = (entropy: TArg) => { + // Checksum is ent.length/4 bits long + const bitsLeft = 8 - entropy.length / 4; + // Zero rightmost "bitsLeft" bits in byte + // For example: bitsLeft=4 val=10111101 -> 10110000 + return new Uint8Array([(sha256(entropy)[0]! >> bitsLeft) << bitsLeft]); +}; + +function getCoder(wordlist: string[]) { + if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string') + throw new TypeError('Wordlist: expected array of 2048 strings'); + wordlist.forEach((i) => { + if (typeof i !== 'string') throw new TypeError('wordlist: non-string element: ' + i); + }); + // BIP-39 appends checksum bits to entropy. + // It then splits the bitstream into 11-bit indexes for a 2048-word list. + return baseUtils.chain( + baseUtils.checksum(1, calcChecksum), + baseUtils.radix2(11, true), + baseUtils.alphabet(wordlist) + ); +} + +/** + * Reversible: Converts mnemonic string to raw entropy in form of byte array. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns Raw entropy bytes. + * @throws If the mnemonic shape or checksum is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Decode a mnemonic back into its original entropy bytes. + * ```ts + * import { mnemonicToEntropy } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const entropy = mnemonicToEntropy(mnem, wordlist); + * // Produces the original 16-byte entropy payload. + * new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]) + * ``` + */ +export function mnemonicToEntropy(mnemonic: string, wordlist: string[]): TRet { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist).decode(words); + aentropy(entropy); + return entropy as TRet; +} + +/** + * Reversible: Converts raw entropy in form of byte array to mnemonic string. + * @param entropy - Byte array. + * @param wordlist - Imported wordlist for a specific language. + * @returns 12-24 words. + * @throws On wrong argument types. {@link TypeError} + * @throws On wrong argument ranges or values. {@link RangeError} + * @example + * Convert raw entropy into an English mnemonic. + * ```ts + * import { entropyToMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ent = new Uint8Array([ + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, + * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f + * ]); + * const mnemonic = entropyToMnemonic(ent, wordlist); + * // 'legal winner thank year wave sausage worth useful legal winner thank yellow' + * ``` + */ +export function entropyToMnemonic(entropy: TArg, wordlist: string[]): string { + aentropy(entropy); + const words = getCoder(wordlist).encode(entropy); + return words.join(isJapanese(wordlist) ? '\u3000' : ' '); +} + +/** + * Validates mnemonic for being 12-24 words contained in `wordlist`. + * @param mnemonic - 12-24 words. + * @param wordlist - Imported wordlist for a specific language. + * @returns `true` when mnemonic checksum and words are valid. + * @example + * Validate one English mnemonic. + * ```ts + * import { validateMnemonic } from '@scure/bip39'; + * import { wordlist } from '@scure/bip39/wordlists/english.js'; + * const ok = validateMnemonic( + * 'legal winner thank year wave sausage worth useful legal winner thank yellow', + * wordlist + * ); + * // => true + * ``` + */ +export function validateMnemonic(mnemonic: string, wordlist: string[]): boolean { + try { + mnemonicToEntropy(mnemonic, wordlist); + } catch (e) { + return false; + } + return true; +} + +// BIP-39 salts PBKDF2 with the UTF-8 NFKD string "mnemonic" + passphrase. +const psalt = (passphrase: string) => nfkd('mnemonic' + passphrase); + +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the async PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeed(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +// BIP-39 seed derivation is independent from mnemonic generation. +// These helpers normalize the phrase but do not verify checksum or wordlist membership. +export function mnemonicToSeed(mnemonic: string, passphrase = ''): Promise> { + return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }) as Promise>; +} + +/** + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed from a mnemonic with the sync PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = mnemonicToSeedSync(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export function mnemonicToSeedSync(mnemonic: string, passphrase = ''): TRet { + return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }) as TRet; +} + +/** + * Uses native, built-in functionality, provided by globalThis.crypto. + * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. + * @param mnemonic - 12-24 words. + * @param passphrase - String that will additionally protect the key. + * @returns 64 bytes of key data. + * @throws If the mnemonic shape is invalid. {@link Error} + * @throws On wrong argument types. {@link TypeError} + * @example + * Derive a seed with the native WebCrypto PBKDF2 helper. + * ```ts + * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow'; + * const seed = await mnemonicToSeedWebcrypto(mnem, 'password'); + * // => new Uint8Array([...64 bytes]) + * ``` + */ +export function mnemonicToSeedWebcrypto( + mnemonic: string, + passphrase = '' +): Promise> { + return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64, + }) as Promise>; +} diff --git a/node_modules/@scure/bip39/wordlists/czech.d.ts b/node_modules/@scure/bip39/wordlists/czech.d.ts new file mode 100644 index 0000000..d16423c --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/czech.d.ts @@ -0,0 +1,3 @@ +/** Czech BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=czech.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/czech.js b/node_modules/@scure/bip39/wordlists/czech.js new file mode 100644 index 0000000..db67192 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/czech.js @@ -0,0 +1,2050 @@ +/** Czech BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`abdikace +abeceda +adresa +agrese +akce +aktovka +alej +alkohol +amputace +ananas +andulka +anekdota +anketa +antika +anulovat +archa +arogance +asfalt +asistent +aspirace +astma +astronom +atlas +atletika +atol +autobus +azyl +babka +bachor +bacil +baculka +badatel +bageta +bagr +bahno +bakterie +balada +baletka +balkon +balonek +balvan +balza +bambus +bankomat +barbar +baret +barman +baroko +barva +baterka +batoh +bavlna +bazalka +bazilika +bazuka +bedna +beran +beseda +bestie +beton +bezinka +bezmoc +beztak +bicykl +bidlo +biftek +bikiny +bilance +biograf +biolog +bitva +bizon +blahobyt +blatouch +blecha +bledule +blesk +blikat +blizna +blokovat +bloudit +blud +bobek +bobr +bodlina +bodnout +bohatost +bojkot +bojovat +bokorys +bolest +borec +borovice +bota +boubel +bouchat +bouda +boule +bourat +boxer +bradavka +brambora +branka +bratr +brepta +briketa +brko +brloh +bronz +broskev +brunetka +brusinka +brzda +brzy +bublina +bubnovat +buchta +buditel +budka +budova +bufet +bujarost +bukvice +buldok +bulva +bunda +bunkr +burza +butik +buvol +buzola +bydlet +bylina +bytovka +bzukot +capart +carevna +cedr +cedule +cejch +cejn +cela +celer +celkem +celnice +cenina +cennost +cenovka +centrum +cenzor +cestopis +cetka +chalupa +chapadlo +charita +chata +chechtat +chemie +chichot +chirurg +chlad +chleba +chlubit +chmel +chmura +chobot +chochol +chodba +cholera +chomout +chopit +choroba +chov +chrapot +chrlit +chrt +chrup +chtivost +chudina +chutnat +chvat +chvilka +chvost +chyba +chystat +chytit +cibule +cigareta +cihelna +cihla +cinkot +cirkus +cisterna +citace +citrus +cizinec +cizost +clona +cokoliv +couvat +ctitel +ctnost +cudnost +cuketa +cukr +cupot +cvaknout +cval +cvik +cvrkot +cyklista +daleko +dareba +datel +datum +dcera +debata +dechovka +decibel +deficit +deflace +dekl +dekret +demokrat +deprese +derby +deska +detektiv +dikobraz +diktovat +dioda +diplom +disk +displej +divadlo +divoch +dlaha +dlouho +dluhopis +dnes +dobro +dobytek +docent +dochutit +dodnes +dohled +dohoda +dohra +dojem +dojnice +doklad +dokola +doktor +dokument +dolar +doleva +dolina +doma +dominant +domluvit +domov +donutit +dopad +dopis +doplnit +doposud +doprovod +dopustit +dorazit +dorost +dort +dosah +doslov +dostatek +dosud +dosyta +dotaz +dotek +dotknout +doufat +doutnat +dovozce +dozadu +doznat +dozorce +drahota +drak +dramatik +dravec +draze +drdol +drobnost +drogerie +drozd +drsnost +drtit +drzost +duben +duchovno +dudek +duha +duhovka +dusit +dusno +dutost +dvojice +dvorec +dynamit +ekolog +ekonomie +elektron +elipsa +email +emise +emoce +empatie +epizoda +epocha +epopej +epos +esej +esence +eskorta +eskymo +etiketa +euforie +evoluce +exekuce +exkurze +expedice +exploze +export +extrakt +facka +fajfka +fakulta +fanatik +fantazie +farmacie +favorit +fazole +federace +fejeton +fenka +fialka +figurant +filozof +filtr +finance +finta +fixace +fjord +flanel +flirt +flotila +fond +fosfor +fotbal +fotka +foton +frakce +freska +fronta +fukar +funkce +fyzika +galeje +garant +genetika +geolog +gilotina +glazura +glejt +golem +golfista +gotika +graf +gramofon +granule +grep +gril +grog +groteska +guma +hadice +hadr +hala +halenka +hanba +hanopis +harfa +harpuna +havran +hebkost +hejkal +hejno +hejtman +hektar +helma +hematom +herec +herna +heslo +hezky +historik +hladovka +hlasivky +hlava +hledat +hlen +hlodavec +hloh +hloupost +hltat +hlubina +hluchota +hmat +hmota +hmyz +hnis +hnojivo +hnout +hoblina +hoboj +hoch +hodiny +hodlat +hodnota +hodovat +hojnost +hokej +holinka +holka +holub +homole +honitba +honorace +horal +horda +horizont +horko +horlivec +hormon +hornina +horoskop +horstvo +hospoda +hostina +hotovost +houba +houf +houpat +houska +hovor +hradba +hranice +hravost +hrazda +hrbolek +hrdina +hrdlo +hrdost +hrnek +hrobka +hromada +hrot +hrouda +hrozen +hrstka +hrubost +hryzat +hubenost +hubnout +hudba +hukot +humr +husita +hustota +hvozd +hybnost +hydrant +hygiena +hymna +hysterik +idylka +ihned +ikona +iluze +imunita +infekce +inflace +inkaso +inovace +inspekce +internet +invalida +investor +inzerce +ironie +jablko +jachta +jahoda +jakmile +jakost +jalovec +jantar +jarmark +jaro +jasan +jasno +jatka +javor +jazyk +jedinec +jedle +jednatel +jehlan +jekot +jelen +jelito +jemnost +jenom +jepice +jeseter +jevit +jezdec +jezero +jinak +jindy +jinoch +jiskra +jistota +jitrnice +jizva +jmenovat +jogurt +jurta +kabaret +kabel +kabinet +kachna +kadet +kadidlo +kahan +kajak +kajuta +kakao +kaktus +kalamita +kalhoty +kalibr +kalnost +kamera +kamkoliv +kamna +kanibal +kanoe +kantor +kapalina +kapela +kapitola +kapka +kaple +kapota +kapr +kapusta +kapybara +karamel +karotka +karton +kasa +katalog +katedra +kauce +kauza +kavalec +kazajka +kazeta +kazivost +kdekoliv +kdesi +kedluben +kemp +keramika +kino +klacek +kladivo +klam +klapot +klasika +klaun +klec +klenba +klepat +klesnout +klid +klima +klisna +klobouk +klokan +klopa +kloub +klubovna +klusat +kluzkost +kmen +kmitat +kmotr +kniha +knot +koalice +koberec +kobka +kobliha +kobyla +kocour +kohout +kojenec +kokos +koktejl +kolaps +koleda +kolize +kolo +komando +kometa +komik +komnata +komora +kompas +komunita +konat +koncept +kondice +konec +konfese +kongres +konina +konkurs +kontakt +konzerva +kopanec +kopie +kopnout +koprovka +korbel +korektor +kormidlo +koroptev +korpus +koruna +koryto +korzet +kosatec +kostka +kotel +kotleta +kotoul +koukat +koupelna +kousek +kouzlo +kovboj +koza +kozoroh +krabice +krach +krajina +kralovat +krasopis +kravata +kredit +krejcar +kresba +kreveta +kriket +kritik +krize +krkavec +krmelec +krmivo +krocan +krok +kronika +kropit +kroupa +krovka +krtek +kruhadlo +krupice +krutost +krvinka +krychle +krypta +krystal +kryt +kudlanka +kufr +kujnost +kukla +kulajda +kulich +kulka +kulomet +kultura +kuna +kupodivu +kurt +kurzor +kutil +kvalita +kvasinka +kvestor +kynolog +kyselina +kytara +kytice +kytka +kytovec +kyvadlo +labrador +lachtan +ladnost +laik +lakomec +lamela +lampa +lanovka +lasice +laso +lastura +latinka +lavina +lebka +leckdy +leden +lednice +ledovka +ledvina +legenda +legie +legrace +lehce +lehkost +lehnout +lektvar +lenochod +lentilka +lepenka +lepidlo +letadlo +letec +letmo +letokruh +levhart +levitace +levobok +libra +lichotka +lidojed +lidskost +lihovina +lijavec +lilek +limetka +linie +linka +linoleum +listopad +litina +litovat +lobista +lodivod +logika +logoped +lokalita +loket +lomcovat +lopata +lopuch +lord +losos +lotr +loudal +louh +louka +louskat +lovec +lstivost +lucerna +lucifer +lump +lusk +lustrace +lvice +lyra +lyrika +lysina +madam +madlo +magistr +mahagon +majetek +majitel +majorita +makak +makovice +makrela +malba +malina +malovat +malvice +maminka +mandle +manko +marnost +masakr +maskot +masopust +matice +matrika +maturita +mazanec +mazivo +mazlit +mazurka +mdloba +mechanik +meditace +medovina +melasa +meloun +mentolka +metla +metoda +metr +mezera +migrace +mihnout +mihule +mikina +mikrofon +milenec +milimetr +milost +mimika +mincovna +minibar +minomet +minulost +miska +mistr +mixovat +mladost +mlha +mlhovina +mlok +mlsat +mluvit +mnich +mnohem +mobil +mocnost +modelka +modlitba +mohyla +mokro +molekula +momentka +monarcha +monokl +monstrum +montovat +monzun +mosaz +moskyt +most +motivace +motorka +motyka +moucha +moudrost +mozaika +mozek +mozol +mramor +mravenec +mrkev +mrtvola +mrzet +mrzutost +mstitel +mudrc +muflon +mulat +mumie +munice +muset +mutace +muzeum +muzikant +myslivec +mzda +nabourat +nachytat +nadace +nadbytek +nadhoz +nadobro +nadpis +nahlas +nahnat +nahodile +nahradit +naivita +najednou +najisto +najmout +naklonit +nakonec +nakrmit +nalevo +namazat +namluvit +nanometr +naoko +naopak +naostro +napadat +napevno +naplnit +napnout +naposled +naprosto +narodit +naruby +narychlo +nasadit +nasekat +naslepo +nastat +natolik +navenek +navrch +navzdory +nazvat +nebe +nechat +necky +nedaleko +nedbat +neduh +negace +nehet +nehoda +nejen +nejprve +neklid +nelibost +nemilost +nemoc +neochota +neonka +nepokoj +nerost +nerv +nesmysl +nesoulad +netvor +neuron +nevina +nezvykle +nicota +nijak +nikam +nikdy +nikl +nikterak +nitro +nocleh +nohavice +nominace +nora +norek +nositel +nosnost +nouze +noviny +novota +nozdra +nuda +nudle +nuget +nutit +nutnost +nutrie +nymfa +obal +obarvit +obava +obdiv +obec +obehnat +obejmout +obezita +obhajoba +obilnice +objasnit +objekt +obklopit +oblast +oblek +obliba +obloha +obluda +obnos +obohatit +obojek +obout +obrazec +obrna +obruba +obrys +obsah +obsluha +obstarat +obuv +obvaz +obvinit +obvod +obvykle +obyvatel +obzor +ocas +ocel +ocenit +ochladit +ochota +ochrana +ocitnout +odboj +odbyt +odchod +odcizit +odebrat +odeslat +odevzdat +odezva +odhadce +odhodit +odjet +odjinud +odkaz +odkoupit +odliv +odluka +odmlka +odolnost +odpad +odpis +odplout +odpor +odpustit +odpykat +odrazka +odsoudit +odstup +odsun +odtok +odtud +odvaha +odveta +odvolat +odvracet +odznak +ofina +ofsajd +ohlas +ohnisko +ohrada +ohrozit +ohryzek +okap +okenice +oklika +okno +okouzlit +okovy +okrasa +okres +okrsek +okruh +okupant +okurka +okusit +olejnina +olizovat +omak +omeleta +omezit +omladina +omlouvat +omluva +omyl +onehdy +opakovat +opasek +operace +opice +opilost +opisovat +opora +opozice +opravdu +oproti +orbital +orchestr +orgie +orlice +orloj +ortel +osada +oschnout +osika +osivo +oslava +oslepit +oslnit +oslovit +osnova +osoba +osolit +ospalec +osten +ostraha +ostuda +ostych +osvojit +oteplit +otisk +otop +otrhat +otrlost +otrok +otruby +otvor +ovanout +ovar +oves +ovlivnit +ovoce +oxid +ozdoba +pachatel +pacient +padouch +pahorek +pakt +palanda +palec +palivo +paluba +pamflet +pamlsek +panenka +panika +panna +panovat +panstvo +pantofle +paprika +parketa +parodie +parta +paruka +paryba +paseka +pasivita +pastelka +patent +patrona +pavouk +pazneht +pazourek +pecka +pedagog +pejsek +peklo +peloton +penalta +pendrek +penze +periskop +pero +pestrost +petarda +petice +petrolej +pevnina +pexeso +pianista +piha +pijavice +pikle +piknik +pilina +pilnost +pilulka +pinzeta +pipeta +pisatel +pistole +pitevna +pivnice +pivovar +placenta +plakat +plamen +planeta +plastika +platit +plavidlo +plaz +plech +plemeno +plenta +ples +pletivo +plevel +plivat +plnit +plno +plocha +plodina +plomba +plout +pluk +plyn +pobavit +pobyt +pochod +pocit +poctivec +podat +podcenit +podepsat +podhled +podivit +podklad +podmanit +podnik +podoba +podpora +podraz +podstata +podvod +podzim +poezie +pohanka +pohnutka +pohovor +pohroma +pohyb +pointa +pojistka +pojmout +pokazit +pokles +pokoj +pokrok +pokuta +pokyn +poledne +polibek +polknout +poloha +polynom +pomalu +pominout +pomlka +pomoc +pomsta +pomyslet +ponechat +ponorka +ponurost +popadat +popel +popisek +poplach +poprosit +popsat +popud +poradce +porce +porod +porucha +poryv +posadit +posed +posila +poskok +poslanec +posoudit +pospolu +postava +posudek +posyp +potah +potkan +potlesk +potomek +potrava +potupa +potvora +poukaz +pouto +pouzdro +povaha +povidla +povlak +povoz +povrch +povstat +povyk +povzdech +pozdrav +pozemek +poznatek +pozor +pozvat +pracovat +prahory +praktika +prales +praotec +praporek +prase +pravda +princip +prkno +probudit +procento +prodej +profese +prohra +projekt +prolomit +promile +pronikat +propad +prorok +prosba +proton +proutek +provaz +prskavka +prsten +prudkost +prut +prvek +prvohory +psanec +psovod +pstruh +ptactvo +puberta +puch +pudl +pukavec +puklina +pukrle +pult +pumpa +punc +pupen +pusa +pusinka +pustina +putovat +putyka +pyramida +pysk +pytel +racek +rachot +radiace +radnice +radon +raft +ragby +raketa +rakovina +rameno +rampouch +rande +rarach +rarita +rasovna +rastr +ratolest +razance +razidlo +reagovat +reakce +recept +redaktor +referent +reflex +rejnok +reklama +rekord +rekrut +rektor +reputace +revize +revma +revolver +rezerva +riskovat +riziko +robotika +rodokmen +rohovka +rokle +rokoko +romaneto +ropovod +ropucha +rorejs +rosol +rostlina +rotmistr +rotoped +rotunda +roubenka +roucho +roup +roura +rovina +rovnice +rozbor +rozchod +rozdat +rozeznat +rozhodce +rozinka +rozjezd +rozkaz +rozloha +rozmar +rozpad +rozruch +rozsah +roztok +rozum +rozvod +rubrika +ruchadlo +rukavice +rukopis +ryba +rybolov +rychlost +rydlo +rypadlo +rytina +ryzost +sadista +sahat +sako +samec +samizdat +samota +sanitka +sardinka +sasanka +satelit +sazba +sazenice +sbor +schovat +sebranka +secese +sedadlo +sediment +sedlo +sehnat +sejmout +sekera +sekta +sekunda +sekvoje +semeno +seno +servis +sesadit +seshora +seskok +seslat +sestra +sesuv +sesypat +setba +setina +setkat +setnout +setrvat +sever +seznam +shoda +shrnout +sifon +silnice +sirka +sirotek +sirup +situace +skafandr +skalisko +skanzen +skaut +skeptik +skica +skladba +sklenice +sklo +skluz +skoba +skokan +skoro +skripta +skrz +skupina +skvost +skvrna +slabika +sladidlo +slanina +slast +slavnost +sledovat +slepec +sleva +slezina +slib +slina +sliznice +slon +sloupek +slovo +sluch +sluha +slunce +slupka +slza +smaragd +smetana +smilstvo +smlouva +smog +smrad +smrk +smrtka +smutek +smysl +snad +snaha +snob +sobota +socha +sodovka +sokol +sopka +sotva +souboj +soucit +soudce +souhlas +soulad +soumrak +souprava +soused +soutok +souviset +spalovna +spasitel +spis +splav +spodek +spojenec +spolu +sponzor +spornost +spousta +sprcha +spustit +sranda +sraz +srdce +srna +srnec +srovnat +srpen +srst +srub +stanice +starosta +statika +stavba +stehno +stezka +stodola +stolek +stopa +storno +stoupat +strach +stres +strhnout +strom +struna +studna +stupnice +stvol +styk +subjekt +subtropy +suchar +sudost +sukno +sundat +sunout +surikata +surovina +svah +svalstvo +svetr +svatba +svazek +svisle +svitek +svoboda +svodidlo +svorka +svrab +sykavka +sykot +synek +synovec +sypat +sypkost +syrovost +sysel +sytost +tabletka +tabule +tahoun +tajemno +tajfun +tajga +tajit +tajnost +taktika +tamhle +tampon +tancovat +tanec +tanker +tapeta +tavenina +tazatel +technika +tehdy +tekutina +telefon +temnota +tendence +tenista +tenor +teplota +tepna +teprve +terapie +termoska +textil +ticho +tiskopis +titulek +tkadlec +tkanina +tlapka +tleskat +tlukot +tlupa +tmel +toaleta +topinka +topol +torzo +touha +toulec +tradice +traktor +tramp +trasa +traverza +trefit +trest +trezor +trhavina +trhlina +trochu +trojice +troska +trouba +trpce +trpitel +trpkost +trubec +truchlit +truhlice +trus +trvat +tudy +tuhnout +tuhost +tundra +turista +turnaj +tuzemsko +tvaroh +tvorba +tvrdost +tvrz +tygr +tykev +ubohost +uboze +ubrat +ubrousek +ubrus +ubytovna +ucho +uctivost +udivit +uhradit +ujednat +ujistit +ujmout +ukazatel +uklidnit +uklonit +ukotvit +ukrojit +ulice +ulita +ulovit +umyvadlo +unavit +uniforma +uniknout +upadnout +uplatnit +uplynout +upoutat +upravit +uran +urazit +usednout +usilovat +usmrtit +usnadnit +usnout +usoudit +ustlat +ustrnout +utahovat +utkat +utlumit +utonout +utopenec +utrousit +uvalit +uvolnit +uvozovka +uzdravit +uzel +uzenina +uzlina +uznat +vagon +valcha +valoun +vana +vandal +vanilka +varan +varhany +varovat +vcelku +vchod +vdova +vedro +vegetace +vejce +velbloud +veletrh +velitel +velmoc +velryba +venkov +veranda +verze +veselka +veskrze +vesnice +vespodu +vesta +veterina +veverka +vibrace +vichr +videohra +vidina +vidle +vila +vinice +viset +vitalita +vize +vizitka +vjezd +vklad +vkus +vlajka +vlak +vlasec +vlevo +vlhkost +vliv +vlnovka +vloupat +vnucovat +vnuk +voda +vodivost +vodoznak +vodstvo +vojensky +vojna +vojsko +volant +volba +volit +volno +voskovka +vozidlo +vozovna +vpravo +vrabec +vracet +vrah +vrata +vrba +vrcholek +vrhat +vrstva +vrtule +vsadit +vstoupit +vstup +vtip +vybavit +vybrat +vychovat +vydat +vydra +vyfotit +vyhledat +vyhnout +vyhodit +vyhradit +vyhubit +vyjasnit +vyjet +vyjmout +vyklopit +vykonat +vylekat +vymazat +vymezit +vymizet +vymyslet +vynechat +vynikat +vynutit +vypadat +vyplatit +vypravit +vypustit +vyrazit +vyrovnat +vyrvat +vyslovit +vysoko +vystavit +vysunout +vysypat +vytasit +vytesat +vytratit +vyvinout +vyvolat +vyvrhel +vyzdobit +vyznat +vzadu +vzbudit +vzchopit +vzdor +vzduch +vzdychat +vzestup +vzhledem +vzkaz +vzlykat +vznik +vzorek +vzpoura +vztah +vztek +xylofon +zabrat +zabydlet +zachovat +zadarmo +zadusit +zafoukat +zahltit +zahodit +zahrada +zahynout +zajatec +zajet +zajistit +zaklepat +zakoupit +zalepit +zamezit +zamotat +zamyslet +zanechat +zanikat +zaplatit +zapojit +zapsat +zarazit +zastavit +zasunout +zatajit +zatemnit +zatknout +zaujmout +zavalit +zavelet +zavinit +zavolat +zavrtat +zazvonit +zbavit +zbrusu +zbudovat +zbytek +zdaleka +zdarma +zdatnost +zdivo +zdobit +zdroj +zdvih +zdymadlo +zelenina +zeman +zemina +zeptat +zezadu +zezdola +zhatit +zhltnout +zhluboka +zhotovit +zhruba +zima +zimnice +zjemnit +zklamat +zkoumat +zkratka +zkumavka +zlato +zlehka +zloba +zlom +zlost +zlozvyk +zmapovat +zmar +zmatek +zmije +zmizet +zmocnit +zmodrat +zmrzlina +zmutovat +znak +znalost +znamenat +znovu +zobrazit +zotavit +zoubek +zoufale +zplodit +zpomalit +zprava +zprostit +zprudka +zprvu +zrada +zranit +zrcadlo +zrnitost +zrno +zrovna +zrychlit +zrzavost +zticha +ztratit +zubovina +zubr +zvednout +zvenku +zvesela +zvon +zvrat +zvukovod +zvyk`.split('\n')); +//# sourceMappingURL=czech.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/english.d.ts b/node_modules/@scure/bip39/wordlists/english.d.ts new file mode 100644 index 0000000..e5877b2 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/english.d.ts @@ -0,0 +1,3 @@ +/** English BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=english.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/english.js b/node_modules/@scure/bip39/wordlists/english.js new file mode 100644 index 0000000..07c18d0 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/english.js @@ -0,0 +1,2050 @@ +/** English BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split('\n')); +//# sourceMappingURL=english.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/french.d.ts b/node_modules/@scure/bip39/wordlists/french.d.ts new file mode 100644 index 0000000..9ad4ee9 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/french.d.ts @@ -0,0 +1,3 @@ +/** French BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=french.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/french.js b/node_modules/@scure/bip39/wordlists/french.js new file mode 100644 index 0000000..93997af --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/french.js @@ -0,0 +1,2050 @@ +/** French BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`abaisser +abandon +abdiquer +abeille +abolir +aborder +aboutir +aboyer +abrasif +abreuver +abriter +abroger +abrupt +absence +absolu +absurde +abusif +abyssal +académie +acajou +acarien +accabler +accepter +acclamer +accolade +accroche +accuser +acerbe +achat +acheter +aciduler +acier +acompte +acquérir +acronyme +acteur +actif +actuel +adepte +adéquat +adhésif +adjectif +adjuger +admettre +admirer +adopter +adorer +adoucir +adresse +adroit +adulte +adverbe +aérer +aéronef +affaire +affecter +affiche +affreux +affubler +agacer +agencer +agile +agiter +agrafer +agréable +agrume +aider +aiguille +ailier +aimable +aisance +ajouter +ajuster +alarmer +alchimie +alerte +algèbre +algue +aliéner +aliment +alléger +alliage +allouer +allumer +alourdir +alpaga +altesse +alvéole +amateur +ambigu +ambre +aménager +amertume +amidon +amiral +amorcer +amour +amovible +amphibie +ampleur +amusant +analyse +anaphore +anarchie +anatomie +ancien +anéantir +angle +angoisse +anguleux +animal +annexer +annonce +annuel +anodin +anomalie +anonyme +anormal +antenne +antidote +anxieux +apaiser +apéritif +aplanir +apologie +appareil +appeler +apporter +appuyer +aquarium +aqueduc +arbitre +arbuste +ardeur +ardoise +argent +arlequin +armature +armement +armoire +armure +arpenter +arracher +arriver +arroser +arsenic +artériel +article +aspect +asphalte +aspirer +assaut +asservir +assiette +associer +assurer +asticot +astre +astuce +atelier +atome +atrium +atroce +attaque +attentif +attirer +attraper +aubaine +auberge +audace +audible +augurer +aurore +automne +autruche +avaler +avancer +avarice +avenir +averse +aveugle +aviateur +avide +avion +aviser +avoine +avouer +avril +axial +axiome +badge +bafouer +bagage +baguette +baignade +balancer +balcon +baleine +balisage +bambin +bancaire +bandage +banlieue +bannière +banquier +barbier +baril +baron +barque +barrage +bassin +bastion +bataille +bateau +batterie +baudrier +bavarder +belette +bélier +belote +bénéfice +berceau +berger +berline +bermuda +besace +besogne +bétail +beurre +biberon +bicycle +bidule +bijou +bilan +bilingue +billard +binaire +biologie +biopsie +biotype +biscuit +bison +bistouri +bitume +bizarre +blafard +blague +blanchir +blessant +blinder +blond +bloquer +blouson +bobard +bobine +boire +boiser +bolide +bonbon +bondir +bonheur +bonifier +bonus +bordure +borne +botte +boucle +boueux +bougie +boulon +bouquin +bourse +boussole +boutique +boxeur +branche +brasier +brave +brebis +brèche +breuvage +bricoler +brigade +brillant +brioche +brique +brochure +broder +bronzer +brousse +broyeur +brume +brusque +brutal +bruyant +buffle +buisson +bulletin +bureau +burin +bustier +butiner +butoir +buvable +buvette +cabanon +cabine +cachette +cadeau +cadre +caféine +caillou +caisson +calculer +calepin +calibre +calmer +calomnie +calvaire +camarade +caméra +camion +campagne +canal +caneton +canon +cantine +canular +capable +caporal +caprice +capsule +capter +capuche +carabine +carbone +caresser +caribou +carnage +carotte +carreau +carton +cascade +casier +casque +cassure +causer +caution +cavalier +caverne +caviar +cédille +ceinture +céleste +cellule +cendrier +censurer +central +cercle +cérébral +cerise +cerner +cerveau +cesser +chagrin +chaise +chaleur +chambre +chance +chapitre +charbon +chasseur +chaton +chausson +chavirer +chemise +chenille +chéquier +chercher +cheval +chien +chiffre +chignon +chimère +chiot +chlorure +chocolat +choisir +chose +chouette +chrome +chute +cigare +cigogne +cimenter +cinéma +cintrer +circuler +cirer +cirque +citerne +citoyen +citron +civil +clairon +clameur +claquer +classe +clavier +client +cligner +climat +clivage +cloche +clonage +cloporte +cobalt +cobra +cocasse +cocotier +coder +codifier +coffre +cogner +cohésion +coiffer +coincer +colère +colibri +colline +colmater +colonel +combat +comédie +commande +compact +concert +conduire +confier +congeler +connoter +consonne +contact +convexe +copain +copie +corail +corbeau +cordage +corniche +corpus +correct +cortège +cosmique +costume +coton +coude +coupure +courage +couteau +couvrir +coyote +crabe +crainte +cravate +crayon +créature +créditer +crémeux +creuser +crevette +cribler +crier +cristal +critère +croire +croquer +crotale +crucial +cruel +crypter +cubique +cueillir +cuillère +cuisine +cuivre +culminer +cultiver +cumuler +cupide +curatif +curseur +cyanure +cycle +cylindre +cynique +daigner +damier +danger +danseur +dauphin +débattre +débiter +déborder +débrider +débutant +décaler +décembre +déchirer +décider +déclarer +décorer +décrire +décupler +dédale +déductif +déesse +défensif +défiler +défrayer +dégager +dégivrer +déglutir +dégrafer +déjeuner +délice +déloger +demander +demeurer +démolir +dénicher +dénouer +dentelle +dénuder +départ +dépenser +déphaser +déplacer +déposer +déranger +dérober +désastre +descente +désert +désigner +désobéir +dessiner +destrier +détacher +détester +détourer +détresse +devancer +devenir +deviner +devoir +diable +dialogue +diamant +dicter +différer +digérer +digital +digne +diluer +dimanche +diminuer +dioxyde +directif +diriger +discuter +disposer +dissiper +distance +divertir +diviser +docile +docteur +dogme +doigt +domaine +domicile +dompter +donateur +donjon +donner +dopamine +dortoir +dorure +dosage +doseur +dossier +dotation +douanier +double +douceur +douter +doyen +dragon +draper +dresser +dribbler +droiture +duperie +duplexe +durable +durcir +dynastie +éblouir +écarter +écharpe +échelle +éclairer +éclipse +éclore +écluse +école +économie +écorce +écouter +écraser +écrémer +écrivain +écrou +écume +écureuil +édifier +éduquer +effacer +effectif +effigie +effort +effrayer +effusion +égaliser +égarer +éjecter +élaborer +élargir +électron +élégant +éléphant +élève +éligible +élitisme +éloge +élucider +éluder +emballer +embellir +embryon +émeraude +émission +emmener +émotion +émouvoir +empereur +employer +emporter +emprise +émulsion +encadrer +enchère +enclave +encoche +endiguer +endosser +endroit +enduire +énergie +enfance +enfermer +enfouir +engager +engin +englober +énigme +enjamber +enjeu +enlever +ennemi +ennuyeux +enrichir +enrobage +enseigne +entasser +entendre +entier +entourer +entraver +énumérer +envahir +enviable +envoyer +enzyme +éolien +épaissir +épargne +épatant +épaule +épicerie +épidémie +épier +épilogue +épine +épisode +épitaphe +époque +épreuve +éprouver +épuisant +équerre +équipe +ériger +érosion +erreur +éruption +escalier +espadon +espèce +espiègle +espoir +esprit +esquiver +essayer +essence +essieu +essorer +estime +estomac +estrade +étagère +étaler +étanche +étatique +éteindre +étendoir +éternel +éthanol +éthique +ethnie +étirer +étoffer +étoile +étonnant +étourdir +étrange +étroit +étude +euphorie +évaluer +évasion +éventail +évidence +éviter +évolutif +évoquer +exact +exagérer +exaucer +exceller +excitant +exclusif +excuse +exécuter +exemple +exercer +exhaler +exhorter +exigence +exiler +exister +exotique +expédier +explorer +exposer +exprimer +exquis +extensif +extraire +exulter +fable +fabuleux +facette +facile +facture +faiblir +falaise +fameux +famille +farceur +farfelu +farine +farouche +fasciner +fatal +fatigue +faucon +fautif +faveur +favori +fébrile +féconder +fédérer +félin +femme +fémur +fendoir +féodal +fermer +féroce +ferveur +festival +feuille +feutre +février +fiasco +ficeler +fictif +fidèle +figure +filature +filetage +filière +filleul +filmer +filou +filtrer +financer +finir +fiole +firme +fissure +fixer +flairer +flamme +flasque +flatteur +fléau +flèche +fleur +flexion +flocon +flore +fluctuer +fluide +fluvial +folie +fonderie +fongible +fontaine +forcer +forgeron +formuler +fortune +fossile +foudre +fougère +fouiller +foulure +fourmi +fragile +fraise +franchir +frapper +frayeur +frégate +freiner +frelon +frémir +frénésie +frère +friable +friction +frisson +frivole +froid +fromage +frontal +frotter +fruit +fugitif +fuite +fureur +furieux +furtif +fusion +futur +gagner +galaxie +galerie +gambader +garantir +gardien +garnir +garrigue +gazelle +gazon +géant +gélatine +gélule +gendarme +général +génie +genou +gentil +géologie +géomètre +géranium +germe +gestuel +geyser +gibier +gicler +girafe +givre +glace +glaive +glisser +globe +gloire +glorieux +golfeur +gomme +gonfler +gorge +gorille +goudron +gouffre +goulot +goupille +gourmand +goutte +graduel +graffiti +graine +grand +grappin +gratuit +gravir +grenat +griffure +griller +grimper +grogner +gronder +grotte +groupe +gruger +grutier +gruyère +guépard +guerrier +guide +guimauve +guitare +gustatif +gymnaste +gyrostat +habitude +hachoir +halte +hameau +hangar +hanneton +haricot +harmonie +harpon +hasard +hélium +hématome +herbe +hérisson +hermine +héron +hésiter +heureux +hiberner +hibou +hilarant +histoire +hiver +homard +hommage +homogène +honneur +honorer +honteux +horde +horizon +horloge +hormone +horrible +houleux +housse +hublot +huileux +humain +humble +humide +humour +hurler +hydromel +hygiène +hymne +hypnose +idylle +ignorer +iguane +illicite +illusion +image +imbiber +imiter +immense +immobile +immuable +impact +impérial +implorer +imposer +imprimer +imputer +incarner +incendie +incident +incliner +incolore +indexer +indice +inductif +inédit +ineptie +inexact +infini +infliger +informer +infusion +ingérer +inhaler +inhiber +injecter +injure +innocent +inoculer +inonder +inscrire +insecte +insigne +insolite +inspirer +instinct +insulter +intact +intense +intime +intrigue +intuitif +inutile +invasion +inventer +inviter +invoquer +ironique +irradier +irréel +irriter +isoler +ivoire +ivresse +jaguar +jaillir +jambe +janvier +jardin +jauger +jaune +javelot +jetable +jeton +jeudi +jeunesse +joindre +joncher +jongler +joueur +jouissif +journal +jovial +joyau +joyeux +jubiler +jugement +junior +jupon +juriste +justice +juteux +juvénile +kayak +kimono +kiosque +label +labial +labourer +lacérer +lactose +lagune +laine +laisser +laitier +lambeau +lamelle +lampe +lanceur +langage +lanterne +lapin +largeur +larme +laurier +lavabo +lavoir +lecture +légal +léger +légume +lessive +lettre +levier +lexique +lézard +liasse +libérer +libre +licence +licorne +liège +lièvre +ligature +ligoter +ligue +limer +limite +limonade +limpide +linéaire +lingot +lionceau +liquide +lisière +lister +lithium +litige +littoral +livreur +logique +lointain +loisir +lombric +loterie +louer +lourd +loutre +louve +loyal +lubie +lucide +lucratif +lueur +lugubre +luisant +lumière +lunaire +lundi +luron +lutter +luxueux +machine +magasin +magenta +magique +maigre +maillon +maintien +mairie +maison +majorer +malaxer +maléfice +malheur +malice +mallette +mammouth +mandater +maniable +manquant +manteau +manuel +marathon +marbre +marchand +mardi +maritime +marqueur +marron +marteler +mascotte +massif +matériel +matière +matraque +maudire +maussade +mauve +maximal +méchant +méconnu +médaille +médecin +méditer +méduse +meilleur +mélange +mélodie +membre +mémoire +menacer +mener +menhir +mensonge +mentor +mercredi +mérite +merle +messager +mesure +métal +météore +méthode +métier +meuble +miauler +microbe +miette +mignon +migrer +milieu +million +mimique +mince +minéral +minimal +minorer +minute +miracle +miroiter +missile +mixte +mobile +moderne +moelleux +mondial +moniteur +monnaie +monotone +monstre +montagne +monument +moqueur +morceau +morsure +mortier +moteur +motif +mouche +moufle +moulin +mousson +mouton +mouvant +multiple +munition +muraille +murène +murmure +muscle +muséum +musicien +mutation +muter +mutuel +myriade +myrtille +mystère +mythique +nageur +nappe +narquois +narrer +natation +nation +nature +naufrage +nautique +navire +nébuleux +nectar +néfaste +négation +négliger +négocier +neige +nerveux +nettoyer +neurone +neutron +neveu +niche +nickel +nitrate +niveau +noble +nocif +nocturne +noirceur +noisette +nomade +nombreux +nommer +normatif +notable +notifier +notoire +nourrir +nouveau +novateur +novembre +novice +nuage +nuancer +nuire +nuisible +numéro +nuptial +nuque +nutritif +obéir +objectif +obliger +obscur +observer +obstacle +obtenir +obturer +occasion +occuper +océan +octobre +octroyer +octupler +oculaire +odeur +odorant +offenser +officier +offrir +ogive +oiseau +oisillon +olfactif +olivier +ombrage +omettre +onctueux +onduler +onéreux +onirique +opale +opaque +opérer +opinion +opportun +opprimer +opter +optique +orageux +orange +orbite +ordonner +oreille +organe +orgueil +orifice +ornement +orque +ortie +osciller +osmose +ossature +otarie +ouragan +ourson +outil +outrager +ouvrage +ovation +oxyde +oxygène +ozone +paisible +palace +palmarès +palourde +palper +panache +panda +pangolin +paniquer +panneau +panorama +pantalon +papaye +papier +papoter +papyrus +paradoxe +parcelle +paresse +parfumer +parler +parole +parrain +parsemer +partager +parure +parvenir +passion +pastèque +paternel +patience +patron +pavillon +pavoiser +payer +paysage +peigne +peintre +pelage +pélican +pelle +pelouse +peluche +pendule +pénétrer +pénible +pensif +pénurie +pépite +péplum +perdrix +perforer +période +permuter +perplexe +persil +perte +peser +pétale +petit +pétrir +peuple +pharaon +phobie +phoque +photon +phrase +physique +piano +pictural +pièce +pierre +pieuvre +pilote +pinceau +pipette +piquer +pirogue +piscine +piston +pivoter +pixel +pizza +placard +plafond +plaisir +planer +plaque +plastron +plateau +pleurer +plexus +pliage +plomb +plonger +pluie +plumage +pochette +poésie +poète +pointe +poirier +poisson +poivre +polaire +policier +pollen +polygone +pommade +pompier +ponctuel +pondérer +poney +portique +position +posséder +posture +potager +poteau +potion +pouce +poulain +poumon +pourpre +poussin +pouvoir +prairie +pratique +précieux +prédire +préfixe +prélude +prénom +présence +prétexte +prévoir +primitif +prince +prison +priver +problème +procéder +prodige +profond +progrès +proie +projeter +prologue +promener +propre +prospère +protéger +prouesse +proverbe +prudence +pruneau +psychose +public +puceron +puiser +pulpe +pulsar +punaise +punitif +pupitre +purifier +puzzle +pyramide +quasar +querelle +question +quiétude +quitter +quotient +racine +raconter +radieux +ragondin +raideur +raisin +ralentir +rallonge +ramasser +rapide +rasage +ratisser +ravager +ravin +rayonner +réactif +réagir +réaliser +réanimer +recevoir +réciter +réclamer +récolter +recruter +reculer +recycler +rédiger +redouter +refaire +réflexe +réformer +refrain +refuge +régalien +région +réglage +régulier +réitérer +rejeter +rejouer +relatif +relever +relief +remarque +remède +remise +remonter +remplir +remuer +renard +renfort +renifler +renoncer +rentrer +renvoi +replier +reporter +reprise +reptile +requin +réserve +résineux +résoudre +respect +rester +résultat +rétablir +retenir +réticule +retomber +retracer +réunion +réussir +revanche +revivre +révolte +révulsif +richesse +rideau +rieur +rigide +rigoler +rincer +riposter +risible +risque +rituel +rival +rivière +rocheux +romance +rompre +ronce +rondin +roseau +rosier +rotatif +rotor +rotule +rouge +rouille +rouleau +routine +royaume +ruban +rubis +ruche +ruelle +rugueux +ruiner +ruisseau +ruser +rustique +rythme +sabler +saboter +sabre +sacoche +safari +sagesse +saisir +salade +salive +salon +saluer +samedi +sanction +sanglier +sarcasme +sardine +saturer +saugrenu +saumon +sauter +sauvage +savant +savonner +scalpel +scandale +scélérat +scénario +sceptre +schéma +science +scinder +score +scrutin +sculpter +séance +sécable +sécher +secouer +sécréter +sédatif +séduire +seigneur +séjour +sélectif +semaine +sembler +semence +séminal +sénateur +sensible +sentence +séparer +séquence +serein +sergent +sérieux +serrure +sérum +service +sésame +sévir +sevrage +sextuple +sidéral +siècle +siéger +siffler +sigle +signal +silence +silicium +simple +sincère +sinistre +siphon +sirop +sismique +situer +skier +social +socle +sodium +soigneux +soldat +soleil +solitude +soluble +sombre +sommeil +somnoler +sonde +songeur +sonnette +sonore +sorcier +sortir +sosie +sottise +soucieux +soudure +souffle +soulever +soupape +source +soutirer +souvenir +spacieux +spatial +spécial +sphère +spiral +stable +station +sternum +stimulus +stipuler +strict +studieux +stupeur +styliste +sublime +substrat +subtil +subvenir +succès +sucre +suffixe +suggérer +suiveur +sulfate +superbe +supplier +surface +suricate +surmener +surprise +sursaut +survie +suspect +syllabe +symbole +symétrie +synapse +syntaxe +système +tabac +tablier +tactile +tailler +talent +talisman +talonner +tambour +tamiser +tangible +tapis +taquiner +tarder +tarif +tartine +tasse +tatami +tatouage +taupe +taureau +taxer +témoin +temporel +tenaille +tendre +teneur +tenir +tension +terminer +terne +terrible +tétine +texte +thème +théorie +thérapie +thorax +tibia +tiède +timide +tirelire +tiroir +tissu +titane +titre +tituber +toboggan +tolérant +tomate +tonique +tonneau +toponyme +torche +tordre +tornade +torpille +torrent +torse +tortue +totem +toucher +tournage +tousser +toxine +traction +trafic +tragique +trahir +train +trancher +travail +trèfle +tremper +trésor +treuil +triage +tribunal +tricoter +trilogie +triomphe +tripler +triturer +trivial +trombone +tronc +tropical +troupeau +tuile +tulipe +tumulte +tunnel +turbine +tuteur +tutoyer +tuyau +tympan +typhon +typique +tyran +ubuesque +ultime +ultrason +unanime +unifier +union +unique +unitaire +univers +uranium +urbain +urticant +usage +usine +usuel +usure +utile +utopie +vacarme +vaccin +vagabond +vague +vaillant +vaincre +vaisseau +valable +valise +vallon +valve +vampire +vanille +vapeur +varier +vaseux +vassal +vaste +vecteur +vedette +végétal +véhicule +veinard +véloce +vendredi +vénérer +venger +venimeux +ventouse +verdure +vérin +vernir +verrou +verser +vertu +veston +vétéran +vétuste +vexant +vexer +viaduc +viande +victoire +vidange +vidéo +vignette +vigueur +vilain +village +vinaigre +violon +vipère +virement +virtuose +virus +visage +viseur +vision +visqueux +visuel +vital +vitesse +viticole +vitrine +vivace +vivipare +vocation +voguer +voile +voisin +voiture +volaille +volcan +voltiger +volume +vorace +vortex +voter +vouloir +voyage +voyelle +wagon +xénon +yacht +zèbre +zénith +zeste +zoologie`.split('\n')); +//# sourceMappingURL=french.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/italian.d.ts b/node_modules/@scure/bip39/wordlists/italian.d.ts new file mode 100644 index 0000000..5564538 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/italian.d.ts @@ -0,0 +1,3 @@ +/** Italian BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=italian.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/italian.js b/node_modules/@scure/bip39/wordlists/italian.js new file mode 100644 index 0000000..cbb1128 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/italian.js @@ -0,0 +1,2050 @@ +/** Italian BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`abaco +abbaglio +abbinato +abete +abisso +abolire +abrasivo +abrogato +accadere +accenno +accusato +acetone +achille +acido +acqua +acre +acrilico +acrobata +acuto +adagio +addebito +addome +adeguato +aderire +adipe +adottare +adulare +affabile +affetto +affisso +affranto +aforisma +afoso +africano +agave +agente +agevole +aggancio +agire +agitare +agonismo +agricolo +agrumeto +aguzzo +alabarda +alato +albatro +alberato +albo +albume +alce +alcolico +alettone +alfa +algebra +aliante +alibi +alimento +allagato +allegro +allievo +allodola +allusivo +almeno +alogeno +alpaca +alpestre +altalena +alterno +alticcio +altrove +alunno +alveolo +alzare +amalgama +amanita +amarena +ambito +ambrato +ameba +america +ametista +amico +ammasso +ammenda +ammirare +ammonito +amore +ampio +ampliare +amuleto +anacardo +anagrafe +analista +anarchia +anatra +anca +ancella +ancora +andare +andrea +anello +angelo +angolare +angusto +anima +annegare +annidato +anno +annuncio +anonimo +anticipo +anzi +apatico +apertura +apode +apparire +appetito +appoggio +approdo +appunto +aprile +arabica +arachide +aragosta +araldica +arancio +aratura +arazzo +arbitro +archivio +ardito +arenile +argento +argine +arguto +aria +armonia +arnese +arredato +arringa +arrosto +arsenico +arso +artefice +arzillo +asciutto +ascolto +asepsi +asettico +asfalto +asino +asola +aspirato +aspro +assaggio +asse +assoluto +assurdo +asta +astenuto +astice +astratto +atavico +ateismo +atomico +atono +attesa +attivare +attorno +attrito +attuale +ausilio +austria +autista +autonomo +autunno +avanzato +avere +avvenire +avviso +avvolgere +azione +azoto +azzimo +azzurro +babele +baccano +bacino +baco +badessa +badilata +bagnato +baita +balcone +baldo +balena +ballata +balzano +bambino +bandire +baraonda +barbaro +barca +baritono +barlume +barocco +basilico +basso +batosta +battuto +baule +bava +bavosa +becco +beffa +belgio +belva +benda +benevole +benigno +benzina +bere +berlina +beta +bibita +bici +bidone +bifido +biga +bilancia +bimbo +binocolo +biologo +bipede +bipolare +birbante +birra +biscotto +bisesto +bisnonno +bisonte +bisturi +bizzarro +blando +blatta +bollito +bonifico +bordo +bosco +botanico +bottino +bozzolo +braccio +bradipo +brama +branca +bravura +bretella +brevetto +brezza +briglia +brillante +brindare +broccolo +brodo +bronzina +brullo +bruno +bubbone +buca +budino +buffone +buio +bulbo +buono +burlone +burrasca +bussola +busta +cadetto +caduco +calamaro +calcolo +calesse +calibro +calmo +caloria +cambusa +camerata +camicia +cammino +camola +campale +canapa +candela +cane +canino +canotto +cantina +capace +capello +capitolo +capogiro +cappero +capra +capsula +carapace +carcassa +cardo +carisma +carovana +carretto +cartolina +casaccio +cascata +caserma +caso +cassone +castello +casuale +catasta +catena +catrame +cauto +cavillo +cedibile +cedrata +cefalo +celebre +cellulare +cena +cenone +centesimo +ceramica +cercare +certo +cerume +cervello +cesoia +cespo +ceto +chela +chiaro +chicca +chiedere +chimera +china +chirurgo +chitarra +ciao +ciclismo +cifrare +cigno +cilindro +ciottolo +circa +cirrosi +citrico +cittadino +ciuffo +civetta +civile +classico +clinica +cloro +cocco +codardo +codice +coerente +cognome +collare +colmato +colore +colposo +coltivato +colza +coma +cometa +commando +comodo +computer +comune +conciso +condurre +conferma +congelare +coniuge +connesso +conoscere +consumo +continuo +convegno +coperto +copione +coppia +copricapo +corazza +cordata +coricato +cornice +corolla +corpo +corredo +corsia +cortese +cosmico +costante +cottura +covato +cratere +cravatta +creato +credere +cremoso +crescita +creta +criceto +crinale +crisi +critico +croce +cronaca +crostata +cruciale +crusca +cucire +cuculo +cugino +cullato +cupola +curatore +cursore +curvo +cuscino +custode +dado +daino +dalmata +damerino +daniela +dannoso +danzare +datato +davanti +davvero +debutto +decennio +deciso +declino +decollo +decreto +dedicato +definito +deforme +degno +delegare +delfino +delirio +delta +demenza +denotato +dentro +deposito +derapata +derivare +deroga +descritto +deserto +desiderio +desumere +detersivo +devoto +diametro +dicembre +diedro +difeso +diffuso +digerire +digitale +diluvio +dinamico +dinnanzi +dipinto +diploma +dipolo +diradare +dire +dirotto +dirupo +disagio +discreto +disfare +disgelo +disposto +distanza +disumano +dito +divano +divelto +dividere +divorato +doblone +docente +doganale +dogma +dolce +domato +domenica +dominare +dondolo +dono +dormire +dote +dottore +dovuto +dozzina +drago +druido +dubbio +dubitare +ducale +duna +duomo +duplice +duraturo +ebano +eccesso +ecco +eclissi +economia +edera +edicola +edile +editoria +educare +egemonia +egli +egoismo +egregio +elaborato +elargire +elegante +elencato +eletto +elevare +elfico +elica +elmo +elsa +eluso +emanato +emblema +emesso +emiro +emotivo +emozione +empirico +emulo +endemico +enduro +energia +enfasi +enoteca +entrare +enzima +epatite +epilogo +episodio +epocale +eppure +equatore +erario +erba +erboso +erede +eremita +erigere +ermetico +eroe +erosivo +errante +esagono +esame +esanime +esaudire +esca +esempio +esercito +esibito +esigente +esistere +esito +esofago +esortato +esoso +espanso +espresso +essenza +esso +esteso +estimare +estonia +estroso +esultare +etilico +etnico +etrusco +etto +euclideo +europa +evaso +evidenza +evitato +evoluto +evviva +fabbrica +faccenda +fachiro +falco +famiglia +fanale +fanfara +fango +fantasma +fare +farfalla +farinoso +farmaco +fascia +fastoso +fasullo +faticare +fato +favoloso +febbre +fecola +fede +fegato +felpa +feltro +femmina +fendere +fenomeno +fermento +ferro +fertile +fessura +festivo +fetta +feudo +fiaba +fiducia +fifa +figurato +filo +finanza +finestra +finire +fiore +fiscale +fisico +fiume +flacone +flamenco +flebo +flemma +florido +fluente +fluoro +fobico +focaccia +focoso +foderato +foglio +folata +folclore +folgore +fondente +fonetico +fonia +fontana +forbito +forchetta +foresta +formica +fornaio +foro +fortezza +forzare +fosfato +fosso +fracasso +frana +frassino +fratello +freccetta +frenata +fresco +frigo +frollino +fronde +frugale +frutta +fucilata +fucsia +fuggente +fulmine +fulvo +fumante +fumetto +fumoso +fune +funzione +fuoco +furbo +furgone +furore +fuso +futile +gabbiano +gaffe +galateo +gallina +galoppo +gambero +gamma +garanzia +garbo +garofano +garzone +gasdotto +gasolio +gastrico +gatto +gaudio +gazebo +gazzella +geco +gelatina +gelso +gemello +gemmato +gene +genitore +gennaio +genotipo +gergo +ghepardo +ghiaccio +ghisa +giallo +gilda +ginepro +giocare +gioiello +giorno +giove +girato +girone +gittata +giudizio +giurato +giusto +globulo +glutine +gnomo +gobba +golf +gomito +gommone +gonfio +gonna +governo +gracile +grado +grafico +grammo +grande +grattare +gravoso +grazia +greca +gregge +grifone +grigio +grinza +grotta +gruppo +guadagno +guaio +guanto +guardare +gufo +guidare +ibernato +icona +identico +idillio +idolo +idra +idrico +idrogeno +igiene +ignaro +ignorato +ilare +illeso +illogico +illudere +imballo +imbevuto +imbocco +imbuto +immane +immerso +immolato +impacco +impeto +impiego +importo +impronta +inalare +inarcare +inattivo +incanto +incendio +inchino +incisivo +incluso +incontro +incrocio +incubo +indagine +india +indole +inedito +infatti +infilare +inflitto +ingaggio +ingegno +inglese +ingordo +ingrosso +innesco +inodore +inoltrare +inondato +insano +insetto +insieme +insonnia +insulina +intasato +intero +intonaco +intuito +inumidire +invalido +invece +invito +iperbole +ipnotico +ipotesi +ippica +iride +irlanda +ironico +irrigato +irrorare +isolato +isotopo +isterico +istituto +istrice +italia +iterare +labbro +labirinto +lacca +lacerato +lacrima +lacuna +laddove +lago +lampo +lancetta +lanterna +lardoso +larga +laringe +lastra +latenza +latino +lattuga +lavagna +lavoro +legale +leggero +lembo +lentezza +lenza +leone +lepre +lesivo +lessato +lesto +letterale +leva +levigato +libero +lido +lievito +lilla +limatura +limitare +limpido +lineare +lingua +liquido +lira +lirica +lisca +lite +litigio +livrea +locanda +lode +logica +lombare +londra +longevo +loquace +lorenzo +loto +lotteria +luce +lucidato +lumaca +luminoso +lungo +lupo +luppolo +lusinga +lusso +lutto +macabro +macchina +macero +macinato +madama +magico +maglia +magnete +magro +maiolica +malafede +malgrado +malinteso +malsano +malto +malumore +mana +mancia +mandorla +mangiare +manifesto +mannaro +manovra +mansarda +mantide +manubrio +mappa +maratona +marcire +maretta +marmo +marsupio +maschera +massaia +mastino +materasso +matricola +mattone +maturo +mazurca +meandro +meccanico +mecenate +medesimo +meditare +mega +melassa +melis +melodia +meninge +meno +mensola +mercurio +merenda +merlo +meschino +mese +messere +mestolo +metallo +metodo +mettere +miagolare +mica +micelio +michele +microbo +midollo +miele +migliore +milano +milite +mimosa +minerale +mini +minore +mirino +mirtillo +miscela +missiva +misto +misurare +mitezza +mitigare +mitra +mittente +mnemonico +modello +modifica +modulo +mogano +mogio +mole +molosso +monastero +monco +mondina +monetario +monile +monotono +monsone +montato +monviso +mora +mordere +morsicato +mostro +motivato +motosega +motto +movenza +movimento +mozzo +mucca +mucosa +muffa +mughetto +mugnaio +mulatto +mulinello +multiplo +mummia +munto +muovere +murale +musa +muscolo +musica +mutevole +muto +nababbo +nafta +nanometro +narciso +narice +narrato +nascere +nastrare +naturale +nautica +naviglio +nebulosa +necrosi +negativo +negozio +nemmeno +neofita +neretto +nervo +nessuno +nettuno +neutrale +neve +nevrotico +nicchia +ninfa +nitido +nobile +nocivo +nodo +nome +nomina +nordico +normale +norvegese +nostrano +notare +notizia +notturno +novella +nucleo +nulla +numero +nuovo +nutrire +nuvola +nuziale +oasi +obbedire +obbligo +obelisco +oblio +obolo +obsoleto +occasione +occhio +occidente +occorrere +occultare +ocra +oculato +odierno +odorare +offerta +offrire +offuscato +oggetto +oggi +ognuno +olandese +olfatto +oliato +oliva +ologramma +oltre +omaggio +ombelico +ombra +omega +omissione +ondoso +onere +onice +onnivoro +onorevole +onta +operato +opinione +opposto +oracolo +orafo +ordine +orecchino +orefice +orfano +organico +origine +orizzonte +orma +ormeggio +ornativo +orologio +orrendo +orribile +ortensia +ortica +orzata +orzo +osare +oscurare +osmosi +ospedale +ospite +ossa +ossidare +ostacolo +oste +otite +otre +ottagono +ottimo +ottobre +ovale +ovest +ovino +oviparo +ovocito +ovunque +ovviare +ozio +pacchetto +pace +pacifico +padella +padrone +paese +paga +pagina +palazzina +palesare +pallido +palo +palude +pandoro +pannello +paolo +paonazzo +paprica +parabola +parcella +parere +pargolo +pari +parlato +parola +partire +parvenza +parziale +passivo +pasticca +patacca +patologia +pattume +pavone +peccato +pedalare +pedonale +peggio +peloso +penare +pendice +penisola +pennuto +penombra +pensare +pentola +pepe +pepita +perbene +percorso +perdonato +perforare +pergamena +periodo +permesso +perno +perplesso +persuaso +pertugio +pervaso +pesatore +pesista +peso +pestifero +petalo +pettine +petulante +pezzo +piacere +pianta +piattino +piccino +picozza +piega +pietra +piffero +pigiama +pigolio +pigro +pila +pilifero +pillola +pilota +pimpante +pineta +pinna +pinolo +pioggia +piombo +piramide +piretico +pirite +pirolisi +pitone +pizzico +placebo +planare +plasma +platano +plenario +pochezza +poderoso +podismo +poesia +poggiare +polenta +poligono +pollice +polmonite +polpetta +polso +poltrona +polvere +pomice +pomodoro +ponte +popoloso +porfido +poroso +porpora +porre +portata +posa +positivo +possesso +postulato +potassio +potere +pranzo +prassi +pratica +precluso +predica +prefisso +pregiato +prelievo +premere +prenotare +preparato +presenza +pretesto +prevalso +prima +principe +privato +problema +procura +produrre +profumo +progetto +prolunga +promessa +pronome +proposta +proroga +proteso +prova +prudente +prugna +prurito +psiche +pubblico +pudica +pugilato +pugno +pulce +pulito +pulsante +puntare +pupazzo +pupilla +puro +quadro +qualcosa +quasi +querela +quota +raccolto +raddoppio +radicale +radunato +raffica +ragazzo +ragione +ragno +ramarro +ramingo +ramo +randagio +rantolare +rapato +rapina +rappreso +rasatura +raschiato +rasente +rassegna +rastrello +rata +ravveduto +reale +recepire +recinto +recluta +recondito +recupero +reddito +redimere +regalato +registro +regola +regresso +relazione +remare +remoto +renna +replica +reprimere +reputare +resa +residente +responso +restauro +rete +retina +retorica +rettifica +revocato +riassunto +ribadire +ribelle +ribrezzo +ricarica +ricco +ricevere +riciclato +ricordo +ricreduto +ridicolo +ridurre +rifasare +riflesso +riforma +rifugio +rigare +rigettato +righello +rilassato +rilevato +rimanere +rimbalzo +rimedio +rimorchio +rinascita +rincaro +rinforzo +rinnovo +rinomato +rinsavito +rintocco +rinuncia +rinvenire +riparato +ripetuto +ripieno +riportare +ripresa +ripulire +risata +rischio +riserva +risibile +riso +rispetto +ristoro +risultato +risvolto +ritardo +ritegno +ritmico +ritrovo +riunione +riva +riverso +rivincita +rivolto +rizoma +roba +robotico +robusto +roccia +roco +rodaggio +rodere +roditore +rogito +rollio +romantico +rompere +ronzio +rosolare +rospo +rotante +rotondo +rotula +rovescio +rubizzo +rubrica +ruga +rullino +rumine +rumoroso +ruolo +rupe +russare +rustico +sabato +sabbiare +sabotato +sagoma +salasso +saldatura +salgemma +salivare +salmone +salone +saltare +saluto +salvo +sapere +sapido +saporito +saraceno +sarcasmo +sarto +sassoso +satellite +satira +satollo +saturno +savana +savio +saziato +sbadiglio +sbalzo +sbancato +sbarra +sbattere +sbavare +sbendare +sbirciare +sbloccato +sbocciato +sbrinare +sbruffone +sbuffare +scabroso +scadenza +scala +scambiare +scandalo +scapola +scarso +scatenare +scavato +scelto +scenico +scettro +scheda +schiena +sciarpa +scienza +scindere +scippo +sciroppo +scivolo +sclerare +scodella +scolpito +scomparto +sconforto +scoprire +scorta +scossone +scozzese +scriba +scrollare +scrutinio +scuderia +scultore +scuola +scuro +scusare +sdebitare +sdoganare +seccatura +secondo +sedano +seggiola +segnalato +segregato +seguito +selciato +selettivo +sella +selvaggio +semaforo +sembrare +seme +seminato +sempre +senso +sentire +sepolto +sequenza +serata +serbato +sereno +serio +serpente +serraglio +servire +sestina +setola +settimana +sfacelo +sfaldare +sfamato +sfarzoso +sfaticato +sfera +sfida +sfilato +sfinge +sfocato +sfoderare +sfogo +sfoltire +sforzato +sfratto +sfruttato +sfuggito +sfumare +sfuso +sgabello +sgarbato +sgonfiare +sgorbio +sgrassato +sguardo +sibilo +siccome +sierra +sigla +signore +silenzio +sillaba +simbolo +simpatico +simulato +sinfonia +singolo +sinistro +sino +sintesi +sinusoide +sipario +sisma +sistole +situato +slitta +slogatura +sloveno +smarrito +smemorato +smentito +smeraldo +smilzo +smontare +smottato +smussato +snellire +snervato +snodo +sobbalzo +sobrio +soccorso +sociale +sodale +soffitto +sogno +soldato +solenne +solido +sollazzo +solo +solubile +solvente +somatico +somma +sonda +sonetto +sonnifero +sopire +soppeso +sopra +sorgere +sorpasso +sorriso +sorso +sorteggio +sorvolato +sospiro +sosta +sottile +spada +spalla +spargere +spatola +spavento +spazzola +specie +spedire +spegnere +spelatura +speranza +spessore +spettrale +spezzato +spia +spigoloso +spillato +spinoso +spirale +splendido +sportivo +sposo +spranga +sprecare +spronato +spruzzo +spuntino +squillo +sradicare +srotolato +stabile +stacco +staffa +stagnare +stampato +stantio +starnuto +stasera +statuto +stelo +steppa +sterzo +stiletto +stima +stirpe +stivale +stizzoso +stonato +storico +strappo +stregato +stridulo +strozzare +strutto +stuccare +stufo +stupendo +subentro +succoso +sudore +suggerito +sugo +sultano +suonare +superbo +supporto +surgelato +surrogato +sussurro +sutura +svagare +svedese +sveglio +svelare +svenuto +svezia +sviluppo +svista +svizzera +svolta +svuotare +tabacco +tabulato +tacciare +taciturno +tale +talismano +tampone +tannino +tara +tardivo +targato +tariffa +tarpare +tartaruga +tasto +tattico +taverna +tavolata +tazza +teca +tecnico +telefono +temerario +tempo +temuto +tendone +tenero +tensione +tentacolo +teorema +terme +terrazzo +terzetto +tesi +tesserato +testato +tetro +tettoia +tifare +tigella +timbro +tinto +tipico +tipografo +tiraggio +tiro +titanio +titolo +titubante +tizio +tizzone +toccare +tollerare +tolto +tombola +tomo +tonfo +tonsilla +topazio +topologia +toppa +torba +tornare +torrone +tortora +toscano +tossire +tostatura +totano +trabocco +trachea +trafila +tragedia +tralcio +tramonto +transito +trapano +trarre +trasloco +trattato +trave +treccia +tremolio +trespolo +tributo +tricheco +trifoglio +trillo +trincea +trio +tristezza +triturato +trivella +tromba +trono +troppo +trottola +trovare +truccato +tubatura +tuffato +tulipano +tumulto +tunisia +turbare +turchino +tuta +tutela +ubicato +uccello +uccisore +udire +uditivo +uffa +ufficio +uguale +ulisse +ultimato +umano +umile +umorismo +uncinetto +ungere +ungherese +unicorno +unificato +unisono +unitario +unte +uovo +upupa +uragano +urgenza +urlo +usanza +usato +uscito +usignolo +usuraio +utensile +utilizzo +utopia +vacante +vaccinato +vagabondo +vagliato +valanga +valgo +valico +valletta +valoroso +valutare +valvola +vampata +vangare +vanitoso +vano +vantaggio +vanvera +vapore +varano +varcato +variante +vasca +vedetta +vedova +veduto +vegetale +veicolo +velcro +velina +velluto +veloce +venato +vendemmia +vento +verace +verbale +vergogna +verifica +vero +verruca +verticale +vescica +vessillo +vestale +veterano +vetrina +vetusto +viandante +vibrante +vicenda +vichingo +vicinanza +vidimare +vigilia +vigneto +vigore +vile +villano +vimini +vincitore +viola +vipera +virgola +virologo +virulento +viscoso +visione +vispo +vissuto +visura +vita +vitello +vittima +vivanda +vivido +viziare +voce +voga +volatile +volere +volpe +voragine +vulcano +zampogna +zanna +zappato +zattera +zavorra +zefiro +zelante +zelo +zenzero +zerbino +zibetto +zinco +zircone +zitto +zolla +zotico +zucchero +zufolo +zulu +zuppa`.split('\n')); +//# sourceMappingURL=italian.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/japanese.d.ts b/node_modules/@scure/bip39/wordlists/japanese.d.ts new file mode 100644 index 0000000..8e39fba --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/japanese.d.ts @@ -0,0 +1,3 @@ +/** Japanese BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=japanese.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/japanese.js b/node_modules/@scure/bip39/wordlists/japanese.js new file mode 100644 index 0000000..ff76e2d --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/japanese.js @@ -0,0 +1,2050 @@ +/** Japanese BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`あいこくしん +あいさつ +あいだ +あおぞら +あかちゃん +あきる +あけがた +あける +あこがれる +あさい +あさひ +あしあと +あじわう +あずかる +あずき +あそぶ +あたえる +あたためる +あたりまえ +あたる +あつい +あつかう +あっしゅく +あつまり +あつめる +あてな +あてはまる +あひる +あぶら +あぶる +あふれる +あまい +あまど +あまやかす +あまり +あみもの +あめりか +あやまる +あゆむ +あらいぐま +あらし +あらすじ +あらためる +あらゆる +あらわす +ありがとう +あわせる +あわてる +あんい +あんがい +あんこ +あんぜん +あんてい +あんない +あんまり +いいだす +いおん +いがい +いがく +いきおい +いきなり +いきもの +いきる +いくじ +いくぶん +いけばな +いけん +いこう +いこく +いこつ +いさましい +いさん +いしき +いじゅう +いじょう +いじわる +いずみ +いずれ +いせい +いせえび +いせかい +いせき +いぜん +いそうろう +いそがしい +いだい +いだく +いたずら +いたみ +いたりあ +いちおう +いちじ +いちど +いちば +いちぶ +いちりゅう +いつか +いっしゅん +いっせい +いっそう +いったん +いっち +いってい +いっぽう +いてざ +いてん +いどう +いとこ +いない +いなか +いねむり +いのち +いのる +いはつ +いばる +いはん +いびき +いひん +いふく +いへん +いほう +いみん +いもうと +いもたれ +いもり +いやがる +いやす +いよかん +いよく +いらい +いらすと +いりぐち +いりょう +いれい +いれもの +いれる +いろえんぴつ +いわい +いわう +いわかん +いわば +いわゆる +いんげんまめ +いんさつ +いんしょう +いんよう +うえき +うえる +うおざ +うがい +うかぶ +うかべる +うきわ +うくらいな +うくれれ +うけたまわる +うけつけ +うけとる +うけもつ +うける +うごかす +うごく +うこん +うさぎ +うしなう +うしろがみ +うすい +うすぎ +うすぐらい +うすめる +うせつ +うちあわせ +うちがわ +うちき +うちゅう +うっかり +うつくしい +うったえる +うつる +うどん +うなぎ +うなじ +うなずく +うなる +うねる +うのう +うぶげ +うぶごえ +うまれる +うめる +うもう +うやまう +うよく +うらがえす +うらぐち +うらない +うりあげ +うりきれ +うるさい +うれしい +うれゆき +うれる +うろこ +うわき +うわさ +うんこう +うんちん +うんてん +うんどう +えいえん +えいが +えいきょう +えいご +えいせい +えいぶん +えいよう +えいわ +えおり +えがお +えがく +えきたい +えくせる +えしゃく +えすて +えつらん +えのぐ +えほうまき +えほん +えまき +えもじ +えもの +えらい +えらぶ +えりあ +えんえん +えんかい +えんぎ +えんげき +えんしゅう +えんぜつ +えんそく +えんちょう +えんとつ +おいかける +おいこす +おいしい +おいつく +おうえん +おうさま +おうじ +おうせつ +おうたい +おうふく +おうべい +おうよう +おえる +おおい +おおう +おおどおり +おおや +おおよそ +おかえり +おかず +おがむ +おかわり +おぎなう +おきる +おくさま +おくじょう +おくりがな +おくる +おくれる +おこす +おこなう +おこる +おさえる +おさない +おさめる +おしいれ +おしえる +おじぎ +おじさん +おしゃれ +おそらく +おそわる +おたがい +おたく +おだやか +おちつく +おっと +おつり +おでかけ +おとしもの +おとなしい +おどり +おどろかす +おばさん +おまいり +おめでとう +おもいで +おもう +おもたい +おもちゃ +おやつ +おやゆび +およぼす +おらんだ +おろす +おんがく +おんけい +おんしゃ +おんせん +おんだん +おんちゅう +おんどけい +かあつ +かいが +がいき +がいけん +がいこう +かいさつ +かいしゃ +かいすいよく +かいぜん +かいぞうど +かいつう +かいてん +かいとう +かいふく +がいへき +かいほう +かいよう +がいらい +かいわ +かえる +かおり +かかえる +かがく +かがし +かがみ +かくご +かくとく +かざる +がぞう +かたい +かたち +がちょう +がっきゅう +がっこう +がっさん +がっしょう +かなざわし +かのう +がはく +かぶか +かほう +かほご +かまう +かまぼこ +かめれおん +かゆい +かようび +からい +かるい +かろう +かわく +かわら +がんか +かんけい +かんこう +かんしゃ +かんそう +かんたん +かんち +がんばる +きあい +きあつ +きいろ +ぎいん +きうい +きうん +きえる +きおう +きおく +きおち +きおん +きかい +きかく +きかんしゃ +ききて +きくばり +きくらげ +きけんせい +きこう +きこえる +きこく +きさい +きさく +きさま +きさらぎ +ぎじかがく +ぎしき +ぎじたいけん +ぎじにってい +ぎじゅつしゃ +きすう +きせい +きせき +きせつ +きそう +きぞく +きぞん +きたえる +きちょう +きつえん +ぎっちり +きつつき +きつね +きてい +きどう +きどく +きない +きなが +きなこ +きぬごし +きねん +きのう +きのした +きはく +きびしい +きひん +きふく +きぶん +きぼう +きほん +きまる +きみつ +きむずかしい +きめる +きもだめし +きもち +きもの +きゃく +きやく +ぎゅうにく +きよう +きょうりゅう +きらい +きらく +きりん +きれい +きれつ +きろく +ぎろん +きわめる +ぎんいろ +きんかくじ +きんじょ +きんようび +ぐあい +くいず +くうかん +くうき +くうぐん +くうこう +ぐうせい +くうそう +ぐうたら +くうふく +くうぼ +くかん +くきょう +くげん +ぐこう +くさい +くさき +くさばな +くさる +くしゃみ +くしょう +くすのき +くすりゆび +くせげ +くせん +ぐたいてき +くださる +くたびれる +くちこみ +くちさき +くつした +ぐっすり +くつろぐ +くとうてん +くどく +くなん +くねくね +くのう +くふう +くみあわせ +くみたてる +くめる +くやくしょ +くらす +くらべる +くるま +くれる +くろう +くわしい +ぐんかん +ぐんしょく +ぐんたい +ぐんて +けあな +けいかく +けいけん +けいこ +けいさつ +げいじゅつ +けいたい +げいのうじん +けいれき +けいろ +けおとす +けおりもの +げきか +げきげん +げきだん +げきちん +げきとつ +げきは +げきやく +げこう +げこくじょう +げざい +けさき +げざん +けしき +けしごむ +けしょう +げすと +けたば +けちゃっぷ +けちらす +けつあつ +けつい +けつえき +けっこん +けつじょ +けっせき +けってい +けつまつ +げつようび +げつれい +けつろん +げどく +けとばす +けとる +けなげ +けなす +けなみ +けぬき +げねつ +けねん +けはい +げひん +けぶかい +げぼく +けまり +けみかる +けむし +けむり +けもの +けらい +けろけろ +けわしい +けんい +けんえつ +けんお +けんか +げんき +けんげん +けんこう +けんさく +けんしゅう +けんすう +げんそう +けんちく +けんてい +けんとう +けんない +けんにん +げんぶつ +けんま +けんみん +けんめい +けんらん +けんり +こあくま +こいぬ +こいびと +ごうい +こうえん +こうおん +こうかん +ごうきゅう +ごうけい +こうこう +こうさい +こうじ +こうすい +ごうせい +こうそく +こうたい +こうちゃ +こうつう +こうてい +こうどう +こうない +こうはい +ごうほう +ごうまん +こうもく +こうりつ +こえる +こおり +ごかい +ごがつ +ごかん +こくご +こくさい +こくとう +こくない +こくはく +こぐま +こけい +こける +ここのか +こころ +こさめ +こしつ +こすう +こせい +こせき +こぜん +こそだて +こたい +こたえる +こたつ +こちょう +こっか +こつこつ +こつばん +こつぶ +こてい +こてん +ことがら +ことし +ことば +ことり +こなごな +こねこね +このまま +このみ +このよ +ごはん +こひつじ +こふう +こふん +こぼれる +ごまあぶら +こまかい +ごますり +こまつな +こまる +こむぎこ +こもじ +こもち +こもの +こもん +こやく +こやま +こゆう +こゆび +こよい +こよう +こりる +これくしょん +ころっけ +こわもて +こわれる +こんいん +こんかい +こんき +こんしゅう +こんすい +こんだて +こんとん +こんなん +こんびに +こんぽん +こんまけ +こんや +こんれい +こんわく +ざいえき +さいかい +さいきん +ざいげん +ざいこ +さいしょ +さいせい +ざいたく +ざいちゅう +さいてき +ざいりょう +さうな +さかいし +さがす +さかな +さかみち +さがる +さぎょう +さくし +さくひん +さくら +さこく +さこつ +さずかる +ざせき +さたん +さつえい +ざつおん +ざっか +ざつがく +さっきょく +ざっし +さつじん +ざっそう +さつたば +さつまいも +さてい +さといも +さとう +さとおや +さとし +さとる +さのう +さばく +さびしい +さべつ +さほう +さほど +さます +さみしい +さみだれ +さむけ +さめる +さやえんどう +さゆう +さよう +さよく +さらだ +ざるそば +さわやか +さわる +さんいん +さんか +さんきゃく +さんこう +さんさい +ざんしょ +さんすう +さんせい +さんそ +さんち +さんま +さんみ +さんらん +しあい +しあげ +しあさって +しあわせ +しいく +しいん +しうち +しえい +しおけ +しかい +しかく +じかん +しごと +しすう +じだい +したうけ +したぎ +したて +したみ +しちょう +しちりん +しっかり +しつじ +しつもん +してい +してき +してつ +じてん +じどう +しなぎれ +しなもの +しなん +しねま +しねん +しのぐ +しのぶ +しはい +しばかり +しはつ +しはらい +しはん +しひょう +しふく +じぶん +しへい +しほう +しほん +しまう +しまる +しみん +しむける +じむしょ +しめい +しめる +しもん +しゃいん +しゃうん +しゃおん +じゃがいも +しやくしょ +しゃくほう +しゃけん +しゃこ +しゃざい +しゃしん +しゃせん +しゃそう +しゃたい +しゃちょう +しゃっきん +じゃま +しゃりん +しゃれい +じゆう +じゅうしょ +しゅくはく +じゅしん +しゅっせき +しゅみ +しゅらば +じゅんばん +しょうかい +しょくたく +しょっけん +しょどう +しょもつ +しらせる +しらべる +しんか +しんこう +じんじゃ +しんせいじ +しんちく +しんりん +すあげ +すあし +すあな +ずあん +すいえい +すいか +すいとう +ずいぶん +すいようび +すうがく +すうじつ +すうせん +すおどり +すきま +すくう +すくない +すける +すごい +すこし +ずさん +すずしい +すすむ +すすめる +すっかり +ずっしり +ずっと +すてき +すてる +すねる +すのこ +すはだ +すばらしい +ずひょう +ずぶぬれ +すぶり +すふれ +すべて +すべる +ずほう +すぼん +すまい +すめし +すもう +すやき +すらすら +するめ +すれちがう +すろっと +すわる +すんぜん +すんぽう +せあぶら +せいかつ +せいげん +せいじ +せいよう +せおう +せかいかん +せきにん +せきむ +せきゆ +せきらんうん +せけん +せこう +せすじ +せたい +せたけ +せっかく +せっきゃく +ぜっく +せっけん +せっこつ +せっさたくま +せつぞく +せつだん +せつでん +せっぱん +せつび +せつぶん +せつめい +せつりつ +せなか +せのび +せはば +せびろ +せぼね +せまい +せまる +せめる +せもたれ +せりふ +ぜんあく +せんい +せんえい +せんか +せんきょ +せんく +せんげん +ぜんご +せんさい +せんしゅ +せんすい +せんせい +せんぞ +せんたく +せんちょう +せんてい +せんとう +せんぬき +せんねん +せんぱい +ぜんぶ +ぜんぽう +せんむ +せんめんじょ +せんもん +せんやく +せんゆう +せんよう +ぜんら +ぜんりゃく +せんれい +せんろ +そあく +そいとげる +そいね +そうがんきょう +そうき +そうご +そうしん +そうだん +そうなん +そうび +そうめん +そうり +そえもの +そえん +そがい +そげき +そこう +そこそこ +そざい +そしな +そせい +そせん +そそぐ +そだてる +そつう +そつえん +そっかん +そつぎょう +そっけつ +そっこう +そっせん +そっと +そとがわ +そとづら +そなえる +そなた +そふぼ +そぼく +そぼろ +そまつ +そまる +そむく +そむりえ +そめる +そもそも +そよかぜ +そらまめ +そろう +そんかい +そんけい +そんざい +そんしつ +そんぞく +そんちょう +ぞんび +ぞんぶん +そんみん +たあい +たいいん +たいうん +たいえき +たいおう +だいがく +たいき +たいぐう +たいけん +たいこ +たいざい +だいじょうぶ +だいすき +たいせつ +たいそう +だいたい +たいちょう +たいてい +だいどころ +たいない +たいねつ +たいのう +たいはん +だいひょう +たいふう +たいへん +たいほ +たいまつばな +たいみんぐ +たいむ +たいめん +たいやき +たいよう +たいら +たいりょく +たいる +たいわん +たうえ +たえる +たおす +たおる +たおれる +たかい +たかね +たきび +たくさん +たこく +たこやき +たさい +たしざん +だじゃれ +たすける +たずさわる +たそがれ +たたかう +たたく +ただしい +たたみ +たちばな +だっかい +だっきゃく +だっこ +だっしゅつ +だったい +たてる +たとえる +たなばた +たにん +たぬき +たのしみ +たはつ +たぶん +たべる +たぼう +たまご +たまる +だむる +ためいき +ためす +ためる +たもつ +たやすい +たよる +たらす +たりきほんがん +たりょう +たりる +たると +たれる +たれんと +たろっと +たわむれる +だんあつ +たんい +たんおん +たんか +たんき +たんけん +たんご +たんさん +たんじょうび +だんせい +たんそく +たんたい +だんち +たんてい +たんとう +だんな +たんにん +だんねつ +たんのう +たんぴん +だんぼう +たんまつ +たんめい +だんれつ +だんろ +だんわ +ちあい +ちあん +ちいき +ちいさい +ちえん +ちかい +ちから +ちきゅう +ちきん +ちけいず +ちけん +ちこく +ちさい +ちしき +ちしりょう +ちせい +ちそう +ちたい +ちたん +ちちおや +ちつじょ +ちてき +ちてん +ちぬき +ちぬり +ちのう +ちひょう +ちへいせん +ちほう +ちまた +ちみつ +ちみどろ +ちめいど +ちゃんこなべ +ちゅうい +ちゆりょく +ちょうし +ちょさくけん +ちらし +ちらみ +ちりがみ +ちりょう +ちるど +ちわわ +ちんたい +ちんもく +ついか +ついたち +つうか +つうじょう +つうはん +つうわ +つかう +つかれる +つくね +つくる +つけね +つける +つごう +つたえる +つづく +つつじ +つつむ +つとめる +つながる +つなみ +つねづね +つのる +つぶす +つまらない +つまる +つみき +つめたい +つもり +つもる +つよい +つるぼ +つるみく +つわもの +つわり +てあし +てあて +てあみ +ていおん +ていか +ていき +ていけい +ていこく +ていさつ +ていし +ていせい +ていたい +ていど +ていねい +ていひょう +ていへん +ていぼう +てうち +ておくれ +てきとう +てくび +でこぼこ +てさぎょう +てさげ +てすり +てそう +てちがい +てちょう +てつがく +てつづき +でっぱ +てつぼう +てつや +でぬかえ +てぬき +てぬぐい +てのひら +てはい +てぶくろ +てふだ +てほどき +てほん +てまえ +てまきずし +てみじか +てみやげ +てらす +てれび +てわけ +てわたし +でんあつ +てんいん +てんかい +てんき +てんぐ +てんけん +てんごく +てんさい +てんし +てんすう +でんち +てんてき +てんとう +てんない +てんぷら +てんぼうだい +てんめつ +てんらんかい +でんりょく +でんわ +どあい +といれ +どうかん +とうきゅう +どうぐ +とうし +とうむぎ +とおい +とおか +とおく +とおす +とおる +とかい +とかす +ときおり +ときどき +とくい +とくしゅう +とくてん +とくに +とくべつ +とけい +とける +とこや +とさか +としょかん +とそう +とたん +とちゅう +とっきゅう +とっくん +とつぜん +とつにゅう +とどける +ととのえる +とない +となえる +となり +とのさま +とばす +どぶがわ +とほう +とまる +とめる +ともだち +ともる +どようび +とらえる +とんかつ +どんぶり +ないかく +ないこう +ないしょ +ないす +ないせん +ないそう +なおす +ながい +なくす +なげる +なこうど +なさけ +なたでここ +なっとう +なつやすみ +ななおし +なにごと +なにもの +なにわ +なのか +なふだ +なまいき +なまえ +なまみ +なみだ +なめらか +なめる +なやむ +ならう +ならび +ならぶ +なれる +なわとび +なわばり +にあう +にいがた +にうけ +におい +にかい +にがて +にきび +にくしみ +にくまん +にげる +にさんかたんそ +にしき +にせもの +にちじょう +にちようび +にっか +にっき +にっけい +にっこう +にっさん +にっしょく +にっすう +にっせき +にってい +になう +にほん +にまめ +にもつ +にやり +にゅういん +にりんしゃ +にわとり +にんい +にんか +にんき +にんげん +にんしき +にんずう +にんそう +にんたい +にんち +にんてい +にんにく +にんぷ +にんまり +にんむ +にんめい +にんよう +ぬいくぎ +ぬかす +ぬぐいとる +ぬぐう +ぬくもり +ぬすむ +ぬまえび +ぬめり +ぬらす +ぬんちゃく +ねあげ +ねいき +ねいる +ねいろ +ねぐせ +ねくたい +ねくら +ねこぜ +ねこむ +ねさげ +ねすごす +ねそべる +ねだん +ねつい +ねっしん +ねつぞう +ねったいぎょ +ねぶそく +ねふだ +ねぼう +ねほりはほり +ねまき +ねまわし +ねみみ +ねむい +ねむたい +ねもと +ねらう +ねわざ +ねんいり +ねんおし +ねんかん +ねんきん +ねんぐ +ねんざ +ねんし +ねんちゃく +ねんど +ねんぴ +ねんぶつ +ねんまつ +ねんりょう +ねんれい +のいず +のおづま +のがす +のきなみ +のこぎり +のこす +のこる +のせる +のぞく +のぞむ +のたまう +のちほど +のっく +のばす +のはら +のべる +のぼる +のみもの +のやま +のらいぬ +のらねこ +のりもの +のりゆき +のれん +のんき +ばあい +はあく +ばあさん +ばいか +ばいく +はいけん +はいご +はいしん +はいすい +はいせん +はいそう +はいち +ばいばい +はいれつ +はえる +はおる +はかい +ばかり +はかる +はくしゅ +はけん +はこぶ +はさみ +はさん +はしご +ばしょ +はしる +はせる +ぱそこん +はそん +はたん +はちみつ +はつおん +はっかく +はづき +はっきり +はっくつ +はっけん +はっこう +はっさん +はっしん +はったつ +はっちゅう +はってん +はっぴょう +はっぽう +はなす +はなび +はにかむ +はぶらし +はみがき +はむかう +はめつ +はやい +はやし +はらう +はろうぃん +はわい +はんい +はんえい +はんおん +はんかく +はんきょう +ばんぐみ +はんこ +はんしゃ +はんすう +はんだん +ぱんち +ぱんつ +はんてい +はんとし +はんのう +はんぱ +はんぶん +はんぺん +はんぼうき +はんめい +はんらん +はんろん +ひいき +ひうん +ひえる +ひかく +ひかり +ひかる +ひかん +ひくい +ひけつ +ひこうき +ひこく +ひさい +ひさしぶり +ひさん +びじゅつかん +ひしょ +ひそか +ひそむ +ひたむき +ひだり +ひたる +ひつぎ +ひっこし +ひっし +ひつじゅひん +ひっす +ひつぜん +ぴったり +ぴっちり +ひつよう +ひてい +ひとごみ +ひなまつり +ひなん +ひねる +ひはん +ひびく +ひひょう +ひほう +ひまわり +ひまん +ひみつ +ひめい +ひめじし +ひやけ +ひやす +ひよう +びょうき +ひらがな +ひらく +ひりつ +ひりょう +ひるま +ひるやすみ +ひれい +ひろい +ひろう +ひろき +ひろゆき +ひんかく +ひんけつ +ひんこん +ひんしゅ +ひんそう +ぴんち +ひんぱん +びんぼう +ふあん +ふいうち +ふうけい +ふうせん +ぷうたろう +ふうとう +ふうふ +ふえる +ふおん +ふかい +ふきん +ふくざつ +ふくぶくろ +ふこう +ふさい +ふしぎ +ふじみ +ふすま +ふせい +ふせぐ +ふそく +ぶたにく +ふたん +ふちょう +ふつう +ふつか +ふっかつ +ふっき +ふっこく +ぶどう +ふとる +ふとん +ふのう +ふはい +ふひょう +ふへん +ふまん +ふみん +ふめつ +ふめん +ふよう +ふりこ +ふりる +ふるい +ふんいき +ぶんがく +ぶんぐ +ふんしつ +ぶんせき +ふんそう +ぶんぽう +へいあん +へいおん +へいがい +へいき +へいげん +へいこう +へいさ +へいしゃ +へいせつ +へいそ +へいたく +へいてん +へいねつ +へいわ +へきが +へこむ +べにいろ +べにしょうが +へらす +へんかん +べんきょう +べんごし +へんさい +へんたい +べんり +ほあん +ほいく +ぼうぎょ +ほうこく +ほうそう +ほうほう +ほうもん +ほうりつ +ほえる +ほおん +ほかん +ほきょう +ぼきん +ほくろ +ほけつ +ほけん +ほこう +ほこる +ほしい +ほしつ +ほしゅ +ほしょう +ほせい +ほそい +ほそく +ほたて +ほたる +ぽちぶくろ +ほっきょく +ほっさ +ほったん +ほとんど +ほめる +ほんい +ほんき +ほんけ +ほんしつ +ほんやく +まいにち +まかい +まかせる +まがる +まける +まこと +まさつ +まじめ +ますく +まぜる +まつり +まとめ +まなぶ +まぬけ +まねく +まほう +まもる +まゆげ +まよう +まろやか +まわす +まわり +まわる +まんが +まんきつ +まんぞく +まんなか +みいら +みうち +みえる +みがく +みかた +みかん +みけん +みこん +みじかい +みすい +みすえる +みせる +みっか +みつかる +みつける +みてい +みとめる +みなと +みなみかさい +みねらる +みのう +みのがす +みほん +みもと +みやげ +みらい +みりょく +みわく +みんか +みんぞく +むいか +むえき +むえん +むかい +むかう +むかえ +むかし +むぎちゃ +むける +むげん +むさぼる +むしあつい +むしば +むじゅん +むしろ +むすう +むすこ +むすぶ +むすめ +むせる +むせん +むちゅう +むなしい +むのう +むやみ +むよう +むらさき +むりょう +むろん +めいあん +めいうん +めいえん +めいかく +めいきょく +めいさい +めいし +めいそう +めいぶつ +めいれい +めいわく +めぐまれる +めざす +めした +めずらしい +めだつ +めまい +めやす +めんきょ +めんせき +めんどう +もうしあげる +もうどうけん +もえる +もくし +もくてき +もくようび +もちろん +もどる +もらう +もんく +もんだい +やおや +やける +やさい +やさしい +やすい +やすたろう +やすみ +やせる +やそう +やたい +やちん +やっと +やっぱり +やぶる +やめる +ややこしい +やよい +やわらかい +ゆうき +ゆうびんきょく +ゆうべ +ゆうめい +ゆけつ +ゆしゅつ +ゆせん +ゆそう +ゆたか +ゆちゃく +ゆでる +ゆにゅう +ゆびわ +ゆらい +ゆれる +ようい +ようか +ようきゅう +ようじ +ようす +ようちえん +よかぜ +よかん +よきん +よくせい +よくぼう +よけい +よごれる +よさん +よしゅう +よそう +よそく +よっか +よてい +よどがわく +よねつ +よやく +よゆう +よろこぶ +よろしい +らいう +らくがき +らくご +らくさつ +らくだ +らしんばん +らせん +らぞく +らたい +らっか +られつ +りえき +りかい +りきさく +りきせつ +りくぐん +りくつ +りけん +りこう +りせい +りそう +りそく +りてん +りねん +りゆう +りゅうがく +りよう +りょうり +りょかん +りょくちゃ +りょこう +りりく +りれき +りろん +りんご +るいけい +るいさい +るいじ +るいせき +るすばん +るりがわら +れいかん +れいぎ +れいせい +れいぞうこ +れいとう +れいぼう +れきし +れきだい +れんあい +れんけい +れんこん +れんさい +れんしゅう +れんぞく +れんらく +ろうか +ろうご +ろうじん +ろうそく +ろくが +ろこつ +ろじうら +ろしゅつ +ろせん +ろてん +ろめん +ろれつ +ろんぎ +ろんぱ +ろんぶん +ろんり +わかす +わかめ +わかやま +わかれる +わしつ +わじまし +わすれもの +わらう +われる`.split('\n')); +//# sourceMappingURL=japanese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/korean.d.ts b/node_modules/@scure/bip39/wordlists/korean.d.ts new file mode 100644 index 0000000..6a4f0a6 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/korean.d.ts @@ -0,0 +1,3 @@ +/** Korean BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=korean.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/korean.js b/node_modules/@scure/bip39/wordlists/korean.js new file mode 100644 index 0000000..fdcaca4 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/korean.js @@ -0,0 +1,2050 @@ +/** Korean BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`가격 +가끔 +가난 +가능 +가득 +가르침 +가뭄 +가방 +가상 +가슴 +가운데 +가을 +가이드 +가입 +가장 +가정 +가족 +가죽 +각오 +각자 +간격 +간부 +간섭 +간장 +간접 +간판 +갈등 +갈비 +갈색 +갈증 +감각 +감기 +감소 +감수성 +감자 +감정 +갑자기 +강남 +강당 +강도 +강력히 +강변 +강북 +강사 +강수량 +강아지 +강원도 +강의 +강제 +강조 +같이 +개구리 +개나리 +개방 +개별 +개선 +개성 +개인 +객관적 +거실 +거액 +거울 +거짓 +거품 +걱정 +건강 +건물 +건설 +건조 +건축 +걸음 +검사 +검토 +게시판 +게임 +겨울 +견해 +결과 +결국 +결론 +결석 +결승 +결심 +결정 +결혼 +경계 +경고 +경기 +경력 +경복궁 +경비 +경상도 +경영 +경우 +경쟁 +경제 +경주 +경찰 +경치 +경향 +경험 +계곡 +계단 +계란 +계산 +계속 +계약 +계절 +계층 +계획 +고객 +고구려 +고궁 +고급 +고등학생 +고무신 +고민 +고양이 +고장 +고전 +고집 +고춧가루 +고통 +고향 +곡식 +골목 +골짜기 +골프 +공간 +공개 +공격 +공군 +공급 +공기 +공동 +공무원 +공부 +공사 +공식 +공업 +공연 +공원 +공장 +공짜 +공책 +공통 +공포 +공항 +공휴일 +과목 +과일 +과장 +과정 +과학 +관객 +관계 +관광 +관념 +관람 +관련 +관리 +관습 +관심 +관점 +관찰 +광경 +광고 +광장 +광주 +괴로움 +굉장히 +교과서 +교문 +교복 +교실 +교양 +교육 +교장 +교직 +교통 +교환 +교훈 +구경 +구름 +구멍 +구별 +구분 +구석 +구성 +구속 +구역 +구입 +구청 +구체적 +국가 +국기 +국내 +국립 +국물 +국민 +국수 +국어 +국왕 +국적 +국제 +국회 +군대 +군사 +군인 +궁극적 +권리 +권위 +권투 +귀국 +귀신 +규정 +규칙 +균형 +그날 +그냥 +그늘 +그러나 +그룹 +그릇 +그림 +그제서야 +그토록 +극복 +극히 +근거 +근교 +근래 +근로 +근무 +근본 +근원 +근육 +근처 +글씨 +글자 +금강산 +금고 +금년 +금메달 +금액 +금연 +금요일 +금지 +긍정적 +기간 +기관 +기념 +기능 +기독교 +기둥 +기록 +기름 +기법 +기본 +기분 +기쁨 +기숙사 +기술 +기억 +기업 +기온 +기운 +기원 +기적 +기준 +기침 +기혼 +기획 +긴급 +긴장 +길이 +김밥 +김치 +김포공항 +깍두기 +깜빡 +깨달음 +깨소금 +껍질 +꼭대기 +꽃잎 +나들이 +나란히 +나머지 +나물 +나침반 +나흘 +낙엽 +난방 +날개 +날씨 +날짜 +남녀 +남대문 +남매 +남산 +남자 +남편 +남학생 +낭비 +낱말 +내년 +내용 +내일 +냄비 +냄새 +냇물 +냉동 +냉면 +냉방 +냉장고 +넥타이 +넷째 +노동 +노란색 +노력 +노인 +녹음 +녹차 +녹화 +논리 +논문 +논쟁 +놀이 +농구 +농담 +농민 +농부 +농업 +농장 +농촌 +높이 +눈동자 +눈물 +눈썹 +뉴욕 +느낌 +늑대 +능동적 +능력 +다방 +다양성 +다음 +다이어트 +다행 +단계 +단골 +단독 +단맛 +단순 +단어 +단위 +단점 +단체 +단추 +단편 +단풍 +달걀 +달러 +달력 +달리 +닭고기 +담당 +담배 +담요 +담임 +답변 +답장 +당근 +당분간 +당연히 +당장 +대규모 +대낮 +대단히 +대답 +대도시 +대략 +대량 +대륙 +대문 +대부분 +대신 +대응 +대장 +대전 +대접 +대중 +대책 +대출 +대충 +대통령 +대학 +대한민국 +대합실 +대형 +덩어리 +데이트 +도대체 +도덕 +도둑 +도망 +도서관 +도심 +도움 +도입 +도자기 +도저히 +도전 +도중 +도착 +독감 +독립 +독서 +독일 +독창적 +동화책 +뒷모습 +뒷산 +딸아이 +마누라 +마늘 +마당 +마라톤 +마련 +마무리 +마사지 +마약 +마요네즈 +마을 +마음 +마이크 +마중 +마지막 +마찬가지 +마찰 +마흔 +막걸리 +막내 +막상 +만남 +만두 +만세 +만약 +만일 +만점 +만족 +만화 +많이 +말기 +말씀 +말투 +맘대로 +망원경 +매년 +매달 +매력 +매번 +매스컴 +매일 +매장 +맥주 +먹이 +먼저 +먼지 +멀리 +메일 +며느리 +며칠 +면담 +멸치 +명단 +명령 +명예 +명의 +명절 +명칭 +명함 +모금 +모니터 +모델 +모든 +모범 +모습 +모양 +모임 +모조리 +모집 +모퉁이 +목걸이 +목록 +목사 +목소리 +목숨 +목적 +목표 +몰래 +몸매 +몸무게 +몸살 +몸속 +몸짓 +몸통 +몹시 +무관심 +무궁화 +무더위 +무덤 +무릎 +무슨 +무엇 +무역 +무용 +무조건 +무지개 +무척 +문구 +문득 +문법 +문서 +문제 +문학 +문화 +물가 +물건 +물결 +물고기 +물론 +물리학 +물음 +물질 +물체 +미국 +미디어 +미사일 +미술 +미역 +미용실 +미움 +미인 +미팅 +미혼 +민간 +민족 +민주 +믿음 +밀가루 +밀리미터 +밑바닥 +바가지 +바구니 +바나나 +바늘 +바닥 +바닷가 +바람 +바이러스 +바탕 +박물관 +박사 +박수 +반대 +반드시 +반말 +반발 +반성 +반응 +반장 +반죽 +반지 +반찬 +받침 +발가락 +발걸음 +발견 +발달 +발레 +발목 +발바닥 +발생 +발음 +발자국 +발전 +발톱 +발표 +밤하늘 +밥그릇 +밥맛 +밥상 +밥솥 +방금 +방면 +방문 +방바닥 +방법 +방송 +방식 +방안 +방울 +방지 +방학 +방해 +방향 +배경 +배꼽 +배달 +배드민턴 +백두산 +백색 +백성 +백인 +백제 +백화점 +버릇 +버섯 +버튼 +번개 +번역 +번지 +번호 +벌금 +벌레 +벌써 +범위 +범인 +범죄 +법률 +법원 +법적 +법칙 +베이징 +벨트 +변경 +변동 +변명 +변신 +변호사 +변화 +별도 +별명 +별일 +병실 +병아리 +병원 +보관 +보너스 +보라색 +보람 +보름 +보상 +보안 +보자기 +보장 +보전 +보존 +보통 +보편적 +보험 +복도 +복사 +복숭아 +복습 +볶음 +본격적 +본래 +본부 +본사 +본성 +본인 +본질 +볼펜 +봉사 +봉지 +봉투 +부근 +부끄러움 +부담 +부동산 +부문 +부분 +부산 +부상 +부엌 +부인 +부작용 +부장 +부정 +부족 +부지런히 +부친 +부탁 +부품 +부회장 +북부 +북한 +분노 +분량 +분리 +분명 +분석 +분야 +분위기 +분필 +분홍색 +불고기 +불과 +불교 +불꽃 +불만 +불법 +불빛 +불안 +불이익 +불행 +브랜드 +비극 +비난 +비닐 +비둘기 +비디오 +비로소 +비만 +비명 +비밀 +비바람 +비빔밥 +비상 +비용 +비율 +비중 +비타민 +비판 +빌딩 +빗물 +빗방울 +빗줄기 +빛깔 +빨간색 +빨래 +빨리 +사건 +사계절 +사나이 +사냥 +사람 +사랑 +사립 +사모님 +사물 +사방 +사상 +사생활 +사설 +사슴 +사실 +사업 +사용 +사월 +사장 +사전 +사진 +사촌 +사춘기 +사탕 +사투리 +사흘 +산길 +산부인과 +산업 +산책 +살림 +살인 +살짝 +삼계탕 +삼국 +삼십 +삼월 +삼촌 +상관 +상금 +상대 +상류 +상반기 +상상 +상식 +상업 +상인 +상자 +상점 +상처 +상추 +상태 +상표 +상품 +상황 +새벽 +색깔 +색연필 +생각 +생명 +생물 +생방송 +생산 +생선 +생신 +생일 +생활 +서랍 +서른 +서명 +서민 +서비스 +서양 +서울 +서적 +서점 +서쪽 +서클 +석사 +석유 +선거 +선물 +선배 +선생 +선수 +선원 +선장 +선전 +선택 +선풍기 +설거지 +설날 +설렁탕 +설명 +설문 +설사 +설악산 +설치 +설탕 +섭씨 +성공 +성당 +성명 +성별 +성인 +성장 +성적 +성질 +성함 +세금 +세미나 +세상 +세월 +세종대왕 +세탁 +센터 +센티미터 +셋째 +소규모 +소극적 +소금 +소나기 +소년 +소득 +소망 +소문 +소설 +소속 +소아과 +소용 +소원 +소음 +소중히 +소지품 +소질 +소풍 +소형 +속담 +속도 +속옷 +손가락 +손길 +손녀 +손님 +손등 +손목 +손뼉 +손실 +손질 +손톱 +손해 +솔직히 +솜씨 +송아지 +송이 +송편 +쇠고기 +쇼핑 +수건 +수년 +수단 +수돗물 +수동적 +수면 +수명 +수박 +수상 +수석 +수술 +수시로 +수업 +수염 +수영 +수입 +수준 +수집 +수출 +수컷 +수필 +수학 +수험생 +수화기 +숙녀 +숙소 +숙제 +순간 +순서 +순수 +순식간 +순위 +숟가락 +술병 +술집 +숫자 +스님 +스물 +스스로 +스승 +스웨터 +스위치 +스케이트 +스튜디오 +스트레스 +스포츠 +슬쩍 +슬픔 +습관 +습기 +승객 +승리 +승부 +승용차 +승진 +시각 +시간 +시골 +시금치 +시나리오 +시댁 +시리즈 +시멘트 +시민 +시부모 +시선 +시설 +시스템 +시아버지 +시어머니 +시월 +시인 +시일 +시작 +시장 +시절 +시점 +시중 +시즌 +시집 +시청 +시합 +시험 +식구 +식기 +식당 +식량 +식료품 +식물 +식빵 +식사 +식생활 +식초 +식탁 +식품 +신고 +신규 +신념 +신문 +신발 +신비 +신사 +신세 +신용 +신제품 +신청 +신체 +신화 +실감 +실내 +실력 +실례 +실망 +실수 +실습 +실시 +실장 +실정 +실질적 +실천 +실체 +실컷 +실태 +실패 +실험 +실현 +심리 +심부름 +심사 +심장 +심정 +심판 +쌍둥이 +씨름 +씨앗 +아가씨 +아나운서 +아드님 +아들 +아쉬움 +아스팔트 +아시아 +아울러 +아저씨 +아줌마 +아직 +아침 +아파트 +아프리카 +아픔 +아홉 +아흔 +악기 +악몽 +악수 +안개 +안경 +안과 +안내 +안녕 +안동 +안방 +안부 +안주 +알루미늄 +알코올 +암시 +암컷 +압력 +앞날 +앞문 +애인 +애정 +액수 +앨범 +야간 +야단 +야옹 +약간 +약국 +약속 +약수 +약점 +약품 +약혼녀 +양념 +양력 +양말 +양배추 +양주 +양파 +어둠 +어려움 +어른 +어젯밤 +어쨌든 +어쩌다가 +어쩐지 +언니 +언덕 +언론 +언어 +얼굴 +얼른 +얼음 +얼핏 +엄마 +업무 +업종 +업체 +엉덩이 +엉망 +엉터리 +엊그제 +에너지 +에어컨 +엔진 +여건 +여고생 +여관 +여군 +여권 +여대생 +여덟 +여동생 +여든 +여론 +여름 +여섯 +여성 +여왕 +여인 +여전히 +여직원 +여학생 +여행 +역사 +역시 +역할 +연결 +연구 +연극 +연기 +연락 +연설 +연세 +연속 +연습 +연애 +연예인 +연인 +연장 +연주 +연출 +연필 +연합 +연휴 +열기 +열매 +열쇠 +열심히 +열정 +열차 +열흘 +염려 +엽서 +영국 +영남 +영상 +영양 +영역 +영웅 +영원히 +영하 +영향 +영혼 +영화 +옆구리 +옆방 +옆집 +예감 +예금 +예방 +예산 +예상 +예선 +예술 +예습 +예식장 +예약 +예전 +예절 +예정 +예컨대 +옛날 +오늘 +오락 +오랫동안 +오렌지 +오로지 +오른발 +오븐 +오십 +오염 +오월 +오전 +오직 +오징어 +오페라 +오피스텔 +오히려 +옥상 +옥수수 +온갖 +온라인 +온몸 +온종일 +온통 +올가을 +올림픽 +올해 +옷차림 +와이셔츠 +와인 +완성 +완전 +왕비 +왕자 +왜냐하면 +왠지 +외갓집 +외국 +외로움 +외삼촌 +외출 +외침 +외할머니 +왼발 +왼손 +왼쪽 +요금 +요일 +요즘 +요청 +용기 +용서 +용어 +우산 +우선 +우승 +우연히 +우정 +우체국 +우편 +운동 +운명 +운반 +운전 +운행 +울산 +울음 +움직임 +웃어른 +웃음 +워낙 +원고 +원래 +원서 +원숭이 +원인 +원장 +원피스 +월급 +월드컵 +월세 +월요일 +웨이터 +위반 +위법 +위성 +위원 +위험 +위협 +윗사람 +유난히 +유럽 +유명 +유물 +유산 +유적 +유치원 +유학 +유행 +유형 +육군 +육상 +육십 +육체 +은행 +음력 +음료 +음반 +음성 +음식 +음악 +음주 +의견 +의논 +의문 +의복 +의식 +의심 +의외로 +의욕 +의원 +의학 +이것 +이곳 +이념 +이놈 +이달 +이대로 +이동 +이렇게 +이력서 +이론적 +이름 +이민 +이발소 +이별 +이불 +이빨 +이상 +이성 +이슬 +이야기 +이용 +이웃 +이월 +이윽고 +이익 +이전 +이중 +이튿날 +이틀 +이혼 +인간 +인격 +인공 +인구 +인근 +인기 +인도 +인류 +인물 +인생 +인쇄 +인연 +인원 +인재 +인종 +인천 +인체 +인터넷 +인하 +인형 +일곱 +일기 +일단 +일대 +일등 +일반 +일본 +일부 +일상 +일생 +일손 +일요일 +일월 +일정 +일종 +일주일 +일찍 +일체 +일치 +일행 +일회용 +임금 +임무 +입대 +입력 +입맛 +입사 +입술 +입시 +입원 +입장 +입학 +자가용 +자격 +자극 +자동 +자랑 +자부심 +자식 +자신 +자연 +자원 +자율 +자전거 +자정 +자존심 +자판 +작가 +작년 +작성 +작업 +작용 +작은딸 +작품 +잔디 +잔뜩 +잔치 +잘못 +잠깐 +잠수함 +잠시 +잠옷 +잠자리 +잡지 +장관 +장군 +장기간 +장래 +장례 +장르 +장마 +장면 +장모 +장미 +장비 +장사 +장소 +장식 +장애인 +장인 +장점 +장차 +장학금 +재능 +재빨리 +재산 +재생 +재작년 +재정 +재채기 +재판 +재학 +재활용 +저것 +저고리 +저곳 +저녁 +저런 +저렇게 +저번 +저울 +저절로 +저축 +적극 +적당히 +적성 +적용 +적응 +전개 +전공 +전기 +전달 +전라도 +전망 +전문 +전반 +전부 +전세 +전시 +전용 +전자 +전쟁 +전주 +전철 +전체 +전통 +전혀 +전후 +절대 +절망 +절반 +절약 +절차 +점검 +점수 +점심 +점원 +점점 +점차 +접근 +접시 +접촉 +젓가락 +정거장 +정도 +정류장 +정리 +정말 +정면 +정문 +정반대 +정보 +정부 +정비 +정상 +정성 +정오 +정원 +정장 +정지 +정치 +정확히 +제공 +제과점 +제대로 +제목 +제발 +제법 +제삿날 +제안 +제일 +제작 +제주도 +제출 +제품 +제한 +조각 +조건 +조금 +조깅 +조명 +조미료 +조상 +조선 +조용히 +조절 +조정 +조직 +존댓말 +존재 +졸업 +졸음 +종교 +종로 +종류 +종소리 +종업원 +종종 +종합 +좌석 +죄인 +주관적 +주름 +주말 +주머니 +주먹 +주문 +주민 +주방 +주변 +주식 +주인 +주일 +주장 +주전자 +주택 +준비 +줄거리 +줄기 +줄무늬 +중간 +중계방송 +중국 +중년 +중단 +중독 +중반 +중부 +중세 +중소기업 +중순 +중앙 +중요 +중학교 +즉석 +즉시 +즐거움 +증가 +증거 +증권 +증상 +증세 +지각 +지갑 +지경 +지극히 +지금 +지급 +지능 +지름길 +지리산 +지방 +지붕 +지식 +지역 +지우개 +지원 +지적 +지점 +지진 +지출 +직선 +직업 +직원 +직장 +진급 +진동 +진로 +진료 +진리 +진짜 +진찰 +진출 +진통 +진행 +질문 +질병 +질서 +짐작 +집단 +집안 +집중 +짜증 +찌꺼기 +차남 +차라리 +차량 +차림 +차별 +차선 +차츰 +착각 +찬물 +찬성 +참가 +참기름 +참새 +참석 +참여 +참외 +참조 +찻잔 +창가 +창고 +창구 +창문 +창밖 +창작 +창조 +채널 +채점 +책가방 +책방 +책상 +책임 +챔피언 +처벌 +처음 +천국 +천둥 +천장 +천재 +천천히 +철도 +철저히 +철학 +첫날 +첫째 +청년 +청바지 +청소 +청춘 +체계 +체력 +체온 +체육 +체중 +체험 +초등학생 +초반 +초밥 +초상화 +초순 +초여름 +초원 +초저녁 +초점 +초청 +초콜릿 +촛불 +총각 +총리 +총장 +촬영 +최근 +최상 +최선 +최신 +최악 +최종 +추석 +추억 +추진 +추천 +추측 +축구 +축소 +축제 +축하 +출근 +출발 +출산 +출신 +출연 +출입 +출장 +출판 +충격 +충고 +충돌 +충분히 +충청도 +취업 +취직 +취향 +치약 +친구 +친척 +칠십 +칠월 +칠판 +침대 +침묵 +침실 +칫솔 +칭찬 +카메라 +카운터 +칼국수 +캐릭터 +캠퍼스 +캠페인 +커튼 +컨디션 +컬러 +컴퓨터 +코끼리 +코미디 +콘서트 +콜라 +콤플렉스 +콩나물 +쾌감 +쿠데타 +크림 +큰길 +큰딸 +큰소리 +큰아들 +큰어머니 +큰일 +큰절 +클래식 +클럽 +킬로 +타입 +타자기 +탁구 +탁자 +탄생 +태권도 +태양 +태풍 +택시 +탤런트 +터널 +터미널 +테니스 +테스트 +테이블 +텔레비전 +토론 +토마토 +토요일 +통계 +통과 +통로 +통신 +통역 +통일 +통장 +통제 +통증 +통합 +통화 +퇴근 +퇴원 +퇴직금 +튀김 +트럭 +특급 +특별 +특성 +특수 +특징 +특히 +튼튼히 +티셔츠 +파란색 +파일 +파출소 +판결 +판단 +판매 +판사 +팔십 +팔월 +팝송 +패션 +팩스 +팩시밀리 +팬티 +퍼센트 +페인트 +편견 +편의 +편지 +편히 +평가 +평균 +평생 +평소 +평양 +평일 +평화 +포스터 +포인트 +포장 +포함 +표면 +표정 +표준 +표현 +품목 +품질 +풍경 +풍속 +풍습 +프랑스 +프린터 +플라스틱 +피곤 +피망 +피아노 +필름 +필수 +필요 +필자 +필통 +핑계 +하느님 +하늘 +하드웨어 +하룻밤 +하반기 +하숙집 +하순 +하여튼 +하지만 +하천 +하품 +하필 +학과 +학교 +학급 +학기 +학년 +학력 +학번 +학부모 +학비 +학생 +학술 +학습 +학용품 +학원 +학위 +학자 +학점 +한계 +한글 +한꺼번에 +한낮 +한눈 +한동안 +한때 +한라산 +한마디 +한문 +한번 +한복 +한식 +한여름 +한쪽 +할머니 +할아버지 +할인 +함께 +함부로 +합격 +합리적 +항공 +항구 +항상 +항의 +해결 +해군 +해답 +해당 +해물 +해석 +해설 +해수욕장 +해안 +핵심 +핸드백 +햄버거 +햇볕 +햇살 +행동 +행복 +행사 +행운 +행위 +향기 +향상 +향수 +허락 +허용 +헬기 +현관 +현금 +현대 +현상 +현실 +현장 +현재 +현지 +혈액 +협력 +형부 +형사 +형수 +형식 +형제 +형태 +형편 +혜택 +호기심 +호남 +호랑이 +호박 +호텔 +호흡 +혹시 +홀로 +홈페이지 +홍보 +홍수 +홍차 +화면 +화분 +화살 +화요일 +화장 +화학 +확보 +확인 +확장 +확정 +환갑 +환경 +환영 +환율 +환자 +활기 +활동 +활발히 +활용 +활짝 +회견 +회관 +회복 +회색 +회원 +회장 +회전 +횟수 +횡단보도 +효율적 +후반 +후춧가루 +훈련 +훨씬 +휴식 +휴일 +흉내 +흐름 +흑백 +흑인 +흔적 +흔히 +흥미 +흥분 +희곡 +희망 +희생 +흰색 +힘껏`.split('\n')); +//# sourceMappingURL=korean.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/portuguese.d.ts b/node_modules/@scure/bip39/wordlists/portuguese.d.ts new file mode 100644 index 0000000..eff14c3 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/portuguese.d.ts @@ -0,0 +1,3 @@ +/** Portuguese BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=portuguese.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/portuguese.js b/node_modules/@scure/bip39/wordlists/portuguese.js new file mode 100644 index 0000000..c7c212a --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/portuguese.js @@ -0,0 +1,2050 @@ +/** Portuguese BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`abacate +abaixo +abalar +abater +abduzir +abelha +aberto +abismo +abotoar +abranger +abreviar +abrigar +abrupto +absinto +absoluto +absurdo +abutre +acabado +acalmar +acampar +acanhar +acaso +aceitar +acelerar +acenar +acervo +acessar +acetona +achatar +acidez +acima +acionado +acirrar +aclamar +aclive +acolhida +acomodar +acoplar +acordar +acumular +acusador +adaptar +adega +adentro +adepto +adequar +aderente +adesivo +adeus +adiante +aditivo +adjetivo +adjunto +admirar +adorar +adquirir +adubo +adverso +advogado +aeronave +afastar +aferir +afetivo +afinador +afivelar +aflito +afluente +afrontar +agachar +agarrar +agasalho +agenciar +agilizar +agiota +agitado +agora +agradar +agreste +agrupar +aguardar +agulha +ajoelhar +ajudar +ajustar +alameda +alarme +alastrar +alavanca +albergue +albino +alcatra +aldeia +alecrim +alegria +alertar +alface +alfinete +algum +alheio +aliar +alicate +alienar +alinhar +aliviar +almofada +alocar +alpiste +alterar +altitude +alucinar +alugar +aluno +alusivo +alvo +amaciar +amador +amarelo +amassar +ambas +ambiente +ameixa +amenizar +amido +amistoso +amizade +amolador +amontoar +amoroso +amostra +amparar +ampliar +ampola +anagrama +analisar +anarquia +anatomia +andaime +anel +anexo +angular +animar +anjo +anomalia +anotado +ansioso +anterior +anuidade +anunciar +anzol +apagador +apalpar +apanhado +apego +apelido +apertada +apesar +apetite +apito +aplauso +aplicada +apoio +apontar +aposta +aprendiz +aprovar +aquecer +arame +aranha +arara +arcada +ardente +areia +arejar +arenito +aresta +argiloso +argola +arma +arquivo +arraial +arrebate +arriscar +arroba +arrumar +arsenal +arterial +artigo +arvoredo +asfaltar +asilado +aspirar +assador +assinar +assoalho +assunto +astral +atacado +atadura +atalho +atarefar +atear +atender +aterro +ateu +atingir +atirador +ativo +atoleiro +atracar +atrevido +atriz +atual +atum +auditor +aumentar +aura +aurora +autismo +autoria +autuar +avaliar +avante +avaria +avental +avesso +aviador +avisar +avulso +axila +azarar +azedo +azeite +azulejo +babar +babosa +bacalhau +bacharel +bacia +bagagem +baiano +bailar +baioneta +bairro +baixista +bajular +baleia +baliza +balsa +banal +bandeira +banho +banir +banquete +barato +barbado +baronesa +barraca +barulho +baseado +bastante +batata +batedor +batida +batom +batucar +baunilha +beber +beijo +beirada +beisebol +beldade +beleza +belga +beliscar +bendito +bengala +benzer +berimbau +berlinda +berro +besouro +bexiga +bezerro +bico +bicudo +bienal +bifocal +bifurcar +bigorna +bilhete +bimestre +bimotor +biologia +biombo +biosfera +bipolar +birrento +biscoito +bisneto +bispo +bissexto +bitola +bizarro +blindado +bloco +bloquear +boato +bobagem +bocado +bocejo +bochecha +boicotar +bolada +boletim +bolha +bolo +bombeiro +bonde +boneco +bonita +borbulha +borda +boreal +borracha +bovino +boxeador +branco +brasa +braveza +breu +briga +brilho +brincar +broa +brochura +bronzear +broto +bruxo +bucha +budismo +bufar +bule +buraco +busca +busto +buzina +cabana +cabelo +cabide +cabo +cabrito +cacau +cacetada +cachorro +cacique +cadastro +cadeado +cafezal +caiaque +caipira +caixote +cajado +caju +calafrio +calcular +caldeira +calibrar +calmante +calota +camada +cambista +camisa +camomila +campanha +camuflar +canavial +cancelar +caneta +canguru +canhoto +canivete +canoa +cansado +cantar +canudo +capacho +capela +capinar +capotar +capricho +captador +capuz +caracol +carbono +cardeal +careca +carimbar +carneiro +carpete +carreira +cartaz +carvalho +casaco +casca +casebre +castelo +casulo +catarata +cativar +caule +causador +cautelar +cavalo +caverna +cebola +cedilha +cegonha +celebrar +celular +cenoura +censo +centeio +cercar +cerrado +certeiro +cerveja +cetim +cevada +chacota +chaleira +chamado +chapada +charme +chatice +chave +chefe +chegada +cheiro +cheque +chicote +chifre +chinelo +chocalho +chover +chumbo +chutar +chuva +cicatriz +ciclone +cidade +cidreira +ciente +cigana +cimento +cinto +cinza +ciranda +circuito +cirurgia +citar +clareza +clero +clicar +clone +clube +coado +coagir +cobaia +cobertor +cobrar +cocada +coelho +coentro +coeso +cogumelo +coibir +coifa +coiote +colar +coleira +colher +colidir +colmeia +colono +coluna +comando +combinar +comentar +comitiva +comover +complexo +comum +concha +condor +conectar +confuso +congelar +conhecer +conjugar +consumir +contrato +convite +cooperar +copeiro +copiador +copo +coquetel +coragem +cordial +corneta +coronha +corporal +correio +cortejo +coruja +corvo +cosseno +costela +cotonete +couro +couve +covil +cozinha +cratera +cravo +creche +credor +creme +crer +crespo +criada +criminal +crioulo +crise +criticar +crosta +crua +cruzeiro +cubano +cueca +cuidado +cujo +culatra +culminar +culpar +cultura +cumprir +cunhado +cupido +curativo +curral +cursar +curto +cuspir +custear +cutelo +damasco +datar +debater +debitar +deboche +debulhar +decalque +decimal +declive +decote +decretar +dedal +dedicado +deduzir +defesa +defumar +degelo +degrau +degustar +deitado +deixar +delator +delegado +delinear +delonga +demanda +demitir +demolido +dentista +depenado +depilar +depois +depressa +depurar +deriva +derramar +desafio +desbotar +descanso +desenho +desfiado +desgaste +desigual +deslize +desmamar +desova +despesa +destaque +desviar +detalhar +detentor +detonar +detrito +deusa +dever +devido +devotado +dezena +diagrama +dialeto +didata +difuso +digitar +dilatado +diluente +diminuir +dinastia +dinheiro +diocese +direto +discreta +disfarce +disparo +disquete +dissipar +distante +ditador +diurno +diverso +divisor +divulgar +dizer +dobrador +dolorido +domador +dominado +donativo +donzela +dormente +dorsal +dosagem +dourado +doutor +drenagem +drible +drogaria +duelar +duende +dueto +duplo +duquesa +durante +duvidoso +eclodir +ecoar +ecologia +edificar +edital +educado +efeito +efetivar +ejetar +elaborar +eleger +eleitor +elenco +elevador +eliminar +elogiar +embargo +embolado +embrulho +embutido +emenda +emergir +emissor +empatia +empenho +empinado +empolgar +emprego +empurrar +emulador +encaixe +encenado +enchente +encontro +endeusar +endossar +enfaixar +enfeite +enfim +engajado +engenho +englobar +engomado +engraxar +enguia +enjoar +enlatar +enquanto +enraizar +enrolado +enrugar +ensaio +enseada +ensino +ensopado +entanto +enteado +entidade +entortar +entrada +entulho +envergar +enviado +envolver +enxame +enxerto +enxofre +enxuto +epiderme +equipar +ereto +erguido +errata +erva +ervilha +esbanjar +esbelto +escama +escola +escrita +escuta +esfinge +esfolar +esfregar +esfumado +esgrima +esmalte +espanto +espelho +espiga +esponja +espreita +espumar +esquerda +estaca +esteira +esticar +estofado +estrela +estudo +esvaziar +etanol +etiqueta +euforia +europeu +evacuar +evaporar +evasivo +eventual +evidente +evoluir +exagero +exalar +examinar +exato +exausto +excesso +excitar +exclamar +executar +exemplo +exibir +exigente +exonerar +expandir +expelir +expirar +explanar +exposto +expresso +expulsar +externo +extinto +extrato +fabricar +fabuloso +faceta +facial +fada +fadiga +faixa +falar +falta +familiar +fandango +fanfarra +fantoche +fardado +farelo +farinha +farofa +farpa +fartura +fatia +fator +favorita +faxina +fazenda +fechado +feijoada +feirante +felino +feminino +fenda +feno +fera +feriado +ferrugem +ferver +festejar +fetal +feudal +fiapo +fibrose +ficar +ficheiro +figurado +fileira +filho +filme +filtrar +firmeza +fisgada +fissura +fita +fivela +fixador +fixo +flacidez +flamingo +flanela +flechada +flora +flutuar +fluxo +focal +focinho +fofocar +fogo +foguete +foice +folgado +folheto +forjar +formiga +forno +forte +fosco +fossa +fragata +fralda +frango +frasco +fraterno +freira +frente +fretar +frieza +friso +fritura +fronha +frustrar +fruteira +fugir +fulano +fuligem +fundar +fungo +funil +furador +furioso +futebol +gabarito +gabinete +gado +gaiato +gaiola +gaivota +galega +galho +galinha +galocha +ganhar +garagem +garfo +gargalo +garimpo +garoupa +garrafa +gasoduto +gasto +gata +gatilho +gaveta +gazela +gelado +geleia +gelo +gemada +gemer +gemido +generoso +gengiva +genial +genoma +genro +geologia +gerador +germinar +gesso +gestor +ginasta +gincana +gingado +girafa +girino +glacial +glicose +global +glorioso +goela +goiaba +golfe +golpear +gordura +gorjeta +gorro +gostoso +goteira +governar +gracejo +gradual +grafite +gralha +grampo +granada +gratuito +graveto +graxa +grego +grelhar +greve +grilo +grisalho +gritaria +grosso +grotesco +grudado +grunhido +gruta +guache +guarani +guaxinim +guerrear +guiar +guincho +guisado +gula +guloso +guru +habitar +harmonia +haste +haver +hectare +herdar +heresia +hesitar +hiato +hibernar +hidratar +hiena +hino +hipismo +hipnose +hipoteca +hoje +holofote +homem +honesto +honrado +hormonal +hospedar +humorado +iate +ideia +idoso +ignorado +igreja +iguana +ileso +ilha +iludido +iluminar +ilustrar +imagem +imediato +imenso +imersivo +iminente +imitador +imortal +impacto +impedir +implante +impor +imprensa +impune +imunizar +inalador +inapto +inativo +incenso +inchar +incidir +incluir +incolor +indeciso +indireto +indutor +ineficaz +inerente +infantil +infestar +infinito +inflamar +informal +infrator +ingerir +inibido +inicial +inimigo +injetar +inocente +inodoro +inovador +inox +inquieto +inscrito +inseto +insistir +inspetor +instalar +insulto +intacto +integral +intimar +intocado +intriga +invasor +inverno +invicto +invocar +iogurte +iraniano +ironizar +irreal +irritado +isca +isento +isolado +isqueiro +italiano +janeiro +jangada +janta +jararaca +jardim +jarro +jasmim +jato +javali +jazida +jejum +joaninha +joelhada +jogador +joia +jornal +jorrar +jovem +juba +judeu +judoca +juiz +julgador +julho +jurado +jurista +juro +justa +labareda +laboral +lacre +lactante +ladrilho +lagarta +lagoa +laje +lamber +lamentar +laminar +lampejo +lanche +lapidar +lapso +laranja +lareira +largura +lasanha +lastro +lateral +latido +lavanda +lavoura +lavrador +laxante +lazer +lealdade +lebre +legado +legendar +legista +leigo +leiloar +leitura +lembrete +leme +lenhador +lentilha +leoa +lesma +leste +letivo +letreiro +levar +leveza +levitar +liberal +libido +liderar +ligar +ligeiro +limitar +limoeiro +limpador +linda +linear +linhagem +liquidez +listagem +lisura +litoral +livro +lixa +lixeira +locador +locutor +lojista +lombo +lona +longe +lontra +lorde +lotado +loteria +loucura +lousa +louvar +luar +lucidez +lucro +luneta +lustre +lutador +luva +macaco +macete +machado +macio +madeira +madrinha +magnata +magreza +maior +mais +malandro +malha +malote +maluco +mamilo +mamoeiro +mamute +manada +mancha +mandato +manequim +manhoso +manivela +manobrar +mansa +manter +manusear +mapeado +maquinar +marcador +maresia +marfim +margem +marinho +marmita +maroto +marquise +marreco +martelo +marujo +mascote +masmorra +massagem +mastigar +matagal +materno +matinal +matutar +maxilar +medalha +medida +medusa +megafone +meiga +melancia +melhor +membro +memorial +menino +menos +mensagem +mental +merecer +mergulho +mesada +mesclar +mesmo +mesquita +mestre +metade +meteoro +metragem +mexer +mexicano +micro +migalha +migrar +milagre +milenar +milhar +mimado +minerar +minhoca +ministro +minoria +miolo +mirante +mirtilo +misturar +mocidade +moderno +modular +moeda +moer +moinho +moita +moldura +moleza +molho +molinete +molusco +montanha +moqueca +morango +morcego +mordomo +morena +mosaico +mosquete +mostarda +motel +motim +moto +motriz +muda +muito +mulata +mulher +multar +mundial +munido +muralha +murcho +muscular +museu +musical +nacional +nadador +naja +namoro +narina +narrado +nascer +nativa +natureza +navalha +navegar +navio +neblina +nebuloso +negativa +negociar +negrito +nervoso +neta +neural +nevasca +nevoeiro +ninar +ninho +nitidez +nivelar +nobreza +noite +noiva +nomear +nominal +nordeste +nortear +notar +noticiar +noturno +novelo +novilho +novo +nublado +nudez +numeral +nupcial +nutrir +nuvem +obcecado +obedecer +objetivo +obrigado +obscuro +obstetra +obter +obturar +ocidente +ocioso +ocorrer +oculista +ocupado +ofegante +ofensiva +oferenda +oficina +ofuscado +ogiva +olaria +oleoso +olhar +oliveira +ombro +omelete +omisso +omitir +ondulado +oneroso +ontem +opcional +operador +oponente +oportuno +oposto +orar +orbitar +ordem +ordinal +orfanato +orgasmo +orgulho +oriental +origem +oriundo +orla +ortodoxo +orvalho +oscilar +ossada +osso +ostentar +otimismo +ousadia +outono +outubro +ouvido +ovelha +ovular +oxidar +oxigenar +pacato +paciente +pacote +pactuar +padaria +padrinho +pagar +pagode +painel +pairar +paisagem +palavra +palestra +palheta +palito +palmada +palpitar +pancada +panela +panfleto +panqueca +pantanal +papagaio +papelada +papiro +parafina +parcial +pardal +parede +partida +pasmo +passado +pastel +patamar +patente +patinar +patrono +paulada +pausar +peculiar +pedalar +pedestre +pediatra +pedra +pegada +peitoral +peixe +pele +pelicano +penca +pendurar +peneira +penhasco +pensador +pente +perceber +perfeito +pergunta +perito +permitir +perna +perplexo +persiana +pertence +peruca +pescado +pesquisa +pessoa +petiscar +piada +picado +piedade +pigmento +pilastra +pilhado +pilotar +pimenta +pincel +pinguim +pinha +pinote +pintar +pioneiro +pipoca +piquete +piranha +pires +pirueta +piscar +pistola +pitanga +pivete +planta +plaqueta +platina +plebeu +plumagem +pluvial +pneu +poda +poeira +poetisa +polegada +policiar +poluente +polvilho +pomar +pomba +ponderar +pontaria +populoso +porta +possuir +postal +pote +poupar +pouso +povoar +praia +prancha +prato +praxe +prece +predador +prefeito +premiar +prensar +preparar +presilha +pretexto +prevenir +prezar +primata +princesa +prisma +privado +processo +produto +profeta +proibido +projeto +prometer +propagar +prosa +protetor +provador +publicar +pudim +pular +pulmonar +pulseira +punhal +punir +pupilo +pureza +puxador +quadra +quantia +quarto +quase +quebrar +queda +queijo +quente +querido +quimono +quina +quiosque +rabanada +rabisco +rachar +racionar +radial +raiar +rainha +raio +raiva +rajada +ralado +ramal +ranger +ranhura +rapadura +rapel +rapidez +raposa +raquete +raridade +rasante +rascunho +rasgar +raspador +rasteira +rasurar +ratazana +ratoeira +realeza +reanimar +reaver +rebaixar +rebelde +rebolar +recado +recente +recheio +recibo +recordar +recrutar +recuar +rede +redimir +redonda +reduzida +reenvio +refinar +refletir +refogar +refresco +refugiar +regalia +regime +regra +reinado +reitor +rejeitar +relativo +remador +remendo +remorso +renovado +reparo +repelir +repleto +repolho +represa +repudiar +requerer +resenha +resfriar +resgatar +residir +resolver +respeito +ressaca +restante +resumir +retalho +reter +retirar +retomada +retratar +revelar +revisor +revolta +riacho +rica +rigidez +rigoroso +rimar +ringue +risada +risco +risonho +robalo +rochedo +rodada +rodeio +rodovia +roedor +roleta +romano +roncar +rosado +roseira +rosto +rota +roteiro +rotina +rotular +rouco +roupa +roxo +rubro +rugido +rugoso +ruivo +rumo +rupestre +russo +sabor +saciar +sacola +sacudir +sadio +safira +saga +sagrada +saibro +salada +saleiro +salgado +saliva +salpicar +salsicha +saltar +salvador +sambar +samurai +sanar +sanfona +sangue +sanidade +sapato +sarda +sargento +sarjeta +saturar +saudade +saxofone +sazonal +secar +secular +seda +sedento +sediado +sedoso +sedutor +segmento +segredo +segundo +seiva +seleto +selvagem +semanal +semente +senador +senhor +sensual +sentado +separado +sereia +seringa +serra +servo +setembro +setor +sigilo +silhueta +silicone +simetria +simpatia +simular +sinal +sincero +singular +sinopse +sintonia +sirene +siri +situado +soberano +sobra +socorro +sogro +soja +solda +soletrar +solteiro +sombrio +sonata +sondar +sonegar +sonhador +sono +soprano +soquete +sorrir +sorteio +sossego +sotaque +soterrar +sovado +sozinho +suavizar +subida +submerso +subsolo +subtrair +sucata +sucesso +suco +sudeste +sufixo +sugador +sugerir +sujeito +sulfato +sumir +suor +superior +suplicar +suposto +suprimir +surdina +surfista +surpresa +surreal +surtir +suspiro +sustento +tabela +tablete +tabuada +tacho +tagarela +talher +talo +talvez +tamanho +tamborim +tampa +tangente +tanto +tapar +tapioca +tardio +tarefa +tarja +tarraxa +tatuagem +taurino +taxativo +taxista +teatral +tecer +tecido +teclado +tedioso +teia +teimar +telefone +telhado +tempero +tenente +tensor +tentar +termal +terno +terreno +tese +tesoura +testado +teto +textura +texugo +tiara +tigela +tijolo +timbrar +timidez +tingido +tinteiro +tiragem +titular +toalha +tocha +tolerar +tolice +tomada +tomilho +tonel +tontura +topete +tora +torcido +torneio +torque +torrada +torto +tostar +touca +toupeira +toxina +trabalho +tracejar +tradutor +trafegar +trajeto +trama +trancar +trapo +traseiro +tratador +travar +treino +tremer +trepidar +trevo +triagem +tribo +triciclo +tridente +trilogia +trindade +triplo +triturar +triunfal +trocar +trombeta +trova +trunfo +truque +tubular +tucano +tudo +tulipa +tupi +turbo +turma +turquesa +tutelar +tutorial +uivar +umbigo +unha +unidade +uniforme +urologia +urso +urtiga +urubu +usado +usina +usufruir +vacina +vadiar +vagaroso +vaidoso +vala +valente +validade +valores +vantagem +vaqueiro +varanda +vareta +varrer +vascular +vasilha +vassoura +vazar +vazio +veado +vedar +vegetar +veicular +veleiro +velhice +veludo +vencedor +vendaval +venerar +ventre +verbal +verdade +vereador +vergonha +vermelho +verniz +versar +vertente +vespa +vestido +vetorial +viaduto +viagem +viajar +viatura +vibrador +videira +vidraria +viela +viga +vigente +vigiar +vigorar +vilarejo +vinco +vinheta +vinil +violeta +virada +virtude +visitar +visto +vitral +viveiro +vizinho +voador +voar +vogal +volante +voleibol +voltagem +volumoso +vontade +vulto +vuvuzela +xadrez +xarope +xeque +xeretar +xerife +xingar +zangado +zarpar +zebu +zelador +zombar +zoologia +zumbido`.split('\n')); +//# sourceMappingURL=portuguese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts b/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts new file mode 100644 index 0000000..d620597 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/simplified-chinese.d.ts @@ -0,0 +1,3 @@ +/** Simplified Chinese BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=simplified-chinese.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/simplified-chinese.js b/node_modules/@scure/bip39/wordlists/simplified-chinese.js new file mode 100644 index 0000000..397e007 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/simplified-chinese.js @@ -0,0 +1,2050 @@ +/** Simplified Chinese BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`的 +一 +是 +在 +不 +了 +有 +和 +人 +这 +中 +大 +为 +上 +个 +国 +我 +以 +要 +他 +时 +来 +用 +们 +生 +到 +作 +地 +于 +出 +就 +分 +对 +成 +会 +可 +主 +发 +年 +动 +同 +工 +也 +能 +下 +过 +子 +说 +产 +种 +面 +而 +方 +后 +多 +定 +行 +学 +法 +所 +民 +得 +经 +十 +三 +之 +进 +着 +等 +部 +度 +家 +电 +力 +里 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +现 +实 +加 +量 +都 +两 +体 +制 +机 +当 +使 +点 +从 +业 +本 +去 +把 +性 +好 +应 +开 +它 +合 +还 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +义 +事 +平 +形 +相 +全 +表 +间 +样 +与 +关 +各 +重 +新 +线 +内 +数 +正 +心 +反 +你 +明 +看 +原 +又 +么 +利 +比 +或 +但 +质 +气 +第 +向 +道 +命 +此 +变 +条 +只 +没 +结 +解 +问 +意 +建 +月 +公 +无 +系 +军 +很 +情 +者 +最 +立 +代 +想 +已 +通 +并 +提 +直 +题 +党 +程 +展 +五 +果 +料 +象 +员 +革 +位 +入 +常 +文 +总 +次 +品 +式 +活 +设 +及 +管 +特 +件 +长 +求 +老 +头 +基 +资 +边 +流 +路 +级 +少 +图 +山 +统 +接 +知 +较 +将 +组 +见 +计 +别 +她 +手 +角 +期 +根 +论 +运 +农 +指 +几 +九 +区 +强 +放 +决 +西 +被 +干 +做 +必 +战 +先 +回 +则 +任 +取 +据 +处 +队 +南 +给 +色 +光 +门 +即 +保 +治 +北 +造 +百 +规 +热 +领 +七 +海 +口 +东 +导 +器 +压 +志 +世 +金 +增 +争 +济 +阶 +油 +思 +术 +极 +交 +受 +联 +什 +认 +六 +共 +权 +收 +证 +改 +清 +美 +再 +采 +转 +更 +单 +风 +切 +打 +白 +教 +速 +花 +带 +安 +场 +身 +车 +例 +真 +务 +具 +万 +每 +目 +至 +达 +走 +积 +示 +议 +声 +报 +斗 +完 +类 +八 +离 +华 +名 +确 +才 +科 +张 +信 +马 +节 +话 +米 +整 +空 +元 +况 +今 +集 +温 +传 +土 +许 +步 +群 +广 +石 +记 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +观 +越 +织 +装 +影 +算 +低 +持 +音 +众 +书 +布 +复 +容 +儿 +须 +际 +商 +非 +验 +连 +断 +深 +难 +近 +矿 +千 +周 +委 +素 +技 +备 +半 +办 +青 +省 +列 +习 +响 +约 +支 +般 +史 +感 +劳 +便 +团 +往 +酸 +历 +市 +克 +何 +除 +消 +构 +府 +称 +太 +准 +精 +值 +号 +率 +族 +维 +划 +选 +标 +写 +存 +候 +毛 +亲 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +养 +易 +置 +派 +层 +片 +始 +却 +专 +状 +育 +厂 +京 +识 +适 +属 +圆 +包 +火 +住 +调 +满 +县 +局 +照 +参 +红 +细 +引 +听 +该 +铁 +价 +严 +首 +底 +液 +官 +德 +随 +病 +苏 +失 +尔 +死 +讲 +配 +女 +黄 +推 +显 +谈 +罪 +神 +艺 +呢 +席 +含 +企 +望 +密 +批 +营 +项 +防 +举 +球 +英 +氧 +势 +告 +李 +台 +落 +木 +帮 +轮 +破 +亚 +师 +围 +注 +远 +字 +材 +排 +供 +河 +态 +封 +另 +施 +减 +树 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +叶 +鱼 +波 +视 +仅 +费 +紧 +爱 +左 +章 +早 +朝 +害 +续 +轻 +服 +试 +食 +充 +兵 +源 +判 +护 +司 +足 +某 +练 +差 +致 +板 +田 +降 +黑 +犯 +负 +击 +范 +继 +兴 +似 +余 +坚 +曲 +输 +修 +故 +城 +夫 +够 +送 +笔 +船 +占 +右 +财 +吃 +富 +春 +职 +觉 +汉 +画 +功 +巴 +跟 +虽 +杂 +飞 +检 +吸 +助 +升 +阳 +互 +初 +创 +抗 +考 +投 +坏 +策 +古 +径 +换 +未 +跑 +留 +钢 +曾 +端 +责 +站 +简 +述 +钱 +副 +尽 +帝 +射 +草 +冲 +承 +独 +令 +限 +阿 +宣 +环 +双 +请 +超 +微 +让 +控 +州 +良 +轴 +找 +否 +纪 +益 +依 +优 +顶 +础 +载 +倒 +房 +突 +坐 +粉 +敌 +略 +客 +袁 +冷 +胜 +绝 +析 +块 +剂 +测 +丝 +协 +诉 +念 +陈 +仍 +罗 +盐 +友 +洋 +错 +苦 +夜 +刑 +移 +频 +逐 +靠 +混 +母 +短 +皮 +终 +聚 +汽 +村 +云 +哪 +既 +距 +卫 +停 +烈 +央 +察 +烧 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +游 +久 +菜 +味 +旧 +模 +湖 +货 +损 +预 +阻 +毫 +普 +稳 +乙 +妈 +植 +息 +扩 +银 +语 +挥 +酒 +守 +拿 +序 +纸 +医 +缺 +雨 +吗 +针 +刘 +啊 +急 +唱 +误 +训 +愿 +审 +附 +获 +茶 +鲜 +粮 +斤 +孩 +脱 +硫 +肥 +善 +龙 +演 +父 +渐 +血 +欢 +械 +掌 +歌 +沙 +刚 +攻 +谓 +盾 +讨 +晚 +粒 +乱 +燃 +矛 +乎 +杀 +药 +宁 +鲁 +贵 +钟 +煤 +读 +班 +伯 +香 +介 +迫 +句 +丰 +培 +握 +兰 +担 +弦 +蛋 +沉 +假 +穿 +执 +答 +乐 +谁 +顺 +烟 +缩 +征 +脸 +喜 +松 +脚 +困 +异 +免 +背 +星 +福 +买 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +静 +补 +评 +翻 +肉 +践 +尼 +衣 +宽 +扬 +棉 +希 +伤 +操 +垂 +秋 +宜 +氢 +套 +督 +振 +架 +亮 +末 +宪 +庆 +编 +牛 +触 +映 +雷 +销 +诗 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +绿 +晶 +厚 +盟 +衡 +鸡 +孙 +延 +危 +胶 +屋 +乡 +临 +陆 +顾 +掉 +呀 +灯 +岁 +措 +束 +耐 +剧 +玉 +赵 +跳 +哥 +季 +课 +凯 +胡 +额 +款 +绍 +卷 +齐 +伟 +蒸 +殖 +永 +宗 +苗 +川 +炉 +岩 +弱 +零 +杨 +奏 +沿 +露 +杆 +探 +滑 +镇 +饭 +浓 +航 +怀 +赶 +库 +夺 +伊 +灵 +税 +途 +灭 +赛 +归 +召 +鼓 +播 +盘 +裁 +险 +康 +唯 +录 +菌 +纯 +借 +糖 +盖 +横 +符 +私 +努 +堂 +域 +枪 +润 +幅 +哈 +竟 +熟 +虫 +泽 +脑 +壤 +碳 +欧 +遍 +侧 +寨 +敢 +彻 +虑 +斜 +薄 +庭 +纳 +弹 +饲 +伸 +折 +麦 +湿 +暗 +荷 +瓦 +塞 +床 +筑 +恶 +户 +访 +塔 +奇 +透 +梁 +刀 +旋 +迹 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +摆 +灰 +彩 +卖 +耗 +夏 +择 +忙 +铜 +献 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +阵 +阴 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +楼 +避 +谋 +吨 +野 +猪 +旗 +累 +偏 +典 +馆 +索 +秦 +脂 +潮 +爷 +豆 +忽 +托 +惊 +塑 +遗 +愈 +朱 +替 +纤 +粗 +倾 +尚 +痛 +楚 +谢 +奋 +购 +磨 +君 +池 +旁 +碎 +骨 +监 +捕 +弟 +暴 +割 +贯 +殊 +释 +词 +亡 +壁 +顿 +宝 +午 +尘 +闻 +揭 +炮 +残 +冬 +桥 +妇 +警 +综 +招 +吴 +付 +浮 +遭 +徐 +您 +摇 +谷 +赞 +箱 +隔 +订 +男 +吹 +园 +纷 +唐 +败 +宋 +玻 +巨 +耕 +坦 +荣 +闭 +湾 +键 +凡 +驻 +锅 +救 +恩 +剥 +凝 +碱 +齿 +截 +炼 +麻 +纺 +禁 +废 +盛 +版 +缓 +净 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +庄 +街 +藏 +姑 +贸 +腐 +奴 +啦 +惯 +乘 +伙 +恢 +匀 +纱 +扎 +辩 +耳 +彪 +臣 +亿 +璃 +抵 +脉 +秀 +萨 +俄 +网 +舞 +店 +喷 +纵 +寸 +汗 +挂 +洪 +贺 +闪 +柬 +爆 +烯 +津 +稻 +墙 +软 +勇 +像 +滚 +厘 +蒙 +芳 +肯 +坡 +柱 +荡 +腿 +仪 +旅 +尾 +轧 +冰 +贡 +登 +黎 +削 +钻 +勒 +逃 +障 +氨 +郭 +峰 +币 +港 +伏 +轨 +亩 +毕 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +岛 +甘 +泡 +睡 +童 +铸 +汤 +阀 +休 +汇 +舍 +牧 +绕 +炸 +哲 +磷 +绩 +朋 +淡 +尖 +启 +陷 +柴 +呈 +徒 +颜 +泪 +稍 +忘 +泵 +蓝 +拖 +洞 +授 +镜 +辛 +壮 +锋 +贫 +虚 +弯 +摩 +泰 +幼 +廷 +尊 +窗 +纲 +弄 +隶 +疑 +氏 +宫 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +违 +夹 +腰 +缘 +珠 +穷 +森 +枝 +竹 +沟 +催 +绳 +忆 +邦 +剩 +幸 +浆 +栏 +拥 +牙 +贮 +礼 +滤 +钠 +纹 +罢 +拍 +咱 +喊 +袖 +埃 +勤 +罚 +焦 +潜 +伍 +墨 +欲 +缝 +姓 +刊 +饱 +仿 +奖 +铝 +鬼 +丽 +跨 +默 +挖 +链 +扫 +喝 +袋 +炭 +污 +幕 +诸 +弧 +励 +梅 +奶 +洁 +灾 +舟 +鉴 +苯 +讼 +抱 +毁 +懂 +寒 +智 +埔 +寄 +届 +跃 +渡 +挑 +丹 +艰 +贝 +碰 +拔 +爹 +戴 +码 +梦 +芽 +熔 +赤 +渔 +哭 +敬 +颗 +奔 +铅 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +仓 +魏 +锐 +晓 +氮 +兼 +隐 +碍 +赫 +拨 +忠 +肃 +缸 +牵 +抢 +博 +巧 +壳 +兄 +杜 +讯 +诚 +碧 +祥 +柯 +页 +巡 +矩 +悲 +灌 +龄 +伦 +票 +寻 +桂 +铺 +圣 +恐 +恰 +郑 +趣 +抬 +荒 +腾 +贴 +柔 +滴 +猛 +阔 +辆 +妻 +填 +撤 +储 +签 +闹 +扰 +紫 +砂 +递 +戏 +吊 +陶 +伐 +喂 +疗 +瓶 +婆 +抚 +臂 +摸 +忍 +虾 +蜡 +邻 +胸 +巩 +挤 +偶 +弃 +槽 +劲 +乳 +邓 +吉 +仁 +烂 +砖 +租 +乌 +舰 +伴 +瓜 +浅 +丙 +暂 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +胆 +详 +簧 +踏 +瓷 +谱 +呆 +宾 +糊 +洛 +辉 +愤 +竞 +隙 +怒 +粘 +乃 +绪 +肩 +籍 +敏 +涂 +熙 +皆 +侦 +悬 +掘 +享 +纠 +醒 +狂 +锁 +淀 +恨 +牲 +霸 +爬 +赏 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鸭 +趋 +凤 +晨 +畜 +辈 +秩 +卵 +署 +梯 +炎 +滩 +棋 +驱 +筛 +峡 +冒 +啥 +寿 +译 +浸 +泉 +帽 +迟 +硅 +疆 +贷 +漏 +稿 +冠 +嫩 +胁 +芯 +牢 +叛 +蚀 +奥 +鸣 +岭 +羊 +凭 +串 +塘 +绘 +酵 +融 +盆 +锡 +庙 +筹 +冻 +辅 +摄 +袭 +筋 +拒 +僚 +旱 +钾 +鸟 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韩 +逼 +扭 +侨 +凉 +挺 +碗 +栽 +炒 +杯 +患 +馏 +劝 +豪 +辽 +勃 +鸿 +旦 +吏 +拜 +狗 +埋 +辊 +掩 +饮 +搬 +骂 +辞 +勾 +扣 +估 +蒋 +绒 +雾 +丈 +朵 +姆 +拟 +宇 +辑 +陕 +雕 +偿 +蓄 +崇 +剪 +倡 +厅 +咬 +驶 +薯 +刷 +斥 +番 +赋 +奉 +佛 +浇 +漫 +曼 +扇 +钙 +桃 +扶 +仔 +返 +俗 +亏 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +骗 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +胀 +谐 +抛 +霉 +桑 +岗 +嘛 +衰 +盗 +渗 +脏 +赖 +涌 +甜 +曹 +阅 +肌 +哩 +厉 +烃 +纬 +毅 +昨 +伪 +症 +煮 +叹 +钉 +搭 +茎 +笼 +酷 +偷 +弓 +锥 +恒 +杰 +坑 +鼻 +翼 +纶 +叙 +狱 +逮 +罐 +络 +棚 +抑 +膨 +蔬 +寺 +骤 +穆 +冶 +枯 +册 +尸 +凸 +绅 +坯 +牺 +焰 +轰 +欣 +晋 +瘦 +御 +锭 +锦 +丧 +旬 +锻 +垄 +搜 +扑 +邀 +亭 +酯 +迈 +舒 +脆 +酶 +闲 +忧 +酚 +顽 +羽 +涨 +卸 +仗 +陪 +辟 +惩 +杭 +姚 +肚 +捉 +飘 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +饰 +萧 +雅 +邮 +迁 +燕 +撒 +姻 +赴 +宴 +烦 +债 +帐 +斑 +铃 +旨 +醇 +董 +饼 +雏 +姿 +拌 +傅 +腹 +妥 +揉 +贤 +拆 +歪 +葡 +胺 +丢 +浩 +徽 +昂 +垫 +挡 +览 +贪 +慰 +缴 +汪 +慌 +冯 +诺 +姜 +谊 +凶 +劣 +诬 +耀 +昏 +躺 +盈 +骑 +乔 +溪 +丛 +卢 +抹 +闷 +咨 +刮 +驾 +缆 +悟 +摘 +铒 +掷 +颇 +幻 +柄 +惠 +惨 +佳 +仇 +腊 +窝 +涤 +剑 +瞧 +堡 +泼 +葱 +罩 +霍 +捞 +胎 +苍 +滨 +俩 +捅 +湘 +砍 +霞 +邵 +萄 +疯 +淮 +遂 +熊 +粪 +烘 +宿 +档 +戈 +驳 +嫂 +裕 +徙 +箭 +捐 +肠 +撑 +晒 +辨 +殿 +莲 +摊 +搅 +酱 +屏 +疫 +哀 +蔡 +堵 +沫 +皱 +畅 +叠 +阁 +莱 +敲 +辖 +钩 +痕 +坝 +巷 +饿 +祸 +丘 +玄 +溜 +曰 +逻 +彭 +尝 +卿 +妨 +艇 +吞 +韦 +怨 +矮 +歇`.split('\n')); +//# sourceMappingURL=simplified-chinese.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/spanish.d.ts b/node_modules/@scure/bip39/wordlists/spanish.d.ts new file mode 100644 index 0000000..19638b0 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/spanish.d.ts @@ -0,0 +1,3 @@ +/** Spanish BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=spanish.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/spanish.js b/node_modules/@scure/bip39/wordlists/spanish.js new file mode 100644 index 0000000..bac4f0e --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/spanish.js @@ -0,0 +1,2050 @@ +/** Spanish BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`ábaco +abdomen +abeja +abierto +abogado +abono +aborto +abrazo +abrir +abuelo +abuso +acabar +academia +acceso +acción +aceite +acelga +acento +aceptar +ácido +aclarar +acné +acoger +acoso +activo +acto +actriz +actuar +acudir +acuerdo +acusar +adicto +admitir +adoptar +adorno +aduana +adulto +aéreo +afectar +afición +afinar +afirmar +ágil +agitar +agonía +agosto +agotar +agregar +agrio +agua +agudo +águila +aguja +ahogo +ahorro +aire +aislar +ajedrez +ajeno +ajuste +alacrán +alambre +alarma +alba +álbum +alcalde +aldea +alegre +alejar +alerta +aleta +alfiler +alga +algodón +aliado +aliento +alivio +alma +almeja +almíbar +altar +alteza +altivo +alto +altura +alumno +alzar +amable +amante +amapola +amargo +amasar +ámbar +ámbito +ameno +amigo +amistad +amor +amparo +amplio +ancho +anciano +ancla +andar +andén +anemia +ángulo +anillo +ánimo +anís +anotar +antena +antiguo +antojo +anual +anular +anuncio +añadir +añejo +año +apagar +aparato +apetito +apio +aplicar +apodo +aporte +apoyo +aprender +aprobar +apuesta +apuro +arado +araña +arar +árbitro +árbol +arbusto +archivo +arco +arder +ardilla +arduo +área +árido +aries +armonía +arnés +aroma +arpa +arpón +arreglo +arroz +arruga +arte +artista +asa +asado +asalto +ascenso +asegurar +aseo +asesor +asiento +asilo +asistir +asno +asombro +áspero +astilla +astro +astuto +asumir +asunto +atajo +ataque +atar +atento +ateo +ático +atleta +átomo +atraer +atroz +atún +audaz +audio +auge +aula +aumento +ausente +autor +aval +avance +avaro +ave +avellana +avena +avestruz +avión +aviso +ayer +ayuda +ayuno +azafrán +azar +azote +azúcar +azufre +azul +baba +babor +bache +bahía +baile +bajar +balanza +balcón +balde +bambú +banco +banda +baño +barba +barco +barniz +barro +báscula +bastón +basura +batalla +batería +batir +batuta +baúl +bazar +bebé +bebida +bello +besar +beso +bestia +bicho +bien +bingo +blanco +bloque +blusa +boa +bobina +bobo +boca +bocina +boda +bodega +boina +bola +bolero +bolsa +bomba +bondad +bonito +bono +bonsái +borde +borrar +bosque +bote +botín +bóveda +bozal +bravo +brazo +brecha +breve +brillo +brinco +brisa +broca +broma +bronce +brote +bruja +brusco +bruto +buceo +bucle +bueno +buey +bufanda +bufón +búho +buitre +bulto +burbuja +burla +burro +buscar +butaca +buzón +caballo +cabeza +cabina +cabra +cacao +cadáver +cadena +caer +café +caída +caimán +caja +cajón +cal +calamar +calcio +caldo +calidad +calle +calma +calor +calvo +cama +cambio +camello +camino +campo +cáncer +candil +canela +canguro +canica +canto +caña +cañón +caoba +caos +capaz +capitán +capote +captar +capucha +cara +carbón +cárcel +careta +carga +cariño +carne +carpeta +carro +carta +casa +casco +casero +caspa +castor +catorce +catre +caudal +causa +cazo +cebolla +ceder +cedro +celda +célebre +celoso +célula +cemento +ceniza +centro +cerca +cerdo +cereza +cero +cerrar +certeza +césped +cetro +chacal +chaleco +champú +chancla +chapa +charla +chico +chiste +chivo +choque +choza +chuleta +chupar +ciclón +ciego +cielo +cien +cierto +cifra +cigarro +cima +cinco +cine +cinta +ciprés +circo +ciruela +cisne +cita +ciudad +clamor +clan +claro +clase +clave +cliente +clima +clínica +cobre +cocción +cochino +cocina +coco +código +codo +cofre +coger +cohete +cojín +cojo +cola +colcha +colegio +colgar +colina +collar +colmo +columna +combate +comer +comida +cómodo +compra +conde +conejo +conga +conocer +consejo +contar +copa +copia +corazón +corbata +corcho +cordón +corona +correr +coser +cosmos +costa +cráneo +cráter +crear +crecer +creído +crema +cría +crimen +cripta +crisis +cromo +crónica +croqueta +crudo +cruz +cuadro +cuarto +cuatro +cubo +cubrir +cuchara +cuello +cuento +cuerda +cuesta +cueva +cuidar +culebra +culpa +culto +cumbre +cumplir +cuna +cuneta +cuota +cupón +cúpula +curar +curioso +curso +curva +cutis +dama +danza +dar +dardo +dátil +deber +débil +década +decir +dedo +defensa +definir +dejar +delfín +delgado +delito +demora +denso +dental +deporte +derecho +derrota +desayuno +deseo +desfile +desnudo +destino +desvío +detalle +detener +deuda +día +diablo +diadema +diamante +diana +diario +dibujo +dictar +diente +dieta +diez +difícil +digno +dilema +diluir +dinero +directo +dirigir +disco +diseño +disfraz +diva +divino +doble +doce +dolor +domingo +don +donar +dorado +dormir +dorso +dos +dosis +dragón +droga +ducha +duda +duelo +dueño +dulce +dúo +duque +durar +dureza +duro +ébano +ebrio +echar +eco +ecuador +edad +edición +edificio +editor +educar +efecto +eficaz +eje +ejemplo +elefante +elegir +elemento +elevar +elipse +élite +elixir +elogio +eludir +embudo +emitir +emoción +empate +empeño +empleo +empresa +enano +encargo +enchufe +encía +enemigo +enero +enfado +enfermo +engaño +enigma +enlace +enorme +enredo +ensayo +enseñar +entero +entrar +envase +envío +época +equipo +erizo +escala +escena +escolar +escribir +escudo +esencia +esfera +esfuerzo +espada +espejo +espía +esposa +espuma +esquí +estar +este +estilo +estufa +etapa +eterno +ética +etnia +evadir +evaluar +evento +evitar +exacto +examen +exceso +excusa +exento +exigir +exilio +existir +éxito +experto +explicar +exponer +extremo +fábrica +fábula +fachada +fácil +factor +faena +faja +falda +fallo +falso +faltar +fama +familia +famoso +faraón +farmacia +farol +farsa +fase +fatiga +fauna +favor +fax +febrero +fecha +feliz +feo +feria +feroz +fértil +fervor +festín +fiable +fianza +fiar +fibra +ficción +ficha +fideo +fiebre +fiel +fiera +fiesta +figura +fijar +fijo +fila +filete +filial +filtro +fin +finca +fingir +finito +firma +flaco +flauta +flecha +flor +flota +fluir +flujo +flúor +fobia +foca +fogata +fogón +folio +folleto +fondo +forma +forro +fortuna +forzar +fosa +foto +fracaso +frágil +franja +frase +fraude +freír +freno +fresa +frío +frito +fruta +fuego +fuente +fuerza +fuga +fumar +función +funda +furgón +furia +fusil +fútbol +futuro +gacela +gafas +gaita +gajo +gala +galería +gallo +gamba +ganar +gancho +ganga +ganso +garaje +garza +gasolina +gastar +gato +gavilán +gemelo +gemir +gen +género +genio +gente +geranio +gerente +germen +gesto +gigante +gimnasio +girar +giro +glaciar +globo +gloria +gol +golfo +goloso +golpe +goma +gordo +gorila +gorra +gota +goteo +gozar +grada +gráfico +grano +grasa +gratis +grave +grieta +grillo +gripe +gris +grito +grosor +grúa +grueso +grumo +grupo +guante +guapo +guardia +guerra +guía +guiño +guion +guiso +guitarra +gusano +gustar +haber +hábil +hablar +hacer +hacha +hada +hallar +hamaca +harina +haz +hazaña +hebilla +hebra +hecho +helado +helio +hembra +herir +hermano +héroe +hervir +hielo +hierro +hígado +higiene +hijo +himno +historia +hocico +hogar +hoguera +hoja +hombre +hongo +honor +honra +hora +hormiga +horno +hostil +hoyo +hueco +huelga +huerta +hueso +huevo +huida +huir +humano +húmedo +humilde +humo +hundir +huracán +hurto +icono +ideal +idioma +ídolo +iglesia +iglú +igual +ilegal +ilusión +imagen +imán +imitar +impar +imperio +imponer +impulso +incapaz +índice +inerte +infiel +informe +ingenio +inicio +inmenso +inmune +innato +insecto +instante +interés +íntimo +intuir +inútil +invierno +ira +iris +ironía +isla +islote +jabalí +jabón +jamón +jarabe +jardín +jarra +jaula +jazmín +jefe +jeringa +jinete +jornada +joroba +joven +joya +juerga +jueves +juez +jugador +jugo +juguete +juicio +junco +jungla +junio +juntar +júpiter +jurar +justo +juvenil +juzgar +kilo +koala +labio +lacio +lacra +lado +ladrón +lagarto +lágrima +laguna +laico +lamer +lámina +lámpara +lana +lancha +langosta +lanza +lápiz +largo +larva +lástima +lata +látex +latir +laurel +lavar +lazo +leal +lección +leche +lector +leer +legión +legumbre +lejano +lengua +lento +leña +león +leopardo +lesión +letal +letra +leve +leyenda +libertad +libro +licor +líder +lidiar +lienzo +liga +ligero +lima +límite +limón +limpio +lince +lindo +línea +lingote +lino +linterna +líquido +liso +lista +litera +litio +litro +llaga +llama +llanto +llave +llegar +llenar +llevar +llorar +llover +lluvia +lobo +loción +loco +locura +lógica +logro +lombriz +lomo +lonja +lote +lucha +lucir +lugar +lujo +luna +lunes +lupa +lustro +luto +luz +maceta +macho +madera +madre +maduro +maestro +mafia +magia +mago +maíz +maldad +maleta +malla +malo +mamá +mambo +mamut +manco +mando +manejar +manga +maniquí +manjar +mano +manso +manta +mañana +mapa +máquina +mar +marco +marea +marfil +margen +marido +mármol +marrón +martes +marzo +masa +máscara +masivo +matar +materia +matiz +matriz +máximo +mayor +mazorca +mecha +medalla +medio +médula +mejilla +mejor +melena +melón +memoria +menor +mensaje +mente +menú +mercado +merengue +mérito +mes +mesón +meta +meter +método +metro +mezcla +miedo +miel +miembro +miga +mil +milagro +militar +millón +mimo +mina +minero +mínimo +minuto +miope +mirar +misa +miseria +misil +mismo +mitad +mito +mochila +moción +moda +modelo +moho +mojar +molde +moler +molino +momento +momia +monarca +moneda +monja +monto +moño +morada +morder +moreno +morir +morro +morsa +mortal +mosca +mostrar +motivo +mover +móvil +mozo +mucho +mudar +mueble +muela +muerte +muestra +mugre +mujer +mula +muleta +multa +mundo +muñeca +mural +muro +músculo +museo +musgo +música +muslo +nácar +nación +nadar +naipe +naranja +nariz +narrar +nasal +natal +nativo +natural +náusea +naval +nave +navidad +necio +néctar +negar +negocio +negro +neón +nervio +neto +neutro +nevar +nevera +nicho +nido +niebla +nieto +niñez +niño +nítido +nivel +nobleza +noche +nómina +noria +norma +norte +nota +noticia +novato +novela +novio +nube +nuca +núcleo +nudillo +nudo +nuera +nueve +nuez +nulo +número +nutria +oasis +obeso +obispo +objeto +obra +obrero +observar +obtener +obvio +oca +ocaso +océano +ochenta +ocho +ocio +ocre +octavo +octubre +oculto +ocupar +ocurrir +odiar +odio +odisea +oeste +ofensa +oferta +oficio +ofrecer +ogro +oído +oír +ojo +ola +oleada +olfato +olivo +olla +olmo +olor +olvido +ombligo +onda +onza +opaco +opción +ópera +opinar +oponer +optar +óptica +opuesto +oración +orador +oral +órbita +orca +orden +oreja +órgano +orgía +orgullo +oriente +origen +orilla +oro +orquesta +oruga +osadía +oscuro +osezno +oso +ostra +otoño +otro +oveja +óvulo +óxido +oxígeno +oyente +ozono +pacto +padre +paella +página +pago +país +pájaro +palabra +palco +paleta +pálido +palma +paloma +palpar +pan +panal +pánico +pantera +pañuelo +papá +papel +papilla +paquete +parar +parcela +pared +parir +paro +párpado +parque +párrafo +parte +pasar +paseo +pasión +paso +pasta +pata +patio +patria +pausa +pauta +pavo +payaso +peatón +pecado +pecera +pecho +pedal +pedir +pegar +peine +pelar +peldaño +pelea +peligro +pellejo +pelo +peluca +pena +pensar +peñón +peón +peor +pepino +pequeño +pera +percha +perder +pereza +perfil +perico +perla +permiso +perro +persona +pesa +pesca +pésimo +pestaña +pétalo +petróleo +pez +pezuña +picar +pichón +pie +piedra +pierna +pieza +pijama +pilar +piloto +pimienta +pino +pintor +pinza +piña +piojo +pipa +pirata +pisar +piscina +piso +pista +pitón +pizca +placa +plan +plata +playa +plaza +pleito +pleno +plomo +pluma +plural +pobre +poco +poder +podio +poema +poesía +poeta +polen +policía +pollo +polvo +pomada +pomelo +pomo +pompa +poner +porción +portal +posada +poseer +posible +poste +potencia +potro +pozo +prado +precoz +pregunta +premio +prensa +preso +previo +primo +príncipe +prisión +privar +proa +probar +proceso +producto +proeza +profesor +programa +prole +promesa +pronto +propio +próximo +prueba +público +puchero +pudor +pueblo +puerta +puesto +pulga +pulir +pulmón +pulpo +pulso +puma +punto +puñal +puño +pupa +pupila +puré +quedar +queja +quemar +querer +queso +quieto +química +quince +quitar +rábano +rabia +rabo +ración +radical +raíz +rama +rampa +rancho +rango +rapaz +rápido +rapto +rasgo +raspa +rato +rayo +raza +razón +reacción +realidad +rebaño +rebote +recaer +receta +rechazo +recoger +recreo +recto +recurso +red +redondo +reducir +reflejo +reforma +refrán +refugio +regalo +regir +regla +regreso +rehén +reino +reír +reja +relato +relevo +relieve +relleno +reloj +remar +remedio +remo +rencor +rendir +renta +reparto +repetir +reposo +reptil +res +rescate +resina +respeto +resto +resumen +retiro +retorno +retrato +reunir +revés +revista +rey +rezar +rico +riego +rienda +riesgo +rifa +rígido +rigor +rincón +riñón +río +riqueza +risa +ritmo +rito +rizo +roble +roce +rociar +rodar +rodeo +rodilla +roer +rojizo +rojo +romero +romper +ron +ronco +ronda +ropa +ropero +rosa +rosca +rostro +rotar +rubí +rubor +rudo +rueda +rugir +ruido +ruina +ruleta +rulo +rumbo +rumor +ruptura +ruta +rutina +sábado +saber +sabio +sable +sacar +sagaz +sagrado +sala +saldo +salero +salir +salmón +salón +salsa +salto +salud +salvar +samba +sanción +sandía +sanear +sangre +sanidad +sano +santo +sapo +saque +sardina +sartén +sastre +satán +sauna +saxofón +sección +seco +secreto +secta +sed +seguir +seis +sello +selva +semana +semilla +senda +sensor +señal +señor +separar +sepia +sequía +ser +serie +sermón +servir +sesenta +sesión +seta +setenta +severo +sexo +sexto +sidra +siesta +siete +siglo +signo +sílaba +silbar +silencio +silla +símbolo +simio +sirena +sistema +sitio +situar +sobre +socio +sodio +sol +solapa +soldado +soledad +sólido +soltar +solución +sombra +sondeo +sonido +sonoro +sonrisa +sopa +soplar +soporte +sordo +sorpresa +sorteo +sostén +sótano +suave +subir +suceso +sudor +suegra +suelo +sueño +suerte +sufrir +sujeto +sultán +sumar +superar +suplir +suponer +supremo +sur +surco +sureño +surgir +susto +sutil +tabaco +tabique +tabla +tabú +taco +tacto +tajo +talar +talco +talento +talla +talón +tamaño +tambor +tango +tanque +tapa +tapete +tapia +tapón +taquilla +tarde +tarea +tarifa +tarjeta +tarot +tarro +tarta +tatuaje +tauro +taza +tazón +teatro +techo +tecla +técnica +tejado +tejer +tejido +tela +teléfono +tema +temor +templo +tenaz +tender +tener +tenis +tenso +teoría +terapia +terco +término +ternura +terror +tesis +tesoro +testigo +tetera +texto +tez +tibio +tiburón +tiempo +tienda +tierra +tieso +tigre +tijera +tilde +timbre +tímido +timo +tinta +tío +típico +tipo +tira +tirón +titán +títere +título +tiza +toalla +tobillo +tocar +tocino +todo +toga +toldo +tomar +tono +tonto +topar +tope +toque +tórax +torero +tormenta +torneo +toro +torpedo +torre +torso +tortuga +tos +tosco +toser +tóxico +trabajo +tractor +traer +tráfico +trago +traje +tramo +trance +trato +trauma +trazar +trébol +tregua +treinta +tren +trepar +tres +tribu +trigo +tripa +triste +triunfo +trofeo +trompa +tronco +tropa +trote +trozo +truco +trueno +trufa +tubería +tubo +tuerto +tumba +tumor +túnel +túnica +turbina +turismo +turno +tutor +ubicar +úlcera +umbral +unidad +unir +universo +uno +untar +uña +urbano +urbe +urgente +urna +usar +usuario +útil +utopía +uva +vaca +vacío +vacuna +vagar +vago +vaina +vajilla +vale +válido +valle +valor +válvula +vampiro +vara +variar +varón +vaso +vecino +vector +vehículo +veinte +vejez +vela +velero +veloz +vena +vencer +venda +veneno +vengar +venir +venta +venus +ver +verano +verbo +verde +vereda +verja +verso +verter +vía +viaje +vibrar +vicio +víctima +vida +vídeo +vidrio +viejo +viernes +vigor +vil +villa +vinagre +vino +viñedo +violín +viral +virgo +virtud +visor +víspera +vista +vitamina +viudo +vivaz +vivero +vivir +vivo +volcán +volumen +volver +voraz +votar +voto +voz +vuelo +vulgar +yacer +yate +yegua +yema +yerno +yeso +yodo +yoga +yogur +zafiro +zanja +zapato +zarza +zona +zorro +zumo +zurdo`.split('\n')); +//# sourceMappingURL=spanish.js.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts b/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts new file mode 100644 index 0000000..6702a87 --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/traditional-chinese.d.ts @@ -0,0 +1,3 @@ +/** Traditional Chinese BIP39 wordlist. */ +export declare const wordlist: string[]; +//# sourceMappingURL=traditional-chinese.d.ts.map \ No newline at end of file diff --git a/node_modules/@scure/bip39/wordlists/traditional-chinese.js b/node_modules/@scure/bip39/wordlists/traditional-chinese.js new file mode 100644 index 0000000..dc9fbdd --- /dev/null +++ b/node_modules/@scure/bip39/wordlists/traditional-chinese.js @@ -0,0 +1,2050 @@ +/** Traditional Chinese BIP39 wordlist. */ +export const wordlist = /* @__PURE__ */ Object.freeze(`的 +一 +是 +在 +不 +了 +有 +和 +人 +這 +中 +大 +為 +上 +個 +國 +我 +以 +要 +他 +時 +來 +用 +們 +生 +到 +作 +地 +於 +出 +就 +分 +對 +成 +會 +可 +主 +發 +年 +動 +同 +工 +也 +能 +下 +過 +子 +說 +產 +種 +面 +而 +方 +後 +多 +定 +行 +學 +法 +所 +民 +得 +經 +十 +三 +之 +進 +著 +等 +部 +度 +家 +電 +力 +裡 +如 +水 +化 +高 +自 +二 +理 +起 +小 +物 +現 +實 +加 +量 +都 +兩 +體 +制 +機 +當 +使 +點 +從 +業 +本 +去 +把 +性 +好 +應 +開 +它 +合 +還 +因 +由 +其 +些 +然 +前 +外 +天 +政 +四 +日 +那 +社 +義 +事 +平 +形 +相 +全 +表 +間 +樣 +與 +關 +各 +重 +新 +線 +內 +數 +正 +心 +反 +你 +明 +看 +原 +又 +麼 +利 +比 +或 +但 +質 +氣 +第 +向 +道 +命 +此 +變 +條 +只 +沒 +結 +解 +問 +意 +建 +月 +公 +無 +系 +軍 +很 +情 +者 +最 +立 +代 +想 +已 +通 +並 +提 +直 +題 +黨 +程 +展 +五 +果 +料 +象 +員 +革 +位 +入 +常 +文 +總 +次 +品 +式 +活 +設 +及 +管 +特 +件 +長 +求 +老 +頭 +基 +資 +邊 +流 +路 +級 +少 +圖 +山 +統 +接 +知 +較 +將 +組 +見 +計 +別 +她 +手 +角 +期 +根 +論 +運 +農 +指 +幾 +九 +區 +強 +放 +決 +西 +被 +幹 +做 +必 +戰 +先 +回 +則 +任 +取 +據 +處 +隊 +南 +給 +色 +光 +門 +即 +保 +治 +北 +造 +百 +規 +熱 +領 +七 +海 +口 +東 +導 +器 +壓 +志 +世 +金 +增 +爭 +濟 +階 +油 +思 +術 +極 +交 +受 +聯 +什 +認 +六 +共 +權 +收 +證 +改 +清 +美 +再 +採 +轉 +更 +單 +風 +切 +打 +白 +教 +速 +花 +帶 +安 +場 +身 +車 +例 +真 +務 +具 +萬 +每 +目 +至 +達 +走 +積 +示 +議 +聲 +報 +鬥 +完 +類 +八 +離 +華 +名 +確 +才 +科 +張 +信 +馬 +節 +話 +米 +整 +空 +元 +況 +今 +集 +溫 +傳 +土 +許 +步 +群 +廣 +石 +記 +需 +段 +研 +界 +拉 +林 +律 +叫 +且 +究 +觀 +越 +織 +裝 +影 +算 +低 +持 +音 +眾 +書 +布 +复 +容 +兒 +須 +際 +商 +非 +驗 +連 +斷 +深 +難 +近 +礦 +千 +週 +委 +素 +技 +備 +半 +辦 +青 +省 +列 +習 +響 +約 +支 +般 +史 +感 +勞 +便 +團 +往 +酸 +歷 +市 +克 +何 +除 +消 +構 +府 +稱 +太 +準 +精 +值 +號 +率 +族 +維 +劃 +選 +標 +寫 +存 +候 +毛 +親 +快 +效 +斯 +院 +查 +江 +型 +眼 +王 +按 +格 +養 +易 +置 +派 +層 +片 +始 +卻 +專 +狀 +育 +廠 +京 +識 +適 +屬 +圓 +包 +火 +住 +調 +滿 +縣 +局 +照 +參 +紅 +細 +引 +聽 +該 +鐵 +價 +嚴 +首 +底 +液 +官 +德 +隨 +病 +蘇 +失 +爾 +死 +講 +配 +女 +黃 +推 +顯 +談 +罪 +神 +藝 +呢 +席 +含 +企 +望 +密 +批 +營 +項 +防 +舉 +球 +英 +氧 +勢 +告 +李 +台 +落 +木 +幫 +輪 +破 +亞 +師 +圍 +注 +遠 +字 +材 +排 +供 +河 +態 +封 +另 +施 +減 +樹 +溶 +怎 +止 +案 +言 +士 +均 +武 +固 +葉 +魚 +波 +視 +僅 +費 +緊 +愛 +左 +章 +早 +朝 +害 +續 +輕 +服 +試 +食 +充 +兵 +源 +判 +護 +司 +足 +某 +練 +差 +致 +板 +田 +降 +黑 +犯 +負 +擊 +范 +繼 +興 +似 +餘 +堅 +曲 +輸 +修 +故 +城 +夫 +夠 +送 +筆 +船 +佔 +右 +財 +吃 +富 +春 +職 +覺 +漢 +畫 +功 +巴 +跟 +雖 +雜 +飛 +檢 +吸 +助 +昇 +陽 +互 +初 +創 +抗 +考 +投 +壞 +策 +古 +徑 +換 +未 +跑 +留 +鋼 +曾 +端 +責 +站 +簡 +述 +錢 +副 +盡 +帝 +射 +草 +衝 +承 +獨 +令 +限 +阿 +宣 +環 +雙 +請 +超 +微 +讓 +控 +州 +良 +軸 +找 +否 +紀 +益 +依 +優 +頂 +礎 +載 +倒 +房 +突 +坐 +粉 +敵 +略 +客 +袁 +冷 +勝 +絕 +析 +塊 +劑 +測 +絲 +協 +訴 +念 +陳 +仍 +羅 +鹽 +友 +洋 +錯 +苦 +夜 +刑 +移 +頻 +逐 +靠 +混 +母 +短 +皮 +終 +聚 +汽 +村 +雲 +哪 +既 +距 +衛 +停 +烈 +央 +察 +燒 +迅 +境 +若 +印 +洲 +刻 +括 +激 +孔 +搞 +甚 +室 +待 +核 +校 +散 +侵 +吧 +甲 +遊 +久 +菜 +味 +舊 +模 +湖 +貨 +損 +預 +阻 +毫 +普 +穩 +乙 +媽 +植 +息 +擴 +銀 +語 +揮 +酒 +守 +拿 +序 +紙 +醫 +缺 +雨 +嗎 +針 +劉 +啊 +急 +唱 +誤 +訓 +願 +審 +附 +獲 +茶 +鮮 +糧 +斤 +孩 +脫 +硫 +肥 +善 +龍 +演 +父 +漸 +血 +歡 +械 +掌 +歌 +沙 +剛 +攻 +謂 +盾 +討 +晚 +粒 +亂 +燃 +矛 +乎 +殺 +藥 +寧 +魯 +貴 +鐘 +煤 +讀 +班 +伯 +香 +介 +迫 +句 +豐 +培 +握 +蘭 +擔 +弦 +蛋 +沉 +假 +穿 +執 +答 +樂 +誰 +順 +煙 +縮 +徵 +臉 +喜 +松 +腳 +困 +異 +免 +背 +星 +福 +買 +染 +井 +概 +慢 +怕 +磁 +倍 +祖 +皇 +促 +靜 +補 +評 +翻 +肉 +踐 +尼 +衣 +寬 +揚 +棉 +希 +傷 +操 +垂 +秋 +宜 +氫 +套 +督 +振 +架 +亮 +末 +憲 +慶 +編 +牛 +觸 +映 +雷 +銷 +詩 +座 +居 +抓 +裂 +胞 +呼 +娘 +景 +威 +綠 +晶 +厚 +盟 +衡 +雞 +孫 +延 +危 +膠 +屋 +鄉 +臨 +陸 +顧 +掉 +呀 +燈 +歲 +措 +束 +耐 +劇 +玉 +趙 +跳 +哥 +季 +課 +凱 +胡 +額 +款 +紹 +卷 +齊 +偉 +蒸 +殖 +永 +宗 +苗 +川 +爐 +岩 +弱 +零 +楊 +奏 +沿 +露 +桿 +探 +滑 +鎮 +飯 +濃 +航 +懷 +趕 +庫 +奪 +伊 +靈 +稅 +途 +滅 +賽 +歸 +召 +鼓 +播 +盤 +裁 +險 +康 +唯 +錄 +菌 +純 +借 +糖 +蓋 +橫 +符 +私 +努 +堂 +域 +槍 +潤 +幅 +哈 +竟 +熟 +蟲 +澤 +腦 +壤 +碳 +歐 +遍 +側 +寨 +敢 +徹 +慮 +斜 +薄 +庭 +納 +彈 +飼 +伸 +折 +麥 +濕 +暗 +荷 +瓦 +塞 +床 +築 +惡 +戶 +訪 +塔 +奇 +透 +梁 +刀 +旋 +跡 +卡 +氯 +遇 +份 +毒 +泥 +退 +洗 +擺 +灰 +彩 +賣 +耗 +夏 +擇 +忙 +銅 +獻 +硬 +予 +繁 +圈 +雪 +函 +亦 +抽 +篇 +陣 +陰 +丁 +尺 +追 +堆 +雄 +迎 +泛 +爸 +樓 +避 +謀 +噸 +野 +豬 +旗 +累 +偏 +典 +館 +索 +秦 +脂 +潮 +爺 +豆 +忽 +托 +驚 +塑 +遺 +愈 +朱 +替 +纖 +粗 +傾 +尚 +痛 +楚 +謝 +奮 +購 +磨 +君 +池 +旁 +碎 +骨 +監 +捕 +弟 +暴 +割 +貫 +殊 +釋 +詞 +亡 +壁 +頓 +寶 +午 +塵 +聞 +揭 +炮 +殘 +冬 +橋 +婦 +警 +綜 +招 +吳 +付 +浮 +遭 +徐 +您 +搖 +谷 +贊 +箱 +隔 +訂 +男 +吹 +園 +紛 +唐 +敗 +宋 +玻 +巨 +耕 +坦 +榮 +閉 +灣 +鍵 +凡 +駐 +鍋 +救 +恩 +剝 +凝 +鹼 +齒 +截 +煉 +麻 +紡 +禁 +廢 +盛 +版 +緩 +淨 +睛 +昌 +婚 +涉 +筒 +嘴 +插 +岸 +朗 +莊 +街 +藏 +姑 +貿 +腐 +奴 +啦 +慣 +乘 +夥 +恢 +勻 +紗 +扎 +辯 +耳 +彪 +臣 +億 +璃 +抵 +脈 +秀 +薩 +俄 +網 +舞 +店 +噴 +縱 +寸 +汗 +掛 +洪 +賀 +閃 +柬 +爆 +烯 +津 +稻 +牆 +軟 +勇 +像 +滾 +厘 +蒙 +芳 +肯 +坡 +柱 +盪 +腿 +儀 +旅 +尾 +軋 +冰 +貢 +登 +黎 +削 +鑽 +勒 +逃 +障 +氨 +郭 +峰 +幣 +港 +伏 +軌 +畝 +畢 +擦 +莫 +刺 +浪 +秘 +援 +株 +健 +售 +股 +島 +甘 +泡 +睡 +童 +鑄 +湯 +閥 +休 +匯 +舍 +牧 +繞 +炸 +哲 +磷 +績 +朋 +淡 +尖 +啟 +陷 +柴 +呈 +徒 +顏 +淚 +稍 +忘 +泵 +藍 +拖 +洞 +授 +鏡 +辛 +壯 +鋒 +貧 +虛 +彎 +摩 +泰 +幼 +廷 +尊 +窗 +綱 +弄 +隸 +疑 +氏 +宮 +姐 +震 +瑞 +怪 +尤 +琴 +循 +描 +膜 +違 +夾 +腰 +緣 +珠 +窮 +森 +枝 +竹 +溝 +催 +繩 +憶 +邦 +剩 +幸 +漿 +欄 +擁 +牙 +貯 +禮 +濾 +鈉 +紋 +罷 +拍 +咱 +喊 +袖 +埃 +勤 +罰 +焦 +潛 +伍 +墨 +欲 +縫 +姓 +刊 +飽 +仿 +獎 +鋁 +鬼 +麗 +跨 +默 +挖 +鏈 +掃 +喝 +袋 +炭 +污 +幕 +諸 +弧 +勵 +梅 +奶 +潔 +災 +舟 +鑑 +苯 +訟 +抱 +毀 +懂 +寒 +智 +埔 +寄 +屆 +躍 +渡 +挑 +丹 +艱 +貝 +碰 +拔 +爹 +戴 +碼 +夢 +芽 +熔 +赤 +漁 +哭 +敬 +顆 +奔 +鉛 +仲 +虎 +稀 +妹 +乏 +珍 +申 +桌 +遵 +允 +隆 +螺 +倉 +魏 +銳 +曉 +氮 +兼 +隱 +礙 +赫 +撥 +忠 +肅 +缸 +牽 +搶 +博 +巧 +殼 +兄 +杜 +訊 +誠 +碧 +祥 +柯 +頁 +巡 +矩 +悲 +灌 +齡 +倫 +票 +尋 +桂 +鋪 +聖 +恐 +恰 +鄭 +趣 +抬 +荒 +騰 +貼 +柔 +滴 +猛 +闊 +輛 +妻 +填 +撤 +儲 +簽 +鬧 +擾 +紫 +砂 +遞 +戲 +吊 +陶 +伐 +餵 +療 +瓶 +婆 +撫 +臂 +摸 +忍 +蝦 +蠟 +鄰 +胸 +鞏 +擠 +偶 +棄 +槽 +勁 +乳 +鄧 +吉 +仁 +爛 +磚 +租 +烏 +艦 +伴 +瓜 +淺 +丙 +暫 +燥 +橡 +柳 +迷 +暖 +牌 +秧 +膽 +詳 +簧 +踏 +瓷 +譜 +呆 +賓 +糊 +洛 +輝 +憤 +競 +隙 +怒 +粘 +乃 +緒 +肩 +籍 +敏 +塗 +熙 +皆 +偵 +懸 +掘 +享 +糾 +醒 +狂 +鎖 +淀 +恨 +牲 +霸 +爬 +賞 +逆 +玩 +陵 +祝 +秒 +浙 +貌 +役 +彼 +悉 +鴨 +趨 +鳳 +晨 +畜 +輩 +秩 +卵 +署 +梯 +炎 +灘 +棋 +驅 +篩 +峽 +冒 +啥 +壽 +譯 +浸 +泉 +帽 +遲 +矽 +疆 +貸 +漏 +稿 +冠 +嫩 +脅 +芯 +牢 +叛 +蝕 +奧 +鳴 +嶺 +羊 +憑 +串 +塘 +繪 +酵 +融 +盆 +錫 +廟 +籌 +凍 +輔 +攝 +襲 +筋 +拒 +僚 +旱 +鉀 +鳥 +漆 +沈 +眉 +疏 +添 +棒 +穗 +硝 +韓 +逼 +扭 +僑 +涼 +挺 +碗 +栽 +炒 +杯 +患 +餾 +勸 +豪 +遼 +勃 +鴻 +旦 +吏 +拜 +狗 +埋 +輥 +掩 +飲 +搬 +罵 +辭 +勾 +扣 +估 +蔣 +絨 +霧 +丈 +朵 +姆 +擬 +宇 +輯 +陝 +雕 +償 +蓄 +崇 +剪 +倡 +廳 +咬 +駛 +薯 +刷 +斥 +番 +賦 +奉 +佛 +澆 +漫 +曼 +扇 +鈣 +桃 +扶 +仔 +返 +俗 +虧 +腔 +鞋 +棱 +覆 +框 +悄 +叔 +撞 +騙 +勘 +旺 +沸 +孤 +吐 +孟 +渠 +屈 +疾 +妙 +惜 +仰 +狠 +脹 +諧 +拋 +黴 +桑 +崗 +嘛 +衰 +盜 +滲 +臟 +賴 +湧 +甜 +曹 +閱 +肌 +哩 +厲 +烴 +緯 +毅 +昨 +偽 +症 +煮 +嘆 +釘 +搭 +莖 +籠 +酷 +偷 +弓 +錐 +恆 +傑 +坑 +鼻 +翼 +綸 +敘 +獄 +逮 +罐 +絡 +棚 +抑 +膨 +蔬 +寺 +驟 +穆 +冶 +枯 +冊 +屍 +凸 +紳 +坯 +犧 +焰 +轟 +欣 +晉 +瘦 +禦 +錠 +錦 +喪 +旬 +鍛 +壟 +搜 +撲 +邀 +亭 +酯 +邁 +舒 +脆 +酶 +閒 +憂 +酚 +頑 +羽 +漲 +卸 +仗 +陪 +闢 +懲 +杭 +姚 +肚 +捉 +飄 +漂 +昆 +欺 +吾 +郎 +烷 +汁 +呵 +飾 +蕭 +雅 +郵 +遷 +燕 +撒 +姻 +赴 +宴 +煩 +債 +帳 +斑 +鈴 +旨 +醇 +董 +餅 +雛 +姿 +拌 +傅 +腹 +妥 +揉 +賢 +拆 +歪 +葡 +胺 +丟 +浩 +徽 +昂 +墊 +擋 +覽 +貪 +慰 +繳 +汪 +慌 +馮 +諾 +姜 +誼 +兇 +劣 +誣 +耀 +昏 +躺 +盈 +騎 +喬 +溪 +叢 +盧 +抹 +悶 +諮 +刮 +駕 +纜 +悟 +摘 +鉺 +擲 +頗 +幻 +柄 +惠 +慘 +佳 +仇 +臘 +窩 +滌 +劍 +瞧 +堡 +潑 +蔥 +罩 +霍 +撈 +胎 +蒼 +濱 +倆 +捅 +湘 +砍 +霞 +邵 +萄 +瘋 +淮 +遂 +熊 +糞 +烘 +宿 +檔 +戈 +駁 +嫂 +裕 +徙 +箭 +捐 +腸 +撐 +曬 +辨 +殿 +蓮 +攤 +攪 +醬 +屏 +疫 +哀 +蔡 +堵 +沫 +皺 +暢 +疊 +閣 +萊 +敲 +轄 +鉤 +痕 +壩 +巷 +餓 +禍 +丘 +玄 +溜 +曰 +邏 +彭 +嘗 +卿 +妨 +艇 +吞 +韋 +怨 +矮 +歇`.split('\n')); +//# sourceMappingURL=traditional-chinese.js.map \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 40e0b04..3627b7b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,13 @@ "requires": true, "packages": { "": { + "dependencies": { + "@noble/curves": "^2.2.0", + "@noble/hashes": "^2.2.0", + "@noble/post-quantum": "^0.6.1", + "@scure/bip32": "^2.2.0", + "@scure/bip39": "^2.2.0" + }, "devDependencies": { "esbuild": "^0.27.2" } @@ -450,6 +457,98 @@ "node": ">=18" } }, + "node_modules/@noble/ciphers": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-2.2.0.tgz", + "integrity": "sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/curves": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.2.0.tgz", + "integrity": "sha512-T/BoHgFXirb0ENSPBquzX0rcjXeM6Lo892a2jlYJkqk83LqZx0l1Of7DzlKJ6jkpvMrkHSnAcgb5JegL8SeIkQ==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.2.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.2.0.tgz", + "integrity": "sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==", + "license": "MIT", + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/post-quantum": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@noble/post-quantum/-/post-quantum-0.6.1.tgz", + "integrity": "sha512-+pormrDZwjRw05U8ADK4JpHejo87+gBd+muRBB/ozztH5yhDLMDF4jHQWN3NQQAsu1zBNPWTG0ZwVI0CR29H0A==", + "license": "MIT", + "dependencies": { + "@noble/ciphers": "~2.2.0", + "@noble/curves": "~2.2.0", + "@noble/hashes": "~2.2.0" + }, + "engines": { + "node": ">= 20.19.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/base": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-2.2.0.tgz", + "integrity": "sha512-b8XEupJibegiXV+tDUseI8oLQc8ei3d/4Jkb2RpbHh3MfE054ov3uIz2dhFkB3FI8iwYkEh0gGCApkrYggkPNg==", + "license": "MIT", + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip32": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-2.2.0.tgz", + "integrity": "sha512-zFr7t2F+a9+5tB7QbarF2HQNYrgjCNaoLAupZdKkrFMYMozJf5zqH2WJCQibMzm1qQ0QogrxVGO3qXfQDYMaQg==", + "license": "MIT", + "dependencies": { + "@noble/curves": "2.2.0", + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@scure/bip39": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-2.2.0.tgz", + "integrity": "sha512-T/Bj/YvYMNkIPq6EENO6/rcs2e7qTNuyoUXf0KBFDmp0ZDu0H2X4Lq6yC3i0c8PcWkov5EbW+yQZZbdMmk154A==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "2.2.0", + "@scure/base": "2.2.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/esbuild": { "version": "0.27.2", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", diff --git a/package.json b/package.json index d4bea98..802a70a 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,12 @@ { "devDependencies": { "esbuild": "^0.27.2" + }, + "dependencies": { + "@noble/curves": "^2.2.0", + "@noble/hashes": "^2.2.0", + "@noble/post-quantum": "^0.6.1", + "@scure/bip32": "^2.2.0", + "@scure/bip39": "^2.2.0" } } diff --git a/www/js/pq-crypto.mjs b/www/js/pq-crypto.mjs new file mode 100644 index 0000000..3c20bca --- /dev/null +++ b/www/js/pq-crypto.mjs @@ -0,0 +1,351 @@ +/** + * Post-Quantum Crypto Module for Nostr + * + * Provides: + * - BIP39 seed phrase generation + * - NIP-06 key derivation (secp256k1 from seed) + * - PQ key derivation from seed (ML-DSA-65, SLH-DSA-128s, ML-KEM-768) + * - PQ signing (ML-DSA, SLH-DSA) + * - NIP-QR event construction + * + * Uses @noble/post-quantum (pure JS, no WASM needed) + */ + +import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; +import { wordlist } from '@scure/bip39/wordlists/english.js'; +import { HDKey } from '@scure/bip32'; +import { hkdf } from '@noble/hashes/hkdf.js'; +import { sha256 as sha256Hash, sha512 as sha512Hash } from '@noble/hashes/sha2.js'; +import { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js'; +import { slh_dsa_sha2_128s } from '@noble/post-quantum/slh-dsa.js'; +import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; + +// ============================================================================ +// BIP39 SEED PHRASE +// ============================================================================ + +/** + * Generate a new 12-word BIP39 mnemonic. + * @returns {string} 12-word seed phrase + */ +export function generateSeedPhrase() { + return generateMnemonic(wordlist, 128); // 128 bits = 12 words +} + +/** + * Convert a mnemonic to a 64-byte BIP39 seed (PBKDF2-HMAC-SHA512). + * @param {string} mnemonic - 12/24 word seed phrase + * @param {string} [passphrase=''] - optional BIP39 passphrase + * @returns {Uint8Array} 64-byte seed + */ +export function mnemonicToSeed(mnemonic, passphrase = '') { + if (!validateMnemonic(mnemonic, wordlist)) { + throw new Error('Invalid mnemonic'); + } + return mnemonicToSeedSync(mnemonic, passphrase); +} + +/** + * Validate a BIP39 mnemonic. + * @param {string} mnemonic + * @returns {boolean} + */ +export function isValidMnemonic(mnemonic) { + return validateMnemonic(mnemonic, wordlist); +} + +// ============================================================================ +// NIP-06 KEY DERIVATION (secp256k1 from seed) +// ============================================================================ + +/** + * Derive a secp256k1 keypair from a BIP39 seed using NIP-06. + * Path: m/44'/1237'/0'/0/0 + * + * @param {Uint8Array} seed - 64-byte BIP39 seed + * @param {number} [accountIndex=0] - account index + * @returns {{privateKey: Uint8Array, publicKey: Uint8Array}} secp256k1 keypair + */ +export function deriveSecp256k1FromSeed(seed, accountIndex = 0) { + const hdKey = HDKey.fromMasterSeed(seed); + const path = `m/44'/1237'/${accountIndex}'/0/0`; + const child = hdKey.derive(path); + if (!child.privateKey) { + throw new Error('Failed to derive private key'); + } + return { + privateKey: child.privateKey, + publicKey: child.publicKey + }; +} + +// ============================================================================ +// PQ KEY DERIVATION FROM SEED +// ============================================================================ + +/** + * Derive PQ key seeds from a BIP39 seed using HKDF. + * Each algorithm gets a unique label so keys are independent. + * + * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed + * @param {string} label - algorithm label (e.g. 'nostr-pq-ml-dsa-65') + * @param {number} length - output length in bytes + * @returns {Uint8Array} deterministic seed for PQ keygen + */ +function derivePQSeed(bip39Seed, label, length) { + const info = new TextEncoder().encode(label); + return hkdf(sha512Hash, bip39Seed, undefined, info, length); +} + +/** + * Derive all PQ keypairs from a BIP39 seed. + * + * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed + * @returns {{ + * mlDsa: {publicKey: Uint8Array, secretKey: Uint8Array}, + * slhDsa: {publicKey: Uint8Array, secretKey: Uint8Array}, + * mlKem: {publicKey: Uint8Array, secretKey: Uint8Array} + * }} + */ +export function derivePQKeysFromSeed(bip39Seed) { + // ML-DSA-65 needs 32-byte seed + const mlDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-dsa-65', 32); + const mlDsa = ml_dsa65.keygen(mlDsaSeed); + + // SLH-DSA-128s needs 48-byte seed (3 * 16 for sk seed, pk seed, etc.) + const slhDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-slh-dsa-128s', 48); + const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed); + + // ML-KEM-768 needs 64-byte seed + const mlKemSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-kem-768', 64); + const mlKem = ml_kem768.keygen(mlKemSeed); + + return { mlDsa, slhDsa, mlKem }; +} + +// ============================================================================ +// PQ SIGNING +// ============================================================================ + +/** + * Sign a message with ML-DSA-65. + * @param {Uint8Array} message + * @param {Uint8Array} secretKey + * @returns {Uint8Array} signature + */ +export function signWithMLDSA(message, secretKey) { + return ml_dsa65.sign(message, secretKey); +} + +/** + * Verify an ML-DSA-65 signature. + * @param {Uint8Array} signature + * @param {Uint8Array} message + * @param {Uint8Array} publicKey + * @returns {boolean} + */ +export function verifyMLDSA(signature, message, publicKey) { + return ml_dsa65.verify(signature, message, publicKey); +} + +/** + * Sign a message with SLH-DSA-128s. + * @param {Uint8Array} message + * @param {Uint8Array} secretKey + * @returns {Uint8Array} signature + */ +export function signWithSLHDSA(message, secretKey) { + return slh_dsa_sha2_128s.sign(message, secretKey); +} + +/** + * Verify an SLH-DSA-128s signature. + * @param {Uint8Array} signature + * @param {Uint8Array} message + * @param {Uint8Array} publicKey + * @returns {boolean} + */ +export function verifySLHDSA(signature, message, publicKey) { + return slh_dsa_sha2_128s.verify(signature, message, publicKey); +} + +// ============================================================================ +// UTILITIES +// ============================================================================ + +/** + * Convert Uint8Array to base64 string. + * @param {Uint8Array} bytes + * @returns {string} + */ +export function bytesToBase64(bytes) { + let binary = ''; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} + +/** + * Convert base64 string to Uint8Array. + * @param {string} base64 + * @returns {Uint8Array} + */ +export function base64ToBytes(base64) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} + +/** + * Convert Uint8Array to hex string. + * @param {Uint8Array} bytes + * @returns {string} + */ +export function bytesToHex(bytes) { + return Array.from(bytes) + .map(b => b.toString(16).padStart(2, '0')) + .join(''); +} + +/** + * Convert hex string to Uint8Array. + * @param {string} hex + * @returns {Uint8Array} + */ +export function hexToBytes(hex) { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + bytes[i / 2] = parseInt(hex.substr(i, 2), 16); + } + return bytes; +} + +// ============================================================================ +// NIP-QR EVENT CONSTRUCTION +// ============================================================================ + +/** + * Build the NIP-QR event content (the JSON that goes in the event's content field). + * + * The content contains: + * - A link statement + * - All PQ public keys + * - PQ signatures over the statement + * - The ML-KEM public key (no signature — KEM can't sign) + * + * @param {string} npub - The user's Nostr npub (hex pubkey) + * @param {string} successorNpub - The successor's hex pubkey (for Path B), or null for Path A + * @param {{mlDsa: *, slhDsa: *, mlKem: *}} pqKeys - PQ keypairs + * @returns {{statement: string, content: object, statementBytes: Uint8Array}} + */ +export function buildNIPQRContent(npub, successorNpub, pqKeys) { + let statement; + if (successorNpub) { + // Path B: migration from old nsec to seed-derived key + statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`; + } else { + // Path A: direct link (identity already seed-derived) + statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`; + } + + const statementBytes = new TextEncoder().encode(statement); + + // Sign the statement with each PQ signature scheme + const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey); + const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey); + + const content = { + statement, + pq_keys: [ + { + algorithm: 'ml-dsa-65', + public_key: bytesToBase64(pqKeys.mlDsa.publicKey), + signature: bytesToBase64(mlDsaSig) + }, + { + algorithm: 'slh-dsa-128s', + public_key: bytesToBase64(pqKeys.slhDsa.publicKey), + signature: bytesToBase64(slhDsaSig) + }, + { + algorithm: 'ml-kem-768', + public_key: bytesToBase64(pqKeys.mlKem.publicKey), + note: 'KEM key for encryption; ownership asserted by secp256k1 signature over this content' + } + ] + }; + + // If Path B, include successor info + if (successorNpub) { + content.successor_pubkey = successorNpub; + } + + return { statement, content, statementBytes }; +} + +/** + * Verify a NIP-QR event's PQ signatures. + * @param {object} content - The parsed content object + * @returns {{valid: boolean, results: Array}} verification results + */ +export function verifyNIPQRContent(content) { + const results = []; + + for (const keyEntry of content.pq_keys) { + if (keyEntry.algorithm === 'ml-kem-768') { + // KEM can't sign — skip verification + results.push({ algorithm: keyEntry.algorithm, valid: true, note: 'KEM (no signature to verify)' }); + continue; + } + + const pubKey = base64ToBytes(keyEntry.public_key); + const sig = base64ToBytes(keyEntry.signature); + const msg = new TextEncoder().encode(content.statement); + + let valid = false; + if (keyEntry.algorithm === 'ml-dsa-65') { + valid = verifyMLDSA(sig, msg, pubKey); + } else if (keyEntry.algorithm === 'slh-dsa-128s') { + valid = verifySLHDSA(sig, msg, pubKey); + } + + results.push({ algorithm: keyEntry.algorithm, valid }); + } + + return { + valid: results.every(r => r.valid), + results + }; +} + +// ============================================================================ +// KEY SIZE INFO (for display) +// ============================================================================ + +export const PQ_KEY_INFO = { + 'ml-dsa-65': { + name: 'ML-DSA-65 (Dilithium)', + publicKeySize: 1952, + signatureSize: 3309, + fips: 'FIPS 204', + type: 'signature' + }, + 'slh-dsa-128s': { + name: 'SLH-DSA-128s (SPHINCS+)', + publicKeySize: 32, + signatureSize: 7856, + fips: 'FIPS 205', + type: 'signature' + }, + 'ml-kem-768': { + name: 'ML-KEM-768 (Kyber)', + publicKeySize: 1184, + ciphertextSize: 1088, + fips: 'FIPS 203', + type: 'kem' + } +}; diff --git a/www/js/version.json b/www/js/version.json index a52f92a..ee89121 100644 --- a/www/js/version.json +++ b/www/js/version.json @@ -1,5 +1,5 @@ { - "VERSION": "v0.7.93", - "VERSION_NUMBER": "0.7.93", - "BUILD_DATE": "2026-07-03T10:29:34.780Z" + "VERSION": "v0.7.94", + "VERSION_NUMBER": "0.7.94", + "BUILD_DATE": "2026-07-12T14:10:59.968Z" } diff --git a/www/post-quantum.html b/www/post-quantum.html new file mode 100644 index 0000000..b4f5c7d --- /dev/null +++ b/www/post-quantum.html @@ -0,0 +1,1135 @@ + + + + + + + Post-Quantum Nostr + + + + + + + + + + + + + + + +

+ + +
+
+
+
🔒 Post-Quantum Nostr
+
+
+
+ + +
+
+ + +
+
🔒 Post-Quantum Nostr
+
Make your Nostr identity quantum-resistant
+
+ Sign in with your Nostr signer to begin. Your npub won't change, your followers stay, + and your social graph is preserved. We'll generate a quantum-safe seed phrase and link + it to your current identity. +
+ +
+ + +
+
🔒 Post-Quantum Migration
+
Step 1 of 4: Overview
+ +
+ Connected as: +
+ +
+ This tool will: +
    +
  1. Generate a new seed phrase (your quantum-safe backup)
  2. +
  3. Derive post-quantum keys from that seed (ML-DSA, SLH-DSA, ML-KEM)
  4. +
  5. Sign a NIP-QR migration event linking your identity to the PQ keys
  6. +
  7. Publish the event to relays with an OpenTimestamps proof
  8. +
+
+ +
+ ⚠️ Important: Your seed phrase is generated and handled entirely in your browser. + It is never sent to any server. Write it down on paper — it's your quantum-safe backup. +
+ + +
+ + +
+
+ 2 + Your Quantum-Safe Seed Phrase +
+ +
+ We've generated a new 12-word seed phrase. This is your quantum-safe root of trust. + Write it down on paper. Never store it digitally. Never share it with anyone. +
+ +
+ +
+ + +
+ + + + +
+ + +
+
+ 3 + Deriving Post-Quantum Keys +
+ +
+ Deriving post-quantum keys from your seed phrase. All keys are generated + deterministically — the same seed will always produce the same keys. +
+ +
+
+
+ +
+
+
+
+
ML-DSA-65 (Dilithium)
+
FIPS 204 · Lattice-based signature · 1952-byte pubkey
+
+
+
+
+
+
+
SLH-DSA-128s (SPHINCS+)
+
FIPS 205 · Hash-based signature · 32-byte pubkey
+
+
+
+
+
+
+
ML-KEM-768 (Kyber)
+
FIPS 203 · Lattice-based KEM · 1184-byte pubkey
+
+
+
+
+ +
+ + +
+ + +
+
+ 4 + Sign & Publish Migration Event +
+ +
+ We'll now create the NIP-QR migration event. This event links your current Nostr identity + to your post-quantum keys. Your signer will be asked to sign the event with your secp256k1 key. +
+ +
+ +
+
+
+
+
PQ signature: ML-DSA-65
+
Done in browser (WASM-free pure JS)
+
+
+
+
+
+
PQ signature: SLH-DSA-128s
+
Done in browser (WASM-free pure JS)
+
+
+
+
+
+
secp256k1 signature (NIP-01)
+
Requires approval from your signer
+
+
+
+
+
+
Publish to relays
+
Broadcast the NIP-QR event
+
+
+
+ + + +
+
Event preview:
+
+
+
+ + +
+
+
🎉
+
Migration Complete!
+
+ Your Nostr identity is now linked to post-quantum keys.

+ What happened:
+ • Your identity is linked to PQ keys (ML-DSA, SLH-DSA, ML-KEM)
+ • The link is established pre-quantum via secp256k1 signature
+ • PQ signatures prove key ownership even after secp256k1 is broken

+ What to do now:
+ • Keep your seed phrase safe — it's your quantum-safe backup
+ • PQ-aware clients will recognize your new keys automatically +
+ +
+ + +
+
+ +
+
+ + +
+
+
+
+
0 sats
+
+ + +
+
+
+
+
+
+
AI
+
+
No saved providers yet.
+
+
+
+
リレー
+
Loading relays...
+
+
+
ブロッサム
+
Loading blossom servers...
+
+
+ v0.0.1 +
+ + +
+
+
+ + + + + + + + + diff --git a/www/pq-crypto.bundle.js b/www/pq-crypto.bundle.js new file mode 100644 index 0000000..65a7fc5 --- /dev/null +++ b/www/pq-crypto.bundle.js @@ -0,0 +1,7454 @@ +var __defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + +// node_modules/@noble/hashes/utils.js +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +function anumber(n, title = "") { + if (typeof n !== "number") { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n}`); + } + if (!Number.isSafeInteger(n) || n < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); + } +} +function abytes(value, length, title = "") { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== void 0; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + return value; +} +function ahash(h) { + if (typeof h !== "function" || typeof h.create !== "function") + throw new TypeError("Hash must wrapped by utils.createHasher"); + anumber(h.outputLen); + anumber(h.blockLen); + if (h.outputLen < 1) + throw new Error('"outputLen" must be >= 1'); + if (h.blockLen < 1) + throw new Error('"blockLen" must be >= 1'); +} +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); +} +function aoutput(out, instance) { + abytes(out, void 0, "digestInto() output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); + } +} +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); +} +function clean(...arrays) { + for (let i = 0; i < arrays.length; i++) { + arrays[i].fill(0); + } +} +function createView(arr) { + return new DataView(arr.buffer, arr.byteOffset, arr.byteLength); +} +function rotr(word, shift) { + return word << 32 - shift | word >>> shift; +} +function rotl(word, shift) { + return word << shift | word >>> 32 - shift >>> 0; +} +var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +function byteSwap(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; +} +function byteSwap32(arr) { + for (let i = 0; i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr; +} +var swap32IfBE = isLE ? (u) => u : byteSwap32; +var hasHexBuiltin = /* @__PURE__ */ (() => ( + // @ts-ignore + typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function" +))(); +var hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); +function bytesToHex(bytes) { + abytes(bytes); + if (hasHexBuiltin) + return bytes.toHex(); + let hex = ""; + for (let i = 0; i < bytes.length; i++) { + hex += hexes[bytes[i]]; + } + return hex; +} +var asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; +function asciiToBase16(ch) { + if (ch >= asciis._0 && ch <= asciis._9) + return ch - asciis._0; + if (ch >= asciis.A && ch <= asciis.F) + return ch - (asciis.A - 10); + if (ch >= asciis.a && ch <= asciis.f) + return ch - (asciis.a - 10); + return; +} +function hexToBytes(hex) { + if (typeof hex !== "string") + throw new TypeError("hex string expected, got " + typeof hex); + if (hasHexBuiltin) { + try { + return Uint8Array.fromHex(hex); + } catch (error) { + if (error instanceof SyntaxError) + throw new RangeError(error.message); + throw error; + } + } + const hl = hex.length; + const al = hl / 2; + if (hl % 2) + throw new RangeError("hex string expected, got unpadded hex of length " + hl); + const array = new Uint8Array(al); + for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) { + const n1 = asciiToBase16(hex.charCodeAt(hi)); + const n2 = asciiToBase16(hex.charCodeAt(hi + 1)); + if (n1 === void 0 || n2 === void 0) { + const char = hex[hi] + hex[hi + 1]; + throw new RangeError('hex string expected, got non-hex character "' + char + '" at index ' + hi); + } + array[ai] = n1 * 16 + n2; + } + return array; +} +function utf8ToBytes(str) { + if (typeof str !== "string") + throw new TypeError("string expected"); + return new Uint8Array(new TextEncoder().encode(str)); +} +function kdfInputToBytes(data, errorTitle = "") { + if (typeof data === "string") + return utf8ToBytes(data); + return abytes(data, void 0, errorTitle); +} +function concatBytes(...arrays) { + let sum = 0; + for (let i = 0; i < arrays.length; i++) { + const a = arrays[i]; + abytes(a); + sum += a.length; + } + const res = new Uint8Array(sum); + for (let i = 0, pad = 0; i < arrays.length; i++) { + const a = arrays[i]; + res.set(a, pad); + pad += a.length; + } + return res; +} +function checkOpts(defaults, opts2) { + if (opts2 !== void 0 && {}.toString.call(opts2) !== "[object Object]") + throw new TypeError("options must be object or undefined"); + const merged = Object.assign(defaults, opts2); + return merged; +} +function createHasher(hashCons, info = {}) { + const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest(); + const tmp = hashCons(void 0); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts2) => hashCons(opts2); + Object.assign(hashC, info); + return Object.freeze(hashC); +} +function randomBytes(bytesLength = 32) { + anumber(bytesLength, "bytesLength"); + const cr = typeof globalThis === "object" ? globalThis.crypto : null; + if (typeof cr?.getRandomValues !== "function") + throw new Error("crypto.getRandomValues must be defined"); + if (bytesLength > 65536) + throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`); + return cr.getRandomValues(new Uint8Array(bytesLength)); +} +var oidNist = (suffix) => ({ + // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet. + // Larger suffix values would need base-128 OID encoding and a different length byte. + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) +}); + +// node_modules/@noble/hashes/hmac.js +var _HMAC = class { + constructor(hash, key) { + __publicField(this, "oHash"); + __publicField(this, "iHash"); + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "finished", false); + __publicField(this, "destroyed", false); + ahash(hash); + abytes(key, void 0, "key"); + this.iHash = hash.create(); + if (typeof this.iHash.update !== "function") + throw new Error("Expected instance of class which extends utils.Hash"); + this.blockLen = this.iHash.blockLen; + this.outputLen = this.iHash.outputLen; + const blockLen = this.blockLen; + const pad = new Uint8Array(blockLen); + pad.set(key.length > blockLen ? hash.create().update(key).digest() : key); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54; + this.iHash.update(pad); + this.oHash = hash.create(); + for (let i = 0; i < pad.length; i++) + pad[i] ^= 54 ^ 92; + this.oHash.update(pad); + clean(pad); + } + update(buf) { + aexists(this); + this.iHash.update(buf); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const buf = out.subarray(0, this.outputLen); + this.iHash.digestInto(buf); + this.oHash.update(buf); + this.oHash.digestInto(buf); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.oHash.outputLen); + this.digestInto(out); + return out; + } + _cloneInto(to) { + to || (to = Object.create(Object.getPrototypeOf(this), {})); + const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this; + to = to; + to.finished = finished; + to.destroyed = destroyed; + to.blockLen = blockLen; + to.outputLen = outputLen; + to.oHash = oHash._cloneInto(to.oHash); + to.iHash = iHash._cloneInto(to.iHash); + return to; + } + clone() { + return this._cloneInto(); + } + destroy() { + this.destroyed = true; + this.oHash.destroy(); + this.iHash.destroy(); + } +}; +var hmac = /* @__PURE__ */ (() => { + const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest()); + hmac_.create = (hash, key) => new _HMAC(hash, key); + return hmac_; +})(); + +// node_modules/@noble/hashes/pbkdf2.js +function pbkdf2Init(hash, _password, _salt, _opts) { + ahash(hash); + const opts2 = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts); + const { c, dkLen, asyncTick } = opts2; + anumber(c, "c"); + anumber(dkLen, "dkLen"); + anumber(asyncTick, "asyncTick"); + if (c < 1) + throw new Error("iterations (c) must be >= 1"); + if (dkLen < 1) + throw new Error('"dkLen" must be >= 1'); + if (dkLen > (2 ** 32 - 1) * hash.outputLen) + throw new Error("derived key too long"); + const password = kdfInputToBytes(_password, "password"); + const salt = kdfInputToBytes(_salt, "salt"); + const DK = new Uint8Array(dkLen); + const PRF = hmac.create(hash, password); + const PRFSalt = PRF._cloneInto().update(salt); + return { c, dkLen, asyncTick, DK, PRF, PRFSalt }; +} +function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) { + PRF.destroy(); + PRFSalt.destroy(); + if (prfW) + prfW.destroy(); + clean(u); + return DK; +} +function pbkdf2(hash, password, salt, opts2) { + const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts2); + let prfW; + const arr = new Uint8Array(4); + const view = createView(arr); + const u = new Uint8Array(PRF.outputLen); + for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) { + const Ti = DK.subarray(pos, pos + PRF.outputLen); + view.setInt32(0, ti, false); + (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u); + Ti.set(u.subarray(0, Ti.length)); + for (let ui = 1; ui < c; ui++) { + PRF._cloneInto(prfW).update(u).digestInto(u); + for (let i = 0; i < Ti.length; i++) + Ti[i] ^= u[i]; + } + } + return pbkdf2Output(PRF, PRFSalt, DK, prfW, u); +} + +// node_modules/@noble/hashes/_md.js +function Chi(a, b, c) { + return a & b ^ ~a & c; +} +function Maj(a, b, c) { + return a & b ^ a & c ^ b & c; +} +var HashMD = class { + constructor(blockLen, outputLen, padOffset, isLE2) { + __publicField(this, "blockLen"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF", false); + __publicField(this, "padOffset"); + __publicField(this, "isLE"); + // For partial updates less than block size + __publicField(this, "buffer"); + __publicField(this, "view"); + __publicField(this, "finished", false); + __publicField(this, "length", 0); + __publicField(this, "pos", 0); + __publicField(this, "destroyed", false); + this.blockLen = blockLen; + this.outputLen = outputLen; + this.padOffset = padOffset; + this.isLE = isLE2; + this.buffer = new Uint8Array(blockLen); + this.view = createView(this.buffer); + } + update(data) { + aexists(this); + abytes(data); + const { view, buffer, blockLen } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + if (take === blockLen) { + const dataView = createView(data); + for (; blockLen <= len - pos; pos += blockLen) + this.process(dataView, pos); + continue; + } + buffer.set(data.subarray(pos, pos + take), this.pos); + this.pos += take; + pos += take; + if (this.pos === blockLen) { + this.process(view, 0); + this.pos = 0; + } + } + this.length += data.length; + this.roundClean(); + return this; + } + digestInto(out) { + aexists(this); + aoutput(out, this); + this.finished = true; + const { buffer, view, blockLen, isLE: isLE2 } = this; + let { pos } = this; + buffer[pos++] = 128; + clean(this.buffer.subarray(pos)); + if (this.padOffset > blockLen - pos) { + this.process(view, 0); + pos = 0; + } + for (let i = pos; i < blockLen; i++) + buffer[i] = 0; + view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE2); + this.process(view, 0); + const oview = createView(out); + const len = this.outputLen; + if (len % 4) + throw new Error("_sha2: outputLen must be aligned to 32bit"); + const outLen = len / 4; + const state = this.get(); + if (outLen > state.length) + throw new Error("_sha2: outputLen bigger than state"); + for (let i = 0; i < outLen; i++) + oview.setUint32(4 * i, state[i], isLE2); + } + digest() { + const { buffer, outputLen } = this; + this.digestInto(buffer); + const res = buffer.slice(0, outputLen); + this.destroy(); + return res; + } + _cloneInto(to) { + to || (to = new this.constructor()); + to.set(...this.get()); + const { blockLen, buffer, length, finished, destroyed, pos } = this; + to.destroyed = destroyed; + to.finished = finished; + to.length = length; + to.pos = pos; + if (length % blockLen) + to.buffer.set(buffer); + return to; + } + clone() { + return this._cloneInto(); + } +}; +var SHA256_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 3144134277, + 1013904242, + 2773480762, + 1359893119, + 2600822924, + 528734635, + 1541459225 +]); +var SHA512_IV = /* @__PURE__ */ Uint32Array.from([ + 1779033703, + 4089235720, + 3144134277, + 2227873595, + 1013904242, + 4271175723, + 2773480762, + 1595750129, + 1359893119, + 2917565137, + 2600822924, + 725511199, + 528734635, + 4215389547, + 1541459225, + 327033209 +]); + +// node_modules/@noble/hashes/_u64.js +var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n = /* @__PURE__ */ BigInt(32); +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split(lst, le = false) { + const len = lst.length; + let Ah = new Uint32Array(len); + let Al = new Uint32Array(len); + for (let i = 0; i < len; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; + } + return [Ah, Al]; +} +var shrSH = (h, _l, s) => h >>> s; +var shrSL = (h, l, s) => h << 32 - s | l >>> s; +var rotrSH = (h, l, s) => h >>> s | l << 32 - s; +var rotrSL = (h, l, s) => h << 32 - s | l >>> s; +var rotrBH = (h, l, s) => h << 64 - s | l >>> s - 32; +var rotrBL = (h, l, s) => h >>> s - 32 | l << 64 - s; +var rotlSH = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; +function add(Ah, Al, Bh, Bl) { + const l = (Al >>> 0) + (Bl >>> 0); + return { h: Ah + Bh + (l / 2 ** 32 | 0) | 0, l: l | 0 }; +} +var add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0); +var add3H = (low, Ah, Bh, Ch) => Ah + Bh + Ch + (low / 2 ** 32 | 0) | 0; +var add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0); +var add4H = (low, Ah, Bh, Ch, Dh) => Ah + Bh + Ch + Dh + (low / 2 ** 32 | 0) | 0; +var add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0); +var add5H = (low, Ah, Bh, Ch, Dh, Eh) => Ah + Bh + Ch + Dh + Eh + (low / 2 ** 32 | 0) | 0; + +// node_modules/@noble/hashes/sha2.js +var SHA256_K = /* @__PURE__ */ Uint32Array.from([ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]); +var SHA256_W = /* @__PURE__ */ new Uint32Array(64); +var SHA2_32B = class extends HashMD { + constructor(outputLen) { + super(64, outputLen, 8, false); + } + get() { + const { A, B, C, D: D2, E, F: F3, G, H } = this; + return [A, B, C, D2, E, F3, G, H]; + } + // prettier-ignore + set(A, B, C, D2, E, F3, G, H) { + this.A = A | 0; + this.B = B | 0; + this.C = C | 0; + this.D = D2 | 0; + this.E = E | 0; + this.F = F3 | 0; + this.G = G | 0; + this.H = H | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + SHA256_W[i] = view.getUint32(offset, false); + for (let i = 16; i < 64; i++) { + const W15 = SHA256_W[i - 15]; + const W2 = SHA256_W[i - 2]; + const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3; + const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10; + SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0; + } + let { A, B, C, D: D2, E, F: F3, G, H } = this; + for (let i = 0; i < 64; i++) { + const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25); + const T1 = H + sigma1 + Chi(E, F3, G) + SHA256_K[i] + SHA256_W[i] | 0; + const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22); + const T2 = sigma0 + Maj(A, B, C) | 0; + H = G; + G = F3; + F3 = E; + E = D2 + T1 | 0; + D2 = C; + C = B; + B = A; + A = T1 + T2 | 0; + } + A = A + this.A | 0; + B = B + this.B | 0; + C = C + this.C | 0; + D2 = D2 + this.D | 0; + E = E + this.E | 0; + F3 = F3 + this.F | 0; + G = G + this.G | 0; + H = H + this.H | 0; + this.set(A, B, C, D2, E, F3, G, H); + } + roundClean() { + clean(SHA256_W); + } + destroy() { + this.destroyed = true; + this.set(0, 0, 0, 0, 0, 0, 0, 0); + clean(this.buffer); + } +}; +var _SHA256 = class extends SHA2_32B { + constructor() { + super(32); + // We cannot use array here since array allows indexing by variable + // which means optimizer/compiler cannot use registers. + __publicField(this, "A", SHA256_IV[0] | 0); + __publicField(this, "B", SHA256_IV[1] | 0); + __publicField(this, "C", SHA256_IV[2] | 0); + __publicField(this, "D", SHA256_IV[3] | 0); + __publicField(this, "E", SHA256_IV[4] | 0); + __publicField(this, "F", SHA256_IV[5] | 0); + __publicField(this, "G", SHA256_IV[6] | 0); + __publicField(this, "H", SHA256_IV[7] | 0); + } +}; +var K512 = /* @__PURE__ */ (() => split([ + "0x428a2f98d728ae22", + "0x7137449123ef65cd", + "0xb5c0fbcfec4d3b2f", + "0xe9b5dba58189dbbc", + "0x3956c25bf348b538", + "0x59f111f1b605d019", + "0x923f82a4af194f9b", + "0xab1c5ed5da6d8118", + "0xd807aa98a3030242", + "0x12835b0145706fbe", + "0x243185be4ee4b28c", + "0x550c7dc3d5ffb4e2", + "0x72be5d74f27b896f", + "0x80deb1fe3b1696b1", + "0x9bdc06a725c71235", + "0xc19bf174cf692694", + "0xe49b69c19ef14ad2", + "0xefbe4786384f25e3", + "0x0fc19dc68b8cd5b5", + "0x240ca1cc77ac9c65", + "0x2de92c6f592b0275", + "0x4a7484aa6ea6e483", + "0x5cb0a9dcbd41fbd4", + "0x76f988da831153b5", + "0x983e5152ee66dfab", + "0xa831c66d2db43210", + "0xb00327c898fb213f", + "0xbf597fc7beef0ee4", + "0xc6e00bf33da88fc2", + "0xd5a79147930aa725", + "0x06ca6351e003826f", + "0x142929670a0e6e70", + "0x27b70a8546d22ffc", + "0x2e1b21385c26c926", + "0x4d2c6dfc5ac42aed", + "0x53380d139d95b3df", + "0x650a73548baf63de", + "0x766a0abb3c77b2a8", + "0x81c2c92e47edaee6", + "0x92722c851482353b", + "0xa2bfe8a14cf10364", + "0xa81a664bbc423001", + "0xc24b8b70d0f89791", + "0xc76c51a30654be30", + "0xd192e819d6ef5218", + "0xd69906245565a910", + "0xf40e35855771202a", + "0x106aa07032bbd1b8", + "0x19a4c116b8d2d0c8", + "0x1e376c085141ab53", + "0x2748774cdf8eeb99", + "0x34b0bcb5e19b48a8", + "0x391c0cb3c5c95a63", + "0x4ed8aa4ae3418acb", + "0x5b9cca4f7763e373", + "0x682e6ff3d6b2b8a3", + "0x748f82ee5defb2fc", + "0x78a5636f43172f60", + "0x84c87814a1f0ab72", + "0x8cc702081a6439ec", + "0x90befffa23631e28", + "0xa4506cebde82bde9", + "0xbef9a3f7b2c67915", + "0xc67178f2e372532b", + "0xca273eceea26619c", + "0xd186b8c721c0c207", + "0xeada7dd6cde0eb1e", + "0xf57d4f7fee6ed178", + "0x06f067aa72176fba", + "0x0a637dc5a2c898a6", + "0x113f9804bef90dae", + "0x1b710b35131c471b", + "0x28db77f523047d84", + "0x32caab7b40c72493", + "0x3c9ebe0a15c9bebc", + "0x431d67c49c100d4c", + "0x4cc5d4becb3e42b6", + "0x597f299cfc657e2a", + "0x5fcb6fab3ad6faec", + "0x6c44198c4a475817" +].map((n) => BigInt(n))))(); +var SHA512_Kh = /* @__PURE__ */ (() => K512[0])(); +var SHA512_Kl = /* @__PURE__ */ (() => K512[1])(); +var SHA512_W_H = /* @__PURE__ */ new Uint32Array(80); +var SHA512_W_L = /* @__PURE__ */ new Uint32Array(80); +var SHA2_64B = class extends HashMD { + constructor(outputLen) { + super(128, outputLen, 16, false); + } + // prettier-ignore + get() { + const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl]; + } + // prettier-ignore + set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl) { + this.Ah = Ah | 0; + this.Al = Al | 0; + this.Bh = Bh | 0; + this.Bl = Bl | 0; + this.Ch = Ch | 0; + this.Cl = Cl | 0; + this.Dh = Dh | 0; + this.Dl = Dl | 0; + this.Eh = Eh | 0; + this.El = El | 0; + this.Fh = Fh | 0; + this.Fl = Fl | 0; + this.Gh = Gh | 0; + this.Gl = Gl | 0; + this.Hh = Hh | 0; + this.Hl = Hl | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) { + SHA512_W_H[i] = view.getUint32(offset); + SHA512_W_L[i] = view.getUint32(offset += 4); + } + for (let i = 16; i < 80; i++) { + const W15h = SHA512_W_H[i - 15] | 0; + const W15l = SHA512_W_L[i - 15] | 0; + const s0h = rotrSH(W15h, W15l, 1) ^ rotrSH(W15h, W15l, 8) ^ shrSH(W15h, W15l, 7); + const s0l = rotrSL(W15h, W15l, 1) ^ rotrSL(W15h, W15l, 8) ^ shrSL(W15h, W15l, 7); + const W2h = SHA512_W_H[i - 2] | 0; + const W2l = SHA512_W_L[i - 2] | 0; + const s1h = rotrSH(W2h, W2l, 19) ^ rotrBH(W2h, W2l, 61) ^ shrSH(W2h, W2l, 6); + const s1l = rotrSL(W2h, W2l, 19) ^ rotrBL(W2h, W2l, 61) ^ shrSL(W2h, W2l, 6); + const SUMl = add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]); + const SUMh = add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]); + SHA512_W_H[i] = SUMh | 0; + SHA512_W_L[i] = SUMl | 0; + } + let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this; + for (let i = 0; i < 80; i++) { + const sigma1h = rotrSH(Eh, El, 14) ^ rotrSH(Eh, El, 18) ^ rotrBH(Eh, El, 41); + const sigma1l = rotrSL(Eh, El, 14) ^ rotrSL(Eh, El, 18) ^ rotrBL(Eh, El, 41); + const CHIh = Eh & Fh ^ ~Eh & Gh; + const CHIl = El & Fl ^ ~El & Gl; + const T1ll = add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]); + const T1h = add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]); + const T1l = T1ll | 0; + const sigma0h = rotrSH(Ah, Al, 28) ^ rotrBH(Ah, Al, 34) ^ rotrBH(Ah, Al, 39); + const sigma0l = rotrSL(Ah, Al, 28) ^ rotrBL(Ah, Al, 34) ^ rotrBL(Ah, Al, 39); + const MAJh = Ah & Bh ^ Ah & Ch ^ Bh & Ch; + const MAJl = Al & Bl ^ Al & Cl ^ Bl & Cl; + Hh = Gh | 0; + Hl = Gl | 0; + Gh = Fh | 0; + Gl = Fl | 0; + Fh = Eh | 0; + Fl = El | 0; + ({ h: Eh, l: El } = add(Dh | 0, Dl | 0, T1h | 0, T1l | 0)); + Dh = Ch | 0; + Dl = Cl | 0; + Ch = Bh | 0; + Cl = Bl | 0; + Bh = Ah | 0; + Bl = Al | 0; + const All = add3L(T1l, sigma0l, MAJl); + Ah = add3H(All, T1h, sigma0h, MAJh); + Al = All | 0; + } + ({ h: Ah, l: Al } = add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0)); + ({ h: Bh, l: Bl } = add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0)); + ({ h: Ch, l: Cl } = add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0)); + ({ h: Dh, l: Dl } = add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0)); + ({ h: Eh, l: El } = add(this.Eh | 0, this.El | 0, Eh | 0, El | 0)); + ({ h: Fh, l: Fl } = add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0)); + ({ h: Gh, l: Gl } = add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0)); + ({ h: Hh, l: Hl } = add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0)); + this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl); + } + roundClean() { + clean(SHA512_W_H, SHA512_W_L); + } + destroy() { + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +}; +var _SHA512 = class extends SHA2_64B { + constructor() { + super(64); + __publicField(this, "Ah", SHA512_IV[0] | 0); + __publicField(this, "Al", SHA512_IV[1] | 0); + __publicField(this, "Bh", SHA512_IV[2] | 0); + __publicField(this, "Bl", SHA512_IV[3] | 0); + __publicField(this, "Ch", SHA512_IV[4] | 0); + __publicField(this, "Cl", SHA512_IV[5] | 0); + __publicField(this, "Dh", SHA512_IV[6] | 0); + __publicField(this, "Dl", SHA512_IV[7] | 0); + __publicField(this, "Eh", SHA512_IV[8] | 0); + __publicField(this, "El", SHA512_IV[9] | 0); + __publicField(this, "Fh", SHA512_IV[10] | 0); + __publicField(this, "Fl", SHA512_IV[11] | 0); + __publicField(this, "Gh", SHA512_IV[12] | 0); + __publicField(this, "Gl", SHA512_IV[13] | 0); + __publicField(this, "Hh", SHA512_IV[14] | 0); + __publicField(this, "Hl", SHA512_IV[15] | 0); + } +}; +var sha256 = /* @__PURE__ */ createHasher( + () => new _SHA256(), + /* @__PURE__ */ oidNist(1) +); +var sha512 = /* @__PURE__ */ createHasher( + () => new _SHA512(), + /* @__PURE__ */ oidNist(3) +); + +// node_modules/@scure/base/index.js +function isBytes2(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +function isArrayOf(isString, arr) { + if (!Array.isArray(arr)) + return false; + if (arr.length === 0) + return true; + if (isString) { + return arr.every((item) => typeof item === "string"); + } else { + return arr.every((item) => Number.isSafeInteger(item)); + } +} +function afn(input) { + if (typeof input !== "function") + throw new TypeError("function expected"); + return true; +} +function astr(label, input) { + if (typeof input !== "string") + throw new TypeError(`${label}: string expected`); + return true; +} +function anumber2(n) { + if (typeof n !== "number") + throw new TypeError(`number expected, got ${typeof n}`); + if (!Number.isSafeInteger(n)) + throw new RangeError(`invalid integer: ${n}`); +} +function aArr(input) { + if (!Array.isArray(input)) + throw new TypeError("array expected"); +} +function astrArr(label, input) { + if (!isArrayOf(true, input)) + throw new TypeError(`${label}: array of strings expected`); +} +function anumArr(label, input) { + if (!isArrayOf(false, input)) + throw new TypeError(`${label}: array of numbers expected`); +} +// @__NO_SIDE_EFFECTS__ +function chain(...args) { + const id2 = (a) => a; + const wrap = (a, b) => (c) => a(b(c)); + const encode = args.map((x) => x.encode).reduceRight(wrap, id2); + const decode = args.map((x) => x.decode).reduce(wrap, id2); + return { encode, decode }; +} +// @__NO_SIDE_EFFECTS__ +function alphabet(letters) { + const lettersA = typeof letters === "string" ? letters.split("") : letters; + const len = lettersA.length; + astrArr("alphabet", lettersA); + const indexes = new Map(lettersA.map((l, i) => [l, i])); + return { + encode: (digits) => { + aArr(digits); + return digits.map((i) => { + if (!Number.isSafeInteger(i) || i < 0 || i >= len) + throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${letters}`); + return lettersA[i]; + }); + }, + decode: (input) => { + aArr(input); + return input.map((letter) => { + astr("alphabet.decode", letter); + const i = indexes.get(letter); + if (i === void 0) + throw new Error(`Unknown letter: "${letter}". Allowed: ${letters}`); + return i; + }); + } + }; +} +// @__NO_SIDE_EFFECTS__ +function join(separator = "") { + astr("join", separator); + return { + encode: (from) => { + astrArr("join.decode", from); + return from.join(separator); + }, + decode: (to) => { + astr("join.decode", to); + return to.split(separator); + } + }; +} +// @__NO_SIDE_EFFECTS__ +function padding(bits, chr = "=") { + anumber2(bits); + astr("padding", chr); + return { + encode(data) { + astrArr("padding.encode", data); + while (data.length * bits % 8) + data.push(chr); + return data; + }, + decode(input) { + astrArr("padding.decode", input); + let end = input.length; + if (end * bits % 8) + throw new Error("padding: invalid, string should have whole number of bytes"); + for (; end > 0 && input[end - 1] === chr; end--) { + const last = end - 1; + const byte = last * bits; + if (byte % 8 === 0) + throw new Error("padding: invalid, string has too much padding"); + } + return input.slice(0, end); + } + }; +} +function convertRadix(data, from, to) { + if (from < 2) + throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`); + if (to < 2) + throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`); + aArr(data); + if (!data.length) + return []; + let pos = 0; + const res = []; + const digits = Array.from(data, (d) => { + anumber2(d); + if (d < 0 || d >= from) + throw new Error(`invalid integer: ${d}`); + return d; + }); + const dlen = digits.length; + while (true) { + let carry = 0; + let done = true; + for (let i = pos; i < dlen; i++) { + const digit = digits[i]; + const fromCarry = from * carry; + const digitBase = fromCarry + digit; + if (!Number.isSafeInteger(digitBase) || fromCarry / from !== carry || digitBase - digit !== fromCarry) { + throw new Error("convertRadix: carry overflow"); + } + const div = digitBase / to; + carry = digitBase % to; + const rounded = Math.floor(div); + digits[i] = rounded; + if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase) + throw new Error("convertRadix: carry overflow"); + if (!done) + continue; + else if (!rounded) + pos = i; + else + done = false; + } + res.push(carry); + if (done) + break; + } + for (let i = 0; i < data.length - 1 && data[i] === 0; i++) + res.push(0); + return res.reverse(); +} +var gcd = (a, b) => b === 0 ? a : gcd(b, a % b); +var radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from, to) => from + (to - gcd(from, to)); +var powers = /* @__PURE__ */ (() => { + let res = []; + for (let i = 0; i < 40; i++) + res.push(2 ** i); + return res; +})(); +function convertRadix2(data, from, to, padding2) { + aArr(data); + if (from <= 0 || from > 32) + throw new RangeError(`convertRadix2: wrong from=${from}`); + if (to <= 0 || to > 32) + throw new RangeError(`convertRadix2: wrong to=${to}`); + if (/* @__PURE__ */ radix2carry(from, to) > 32) { + throw new Error(`convertRadix2: carry overflow from=${from} to=${to} carryBits=${/* @__PURE__ */ radix2carry(from, to)}`); + } + let carry = 0; + let pos = 0; + const max = powers[from]; + const mask = powers[to] - 1; + const res = []; + for (const n of data) { + anumber2(n); + if (n >= max) + throw new Error(`convertRadix2: invalid data word=${n} from=${from}`); + carry = carry << from | n; + if (pos + from > 32) + throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`); + pos += from; + for (; pos >= to; pos -= to) + res.push((carry >> pos - to & mask) >>> 0); + const pow = powers[pos]; + if (pow === void 0) + throw new Error("invalid carry"); + carry &= pow - 1; + } + carry = carry << to - pos & mask; + if (!padding2 && pos >= from) + throw new Error("Excess padding"); + if (!padding2 && carry > 0) + throw new Error(`Non-zero padding: ${carry}`); + if (padding2 && pos > 0) + res.push(carry >>> 0); + return res; +} +// @__NO_SIDE_EFFECTS__ +function radix(num) { + anumber2(num); + const _256 = 2 ** 8; + return { + encode: (bytes) => { + if (!isBytes2(bytes)) + throw new TypeError("radix.encode input should be Uint8Array"); + return convertRadix(Array.from(bytes), _256, num); + }, + decode: (digits) => { + anumArr("radix.decode", digits); + return Uint8Array.from(convertRadix(digits, num, _256)); + } + }; +} +// @__NO_SIDE_EFFECTS__ +function radix2(bits, revPadding = false) { + anumber2(bits); + if (bits <= 0 || bits > 32) + throw new RangeError("radix2: bits should be in (0..32]"); + if (/* @__PURE__ */ radix2carry(8, bits) > 32 || /* @__PURE__ */ radix2carry(bits, 8) > 32) + throw new RangeError("radix2: carry overflow"); + return { + encode: (bytes) => { + if (!isBytes2(bytes)) + throw new TypeError("radix2.encode input should be Uint8Array"); + return convertRadix2(Array.from(bytes), 8, bits, !revPadding); + }, + decode: (digits) => { + anumArr("radix2.decode", digits); + return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding)); + } + }; +} +function checksum(len, fn) { + anumber2(len); + if (len <= 0) + throw new RangeError(`checksum length must be positive: ${len}`); + afn(fn); + const _fn = fn; + return { + encode(data) { + if (!isBytes2(data)) + throw new TypeError("checksum.encode: input should be Uint8Array"); + const sum = _fn(data).slice(0, len); + const res = new Uint8Array(data.length + len); + res.set(data); + res.set(sum, data.length); + return res; + }, + decode(data) { + if (!isBytes2(data)) + throw new TypeError("checksum.decode: input should be Uint8Array"); + const payload = data.slice(0, -len); + const oldChecksum = data.slice(-len); + const newChecksum = _fn(payload).slice(0, len); + for (let i = 0; i < len; i++) + if (newChecksum[i] !== oldChecksum[i]) + throw new Error("Invalid checksum"); + return payload; + } + }; +} +var utils = /* @__PURE__ */ Object.freeze({ + alphabet, + chain, + checksum, + convertRadix, + convertRadix2, + radix, + radix2, + join, + padding +}); +var genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc) => /* @__PURE__ */ chain(/* @__PURE__ */ radix(58), /* @__PURE__ */ alphabet(abc), /* @__PURE__ */ join("")); +var base58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ genBase58("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")); +var createBase58check = (sha2562) => { + afn(sha2562); + const _sha256 = sha2562; + return /* @__PURE__ */ chain(checksum(4, (data) => _sha256(_sha256(data))), base58); +}; + +// node_modules/@scure/bip39/index.js +var isJapanese = (wordlist2) => wordlist2[0] === "\u3042\u3044\u3053\u304F\u3057\u3093"; +function nfkd(str) { + if (typeof str !== "string") + throw new TypeError("invalid mnemonic type: " + typeof str); + return str.normalize("NFKD"); +} +function normalize(str) { + const norm = nfkd(str); + const words = norm.split(" "); + if (![12, 15, 18, 21, 24].includes(words.length)) + throw new Error("Invalid mnemonic"); + return { nfkd: norm, words }; +} +function aentropy(ent) { + abytes(ent); + if (![16, 20, 24, 28, 32].includes(ent.length)) + throw new RangeError("invalid entropy length"); +} +function generateMnemonic(wordlist2, strength = 128) { + anumber(strength); + if (strength % 32 !== 0 || strength > 256) + throw new RangeError("Invalid entropy"); + return entropyToMnemonic(randomBytes(strength / 8), wordlist2); +} +var calcChecksum = (entropy) => { + const bitsLeft = 8 - entropy.length / 4; + return new Uint8Array([sha256(entropy)[0] >> bitsLeft << bitsLeft]); +}; +function getCoder(wordlist2) { + if (!Array.isArray(wordlist2) || wordlist2.length !== 2048 || typeof wordlist2[0] !== "string") + throw new TypeError("Wordlist: expected array of 2048 strings"); + wordlist2.forEach((i) => { + if (typeof i !== "string") + throw new TypeError("wordlist: non-string element: " + i); + }); + return utils.chain(utils.checksum(1, calcChecksum), utils.radix2(11, true), utils.alphabet(wordlist2)); +} +function mnemonicToEntropy(mnemonic, wordlist2) { + const { words } = normalize(mnemonic); + const entropy = getCoder(wordlist2).decode(words); + aentropy(entropy); + return entropy; +} +function entropyToMnemonic(entropy, wordlist2) { + aentropy(entropy); + const words = getCoder(wordlist2).encode(entropy); + return words.join(isJapanese(wordlist2) ? "\u3000" : " "); +} +function validateMnemonic(mnemonic, wordlist2) { + try { + mnemonicToEntropy(mnemonic, wordlist2); + } catch (e) { + return false; + } + return true; +} +var psalt = (passphrase) => nfkd("mnemonic" + passphrase); +function mnemonicToSeedSync(mnemonic, passphrase = "") { + return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), { + c: 2048, + dkLen: 64 + }); +} + +// node_modules/@scure/bip39/wordlists/english.js +var wordlist = /* @__PURE__ */ Object.freeze(`abandon +ability +able +about +above +absent +absorb +abstract +absurd +abuse +access +accident +account +accuse +achieve +acid +acoustic +acquire +across +act +action +actor +actress +actual +adapt +add +addict +address +adjust +admit +adult +advance +advice +aerobic +affair +afford +afraid +again +age +agent +agree +ahead +aim +air +airport +aisle +alarm +album +alcohol +alert +alien +all +alley +allow +almost +alone +alpha +already +also +alter +always +amateur +amazing +among +amount +amused +analyst +anchor +ancient +anger +angle +angry +animal +ankle +announce +annual +another +answer +antenna +antique +anxiety +any +apart +apology +appear +apple +approve +april +arch +arctic +area +arena +argue +arm +armed +armor +army +around +arrange +arrest +arrive +arrow +art +artefact +artist +artwork +ask +aspect +assault +asset +assist +assume +asthma +athlete +atom +attack +attend +attitude +attract +auction +audit +august +aunt +author +auto +autumn +average +avocado +avoid +awake +aware +away +awesome +awful +awkward +axis +baby +bachelor +bacon +badge +bag +balance +balcony +ball +bamboo +banana +banner +bar +barely +bargain +barrel +base +basic +basket +battle +beach +bean +beauty +because +become +beef +before +begin +behave +behind +believe +below +belt +bench +benefit +best +betray +better +between +beyond +bicycle +bid +bike +bind +biology +bird +birth +bitter +black +blade +blame +blanket +blast +bleak +bless +blind +blood +blossom +blouse +blue +blur +blush +board +boat +body +boil +bomb +bone +bonus +book +boost +border +boring +borrow +boss +bottom +bounce +box +boy +bracket +brain +brand +brass +brave +bread +breeze +brick +bridge +brief +bright +bring +brisk +broccoli +broken +bronze +broom +brother +brown +brush +bubble +buddy +budget +buffalo +build +bulb +bulk +bullet +bundle +bunker +burden +burger +burst +bus +business +busy +butter +buyer +buzz +cabbage +cabin +cable +cactus +cage +cake +call +calm +camera +camp +can +canal +cancel +candy +cannon +canoe +canvas +canyon +capable +capital +captain +car +carbon +card +cargo +carpet +carry +cart +case +cash +casino +castle +casual +cat +catalog +catch +category +cattle +caught +cause +caution +cave +ceiling +celery +cement +census +century +cereal +certain +chair +chalk +champion +change +chaos +chapter +charge +chase +chat +cheap +check +cheese +chef +cherry +chest +chicken +chief +child +chimney +choice +choose +chronic +chuckle +chunk +churn +cigar +cinnamon +circle +citizen +city +civil +claim +clap +clarify +claw +clay +clean +clerk +clever +click +client +cliff +climb +clinic +clip +clock +clog +close +cloth +cloud +clown +club +clump +cluster +clutch +coach +coast +coconut +code +coffee +coil +coin +collect +color +column +combine +come +comfort +comic +common +company +concert +conduct +confirm +congress +connect +consider +control +convince +cook +cool +copper +copy +coral +core +corn +correct +cost +cotton +couch +country +couple +course +cousin +cover +coyote +crack +cradle +craft +cram +crane +crash +crater +crawl +crazy +cream +credit +creek +crew +cricket +crime +crisp +critic +crop +cross +crouch +crowd +crucial +cruel +cruise +crumble +crunch +crush +cry +crystal +cube +culture +cup +cupboard +curious +current +curtain +curve +cushion +custom +cute +cycle +dad +damage +damp +dance +danger +daring +dash +daughter +dawn +day +deal +debate +debris +decade +december +decide +decline +decorate +decrease +deer +defense +define +defy +degree +delay +deliver +demand +demise +denial +dentist +deny +depart +depend +deposit +depth +deputy +derive +describe +desert +design +desk +despair +destroy +detail +detect +develop +device +devote +diagram +dial +diamond +diary +dice +diesel +diet +differ +digital +dignity +dilemma +dinner +dinosaur +direct +dirt +disagree +discover +disease +dish +dismiss +disorder +display +distance +divert +divide +divorce +dizzy +doctor +document +dog +doll +dolphin +domain +donate +donkey +donor +door +dose +double +dove +draft +dragon +drama +drastic +draw +dream +dress +drift +drill +drink +drip +drive +drop +drum +dry +duck +dumb +dune +during +dust +dutch +duty +dwarf +dynamic +eager +eagle +early +earn +earth +easily +east +easy +echo +ecology +economy +edge +edit +educate +effort +egg +eight +either +elbow +elder +electric +elegant +element +elephant +elevator +elite +else +embark +embody +embrace +emerge +emotion +employ +empower +empty +enable +enact +end +endless +endorse +enemy +energy +enforce +engage +engine +enhance +enjoy +enlist +enough +enrich +enroll +ensure +enter +entire +entry +envelope +episode +equal +equip +era +erase +erode +erosion +error +erupt +escape +essay +essence +estate +eternal +ethics +evidence +evil +evoke +evolve +exact +example +excess +exchange +excite +exclude +excuse +execute +exercise +exhaust +exhibit +exile +exist +exit +exotic +expand +expect +expire +explain +expose +express +extend +extra +eye +eyebrow +fabric +face +faculty +fade +faint +faith +fall +false +fame +family +famous +fan +fancy +fantasy +farm +fashion +fat +fatal +father +fatigue +fault +favorite +feature +february +federal +fee +feed +feel +female +fence +festival +fetch +fever +few +fiber +fiction +field +figure +file +film +filter +final +find +fine +finger +finish +fire +firm +first +fiscal +fish +fit +fitness +fix +flag +flame +flash +flat +flavor +flee +flight +flip +float +flock +floor +flower +fluid +flush +fly +foam +focus +fog +foil +fold +follow +food +foot +force +forest +forget +fork +fortune +forum +forward +fossil +foster +found +fox +fragile +frame +frequent +fresh +friend +fringe +frog +front +frost +frown +frozen +fruit +fuel +fun +funny +furnace +fury +future +gadget +gain +galaxy +gallery +game +gap +garage +garbage +garden +garlic +garment +gas +gasp +gate +gather +gauge +gaze +general +genius +genre +gentle +genuine +gesture +ghost +giant +gift +giggle +ginger +giraffe +girl +give +glad +glance +glare +glass +glide +glimpse +globe +gloom +glory +glove +glow +glue +goat +goddess +gold +good +goose +gorilla +gospel +gossip +govern +gown +grab +grace +grain +grant +grape +grass +gravity +great +green +grid +grief +grit +grocery +group +grow +grunt +guard +guess +guide +guilt +guitar +gun +gym +habit +hair +half +hammer +hamster +hand +happy +harbor +hard +harsh +harvest +hat +have +hawk +hazard +head +health +heart +heavy +hedgehog +height +hello +helmet +help +hen +hero +hidden +high +hill +hint +hip +hire +history +hobby +hockey +hold +hole +holiday +hollow +home +honey +hood +hope +horn +horror +horse +hospital +host +hotel +hour +hover +hub +huge +human +humble +humor +hundred +hungry +hunt +hurdle +hurry +hurt +husband +hybrid +ice +icon +idea +identify +idle +ignore +ill +illegal +illness +image +imitate +immense +immune +impact +impose +improve +impulse +inch +include +income +increase +index +indicate +indoor +industry +infant +inflict +inform +inhale +inherit +initial +inject +injury +inmate +inner +innocent +input +inquiry +insane +insect +inside +inspire +install +intact +interest +into +invest +invite +involve +iron +island +isolate +issue +item +ivory +jacket +jaguar +jar +jazz +jealous +jeans +jelly +jewel +job +join +joke +journey +joy +judge +juice +jump +jungle +junior +junk +just +kangaroo +keen +keep +ketchup +key +kick +kid +kidney +kind +kingdom +kiss +kit +kitchen +kite +kitten +kiwi +knee +knife +knock +know +lab +label +labor +ladder +lady +lake +lamp +language +laptop +large +later +latin +laugh +laundry +lava +law +lawn +lawsuit +layer +lazy +leader +leaf +learn +leave +lecture +left +leg +legal +legend +leisure +lemon +lend +length +lens +leopard +lesson +letter +level +liar +liberty +library +license +life +lift +light +like +limb +limit +link +lion +liquid +list +little +live +lizard +load +loan +lobster +local +lock +logic +lonely +long +loop +lottery +loud +lounge +love +loyal +lucky +luggage +lumber +lunar +lunch +luxury +lyrics +machine +mad +magic +magnet +maid +mail +main +major +make +mammal +man +manage +mandate +mango +mansion +manual +maple +marble +march +margin +marine +market +marriage +mask +mass +master +match +material +math +matrix +matter +maximum +maze +meadow +mean +measure +meat +mechanic +medal +media +melody +melt +member +memory +mention +menu +mercy +merge +merit +merry +mesh +message +metal +method +middle +midnight +milk +million +mimic +mind +minimum +minor +minute +miracle +mirror +misery +miss +mistake +mix +mixed +mixture +mobile +model +modify +mom +moment +monitor +monkey +monster +month +moon +moral +more +morning +mosquito +mother +motion +motor +mountain +mouse +move +movie +much +muffin +mule +multiply +muscle +museum +mushroom +music +must +mutual +myself +mystery +myth +naive +name +napkin +narrow +nasty +nation +nature +near +neck +need +negative +neglect +neither +nephew +nerve +nest +net +network +neutral +never +news +next +nice +night +noble +noise +nominee +noodle +normal +north +nose +notable +note +nothing +notice +novel +now +nuclear +number +nurse +nut +oak +obey +object +oblige +obscure +observe +obtain +obvious +occur +ocean +october +odor +off +offer +office +often +oil +okay +old +olive +olympic +omit +once +one +onion +online +only +open +opera +opinion +oppose +option +orange +orbit +orchard +order +ordinary +organ +orient +original +orphan +ostrich +other +outdoor +outer +output +outside +oval +oven +over +own +owner +oxygen +oyster +ozone +pact +paddle +page +pair +palace +palm +panda +panel +panic +panther +paper +parade +parent +park +parrot +party +pass +patch +path +patient +patrol +pattern +pause +pave +payment +peace +peanut +pear +peasant +pelican +pen +penalty +pencil +people +pepper +perfect +permit +person +pet +phone +photo +phrase +physical +piano +picnic +picture +piece +pig +pigeon +pill +pilot +pink +pioneer +pipe +pistol +pitch +pizza +place +planet +plastic +plate +play +please +pledge +pluck +plug +plunge +poem +poet +point +polar +pole +police +pond +pony +pool +popular +portion +position +possible +post +potato +pottery +poverty +powder +power +practice +praise +predict +prefer +prepare +present +pretty +prevent +price +pride +primary +print +priority +prison +private +prize +problem +process +produce +profit +program +project +promote +proof +property +prosper +protect +proud +provide +public +pudding +pull +pulp +pulse +pumpkin +punch +pupil +puppy +purchase +purity +purpose +purse +push +put +puzzle +pyramid +quality +quantum +quarter +question +quick +quit +quiz +quote +rabbit +raccoon +race +rack +radar +radio +rail +rain +raise +rally +ramp +ranch +random +range +rapid +rare +rate +rather +raven +raw +razor +ready +real +reason +rebel +rebuild +recall +receive +recipe +record +recycle +reduce +reflect +reform +refuse +region +regret +regular +reject +relax +release +relief +rely +remain +remember +remind +remove +render +renew +rent +reopen +repair +repeat +replace +report +require +rescue +resemble +resist +resource +response +result +retire +retreat +return +reunion +reveal +review +reward +rhythm +rib +ribbon +rice +rich +ride +ridge +rifle +right +rigid +ring +riot +ripple +risk +ritual +rival +river +road +roast +robot +robust +rocket +romance +roof +rookie +room +rose +rotate +rough +round +route +royal +rubber +rude +rug +rule +run +runway +rural +sad +saddle +sadness +safe +sail +salad +salmon +salon +salt +salute +same +sample +sand +satisfy +satoshi +sauce +sausage +save +say +scale +scan +scare +scatter +scene +scheme +school +science +scissors +scorpion +scout +scrap +screen +script +scrub +sea +search +season +seat +second +secret +section +security +seed +seek +segment +select +sell +seminar +senior +sense +sentence +series +service +session +settle +setup +seven +shadow +shaft +shallow +share +shed +shell +sheriff +shield +shift +shine +ship +shiver +shock +shoe +shoot +shop +short +shoulder +shove +shrimp +shrug +shuffle +shy +sibling +sick +side +siege +sight +sign +silent +silk +silly +silver +similar +simple +since +sing +siren +sister +situate +six +size +skate +sketch +ski +skill +skin +skirt +skull +slab +slam +sleep +slender +slice +slide +slight +slim +slogan +slot +slow +slush +small +smart +smile +smoke +smooth +snack +snake +snap +sniff +snow +soap +soccer +social +sock +soda +soft +solar +soldier +solid +solution +solve +someone +song +soon +sorry +sort +soul +sound +soup +source +south +space +spare +spatial +spawn +speak +special +speed +spell +spend +sphere +spice +spider +spike +spin +spirit +split +spoil +sponsor +spoon +sport +spot +spray +spread +spring +spy +square +squeeze +squirrel +stable +stadium +staff +stage +stairs +stamp +stand +start +state +stay +steak +steel +stem +step +stereo +stick +still +sting +stock +stomach +stone +stool +story +stove +strategy +street +strike +strong +struggle +student +stuff +stumble +style +subject +submit +subway +success +such +sudden +suffer +sugar +suggest +suit +summer +sun +sunny +sunset +super +supply +supreme +sure +surface +surge +surprise +surround +survey +suspect +sustain +swallow +swamp +swap +swarm +swear +sweet +swift +swim +swing +switch +sword +symbol +symptom +syrup +system +table +tackle +tag +tail +talent +talk +tank +tape +target +task +taste +tattoo +taxi +teach +team +tell +ten +tenant +tennis +tent +term +test +text +thank +that +theme +then +theory +there +they +thing +this +thought +three +thrive +throw +thumb +thunder +ticket +tide +tiger +tilt +timber +time +tiny +tip +tired +tissue +title +toast +tobacco +today +toddler +toe +together +toilet +token +tomato +tomorrow +tone +tongue +tonight +tool +tooth +top +topic +topple +torch +tornado +tortoise +toss +total +tourist +toward +tower +town +toy +track +trade +traffic +tragic +train +transfer +trap +trash +travel +tray +treat +tree +trend +trial +tribe +trick +trigger +trim +trip +trophy +trouble +truck +true +truly +trumpet +trust +truth +try +tube +tuition +tumble +tuna +tunnel +turkey +turn +turtle +twelve +twenty +twice +twin +twist +two +type +typical +ugly +umbrella +unable +unaware +uncle +uncover +under +undo +unfair +unfold +unhappy +uniform +unique +unit +universe +unknown +unlock +until +unusual +unveil +update +upgrade +uphold +upon +upper +upset +urban +urge +usage +use +used +useful +useless +usual +utility +vacant +vacuum +vague +valid +valley +valve +van +vanish +vapor +various +vast +vault +vehicle +velvet +vendor +venture +venue +verb +verify +version +very +vessel +veteran +viable +vibrant +vicious +victory +video +view +village +vintage +violin +virtual +virus +visa +visit +visual +vital +vivid +vocal +voice +void +volcano +volume +vote +voyage +wage +wagon +wait +walk +wall +walnut +want +warfare +warm +warrior +wash +wasp +waste +water +wave +way +wealth +weapon +wear +weasel +weather +web +wedding +weekend +weird +welcome +west +wet +whale +what +wheat +wheel +when +where +whip +whisper +wide +width +wife +wild +will +win +window +wine +wing +wink +winner +winter +wire +wisdom +wise +wish +witness +wolf +woman +wonder +wood +wool +word +work +world +worry +worth +wrap +wreck +wrestle +wrist +write +wrong +yard +year +yellow +you +young +youth +zebra +zero +zone +zoo`.split("\n")); + +// node_modules/@noble/curves/utils.js +var abytes2 = (value, length, title) => abytes(value, length, title); +var anumber3 = anumber; +var bytesToHex2 = bytesToHex; +var concatBytes2 = (...arrays) => concatBytes(...arrays); +var hexToBytes2 = (hex) => hexToBytes(hex); +var isBytes3 = isBytes; +var randomBytes2 = (bytesLength) => randomBytes(bytesLength); +var _0n = /* @__PURE__ */ BigInt(0); +var _1n = /* @__PURE__ */ BigInt(1); +function abool(value, title = "") { + if (typeof value !== "boolean") { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + "expected boolean, got type=" + typeof value); + } + return value; +} +function abignumber(n) { + if (typeof n === "bigint") { + if (!isPosBig(n)) + throw new RangeError("positive bigint expected, got " + n); + } else + anumber3(n); + return n; +} +function asafenumber(value, title = "") { + if (typeof value !== "number") { + const prefix = title && `"${title}" `; + throw new TypeError(prefix + "expected number, got type=" + typeof value); + } + if (!Number.isSafeInteger(value)) { + const prefix = title && `"${title}" `; + throw new RangeError(prefix + "expected safe integer, got " + value); + } +} +function numberToHexUnpadded(num) { + const hex = abignumber(num).toString(16); + return hex.length & 1 ? "0" + hex : hex; +} +function hexToNumber(hex) { + if (typeof hex !== "string") + throw new TypeError("hex string expected, got " + typeof hex); + return hex === "" ? _0n : BigInt("0x" + hex); +} +function bytesToNumberBE(bytes) { + return hexToNumber(bytesToHex(bytes)); +} +function bytesToNumberLE(bytes) { + return hexToNumber(bytesToHex(copyBytes(abytes(bytes)).reverse())); +} +function numberToBytesBE(n, len) { + anumber(len); + if (len === 0) + throw new RangeError("zero length"); + n = abignumber(n); + const hex = n.toString(16); + if (hex.length > len * 2) + throw new RangeError("number too large"); + return hexToBytes(hex.padStart(len * 2, "0")); +} +function numberToBytesLE(n, len) { + return numberToBytesBE(n, len).reverse(); +} +function copyBytes(bytes) { + return Uint8Array.from(abytes2(bytes)); +} +var isPosBig = (n) => typeof n === "bigint" && _0n <= n; +function inRange(n, min, max) { + return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max; +} +function aInRange(title, n, min, max) { + if (!inRange(n, min, max)) + throw new RangeError("expected valid " + title + ": " + min + " <= n < " + max + ", got " + n); +} +function bitLen(n) { + if (n < _0n) + throw new Error("expected non-negative bigint, got " + n); + let len; + for (len = 0; n > _0n; n >>= _1n, len += 1) + ; + return len; +} +var bitMask = (n) => (_1n << BigInt(n)) - _1n; +function createHmacDrbg(hashLen, qByteLen, hmacFn) { + anumber(hashLen, "hashLen"); + anumber(qByteLen, "qByteLen"); + if (typeof hmacFn !== "function") + throw new TypeError("hmacFn must be a function"); + const u8n = (len) => new Uint8Array(len); + const NULL = Uint8Array.of(); + const byte0 = Uint8Array.of(0); + const byte1 = Uint8Array.of(1); + const _maxDrbgIters = 1e3; + let v = u8n(hashLen); + let k = u8n(hashLen); + let i = 0; + const reset = () => { + v.fill(1); + k.fill(0); + i = 0; + }; + const h = (...msgs) => hmacFn(k, concatBytes2(v, ...msgs)); + const reseed = (seed = NULL) => { + k = h(byte0, seed); + v = h(); + if (seed.length === 0) + return; + k = h(byte1, seed); + v = h(); + }; + const gen2 = () => { + if (i++ >= _maxDrbgIters) + throw new Error("drbg: tried max amount of iterations"); + let len = 0; + const out = []; + while (len < qByteLen) { + v = h(); + const sl = v.slice(); + out.push(sl); + len += v.length; + } + return concatBytes2(...out); + }; + const genUntil = (seed, pred) => { + reset(); + reseed(seed); + let res = void 0; + while ((res = pred(gen2())) === void 0) + reseed(); + reset(); + return res; + }; + return genUntil; +} +function validateObject(object, fields = {}, optFields = {}) { + if (Object.prototype.toString.call(object) !== "[object Object]") + throw new TypeError("expected valid options object"); + function checkField(fieldName, expectedType, isOpt) { + if (!isOpt && expectedType !== "function" && !Object.hasOwn(object, fieldName)) + throw new TypeError(`param "${fieldName}" is invalid: expected own property`); + const val = object[fieldName]; + if (isOpt && val === void 0) + return; + const current = typeof val; + if (current !== expectedType || val === null) + throw new TypeError(`param "${fieldName}" is invalid: expected ${expectedType}, got ${current}`); + } + const iter = (f, isOpt) => Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt)); + iter(fields, false); + iter(optFields, true); +} + +// node_modules/@noble/curves/abstract/modular.js +var _0n2 = /* @__PURE__ */ BigInt(0); +var _1n2 = /* @__PURE__ */ BigInt(1); +var _2n = /* @__PURE__ */ BigInt(2); +var _3n = /* @__PURE__ */ BigInt(3); +var _4n = /* @__PURE__ */ BigInt(4); +var _5n = /* @__PURE__ */ BigInt(5); +var _7n = /* @__PURE__ */ BigInt(7); +var _8n = /* @__PURE__ */ BigInt(8); +var _9n = /* @__PURE__ */ BigInt(9); +var _16n = /* @__PURE__ */ BigInt(16); +function mod(a, b) { + if (b <= _0n2) + throw new Error("mod: expected positive modulus, got " + b); + const result = a % b; + return result >= _0n2 ? result : b + result; +} +function pow2(x, power, modulo) { + if (power < _0n2) + throw new Error("pow2: expected non-negative exponent, got " + power); + let res = x; + while (power-- > _0n2) { + res *= res; + res %= modulo; + } + return res; +} +function invert(number, modulo) { + if (number === _0n2) + throw new Error("invert: expected non-zero number"); + if (modulo <= _0n2) + throw new Error("invert: expected positive modulus, got " + modulo); + let a = mod(number, modulo); + let b = modulo; + let x = _0n2, y = _1n2, u = _1n2, v = _0n2; + while (a !== _0n2) { + const q = b / a; + const r = b - a * q; + const m = x - u * q; + const n = y - v * q; + b = a, a = r, x = u, y = v, u = m, v = n; + } + const gcd2 = b; + if (gcd2 !== _1n2) + throw new Error("invert: does not exist"); + return mod(x, modulo); +} +function assertIsSquare(Fp, root, n) { + const F3 = Fp; + if (!F3.eql(F3.sqr(root), n)) + throw new Error("Cannot find square root"); +} +function sqrt3mod4(Fp, n) { + const F3 = Fp; + const p1div4 = (F3.ORDER + _1n2) / _4n; + const root = F3.pow(n, p1div4); + assertIsSquare(F3, root, n); + return root; +} +function sqrt5mod8(Fp, n) { + const F3 = Fp; + const p5div8 = (F3.ORDER - _5n) / _8n; + const n2 = F3.mul(n, _2n); + const v = F3.pow(n2, p5div8); + const nv = F3.mul(n, v); + const i = F3.mul(F3.mul(nv, _2n), v); + const root = F3.mul(nv, F3.sub(i, F3.ONE)); + assertIsSquare(F3, root, n); + return root; +} +function sqrt9mod16(P) { + const Fp_ = Field(P); + const tn = tonelliShanks(P); + const c1 = tn(Fp_, Fp_.neg(Fp_.ONE)); + const c2 = tn(Fp_, c1); + const c3 = tn(Fp_, Fp_.neg(c1)); + const c4 = (P + _7n) / _16n; + return ((Fp, n) => { + const F3 = Fp; + let tv1 = F3.pow(n, c4); + let tv2 = F3.mul(tv1, c1); + const tv3 = F3.mul(tv1, c2); + const tv4 = F3.mul(tv1, c3); + const e1 = F3.eql(F3.sqr(tv2), n); + const e2 = F3.eql(F3.sqr(tv3), n); + tv1 = F3.cmov(tv1, tv2, e1); + tv2 = F3.cmov(tv4, tv3, e2); + const e3 = F3.eql(F3.sqr(tv2), n); + const root = F3.cmov(tv1, tv2, e3); + assertIsSquare(F3, root, n); + return root; + }); +} +function tonelliShanks(P) { + if (P < _3n) + throw new Error("sqrt is not defined for small field"); + let Q3 = P - _1n2; + let S = 0; + while (Q3 % _2n === _0n2) { + Q3 /= _2n; + S++; + } + let Z = _2n; + const _Fp = Field(P); + while (FpLegendre(_Fp, Z) === 1) { + if (Z++ > 1e3) + throw new Error("Cannot find square root: probably non-prime P"); + } + if (S === 1) + return sqrt3mod4; + let cc = _Fp.pow(Z, Q3); + const Q1div2 = (Q3 + _1n2) / _2n; + return function tonelliSlow(Fp, n) { + const F3 = Fp; + if (F3.is0(n)) + return n; + if (FpLegendre(F3, n) !== 1) + throw new Error("Cannot find square root"); + let M = S; + let c = F3.mul(F3.ONE, cc); + let t = F3.pow(n, Q3); + let R = F3.pow(n, Q1div2); + while (!F3.eql(t, F3.ONE)) { + if (F3.is0(t)) + return F3.ZERO; + let i = 1; + let t_tmp = F3.sqr(t); + while (!F3.eql(t_tmp, F3.ONE)) { + i++; + t_tmp = F3.sqr(t_tmp); + if (i === M) + throw new Error("Cannot find square root"); + } + const exponent = _1n2 << BigInt(M - i - 1); + const b = F3.pow(c, exponent); + M = i; + c = F3.sqr(b); + t = F3.mul(t, c); + R = F3.mul(R, b); + } + return R; + }; +} +function FpSqrt(P) { + if (P % _4n === _3n) + return sqrt3mod4; + if (P % _8n === _5n) + return sqrt5mod8; + if (P % _16n === _9n) + return sqrt9mod16(P); + return tonelliShanks(P); +} +var FIELD_FIELDS = [ + "create", + "isValid", + "is0", + "neg", + "inv", + "sqrt", + "sqr", + "eql", + "add", + "sub", + "mul", + "pow", + "div", + "addN", + "subN", + "mulN", + "sqrN" +]; +function validateField(field) { + const initial = { + ORDER: "bigint", + BYTES: "number", + BITS: "number" + }; + const opts2 = FIELD_FIELDS.reduce((map, val) => { + map[val] = "function"; + return map; + }, initial); + validateObject(field, opts2); + asafenumber(field.BYTES, "BYTES"); + asafenumber(field.BITS, "BITS"); + if (field.BYTES < 1 || field.BITS < 1) + throw new Error("invalid field: expected BYTES/BITS > 0"); + if (field.ORDER <= _1n2) + throw new Error("invalid field: expected ORDER > 1, got " + field.ORDER); + return field; +} +function FpPow(Fp, num, power) { + const F3 = Fp; + if (power < _0n2) + throw new Error("invalid exponent, negatives unsupported"); + if (power === _0n2) + return F3.ONE; + if (power === _1n2) + return num; + let p = F3.ONE; + let d = num; + while (power > _0n2) { + if (power & _1n2) + p = F3.mul(p, d); + d = F3.sqr(d); + power >>= _1n2; + } + return p; +} +function FpInvertBatch(Fp, nums, passZero = false) { + const F3 = Fp; + const inverted = new Array(nums.length).fill(passZero ? F3.ZERO : void 0); + const multipliedAcc = nums.reduce((acc, num, i) => { + if (F3.is0(num)) + return acc; + inverted[i] = acc; + return F3.mul(acc, num); + }, F3.ONE); + const invertedAcc = F3.inv(multipliedAcc); + nums.reduceRight((acc, num, i) => { + if (F3.is0(num)) + return acc; + inverted[i] = F3.mul(acc, inverted[i]); + return F3.mul(acc, num); + }, invertedAcc); + return inverted; +} +function FpLegendre(Fp, n) { + const F3 = Fp; + const p1mod2 = (F3.ORDER - _1n2) / _2n; + const powered = F3.pow(n, p1mod2); + const yes = F3.eql(powered, F3.ONE); + const zero = F3.eql(powered, F3.ZERO); + const no = F3.eql(powered, F3.neg(F3.ONE)); + if (!yes && !zero && !no) + throw new Error("invalid Legendre symbol result"); + return yes ? 1 : zero ? 0 : -1; +} +function nLength(n, nBitLength) { + if (nBitLength !== void 0) + anumber3(nBitLength); + if (n <= _0n2) + throw new Error("invalid n length: expected positive n, got " + n); + if (nBitLength !== void 0 && nBitLength < 1) + throw new Error("invalid n length: expected positive bit length, got " + nBitLength); + const bits = bitLen(n); + if (nBitLength !== void 0 && nBitLength < bits) + throw new Error(`invalid n length: expected bit length (${bits}) >= n.length (${nBitLength})`); + const _nBitLength = nBitLength !== void 0 ? nBitLength : bits; + const nByteLength = Math.ceil(_nBitLength / 8); + return { nBitLength: _nBitLength, nByteLength }; +} +var FIELD_SQRT = /* @__PURE__ */ new WeakMap(); +var _Field = class { + constructor(ORDER, opts2 = {}) { + __publicField(this, "ORDER"); + __publicField(this, "BITS"); + __publicField(this, "BYTES"); + __publicField(this, "isLE"); + __publicField(this, "ZERO", _0n2); + __publicField(this, "ONE", _1n2); + __publicField(this, "_lengths"); + __publicField(this, "_mod"); + if (ORDER <= _1n2) + throw new Error("invalid field: expected ORDER > 1, got " + ORDER); + let _nbitLength = void 0; + this.isLE = false; + if (opts2 != null && typeof opts2 === "object") { + if (typeof opts2.BITS === "number") + _nbitLength = opts2.BITS; + if (typeof opts2.sqrt === "function") + Object.defineProperty(this, "sqrt", { value: opts2.sqrt, enumerable: true }); + if (typeof opts2.isLE === "boolean") + this.isLE = opts2.isLE; + if (opts2.allowedLengths) + this._lengths = Object.freeze(opts2.allowedLengths.slice()); + if (typeof opts2.modFromBytes === "boolean") + this._mod = opts2.modFromBytes; + } + const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength); + if (nByteLength > 2048) + throw new Error("invalid field: expected ORDER of <= 2048 bytes"); + this.ORDER = ORDER; + this.BITS = nBitLength; + this.BYTES = nByteLength; + Object.freeze(this); + } + create(num) { + return mod(num, this.ORDER); + } + isValid(num) { + if (typeof num !== "bigint") + throw new TypeError("invalid field element: expected bigint, got " + typeof num); + return _0n2 <= num && num < this.ORDER; + } + is0(num) { + return num === _0n2; + } + // is valid and invertible + isValidNot0(num) { + return !this.is0(num) && this.isValid(num); + } + isOdd(num) { + return (num & _1n2) === _1n2; + } + neg(num) { + return mod(-num, this.ORDER); + } + eql(lhs, rhs) { + return lhs === rhs; + } + sqr(num) { + return mod(num * num, this.ORDER); + } + add(lhs, rhs) { + return mod(lhs + rhs, this.ORDER); + } + sub(lhs, rhs) { + return mod(lhs - rhs, this.ORDER); + } + mul(lhs, rhs) { + return mod(lhs * rhs, this.ORDER); + } + pow(num, power) { + return FpPow(this, num, power); + } + div(lhs, rhs) { + return mod(lhs * invert(rhs, this.ORDER), this.ORDER); + } + // Same as above, but doesn't normalize + sqrN(num) { + return num * num; + } + addN(lhs, rhs) { + return lhs + rhs; + } + subN(lhs, rhs) { + return lhs - rhs; + } + mulN(lhs, rhs) { + return lhs * rhs; + } + inv(num) { + return invert(num, this.ORDER); + } + sqrt(num) { + let sqrt = FIELD_SQRT.get(this); + if (!sqrt) + FIELD_SQRT.set(this, sqrt = FpSqrt(this.ORDER)); + return sqrt(this, num); + } + toBytes(num) { + return this.isLE ? numberToBytesLE(num, this.BYTES) : numberToBytesBE(num, this.BYTES); + } + fromBytes(bytes, skipValidation = false) { + abytes2(bytes); + const { _lengths: allowedLengths, BYTES, isLE: isLE2, ORDER, _mod: modFromBytes } = this; + if (allowedLengths) { + if (bytes.length < 1 || !allowedLengths.includes(bytes.length) || bytes.length > BYTES) { + throw new Error("Field.fromBytes: expected " + allowedLengths + " bytes, got " + bytes.length); + } + const padded = new Uint8Array(BYTES); + padded.set(bytes, isLE2 ? 0 : padded.length - bytes.length); + bytes = padded; + } + if (bytes.length !== BYTES) + throw new Error("Field.fromBytes: expected " + BYTES + " bytes, got " + bytes.length); + let scalar = isLE2 ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes); + if (modFromBytes) + scalar = mod(scalar, ORDER); + if (!skipValidation) { + if (!this.isValid(scalar)) + throw new Error("invalid field element: outside of range 0..ORDER"); + } + return scalar; + } + // TODO: we don't need it here, move out to separate fn + invertBatch(lst) { + return FpInvertBatch(this, lst); + } + // We can't move this out because Fp6, Fp12 implement it + // and it's unclear what to return in there. + cmov(a, b, condition) { + abool(condition, "condition"); + return condition ? b : a; + } +}; +Object.freeze(_Field.prototype); +function Field(ORDER, opts2 = {}) { + return new _Field(ORDER, opts2); +} +function getFieldBytesLength(fieldOrder) { + if (typeof fieldOrder !== "bigint") + throw new Error("field order must be bigint"); + if (fieldOrder <= _1n2) + throw new Error("field order must be greater than 1"); + const bitLength = bitLen(fieldOrder - _1n2); + return Math.ceil(bitLength / 8); +} +function getMinHashLength(fieldOrder) { + const length = getFieldBytesLength(fieldOrder); + return length + Math.ceil(length / 2); +} +function mapHashToField(key, fieldOrder, isLE2 = false) { + abytes2(key); + const len = key.length; + const fieldLen = getFieldBytesLength(fieldOrder); + const minLen = Math.max(getMinHashLength(fieldOrder), 16); + if (len < minLen || len > 1024) + throw new Error("expected " + minLen + "-1024 bytes of input, got " + len); + const num = isLE2 ? bytesToNumberLE(key) : bytesToNumberBE(key); + const reduced = mod(num, fieldOrder - _1n2) + _1n2; + return isLE2 ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen); +} + +// node_modules/@noble/curves/abstract/curve.js +var _0n3 = /* @__PURE__ */ BigInt(0); +var _1n3 = /* @__PURE__ */ BigInt(1); +function negateCt(condition, item) { + const neg = item.negate(); + return condition ? neg : item; +} +function normalizeZ(c, points) { + const invertedZs = FpInvertBatch(c.Fp, points.map((p) => p.Z)); + return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i]))); +} +function validateW(W, bits) { + if (!Number.isSafeInteger(W) || W <= 0 || W > bits) + throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W); +} +function calcWOpts(W, scalarBits) { + validateW(W, scalarBits); + const windows = Math.ceil(scalarBits / W) + 1; + const windowSize = 2 ** (W - 1); + const maxNumber = 2 ** W; + const mask = bitMask(W); + const shiftBy = BigInt(W); + return { windows, windowSize, mask, maxNumber, shiftBy }; +} +function calcOffsets(n, window, wOpts) { + const { windowSize, mask, maxNumber, shiftBy } = wOpts; + let wbits = Number(n & mask); + let nextN = n >> shiftBy; + if (wbits > windowSize) { + wbits -= maxNumber; + nextN += _1n3; + } + const offsetStart = window * windowSize; + const offset = offsetStart + Math.abs(wbits) - 1; + const isZero = wbits === 0; + const isNeg = wbits < 0; + const isNegF = window % 2 !== 0; + const offsetF = offsetStart; + return { nextN, offset, isZero, isNeg, isNegF, offsetF }; +} +var pointPrecomputes = /* @__PURE__ */ new WeakMap(); +var pointWindowSizes = /* @__PURE__ */ new WeakMap(); +function getW(P) { + return pointWindowSizes.get(P) || 1; +} +function assert0(n) { + if (n !== _0n3) + throw new Error("invalid wNAF"); +} +var wNAF = class { + // Parametrized with a given Point class (not individual point) + constructor(Point2, bits) { + __publicField(this, "BASE"); + __publicField(this, "ZERO"); + __publicField(this, "Fn"); + __publicField(this, "bits"); + this.BASE = Point2.BASE; + this.ZERO = Point2.ZERO; + this.Fn = Point2.Fn; + this.bits = bits; + } + // non-const time multiplication ladder + _unsafeLadder(elm, n, p = this.ZERO) { + let d = elm; + while (n > _0n3) { + if (n & _1n3) + p = p.add(d); + d = d.double(); + n >>= _1n3; + } + return p; + } + /** + * Creates a wNAF precomputation window. Used for caching. + * Default window size is set by `utils.precompute()` and is equal to 8. + * Number of precomputed points depends on the curve size: + * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where: + * - 𝑊 is the window size + * - 𝑛 is the bitlength of the curve order. + * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224. + * @param point - Point instance + * @param W - window size + * @returns precomputed point tables flattened to a single array + */ + precomputeWindow(point, W) { + const { windows, windowSize } = calcWOpts(W, this.bits); + const points = []; + let p = point; + let base = p; + for (let window = 0; window < windows; window++) { + base = p; + points.push(base); + for (let i = 1; i < windowSize; i++) { + base = base.add(p); + points.push(base); + } + p = base.double(); + } + return points; + } + /** + * Implements ec multiplication using precomputed tables and w-ary non-adjacent form. + * More compact implementation: + * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541 + * @returns real and fake (for const-time) points + */ + wNAF(W, precomputes, n) { + if (!this.Fn.isValid(n)) + throw new Error("invalid scalar"); + let p = this.ZERO; + let f = this.BASE; + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + f = f.add(negateCt(isNegF, precomputes[offsetF])); + } else { + p = p.add(negateCt(isNeg, precomputes[offset])); + } + } + assert0(n); + return { p, f }; + } + /** + * Implements unsafe EC multiplication using precomputed tables + * and w-ary non-adjacent form. + * @param acc - accumulator point to add result of multiplication + * @returns point + */ + wNAFUnsafe(W, precomputes, n, acc = this.ZERO) { + const wo = calcWOpts(W, this.bits); + for (let window = 0; window < wo.windows; window++) { + if (n === _0n3) + break; + const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo); + n = nextN; + if (isZero) { + continue; + } else { + const item = precomputes[offset]; + acc = acc.add(isNeg ? item.negate() : item); + } + } + assert0(n); + return acc; + } + getPrecomputes(W, point, transform) { + let comp = pointPrecomputes.get(point); + if (!comp) { + comp = this.precomputeWindow(point, W); + if (W !== 1) { + if (typeof transform === "function") + comp = transform(comp); + pointPrecomputes.set(point, comp); + } + } + return comp; + } + cached(point, scalar, transform) { + const W = getW(point); + return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar); + } + unsafe(point, scalar, transform, prev) { + const W = getW(point); + if (W === 1) + return this._unsafeLadder(point, scalar, prev); + return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev); + } + // We calculate precomputes for elliptic curve point multiplication + // using windowed method. This specifies window size and + // stores precomputed values. Usually only base point would be precomputed. + createCache(P, W) { + validateW(W, this.bits); + pointWindowSizes.set(P, W); + pointPrecomputes.delete(P); + } + hasCache(elm) { + return getW(elm) !== 1; + } +}; +function mulEndoUnsafe(Point2, point, k1, k2) { + let acc = point; + let p1 = Point2.ZERO; + let p2 = Point2.ZERO; + while (k1 > _0n3 || k2 > _0n3) { + if (k1 & _1n3) + p1 = p1.add(acc); + if (k2 & _1n3) + p2 = p2.add(acc); + acc = acc.double(); + k1 >>= _1n3; + k2 >>= _1n3; + } + return { p1, p2 }; +} +function createField(order, field, isLE2) { + if (field) { + if (field.ORDER !== order) + throw new Error("Field.ORDER must match order: Fp == p, Fn == n"); + validateField(field); + return field; + } else { + return Field(order, { isLE: isLE2 }); + } +} +function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) { + if (FpFnLE === void 0) + FpFnLE = type === "edwards"; + if (!CURVE || typeof CURVE !== "object") + throw new Error(`expected valid ${type} CURVE object`); + for (const p of ["p", "n", "h"]) { + const val = CURVE[p]; + if (!(typeof val === "bigint" && val > _0n3)) + throw new Error(`CURVE.${p} must be positive bigint`); + } + const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE); + const Fn2 = createField(CURVE.n, curveOpts.Fn, FpFnLE); + const _b = type === "weierstrass" ? "b" : "d"; + const params = ["Gx", "Gy", "a", _b]; + for (const p of params) { + if (!Fp.isValid(CURVE[p])) + throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`); + } + CURVE = Object.freeze(Object.assign({}, CURVE)); + return { CURVE, Fp, Fn: Fn2 }; +} +function createKeygen(randomSecretKey, getPublicKey) { + return function keygen(seed) { + const secretKey = randomSecretKey(seed); + return { secretKey, publicKey: getPublicKey(secretKey) }; + }; +} + +// node_modules/@noble/curves/abstract/fft.js +function checkU32(n) { + if (!Number.isSafeInteger(n) || n < 0 || n > 4294967295) + throw new Error("wrong u32 integer:" + n); + return n; +} +function isPowerOfTwo(x) { + checkU32(x); + return (x & x - 1) === 0 && x !== 0; +} +function reverseBits(n, bits) { + checkU32(n); + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`); + let reversed = 0; + for (let i = 0; i < bits; i++, n >>>= 1) + reversed = reversed << 1 | n & 1; + return reversed >>> 0; +} +function log2(n) { + checkU32(n); + return 31 - Math.clz32(n); +} +function bitReversalInplace(values) { + const n = values.length; + if (!isPowerOfTwo(n)) + throw new Error("expected positive power-of-two length, got " + n); + const bits = log2(n); + for (let i = 0; i < n; i++) { + const j = reverseBits(i, bits); + if (i < j) { + const tmp = values[i]; + values[i] = values[j]; + values[j] = tmp; + } + } + return values; +} +var FFTCore = (F3, coreOpts) => { + const { N: N3, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts; + const bits = log2(N3); + if (!isPowerOfTwo(N3)) + throw new Error("FFT: Polynomial size should be power of two"); + if (roots.length !== N3) + throw new Error(`FFT: wrong roots length: expected ${N3}, got ${roots.length}`); + const isDit = dit !== invertButterflies; + isDit; + return (values) => { + if (values.length !== N3) + throw new Error("FFT: wrong Polynomial length"); + if (dit && brp) + bitReversalInplace(values); + for (let i = 0, g = 1; i < bits - skipStages; i++) { + const s = dit ? i + 1 + skipStages : bits - i; + const m = 1 << s; + const m2 = m >> 1; + const stride = N3 >> s; + for (let k = 0; k < N3; k += m) { + for (let j = 0, grp = g++; j < m2; j++) { + const rootPos = invertButterflies ? dit ? N3 - grp : grp : j * stride; + const i0 = k + j; + const i1 = k + j + m2; + const omega = roots[rootPos]; + const b = values[i1]; + const a = values[i0]; + if (isDit) { + const t = F3.mul(b, omega); + values[i0] = F3.add(a, t); + values[i1] = F3.sub(a, t); + } else if (invertButterflies) { + values[i0] = F3.add(b, a); + values[i1] = F3.mul(F3.sub(b, a), omega); + } else { + values[i0] = F3.add(a, b); + values[i1] = F3.mul(F3.sub(a, b), omega); + } + } + } + } + if (!dit && brp) + bitReversalInplace(values); + return values; + }; +}; + +// node_modules/@noble/curves/abstract/weierstrass.js +var divNearest = (num, den) => (num + (num >= 0 ? den : -den) / _2n2) / den; +function _splitEndoScalar(k, basis, n) { + aInRange("scalar", k, _0n4, n); + const [[a1, b1], [a2, b2]] = basis; + const c1 = divNearest(b2 * k, n); + const c2 = divNearest(-b1 * k, n); + let k1 = k - c1 * a1 - c2 * a2; + let k2 = -c1 * b1 - c2 * b2; + const k1neg = k1 < _0n4; + const k2neg = k2 < _0n4; + if (k1neg) + k1 = -k1; + if (k2neg) + k2 = -k2; + const MAX_NUM = bitMask(Math.ceil(bitLen(n) / 2)) + _1n4; + if (k1 < _0n4 || k1 >= MAX_NUM || k2 < _0n4 || k2 >= MAX_NUM) { + throw new Error("splitScalar (endomorphism): failed for k"); + } + return { k1neg, k1, k2neg, k2 }; +} +function validateSigFormat(format) { + if (!["compact", "recovered", "der"].includes(format)) + throw new Error('Signature format must be "compact", "recovered", or "der"'); + return format; +} +function validateSigOpts(opts2, def) { + validateObject(opts2); + const optsn = {}; + for (let optName of Object.keys(def)) { + optsn[optName] = opts2[optName] === void 0 ? def[optName] : opts2[optName]; + } + abool(optsn.lowS, "lowS"); + abool(optsn.prehash, "prehash"); + if (optsn.format !== void 0) + validateSigFormat(optsn.format); + return optsn; +} +var DERErr = class extends Error { + constructor(m = "") { + super(m); + } +}; +var DER = { + // asn.1 DER encoding utils + Err: DERErr, + // Basic building block is TLV (Tag-Length-Value) + _tlv: { + encode: (tag, data) => { + const { Err: E } = DER; + asafenumber(tag, "tag"); + if (tag < 0 || tag > 255) + throw new E("tlv.encode: wrong tag"); + if (typeof data !== "string") + throw new TypeError('"data" expected string, got type=' + typeof data); + if (data.length & 1) + throw new E("tlv.encode: unpadded data"); + const dataLen = data.length / 2; + const len = numberToHexUnpadded(dataLen); + if (len.length / 2 & 128) + throw new E("tlv.encode: long form length too big"); + const lenLen = dataLen > 127 ? numberToHexUnpadded(len.length / 2 | 128) : ""; + const t = numberToHexUnpadded(tag); + return t + lenLen + len + data; + }, + // v - value, l - left bytes (unparsed) + decode(tag, data) { + const { Err: E } = DER; + data = abytes2(data, void 0, "DER data"); + let pos = 0; + if (tag < 0 || tag > 255) + throw new E("tlv.encode: wrong tag"); + if (data.length < 2 || data[pos++] !== tag) + throw new E("tlv.decode: wrong tlv"); + const first = data[pos++]; + const isLong = !!(first & 128); + let length = 0; + if (!isLong) + length = first; + else { + const lenLen = first & 127; + if (!lenLen) + throw new E("tlv.decode(long): indefinite length not supported"); + if (lenLen > 4) + throw new E("tlv.decode(long): byte length is too big"); + const lengthBytes = data.subarray(pos, pos + lenLen); + if (lengthBytes.length !== lenLen) + throw new E("tlv.decode: length bytes not complete"); + if (lengthBytes[0] === 0) + throw new E("tlv.decode(long): zero leftmost byte"); + for (const b of lengthBytes) + length = length << 8 | b; + pos += lenLen; + if (length < 128) + throw new E("tlv.decode(long): not minimal encoding"); + } + const v = data.subarray(pos, pos + length); + if (v.length !== length) + throw new E("tlv.decode: wrong value length"); + return { v, l: data.subarray(pos + length) }; + } + }, + // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag, + // since we always use positive integers here. It must always be empty: + // - add zero byte if exists + // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding) + _int: { + encode(num) { + const { Err: E } = DER; + abignumber(num); + if (num < _0n4) + throw new E("integer: negative integers are not allowed"); + let hex = numberToHexUnpadded(num); + if (Number.parseInt(hex[0], 16) & 8) + hex = "00" + hex; + if (hex.length & 1) + throw new E("unexpected DER parsing assertion: unpadded hex"); + return hex; + }, + decode(data) { + const { Err: E } = DER; + if (data.length < 1) + throw new E("invalid signature integer: empty"); + if (data[0] & 128) + throw new E("invalid signature integer: negative"); + if (data.length > 1 && data[0] === 0 && !(data[1] & 128)) + throw new E("invalid signature integer: unnecessary leading zero"); + return bytesToNumberBE(data); + } + }, + toSig(bytes) { + const { Err: E, _int: int, _tlv: tlv } = DER; + const data = abytes2(bytes, void 0, "signature"); + const { v: seqBytes, l: seqLeftBytes } = tlv.decode(48, data); + if (seqLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + const { v: rBytes, l: rLeftBytes } = tlv.decode(2, seqBytes); + const { v: sBytes, l: sLeftBytes } = tlv.decode(2, rLeftBytes); + if (sLeftBytes.length) + throw new E("invalid signature: left bytes after parsing"); + return { r: int.decode(rBytes), s: int.decode(sBytes) }; + }, + hexFromSig(sig) { + const { _tlv: tlv, _int: int } = DER; + const rs = tlv.encode(2, int.encode(sig.r)); + const ss = tlv.encode(2, int.encode(sig.s)); + const seq = rs + ss; + return tlv.encode(48, seq); + } +}; +Object.freeze(DER._tlv); +Object.freeze(DER._int); +Object.freeze(DER); +var _0n4 = /* @__PURE__ */ BigInt(0); +var _1n4 = /* @__PURE__ */ BigInt(1); +var _2n2 = /* @__PURE__ */ BigInt(2); +var _3n2 = /* @__PURE__ */ BigInt(3); +var _4n2 = /* @__PURE__ */ BigInt(4); +function weierstrass(params, extraOpts = {}) { + const validated = createCurveFields("weierstrass", params, extraOpts); + const Fp = validated.Fp; + const Fn2 = validated.Fn; + let CURVE = validated.CURVE; + const { h: cofactor, n: CURVE_ORDER } = CURVE; + validateObject(extraOpts, {}, { + allowInfinityPoint: "boolean", + clearCofactor: "function", + isTorsionFree: "function", + fromBytes: "function", + toBytes: "function", + endo: "object" + }); + const { endo, allowInfinityPoint } = extraOpts; + if (endo) { + if (!Fp.is0(CURVE.a) || typeof endo.beta !== "bigint" || !Array.isArray(endo.basises)) { + throw new Error('invalid endo: expected "beta": bigint and "basises": array'); + } + } + const lengths = getWLengths(Fp, Fn2); + function assertCompressionIsSupported() { + if (!Fp.isOdd) + throw new Error("compression is not supported: Field does not have .isOdd()"); + } + function pointToBytes(_c, point, isCompressed) { + if (allowInfinityPoint && point.is0()) + return Uint8Array.of(0); + const { x, y } = point.toAffine(); + const bx = Fp.toBytes(x); + abool(isCompressed, "isCompressed"); + if (isCompressed) { + assertCompressionIsSupported(); + const hasEvenY = !Fp.isOdd(y); + return concatBytes2(pprefix(hasEvenY), bx); + } else { + return concatBytes2(Uint8Array.of(4), bx, Fp.toBytes(y)); + } + } + function pointFromBytes(bytes) { + abytes2(bytes, void 0, "Point"); + const { publicKey: comp, publicKeyUncompressed: uncomp } = lengths; + const length = bytes.length; + const head = bytes[0]; + const tail = bytes.subarray(1); + if (allowInfinityPoint && length === 1 && head === 0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (length === comp && (head === 2 || head === 3)) { + const x = Fp.fromBytes(tail); + if (!Fp.isValid(x)) + throw new Error("bad point: is not on curve, wrong x"); + const y2 = weierstrassEquation(x); + let y; + try { + y = Fp.sqrt(y2); + } catch (sqrtError) { + const err = sqrtError instanceof Error ? ": " + sqrtError.message : ""; + throw new Error("bad point: is not on curve, sqrt error" + err); + } + assertCompressionIsSupported(); + const evenY = Fp.isOdd(y); + const evenH = (head & 1) === 1; + if (evenH !== evenY) + y = Fp.neg(y); + return { x, y }; + } else if (length === uncomp && head === 4) { + const L = Fp.BYTES; + const x = Fp.fromBytes(tail.subarray(0, L)); + const y = Fp.fromBytes(tail.subarray(L, L * 2)); + if (!isValidXY(x, y)) + throw new Error("bad point: is not on curve"); + return { x, y }; + } else { + throw new Error(`bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`); + } + } + const encodePoint = extraOpts.toBytes === void 0 ? pointToBytes : extraOpts.toBytes; + const decodePoint = extraOpts.fromBytes === void 0 ? pointFromBytes : extraOpts.fromBytes; + function weierstrassEquation(x) { + const x2 = Fp.sqr(x); + const x3 = Fp.mul(x2, x); + return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); + } + function isValidXY(x, y) { + const left = Fp.sqr(y); + const right = weierstrassEquation(x); + return Fp.eql(left, right); + } + if (!isValidXY(CURVE.Gx, CURVE.Gy)) + throw new Error("bad curve params: generator point"); + const _4a3 = Fp.mul(Fp.pow(CURVE.a, _3n2), _4n2); + const _27b2 = Fp.mul(Fp.sqr(CURVE.b), BigInt(27)); + if (Fp.is0(Fp.add(_4a3, _27b2))) + throw new Error("bad curve params: a or b"); + function acoord(title, n, banZero = false) { + if (!Fp.isValid(n) || banZero && Fp.is0(n)) + throw new Error(`bad point coordinate ${title}`); + return n; + } + function aprjpoint(other) { + if (!(other instanceof Point2)) + throw new Error("Weierstrass Point expected"); + } + function splitEndoScalarN(k) { + if (!endo || !endo.basises) + throw new Error("no endo"); + return _splitEndoScalar(k, endo.basises, Fn2.ORDER); + } + function finishEndo(endoBeta, k1p, k2p, k1neg, k2neg) { + k2p = new Point2(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z); + k1p = negateCt(k1neg, k1p); + k2p = negateCt(k2neg, k2p); + return k1p.add(k2p); + } + const _Point = class _Point { + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + constructor(X, Y, Z) { + __publicField(this, "X"); + __publicField(this, "Y"); + __publicField(this, "Z"); + this.X = acoord("x", X); + this.Y = acoord("y", Y, true); + this.Z = acoord("z", Z); + Object.freeze(this); + } + static CURVE() { + return CURVE; + } + /** Does NOT validate if the point is valid. Use `.assertValidity()`. */ + static fromAffine(p) { + const { x, y } = p || {}; + if (!p || !Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("invalid affine point"); + if (p instanceof _Point) + throw new Error("projective point not allowed"); + if (Fp.is0(x) && Fp.is0(y)) + return _Point.ZERO; + return new _Point(x, y, Fp.ONE); + } + static fromBytes(bytes) { + const P = _Point.fromAffine(decodePoint(abytes2(bytes, void 0, "point"))); + P.assertValidity(); + return P; + } + static fromHex(hex) { + return _Point.fromBytes(hexToBytes2(hex)); + } + get x() { + return this.toAffine().x; + } + get y() { + return this.toAffine().y; + } + /** + * + * @param windowSize + * @param isLazy - true will defer table computation until the first multiplication + * @returns + */ + precompute(windowSize = 8, isLazy = true) { + wnaf.createCache(this, windowSize); + if (!isLazy) + this.multiply(_3n2); + return this; + } + // TODO: return `this` + /** A point on curve is valid if it conforms to equation. */ + assertValidity() { + const p = this; + if (p.is0()) { + if (extraOpts.allowInfinityPoint && Fp.is0(p.X) && Fp.eql(p.Y, Fp.ONE) && Fp.is0(p.Z)) + return; + throw new Error("bad point: ZERO"); + } + const { x, y } = p.toAffine(); + if (!Fp.isValid(x) || !Fp.isValid(y)) + throw new Error("bad point: x or y not field elements"); + if (!isValidXY(x, y)) + throw new Error("bad point: equation left != right"); + if (!p.isTorsionFree()) + throw new Error("bad point: not in prime-order subgroup"); + } + hasEvenY() { + const { y } = this.toAffine(); + if (!Fp.isOdd) + throw new Error("Field doesn't support isOdd"); + return !Fp.isOdd(y); + } + /** Compare one point to another. */ + equals(other) { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1)); + const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1)); + return U1 && U2; + } + /** Flips point to one corresponding to (x, -y) in Affine coordinates. */ + negate() { + return new _Point(this.X, Fp.neg(this.Y), this.Z); + } + // Renes-Costello-Batina exception-free doubling formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 3 + // Cost: 8M + 3S + 3*a + 2*b3 + 15add. + double() { + const { a, b } = CURVE; + const b3 = Fp.mul(b, _3n2); + const { X: X1, Y: Y1, Z: Z1 } = this; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + let t0 = Fp.mul(X1, X1); + let t1 = Fp.mul(Y1, Y1); + let t2 = Fp.mul(Z1, Z1); + let t3 = Fp.mul(X1, Y1); + t3 = Fp.add(t3, t3); + Z3 = Fp.mul(X1, Z1); + Z3 = Fp.add(Z3, Z3); + X3 = Fp.mul(a, Z3); + Y3 = Fp.mul(b3, t2); + Y3 = Fp.add(X3, Y3); + X3 = Fp.sub(t1, Y3); + Y3 = Fp.add(t1, Y3); + Y3 = Fp.mul(X3, Y3); + X3 = Fp.mul(t3, X3); + Z3 = Fp.mul(b3, Z3); + t2 = Fp.mul(a, t2); + t3 = Fp.sub(t0, t2); + t3 = Fp.mul(a, t3); + t3 = Fp.add(t3, Z3); + Z3 = Fp.add(t0, t0); + t0 = Fp.add(Z3, t0); + t0 = Fp.add(t0, t2); + t0 = Fp.mul(t0, t3); + Y3 = Fp.add(Y3, t0); + t2 = Fp.mul(Y1, Z1); + t2 = Fp.add(t2, t2); + t0 = Fp.mul(t2, t3); + X3 = Fp.sub(X3, t0); + Z3 = Fp.mul(t2, t1); + Z3 = Fp.add(Z3, Z3); + Z3 = Fp.add(Z3, Z3); + return new _Point(X3, Y3, Z3); + } + // Renes-Costello-Batina exception-free addition formula. + // There is 30% faster Jacobian formula, but it is not complete. + // https://eprint.iacr.org/2015/1060, algorithm 1 + // Cost: 12M + 0S + 3*a + 3*b3 + 23add. + add(other) { + aprjpoint(other); + const { X: X1, Y: Y1, Z: Z1 } = this; + const { X: X2, Y: Y2, Z: Z2 } = other; + let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; + const a = CURVE.a; + const b3 = Fp.mul(CURVE.b, _3n2); + let t0 = Fp.mul(X1, X2); + let t1 = Fp.mul(Y1, Y2); + let t2 = Fp.mul(Z1, Z2); + let t3 = Fp.add(X1, Y1); + let t4 = Fp.add(X2, Y2); + t3 = Fp.mul(t3, t4); + t4 = Fp.add(t0, t1); + t3 = Fp.sub(t3, t4); + t4 = Fp.add(X1, Z1); + let t5 = Fp.add(X2, Z2); + t4 = Fp.mul(t4, t5); + t5 = Fp.add(t0, t2); + t4 = Fp.sub(t4, t5); + t5 = Fp.add(Y1, Z1); + X3 = Fp.add(Y2, Z2); + t5 = Fp.mul(t5, X3); + X3 = Fp.add(t1, t2); + t5 = Fp.sub(t5, X3); + Z3 = Fp.mul(a, t4); + X3 = Fp.mul(b3, t2); + Z3 = Fp.add(X3, Z3); + X3 = Fp.sub(t1, Z3); + Z3 = Fp.add(t1, Z3); + Y3 = Fp.mul(X3, Z3); + t1 = Fp.add(t0, t0); + t1 = Fp.add(t1, t0); + t2 = Fp.mul(a, t2); + t4 = Fp.mul(b3, t4); + t1 = Fp.add(t1, t2); + t2 = Fp.sub(t0, t2); + t2 = Fp.mul(a, t2); + t4 = Fp.add(t4, t2); + t0 = Fp.mul(t1, t4); + Y3 = Fp.add(Y3, t0); + t0 = Fp.mul(t5, t4); + X3 = Fp.mul(t3, X3); + X3 = Fp.sub(X3, t0); + t0 = Fp.mul(t3, t1); + Z3 = Fp.mul(t5, Z3); + Z3 = Fp.add(Z3, t0); + return new _Point(X3, Y3, Z3); + } + subtract(other) { + aprjpoint(other); + return this.add(other.negate()); + } + is0() { + return this.equals(_Point.ZERO); + } + /** + * Constant time multiplication. + * Uses wNAF method. Windowed method may be 10% faster, + * but takes 2x longer to generate and consumes 2x memory. + * Uses precomputes when available. + * Uses endomorphism for Koblitz curves. + * @param scalar - by which the point would be multiplied + * @returns New point + */ + multiply(scalar) { + const { endo: endo2 } = extraOpts; + if (!Fn2.isValidNot0(scalar)) + throw new RangeError("invalid scalar: out of range"); + let point, fake; + const mul = (n) => wnaf.cached(this, n, (p) => normalizeZ(_Point, p)); + if (endo2) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar); + const { p: k1p, f: k1f } = mul(k1); + const { p: k2p, f: k2f } = mul(k2); + fake = k1f.add(k2f); + point = finishEndo(endo2.beta, k1p, k2p, k1neg, k2neg); + } else { + const { p, f } = mul(scalar); + point = p; + fake = f; + } + return normalizeZ(_Point, [point, fake])[0]; + } + /** + * Non-constant-time multiplication. Uses double-and-add algorithm. + * It's faster, but should only be used when you don't care about + * an exposed secret key e.g. sig verification, which works over *public* keys. + */ + multiplyUnsafe(scalar) { + const { endo: endo2 } = extraOpts; + const p = this; + const sc = scalar; + if (!Fn2.isValid(sc)) + throw new RangeError("invalid scalar: out of range"); + if (sc === _0n4 || p.is0()) + return _Point.ZERO; + if (sc === _1n4) + return p; + if (wnaf.hasCache(this)) + return this.multiply(sc); + if (endo2) { + const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc); + const { p1, p2 } = mulEndoUnsafe(_Point, p, k1, k2); + return finishEndo(endo2.beta, p1, p2, k1neg, k2neg); + } else { + return wnaf.unsafe(p, sc); + } + } + /** + * Converts Projective point to affine (x, y) coordinates. + * (X, Y, Z) ∋ (x=X/Z, y=Y/Z). + * @param invertedZ - Z^-1 (inverted zero) - optional, precomputation is useful for invertBatch + */ + toAffine(invertedZ) { + const p = this; + let iz = invertedZ; + const { X, Y, Z } = p; + if (Fp.eql(Z, Fp.ONE)) + return { x: X, y: Y }; + const is0 = p.is0(); + if (iz == null) + iz = is0 ? Fp.ONE : Fp.inv(Z); + const x = Fp.mul(X, iz); + const y = Fp.mul(Y, iz); + const zz = Fp.mul(Z, iz); + if (is0) + return { x: Fp.ZERO, y: Fp.ZERO }; + if (!Fp.eql(zz, Fp.ONE)) + throw new Error("invZ was invalid"); + return { x, y }; + } + /** + * Checks whether Point is free of torsion elements (is in prime subgroup). + * Always torsion-free for cofactor=1 curves. + */ + isTorsionFree() { + const { isTorsionFree } = extraOpts; + if (cofactor === _1n4) + return true; + if (isTorsionFree) + return isTorsionFree(_Point, this); + return wnaf.unsafe(this, CURVE_ORDER).is0(); + } + clearCofactor() { + const { clearCofactor } = extraOpts; + if (cofactor === _1n4) + return this; + if (clearCofactor) + return clearCofactor(_Point, this); + return this.multiplyUnsafe(cofactor); + } + isSmallOrder() { + if (cofactor === _1n4) + return this.is0(); + return this.clearCofactor().is0(); + } + toBytes(isCompressed = true) { + abool(isCompressed, "isCompressed"); + this.assertValidity(); + return encodePoint(_Point, this, isCompressed); + } + toHex(isCompressed = true) { + return bytesToHex2(this.toBytes(isCompressed)); + } + toString() { + return ``; + } + }; + // base / generator point + __publicField(_Point, "BASE", new _Point(CURVE.Gx, CURVE.Gy, Fp.ONE)); + // zero / infinity / identity point + __publicField(_Point, "ZERO", new _Point(Fp.ZERO, Fp.ONE, Fp.ZERO)); + // 0, 1, 0 + // math field + __publicField(_Point, "Fp", Fp); + // scalar field + __publicField(_Point, "Fn", Fn2); + let Point2 = _Point; + const bits = Fn2.BITS; + const wnaf = new wNAF(Point2, extraOpts.endo ? Math.ceil(bits / 2) : bits); + if (bits >= 8) + Point2.BASE.precompute(8); + Object.freeze(Point2.prototype); + Object.freeze(Point2); + return Point2; +} +function pprefix(hasEvenY) { + return Uint8Array.of(hasEvenY ? 2 : 3); +} +function getWLengths(Fp, Fn2) { + return { + secretKey: Fn2.BYTES, + publicKey: 1 + Fp.BYTES, + publicKeyUncompressed: 1 + 2 * Fp.BYTES, + publicKeyHasPrefix: true, + // Raw compact `(r || s)` signature width; DER and recovered signatures use + // different lengths outside this helper. + signature: 2 * Fn2.BYTES + }; +} +function ecdh(Point2, ecdhOpts = {}) { + const { Fn: Fn2 } = Point2; + const randomBytes_ = ecdhOpts.randomBytes === void 0 ? randomBytes2 : ecdhOpts.randomBytes; + const lengths = Object.assign(getWLengths(Point2.Fp, Fn2), { + seed: Math.max(getMinHashLength(Fn2.ORDER), 16) + }); + function isValidSecretKey(secretKey) { + try { + const num = Fn2.fromBytes(secretKey); + return Fn2.isValidNot0(num); + } catch (error) { + return false; + } + } + function isValidPublicKey(publicKey, isCompressed) { + const { publicKey: comp, publicKeyUncompressed } = lengths; + try { + const l = publicKey.length; + if (isCompressed === true && l !== comp) + return false; + if (isCompressed === false && l !== publicKeyUncompressed) + return false; + return !!Point2.fromBytes(publicKey); + } catch (error) { + return false; + } + } + function randomSecretKey(seed) { + seed = seed === void 0 ? randomBytes_(lengths.seed) : seed; + return mapHashToField(abytes2(seed, lengths.seed, "seed"), Fn2.ORDER); + } + function getPublicKey(secretKey, isCompressed = true) { + return Point2.BASE.multiply(Fn2.fromBytes(secretKey)).toBytes(isCompressed); + } + function isProbPub(item) { + const { secretKey, publicKey, publicKeyUncompressed } = lengths; + const allowedLengths = Fn2._lengths; + if (!isBytes3(item)) + return void 0; + const l = abytes2(item, void 0, "key").length; + const isPub = l === publicKey || l === publicKeyUncompressed; + const isSec = l === secretKey || !!allowedLengths?.includes(l); + if (isPub && isSec) + return void 0; + return isPub; + } + function getSharedSecret(secretKeyA, publicKeyB, isCompressed = true) { + if (isProbPub(secretKeyA) === true) + throw new Error("first arg must be private key"); + if (isProbPub(publicKeyB) === false) + throw new Error("second arg must be public key"); + const s = Fn2.fromBytes(secretKeyA); + const b = Point2.fromBytes(publicKeyB); + return b.multiply(s).toBytes(isCompressed); + } + const utils2 = { + isValidSecretKey, + isValidPublicKey, + randomSecretKey + }; + const keygen = createKeygen(randomSecretKey, getPublicKey); + Object.freeze(utils2); + Object.freeze(lengths); + return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point: Point2, utils: utils2, lengths }); +} +function ecdsa(Point2, hash, ecdsaOpts = {}) { + const hash_ = hash; + ahash(hash_); + validateObject(ecdsaOpts, {}, { + hmac: "function", + lowS: "boolean", + randomBytes: "function", + bits2int: "function", + bits2int_modN: "function" + }); + ecdsaOpts = Object.assign({}, ecdsaOpts); + const randomBytes4 = ecdsaOpts.randomBytes === void 0 ? randomBytes2 : ecdsaOpts.randomBytes; + const hmac2 = ecdsaOpts.hmac === void 0 ? (key, msg) => hmac(hash_, key, msg) : ecdsaOpts.hmac; + const { Fp, Fn: Fn2 } = Point2; + const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn2; + const { keygen, getPublicKey, getSharedSecret, utils: utils2, lengths } = ecdh(Point2, ecdsaOpts); + const defaultSigOpts = { + prehash: true, + lowS: typeof ecdsaOpts.lowS === "boolean" ? ecdsaOpts.lowS : true, + format: "compact", + extraEntropy: false + }; + const hasLargeRecoveryLifts = CURVE_ORDER * _2n2 + _1n4 < Fp.ORDER; + function isBiggerThanHalfOrder(number) { + const HALF = CURVE_ORDER >> _1n4; + return number > HALF; + } + function validateRS(title, num) { + if (!Fn2.isValidNot0(num)) + throw new Error(`invalid signature ${title}: out of range 1..Point.Fn.ORDER`); + return num; + } + function assertRecoverableCurve() { + if (hasLargeRecoveryLifts) + throw new Error('"recovered" sig type is not supported for cofactor >2 curves'); + } + function validateSigLength(bytes, format) { + validateSigFormat(format); + const size = lengths.signature; + const sizer = format === "compact" ? size : format === "recovered" ? size + 1 : void 0; + return abytes2(bytes, sizer); + } + class Signature { + constructor(r, s, recovery) { + __publicField(this, "r"); + __publicField(this, "s"); + __publicField(this, "recovery"); + this.r = validateRS("r", r); + this.s = validateRS("s", s); + if (recovery != null) { + assertRecoverableCurve(); + if (![0, 1, 2, 3].includes(recovery)) + throw new Error("invalid recovery id"); + this.recovery = recovery; + } + Object.freeze(this); + } + static fromBytes(bytes, format = defaultSigOpts.format) { + validateSigLength(bytes, format); + let recid; + if (format === "der") { + const { r: r2, s: s2 } = DER.toSig(abytes2(bytes)); + return new Signature(r2, s2); + } + if (format === "recovered") { + recid = bytes[0]; + format = "compact"; + bytes = bytes.subarray(1); + } + const L = lengths.signature / 2; + const r = bytes.subarray(0, L); + const s = bytes.subarray(L, L * 2); + return new Signature(Fn2.fromBytes(r), Fn2.fromBytes(s), recid); + } + static fromHex(hex, format) { + return this.fromBytes(hexToBytes2(hex), format); + } + assertRecovery() { + const { recovery } = this; + if (recovery == null) + throw new Error("invalid recovery id: must be present"); + return recovery; + } + addRecoveryBit(recovery) { + return new Signature(this.r, this.s, recovery); + } + // Unlike the top-level helper below, this method expects a digest that has + // already been hashed to the curve's message representative. + recoverPublicKey(messageHash) { + const { r, s } = this; + const recovery = this.assertRecovery(); + const radj = recovery === 2 || recovery === 3 ? r + CURVE_ORDER : r; + if (!Fp.isValid(radj)) + throw new Error("invalid recovery id: sig.r+curve.n != R.x"); + const x = Fp.toBytes(radj); + const R = Point2.fromBytes(concatBytes2(pprefix((recovery & 1) === 0), x)); + const ir = Fn2.inv(radj); + const h = bits2int_modN(abytes2(messageHash, void 0, "msgHash")); + const u1 = Fn2.create(-h * ir); + const u2 = Fn2.create(s * ir); + const Q3 = Point2.BASE.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2)); + if (Q3.is0()) + throw new Error("invalid recovery: point at infinify"); + Q3.assertValidity(); + return Q3; + } + // Signatures should be low-s, to prevent malleability. + hasHighS() { + return isBiggerThanHalfOrder(this.s); + } + toBytes(format = defaultSigOpts.format) { + validateSigFormat(format); + if (format === "der") + return hexToBytes2(DER.hexFromSig(this)); + const { r, s } = this; + const rb = Fn2.toBytes(r); + const sb = Fn2.toBytes(s); + if (format === "recovered") { + assertRecoverableCurve(); + return concatBytes2(Uint8Array.of(this.assertRecovery()), rb, sb); + } + return concatBytes2(rb, sb); + } + toHex(format) { + return bytesToHex2(this.toBytes(format)); + } + } + Object.freeze(Signature.prototype); + Object.freeze(Signature); + const bits2int = ecdsaOpts.bits2int === void 0 ? function bits2int_def(bytes) { + if (bytes.length > 8192) + throw new Error("input is too large"); + const num = bytesToNumberBE(bytes); + const delta = bytes.length * 8 - fnBits; + return delta > 0 ? num >> BigInt(delta) : num; + } : ecdsaOpts.bits2int; + const bits2int_modN = ecdsaOpts.bits2int_modN === void 0 ? function bits2int_modN_def(bytes) { + return Fn2.create(bits2int(bytes)); + } : ecdsaOpts.bits2int_modN; + const ORDER_MASK = bitMask(fnBits); + function int2octets(num) { + aInRange("num < 2^" + fnBits, num, _0n4, ORDER_MASK); + return Fn2.toBytes(num); + } + function validateMsgAndHash(message, prehash) { + abytes2(message, void 0, "message"); + return prehash ? abytes2(hash_(message), void 0, "prehashed message") : message; + } + function prepSig(message, secretKey, opts2) { + const { lowS, prehash, extraEntropy } = validateSigOpts(opts2, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + const h1int = bits2int_modN(message); + const d = Fn2.fromBytes(secretKey); + if (!Fn2.isValidNot0(d)) + throw new Error("invalid private key"); + const seedArgs = [int2octets(d), int2octets(h1int)]; + if (extraEntropy != null && extraEntropy !== false) { + const e = extraEntropy === true ? randomBytes4(lengths.secretKey) : extraEntropy; + seedArgs.push(abytes2(e, void 0, "extraEntropy")); + } + const seed = concatBytes2(...seedArgs); + const m = h1int; + function k2sig(kBytes) { + const k = bits2int(kBytes); + if (!Fn2.isValidNot0(k)) + return; + const ik = Fn2.inv(k); + const q = Point2.BASE.multiply(k).toAffine(); + const r = Fn2.create(q.x); + if (r === _0n4) + return; + const s = Fn2.create(ik * Fn2.create(m + r * d)); + if (s === _0n4) + return; + let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n4); + let normS = s; + if (lowS && isBiggerThanHalfOrder(s)) { + normS = Fn2.neg(s); + recovery ^= 1; + } + return new Signature(r, normS, hasLargeRecoveryLifts ? void 0 : recovery); + } + return { seed, k2sig }; + } + function sign(message, secretKey, opts2 = {}) { + const { seed, k2sig } = prepSig(message, secretKey, opts2); + const drbg = createHmacDrbg(hash_.outputLen, Fn2.BYTES, hmac2); + const sig = drbg(seed, k2sig); + return sig.toBytes(opts2.format); + } + function verify(signature, message, publicKey, opts2 = {}) { + const { lowS, prehash, format } = validateSigOpts(opts2, defaultSigOpts); + publicKey = abytes2(publicKey, void 0, "publicKey"); + message = validateMsgAndHash(message, prehash); + if (!isBytes3(signature)) { + const end = signature instanceof Signature ? ", use sig.toBytes()" : ""; + throw new Error("verify expects Uint8Array signature" + end); + } + validateSigLength(signature, format); + try { + const sig = Signature.fromBytes(signature, format); + const P = Point2.fromBytes(publicKey); + if (lowS && sig.hasHighS()) + return false; + const { r, s } = sig; + const h = bits2int_modN(message); + const is = Fn2.inv(s); + const u1 = Fn2.create(h * is); + const u2 = Fn2.create(r * is); + const R = Point2.BASE.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); + if (R.is0()) + return false; + const v = Fn2.create(R.x); + return v === r; + } catch (e) { + return false; + } + } + function recoverPublicKey(signature, message, opts2 = {}) { + const { prehash } = validateSigOpts(opts2, defaultSigOpts); + message = validateMsgAndHash(message, prehash); + return Signature.fromBytes(signature, "recovered").recoverPublicKey(message).toBytes(); + } + return Object.freeze({ + keygen, + getPublicKey, + getSharedSecret, + utils: utils2, + lengths, + Point: Point2, + sign, + verify, + recoverPublicKey, + Signature, + hash: hash_ + }); +} + +// node_modules/@noble/curves/secp256k1.js +var secp256k1_CURVE = { + p: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"), + n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"), + h: BigInt(1), + a: BigInt(0), + b: BigInt(7), + Gx: BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"), + Gy: BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8") +}; +var secp256k1_ENDO = { + beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"), + basises: [ + [BigInt("0x3086d221a7d46bcde86c90e49284eb15"), -BigInt("0xe4437ed6010e88286f547fa90abfe4c3")], + [BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"), BigInt("0x3086d221a7d46bcde86c90e49284eb15")] + ] +}; +var _2n3 = /* @__PURE__ */ BigInt(2); +function sqrtMod(y) { + const P = secp256k1_CURVE.p; + const _3n3 = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22); + const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88); + const b2 = y * y * y % P; + const b3 = b2 * b2 * y % P; + const b6 = pow2(b3, _3n3, P) * b3 % P; + const b9 = pow2(b6, _3n3, P) * b3 % P; + const b11 = pow2(b9, _2n3, P) * b2 % P; + const b22 = pow2(b11, _11n, P) * b11 % P; + const b44 = pow2(b22, _22n, P) * b22 % P; + const b88 = pow2(b44, _44n, P) * b44 % P; + const b176 = pow2(b88, _88n, P) * b88 % P; + const b220 = pow2(b176, _44n, P) * b44 % P; + const b223 = pow2(b220, _3n3, P) * b3 % P; + const t1 = pow2(b223, _23n, P) * b22 % P; + const t2 = pow2(t1, _6n, P) * b2 % P; + const root = pow2(t2, _2n3, P); + if (!Fpk1.eql(Fpk1.sqr(root), y)) + throw new Error("Cannot find square root"); + return root; +} +var Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod }); +var Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, { + Fp: Fpk1, + endo: secp256k1_ENDO +}); +var secp256k1 = /* @__PURE__ */ ecdsa(Pointk1, sha256); + +// node_modules/@noble/hashes/legacy.js +var Rho160 = /* @__PURE__ */ Uint8Array.from([ + 7, + 4, + 13, + 1, + 10, + 6, + 15, + 3, + 12, + 0, + 9, + 5, + 2, + 14, + 11, + 8 +]); +var Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))(); +var Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))(); +var idxLR = /* @__PURE__ */ (() => { + const L = [Id160]; + const R = [Pi160]; + const res = [L, R]; + for (let i = 0; i < 4; i++) + for (let j of res) + j.push(j[i].map((k) => Rho160[k])); + return res; +})(); +var idxL = /* @__PURE__ */ (() => idxLR[0])(); +var idxR = /* @__PURE__ */ (() => idxLR[1])(); +var shifts160 = /* @__PURE__ */ [ + [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8], + [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7], + [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9], + [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6], + [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5] +].map((i) => Uint8Array.from(i)); +var shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j])); +var shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j])); +var Kl160 = /* @__PURE__ */ Uint32Array.from([ + 0, + 1518500249, + 1859775393, + 2400959708, + 2840853838 +]); +var Kr160 = /* @__PURE__ */ Uint32Array.from([ + 1352829926, + 1548603684, + 1836072691, + 2053994217, + 0 +]); +function ripemd_f(group, x, y, z) { + if (group === 0) + return x ^ y ^ z; + if (group === 1) + return x & y | ~x & z; + if (group === 2) + return (x | ~y) ^ z; + if (group === 3) + return x & z | y & ~z; + return x ^ (y | ~z); +} +var BUF_160 = /* @__PURE__ */ new Uint32Array(16); +var _RIPEMD160 = class extends HashMD { + constructor() { + super(64, 20, 8, true); + __publicField(this, "h0", 1732584193 | 0); + __publicField(this, "h1", 4023233417 | 0); + __publicField(this, "h2", 2562383102 | 0); + __publicField(this, "h3", 271733878 | 0); + __publicField(this, "h4", 3285377520 | 0); + } + get() { + const { h0, h1, h2, h3, h4 } = this; + return [h0, h1, h2, h3, h4]; + } + set(h0, h1, h2, h3, h4) { + this.h0 = h0 | 0; + this.h1 = h1 | 0; + this.h2 = h2 | 0; + this.h3 = h3 | 0; + this.h4 = h4 | 0; + } + process(view, offset) { + for (let i = 0; i < 16; i++, offset += 4) + BUF_160[i] = view.getUint32(offset, true); + let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el; + for (let group = 0; group < 5; group++) { + const rGroup = 4 - group; + const hbl = Kl160[group], hbr = Kr160[group]; + const rl = idxL[group], rr = idxR[group]; + const sl = shiftsL160[group], sr = shiftsR160[group]; + for (let i = 0; i < 16; i++) { + const tl = rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el | 0; + al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; + } + for (let i = 0; i < 16; i++) { + const tr = rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er | 0; + ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; + } + } + this.set(this.h1 + cl + dr | 0, this.h2 + dl + er | 0, this.h3 + el + ar | 0, this.h4 + al + br | 0, this.h0 + bl + cr | 0); + } + roundClean() { + clean(BUF_160); + } + destroy() { + this.destroyed = true; + clean(this.buffer); + this.set(0, 0, 0, 0, 0); + } +}; +var ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160()); + +// node_modules/@scure/bip32/index.js +var Point = /* @__PURE__ */ (() => secp256k1.Point)(); +var Fn = /* @__PURE__ */ (() => Point.Fn)(); +var base58check = /* @__PURE__ */ createBase58check(sha256); +var MASTER_SECRET = /* @__PURE__ */ (() => { + return Uint8Array.from("Bitcoin seed".split(""), (char) => char.charCodeAt(0)); +})(); +var BITCOIN_VERSIONS = { private: 76066276, public: 76067358 }; +var HARDENED_OFFSET = 2147483648; +var hash160 = (data) => ripemd160(sha256(data)); +var fromU32 = (data) => createView(data).getUint32(0, false); +var toU32 = (n) => { + if (typeof n !== "number") + throw new TypeError("invalid number, should be from 0 to 2**32-1, got " + n); + if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1) + throw new RangeError("invalid number, should be from 0 to 2**32-1, got " + n); + const buf = new Uint8Array(4); + createView(buf).setUint32(0, n, false); + return buf; +}; +var HDKey = class _HDKey { + constructor(opt) { + __publicField(this, "versions"); + __publicField(this, "depth", 0); + __publicField(this, "index", 0); + __publicField(this, "chainCode", null); + __publicField(this, "parentFingerprint", 0); + __publicField(this, "_privateKey"); + __publicField(this, "_publicKey"); + __publicField(this, "pubHash"); + if (!opt || typeof opt !== "object") { + throw new Error("HDKey.constructor must not be called directly"); + } + this.versions = opt.versions || BITCOIN_VERSIONS; + this.depth = opt.depth || 0; + this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null; + this.index = opt.index || 0; + this.parentFingerprint = opt.parentFingerprint || 0; + if (!this.depth) { + if (this.parentFingerprint || this.index) { + throw new Error("HDKey: zero depth with non-zero index/parent fingerprint"); + } + } + if (this.depth > 255) { + throw new Error("HDKey: depth exceeds the serializable value 255"); + } + if (opt.publicKey && opt.privateKey) { + throw new Error("HDKey: publicKey and privateKey at same time."); + } + if (opt.privateKey) { + if (!secp256k1.utils.isValidSecretKey(opt.privateKey)) + throw new Error("Invalid private key"); + this._privateKey = Uint8Array.from(opt.privateKey); + this._publicKey = secp256k1.getPublicKey(this._privateKey, true); + } else if (opt.publicKey) { + this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); + } else { + throw new Error("HDKey: no public or private key provided"); + } + this.pubHash = hash160(this._publicKey); + } + get fingerprint() { + if (!this.pubHash) { + throw new Error("No publicKey set!"); + } + return fromU32(this.pubHash); + } + get identifier() { + return this.pubHash; + } + get pubKeyHash() { + return this.pubHash; + } + // Returns the live private key buffer for this instance. + // Copy it first if you need an immutable snapshot. + get privateKey() { + return this._privateKey || null; + } + get publicKey() { + return this._publicKey || null; + } + get privateExtendedKey() { + const priv = this._privateKey; + if (!priv) { + throw new Error("No private key"); + } + return base58check.encode(this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))); + } + get publicExtendedKey() { + if (!this._publicKey) { + throw new Error("No public key"); + } + return base58check.encode(this.serialize(this.versions.public, this._publicKey)); + } + static fromMasterSeed(seed, versions = BITCOIN_VERSIONS) { + abytes(seed); + if (8 * seed.length < 128 || 8 * seed.length > 512) { + throw new RangeError("HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got " + seed.length); + } + const I = hmac(sha512, MASTER_SECRET, seed); + const privateKey = I.slice(0, 32); + const chainCode = I.slice(32); + return new _HDKey({ versions, chainCode, privateKey }); + } + static fromExtendedKey(base58key, versions = BITCOIN_VERSIONS) { + const keyBuffer = base58check.decode(base58key); + const keyView = createView(keyBuffer); + const version = keyView.getUint32(0, false); + const opt = { + versions, + depth: keyBuffer[4], + parentFingerprint: keyView.getUint32(5, false), + index: keyView.getUint32(9, false), + chainCode: keyBuffer.slice(13, 45) + }; + const key = keyBuffer.slice(45); + const isPriv = key[0] === 0; + if (version !== versions[isPriv ? "private" : "public"]) { + throw new Error("Version mismatch"); + } + if (isPriv) { + return new _HDKey({ ...opt, privateKey: key.slice(1) }); + } else { + return new _HDKey({ ...opt, publicKey: key }); + } + } + static fromJSON(json) { + return _HDKey.fromExtendedKey(json.xpriv); + } + derive(path) { + if (!/^[mM]'?/.test(path)) { + throw new Error('Path must start with "m" or "M"'); + } + if (/^[mM]'?$/.test(path)) { + return this; + } + const parts = path.replace(/^[mM]'?\//, "").split("/"); + let child = this; + for (const c of parts) { + const m = /^(\d+)('?)$/.exec(c); + const m1 = m && m[1]; + if (!m || m.length !== 3 || typeof m1 !== "string") + throw new Error("invalid child index: " + c); + let idx = +m1; + if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) { + throw new Error("Invalid index"); + } + if (m[2] === "'") { + idx += HARDENED_OFFSET; + } + child = child.deriveChild(idx); + } + return child; + } + /** + * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it. + */ + deriveChild(index, _I) { + if (!this._publicKey || !this.chainCode) { + throw new Error("No publicKey or chainCode set"); + } + let data = toU32(index); + if (index >= HARDENED_OFFSET) { + const priv = this._privateKey; + if (!priv) { + throw new Error("Could not derive hardened child key"); + } + data = concatBytes(Uint8Array.of(0), priv, data); + } else { + data = concatBytes(this._publicKey, data); + } + const out = _I || hmac(sha512, this.chainCode, data); + abytes(out, 64); + const childTweak = out.slice(0, 32); + const chainCode = out.slice(32); + const opt = { + versions: this.versions, + chainCode, + depth: this.depth + 1, + parentFingerprint: this.fingerprint, + index + }; + if (opt.depth > 255) { + throw new Error("HDKey: depth exceeds the serializable value 255"); + } + try { + const ctweak = Fn.fromBytes(childTweak); + if (this._privateKey) { + const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak); + if (!Fn.isValidNot0(added)) { + throw new Error("The tweak was out of range or the resulted private key is invalid"); + } + opt.privateKey = Fn.toBytes(added); + } else { + const point = Point.fromBytes(this._publicKey); + const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak)); + if (added.equals(Point.ZERO)) { + throw new Error("The tweak was equal to negative P, which made the result key invalid"); + } + opt.publicKey = added.toBytes(true); + } + return new _HDKey(opt); + } catch (err) { + return this.deriveChild(index + 1); + } + } + sign(hash) { + if (!this._privateKey) { + throw new Error("No privateKey set!"); + } + abytes(hash, 32); + return secp256k1.sign(hash, this._privateKey, { prehash: false }); + } + verify(hash, signature) { + abytes(hash, 32); + abytes(signature, 64); + if (!this._publicKey) { + throw new Error("No publicKey set!"); + } + return secp256k1.verify(signature, hash, this._publicKey, { prehash: false }); + } + wipePrivateData() { + if (this._privateKey) { + this._privateKey.fill(0); + this._privateKey = void 0; + } + return this; + } + toJSON() { + return { + xpriv: this.privateExtendedKey, + xpub: this.publicExtendedKey + }; + } + serialize(version, key) { + if (!this.chainCode) { + throw new Error("No chainCode set"); + } + abytes(key, 33); + return concatBytes(toU32(version), new Uint8Array([this.depth]), toU32(this.parentFingerprint), toU32(this.index), this.chainCode, key); + } +}; + +// node_modules/@noble/hashes/hkdf.js +function extract(hash, ikm, salt) { + ahash(hash); + if (salt === void 0) + salt = new Uint8Array(hash.outputLen); + return hmac(hash, salt, ikm); +} +var HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0); +var EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of(); +function expand(hash, prk, info, length = 32) { + ahash(hash); + anumber(length, "length"); + abytes(prk, void 0, "prk"); + const olen = hash.outputLen; + if (prk.length < olen) + throw new Error('"prk" must be at least HashLen octets'); + if (length > 255 * olen) + throw new Error("Length must be <= 255*HashLen"); + const blocks = Math.ceil(length / olen); + if (info === void 0) + info = EMPTY_BUFFER; + else + abytes(info, void 0, "info"); + const okm = new Uint8Array(blocks * olen); + const HMAC = hmac.create(hash, prk); + const HMACTmp = HMAC._cloneInto(); + const T = new Uint8Array(HMAC.outputLen); + for (let counter = 0; counter < blocks; counter++) { + HKDF_COUNTER[0] = counter + 1; + HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info).update(HKDF_COUNTER).digestInto(T); + okm.set(T, olen * counter); + HMAC._cloneInto(HMACTmp); + } + HMAC.destroy(); + HMACTmp.destroy(); + clean(T, HKDF_COUNTER); + return okm.slice(0, length); +} +var hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length); + +// node_modules/@noble/hashes/sha3.js +var _0n5 = BigInt(0); +var _1n5 = BigInt(1); +var _2n4 = BigInt(2); +var _7n2 = BigInt(7); +var _256n = BigInt(256); +var _0x71n = BigInt(113); +var SHA3_PI = []; +var SHA3_ROTL = []; +var _SHA3_IOTA = []; +for (let round = 0, R = _1n5, x = 1, y = 0; round < 24; round++) { + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + let t = _0n5; + for (let j = 0; j < 7; j++) { + R = (R << _1n5 ^ (R >> _7n2) * _0x71n) % _256n; + if (R & _2n4) + t ^= _1n5 << (_1n5 << BigInt(j)) - _1n5; + } + _SHA3_IOTA.push(t); +} +var IOTAS = split(_SHA3_IOTA, true); +var SHA3_IOTA_H = IOTAS[0]; +var SHA3_IOTA_L = IOTAS[1]; +var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); +var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); +function keccakP(s, rounds = 24) { + anumber(rounds, "rounds"); + if (rounds < 1 || rounds > 24) + throw new Error('"rounds" expected integer 1..24'); + const B = new Uint32Array(5 * 2); + for (let round = 24 - rounds; round < 24; round++) { + for (let x = 0; x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0; x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0; y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; + } + } + let curH = s[2]; + let curL = s[3]; + for (let t = 0; t < 24; t++) { + const shift = SHA3_ROTL[t]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + for (let y = 0; y < 50; y += 10) { + const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3]; + s[y] ^= ~s[y + 2] & s[y + 4]; + s[y + 1] ^= ~s[y + 3] & s[y + 5]; + s[y + 2] ^= ~s[y + 4] & s[y + 6]; + s[y + 3] ^= ~s[y + 5] & s[y + 7]; + s[y + 4] ^= ~s[y + 6] & s[y + 8]; + s[y + 5] ^= ~s[y + 7] & s[y + 9]; + s[y + 6] ^= ~s[y + 8] & b0; + s[y + 7] ^= ~s[y + 9] & b1; + s[y + 8] ^= ~b0 & b2; + s[y + 9] ^= ~b1 & b3; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; + } + clean(B); +} +var Keccak = class _Keccak { + // NOTE: we accept arguments in bytes instead of bits here. + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + __publicField(this, "state"); + __publicField(this, "pos", 0); + __publicField(this, "posOut", 0); + __publicField(this, "finished", false); + __publicField(this, "state32"); + __publicField(this, "destroyed", false); + __publicField(this, "blockLen"); + __publicField(this, "suffix"); + __publicField(this, "outputLen"); + __publicField(this, "canXOF"); + __publicField(this, "enableXOF", false); + __publicField(this, "rounds"); + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.canXOF = enableXOF; + this.rounds = rounds; + anumber(outputLen, "outputLen"); + if (!(0 < blockLen && blockLen < 200)) + throw new Error("only keccak-f1600 function is supported"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); + } + clone() { + return this._cloneInto(); + } + keccak() { + swap32IfBE(this.state32); + keccakP(this.state32, this.rounds); + swap32IfBE(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + abytes(data); + const { blockLen, state } = this; + const len = data.length; + for (let pos = 0; pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0; i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length; pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out; + } + destroy() { + this.destroyed = true; + clean(this.state); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to || (to = new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds)); + to.blockLen = blockLen; + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.canXOF = this.canXOF; + to.destroyed = this.destroyed; + return to; + } +}; +var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); +var sha3_256 = /* @__PURE__ */ genKeccak( + 6, + 136, + 32, + /* @__PURE__ */ oidNist(8) +); +var sha3_512 = /* @__PURE__ */ genKeccak( + 6, + 72, + 64, + /* @__PURE__ */ oidNist(10) +); +var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info); +var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11)); +var shake256 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12)); + +// node_modules/@noble/post-quantum/utils.js +var abytesDoc = abytes; +var randomBytes3 = randomBytes; +function equalBytes(a, b) { + if (a.length !== b.length) + return false; + let diff = 0; + for (let i = 0; i < a.length; i++) + diff |= a[i] ^ b[i]; + return diff === 0; +} +function copyBytes2(bytes) { + return Uint8Array.from(abytes(bytes)); +} +function validateOpts(opts2) { + if (Object.prototype.toString.call(opts2) !== "[object Object]") + throw new TypeError("expected valid options object"); +} +function validateVerOpts(opts2) { + validateOpts(opts2); + if (opts2.context !== void 0) + abytes(opts2.context, void 0, "opts.context"); +} +function validateSigOpts2(opts2) { + validateVerOpts(opts2); + if (opts2.extraEntropy !== false && opts2.extraEntropy !== void 0) + abytes(opts2.extraEntropy, void 0, "opts.extraEntropy"); +} +function splitCoder(label, ...lengths) { + const getLength = (c) => typeof c === "number" ? c : c.bytesLen; + const bytesLen = lengths.reduce((sum, a) => sum + getLength(a), 0); + return { + bytesLen, + encode: (bufs) => { + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < lengths.length; i++) { + const c = lengths[i]; + const l = getLength(c); + const b = typeof c === "number" ? bufs[i] : c.encode(bufs[i]); + abytes(b, l, label); + res.set(b, pos); + if (typeof c !== "number") + b.fill(0); + pos += l; + } + return res; + }, + decode: (buf) => { + abytes(buf, bytesLen, label); + const res = []; + for (const c of lengths) { + const l = getLength(c); + const b = buf.subarray(0, l); + res.push(typeof c === "number" ? b : c.decode(b)); + buf = buf.subarray(l); + } + return res; + } + }; +} +function vecCoder(c, vecLen) { + const coder = c; + const bytesLen = vecLen * coder.bytesLen; + return { + bytesLen, + encode: (u) => { + if (u.length !== vecLen) + throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`); + const res = new Uint8Array(bytesLen); + for (let i = 0, pos = 0; i < u.length; i++) { + const b = coder.encode(u[i]); + res.set(b, pos); + b.fill(0); + pos += b.length; + } + return res; + }, + decode: (a) => { + abytes(a, bytesLen); + const r = []; + for (let i = 0; i < a.length; i += coder.bytesLen) + r.push(coder.decode(a.subarray(i, i + coder.bytesLen))); + return r; + } + }; +} +function cleanBytes(...list) { + for (const t of list) { + if (Array.isArray(t)) + for (const b of t) + b.fill(0); + else + t.fill(0); + } +} +function getMask(bits) { + if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32) + throw new RangeError(`expected bits in [0..32], got ${bits}`); + return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0; +} +var EMPTY = /* @__PURE__ */ Uint8Array.of(); +function getMessage(msg, ctx = EMPTY) { + abytes(msg); + abytes(ctx); + if (ctx.length > 255) + throw new RangeError("context should be 255 bytes or less"); + return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg); +} +var oidNistP = /* @__PURE__ */ Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2]); +function checkHash(hash, requiredStrength = 0) { + if (!hash.oid || !equalBytes(hash.oid.subarray(0, 10), oidNistP)) + throw new Error("hash.oid is invalid: expected NIST hash"); + const collisionResistance = hash.outputLen * 8 / 2; + if (requiredStrength > collisionResistance) { + throw new Error("Pre-hash security strength too low: " + collisionResistance + ", required: " + requiredStrength); + } +} +function getMessagePrehash(hash, msg, ctx = EMPTY) { + abytes(msg); + abytes(ctx); + if (ctx.length > 255) + throw new RangeError("context should be 255 bytes or less"); + const hashed = hash(msg); + return concatBytes(new Uint8Array([1, ctx.length]), ctx, hash.oid, hashed); +} + +// node_modules/@noble/post-quantum/_crystals.js +var genCrystals = (opts2) => { + const { newPoly: newPoly2, N: N3, Q: Q3, F: F3, ROOT_OF_UNITY: ROOT_OF_UNITY3, brvBits, isKyber } = opts2; + const mod2 = (a, modulo = Q3) => { + const result = a % modulo | 0; + return (result >= 0 ? result | 0 : modulo + result | 0) | 0; + }; + const smod = (a, modulo = Q3) => { + const r = mod2(a, modulo) | 0; + return (r > modulo >> 1 ? r - modulo | 0 : r) | 0; + }; + function getZettas() { + const out = newPoly2(N3); + for (let i = 0; i < N3; i++) { + const b = reverseBits(i, brvBits); + const p = BigInt(ROOT_OF_UNITY3) ** BigInt(b) % BigInt(Q3); + out[i] = Number(p) | 0; + } + return out; + } + const nttZetas = getZettas(); + const field = { + add: (a, b) => mod2((a | 0) + (b | 0)) | 0, + sub: (a, b) => mod2((a | 0) - (b | 0)) | 0, + mul: (a, b) => mod2((a | 0) * (b | 0)) | 0, + inv: (_a) => { + throw new Error("not implemented"); + } + }; + const nttOpts = { + N: N3, + roots: nttZetas, + invertButterflies: true, + skipStages: isKyber ? 1 : 0, + brp: false + }; + const dif = FFTCore(field, { dit: false, ...nttOpts }); + const dit = FFTCore(field, { dit: true, ...nttOpts }); + const NTT = { + encode: (r) => { + return dif(r); + }, + decode: (r) => { + dit(r); + for (let i = 0; i < r.length; i++) + r[i] = mod2(F3 * r[i]); + return r; + } + }; + const bitsCoder = (d, c) => { + const mask = getMask(d); + const bytesLen = d * (N3 / 8); + return { + bytesLen, + encode: (poly_) => { + const poly = poly_; + const r = new Uint8Array(bytesLen); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < poly.length; i++) { + buf |= (c.encode(poly[i]) & mask) << bufLen; + bufLen += d; + for (; bufLen >= 8; bufLen -= 8, buf >>= 8) + r[pos++] = buf & getMask(bufLen); + } + return r; + }, + decode: (bytes) => { + const r = newPoly2(N3); + for (let i = 0, buf = 0, bufLen = 0, pos = 0; i < bytes.length; i++) { + buf |= bytes[i] << bufLen; + bufLen += 8; + for (; bufLen >= d; bufLen -= d, buf >>= d) + r[pos++] = c.decode(buf & mask); + } + return r; + } + }; + }; + return { + mod: mod2, + smod, + nttZetas, + NTT: { + encode: (r) => NTT.encode(r), + decode: (r) => NTT.decode(r) + }, + bitsCoder + }; +}; +var createXofShake = (shake) => (seed, blockLen) => { + if (!blockLen) + blockLen = shake.blockLen; + const _seed = new Uint8Array(seed.length + 2); + _seed.set(seed); + const seedLen = seed.length; + const buf = new Uint8Array(blockLen); + let h = shake.create({}); + let calls = 0; + let xofs = 0; + return { + stats: () => ({ calls, xofs }), + get: (x, y) => { + _seed[seedLen + 0] = x; + _seed[seedLen + 1] = y; + h.destroy(); + h = shake.create({}).update(_seed); + calls++; + return () => { + xofs++; + return h.xofInto(buf); + }; + }, + clean: () => { + h.destroy(); + cleanBytes(buf, _seed); + } + }; +}; +var XOF128 = /* @__PURE__ */ createXofShake(shake128); +var XOF256 = /* @__PURE__ */ createXofShake(shake256); + +// node_modules/@noble/post-quantum/ml-dsa.js +function validateInternalOpts(opts2) { + validateOpts(opts2); + if (opts2.externalMu !== void 0) + abool(opts2.externalMu, "opts.externalMu"); +} +var N = 256; +var Q = 8380417; +var ROOT_OF_UNITY = 1753; +var F = 8347681; +var D = 13; +var GAMMA2_1 = Math.floor((Q - 1) / 88) | 0; +var GAMMA2_2 = Math.floor((Q - 1) / 32) | 0; +var PARAMS = /* @__PURE__ */ (() => Object.freeze({ + 2: Object.freeze({ + K: 4, + L: 4, + D, + GAMMA1: 2 ** 17, + GAMMA2: GAMMA2_1, + TAU: 39, + ETA: 2, + OMEGA: 80 + }), + 3: Object.freeze({ + K: 6, + L: 5, + D, + GAMMA1: 2 ** 19, + GAMMA2: GAMMA2_2, + TAU: 49, + ETA: 4, + OMEGA: 55 + }), + 5: Object.freeze({ + K: 8, + L: 7, + D, + GAMMA1: 2 ** 19, + GAMMA2: GAMMA2_2, + TAU: 60, + ETA: 2, + OMEGA: 75 + }) +}))(); +var newPoly = (n) => new Int32Array(n); +var crystals = /* @__PURE__ */ genCrystals({ + N, + Q, + F, + ROOT_OF_UNITY, + newPoly, + isKyber: false, + brvBits: 8 +}); +var id = (n) => n; +var polyCoder = (d, compress2 = id, verify = id) => crystals.bitsCoder(d, { + encode: (i) => compress2(verify(i)), + decode: (i) => verify(compress2(i)) +}); +var polyAdd = (a_, b_) => { + const a = a_; + const b = b_; + for (let i = 0; i < a.length; i++) + a[i] = crystals.mod(a[i] + b[i]); + return a; +}; +var polySub = (a_, b_) => { + const a = a_; + const b = b_; + for (let i = 0; i < a.length; i++) + a[i] = crystals.mod(a[i] - b[i]); + return a; +}; +var polyShiftl = (p_) => { + const p = p_; + for (let i = 0; i < N; i++) + p[i] <<= D; + return p; +}; +var polyChknorm = (p_, B) => { + const p = p_; + for (let i = 0; i < N; i++) + if (Math.abs(crystals.smod(p[i])) >= B) + return true; + return false; +}; +var MultiplyNTTs = (a_, b_) => { + const a = a_; + const b = b_; + const c = newPoly(N); + for (let i = 0; i < a.length; i++) + c[i] = crystals.mod(a[i] * b[i]); + return c; +}; +function RejNTTPoly(xof_) { + const xof = xof_; + const r = newPoly(N); + for (let j = 0; j < N; ) { + const b = xof(); + if (b.length % 3) + throw new Error("RejNTTPoly: unaligned block"); + for (let i = 0; j < N && i <= b.length - 3; i += 3) { + const t = (b[i + 0] | b[i + 1] << 8 | b[i + 2] << 16) & 8388607; + if (t < Q) + r[j++] = t; + } + } + return r; +} +function getDilithium(opts_) { + const opts2 = opts_; + const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts2; + const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128: XOF1282, XOF256: XOF2562, securityLevel } = opts2; + if (![2, 4].includes(ETA)) + throw new Error("Wrong ETA"); + if (![1 << 17, 1 << 19].includes(GAMMA1)) + throw new Error("Wrong GAMMA1"); + if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) + throw new Error("Wrong GAMMA2"); + const BETA = TAU * ETA; + const decompose = (r) => { + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 * GAMMA2) | 0; + if (rPlus - r0 === Q - 1) + return { r1: 0 | 0, r0: r0 - 1 | 0 }; + const r1 = Math.floor((rPlus - r0) / (2 * GAMMA2)) | 0; + return { r1, r0 }; + }; + const HighBits = (r) => decompose(r).r1; + const LowBits = (r) => decompose(r).r0; + const MakeHint = (z, r) => { + const res0 = z <= GAMMA2 || z > Q - GAMMA2 || z === Q - GAMMA2 && r === 0 ? 0 : 1; + return res0; + }; + const UseHint = (h, r) => { + const m = Math.floor((Q - 1) / (2 * GAMMA2)); + const { r1, r0 } = decompose(r); + if (h === 1) + return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0; + return r1 | 0; + }; + const Power2Round = (r) => { + const rPlus = crystals.mod(r); + const r0 = crystals.smod(rPlus, 2 ** D) | 0; + return { r1: Math.floor((rPlus - r0) / 2 ** D) | 0, r0 }; + }; + const hintCoder = { + bytesLen: OMEGA + K, + encode: (h_) => { + const h = h_; + if (h === false) + throw new Error("hint.encode: hint is false"); + const res = new Uint8Array(OMEGA + K); + for (let i = 0, k = 0; i < K; i++) { + for (let j = 0; j < N; j++) + if (h[i][j] !== 0) + res[k++] = j; + res[OMEGA + i] = k; + } + return res; + }, + decode: (buf) => { + const h = []; + let k = 0; + for (let i = 0; i < K; i++) { + const hi = newPoly(N); + if (buf[OMEGA + i] < k || buf[OMEGA + i] > OMEGA) + return false; + for (let j = k; j < buf[OMEGA + i]; j++) { + if (j > k && buf[j] <= buf[j - 1]) + return false; + hi[buf[j]] = 1; + } + k = buf[OMEGA + i]; + h.push(hi); + } + for (let j = k; j < OMEGA; j++) + if (buf[j] !== 0) + return false; + return h; + } + }; + const ETACoder = polyCoder(ETA === 2 ? 3 : 4, (i) => ETA - i, (i) => { + if (!(-ETA <= i && i <= ETA)) + throw new Error(`malformed key s1/s3 ${i} outside of ETA range [${-ETA}, ${ETA}]`); + return i; + }); + const T0Coder = polyCoder(13, (i) => (1 << D - 1) - i); + const T1Coder = polyCoder(10); + const ZCoder = polyCoder(GAMMA1 === 1 << 17 ? 18 : 20, (i) => crystals.smod(GAMMA1 - i)); + const W1Coder = polyCoder(GAMMA2 === GAMMA2_1 ? 6 : 4); + const W1Vec = vecCoder(W1Coder, K); + const publicCoder = splitCoder("publicKey", 32, vecCoder(T1Coder, K)); + const secretCoder = splitCoder("secretKey", 32, 32, TR_BYTES, vecCoder(ETACoder, L), vecCoder(ETACoder, K), vecCoder(T0Coder, K)); + const sigCoder = splitCoder("signature", C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder); + const CoefFromHalfByte = ETA === 2 ? (n) => n < 15 ? 2 - n % 5 : false : (n) => n < 9 ? 4 - n : false; + function RejBoundedPoly(xof_) { + const xof = xof_; + const r = newPoly(N); + for (let j = 0; j < N; ) { + const b = xof(); + for (let i = 0; j < N && i < b.length; i += 1) { + const d1 = CoefFromHalfByte(b[i] & 15); + const d2 = CoefFromHalfByte(b[i] >> 4 & 15); + if (d1 !== false) + r[j++] = d1; + if (j < N && d2 !== false) + r[j++] = d2; + } + } + return r; + } + const SampleInBall = (seed) => { + const pre = newPoly(N); + const s = shake256.create({}).update(seed); + const buf = new Uint8Array(shake256.blockLen); + s.xofInto(buf); + const masks = buf.slice(0, 8); + for (let i = N - TAU, pos = 8, maskPos = 0, maskBit = 0; i < N; i++) { + let b = i + 1; + for (; b > i; ) { + b = buf[pos++]; + if (pos < shake256.blockLen) + continue; + s.xofInto(buf); + pos = 0; + } + pre[i] = pre[b]; + pre[b] = 1 - ((masks[maskPos] >> maskBit++ & 1) << 1); + if (maskBit >= 8) { + maskPos++; + maskBit = 0; + } + } + return pre; + }; + const polyPowerRound = (p_) => { + const p = p_; + const res0 = newPoly(N); + const res1 = newPoly(N); + for (let i = 0; i < p.length; i++) { + const { r0, r1 } = Power2Round(p[i]); + res0[i] = r0; + res1[i] = r1; + } + return { r0: res0, r1: res1 }; + }; + const polyUseHint = (u_, h_) => { + const u = u_; + const h = h_; + for (let i = 0; i < N; i++) + u[i] = UseHint(h[i], u[i]); + return u; + }; + const polyMakeHint = (a_, b_) => { + const a = a_; + const b = b_; + const v = newPoly(N); + let cnt = 0; + for (let i = 0; i < N; i++) { + const h = MakeHint(a[i], b[i]); + v[i] = h; + cnt += h; + } + return { v, cnt }; + }; + const signRandBytes = 32; + const seedCoder = splitCoder("seed", 32, 64, 32); + const internal = Object.freeze({ + info: Object.freeze({ type: "internal-ml-dsa" }), + lengths: Object.freeze({ + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + seed: 32, + signature: sigCoder.bytesLen, + signRand: signRandBytes + }), + keygen: (seed) => { + const seedDst = new Uint8Array(32 + 2); + const randSeed = seed === void 0; + if (randSeed) + seed = randomBytes3(32); + abytesDoc(seed, 32, "seed"); + seedDst.set(seed); + if (randSeed) + cleanBytes(seed); + seedDst[32] = K; + seedDst[33] = L; + const [rho, rhoPrime, K_] = seedCoder.decode(shake256(seedDst, { dkLen: seedCoder.bytesLen })); + const xofPrime = XOF2562(rhoPrime); + const s1 = []; + for (let i = 0; i < L; i++) + s1.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255))); + const s2 = []; + for (let i = L; i < L + K; i++) + s2.push(RejBoundedPoly(xofPrime.get(i & 255, i >> 8 & 255))); + const s1Hat = s1.map((i) => crystals.NTT.encode(i.slice())); + const t0 = []; + const t1 = []; + const xof = XOF1282(rho); + const t = newPoly(N); + for (let i = 0; i < K; i++) { + cleanBytes(t); + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); + polyAdd(t, MultiplyNTTs(aij, s1Hat[j])); + } + crystals.NTT.decode(t); + const { r0, r1 } = polyPowerRound(polyAdd(t, s2[i])); + t0.push(r0); + t1.push(r1); + } + const publicKey = publicCoder.encode([rho, t1]); + const tr = shake256(publicKey, { dkLen: TR_BYTES }); + const secretKey = secretCoder.encode([rho, K_, tr, s1, s2, t0]); + xof.clean(); + xofPrime.clean(); + cleanBytes(rho, rhoPrime, K_, s1, s2, s1Hat, t, t0, t1, tr, seedDst); + return { + publicKey, + secretKey + }; + }, + getPublicKey: (secretKey) => { + const [rho, _K, _tr, s1, s2, _t0] = secretCoder.decode(secretKey); + const xof = XOF1282(rho); + const s1Hat = s1.map((p) => crystals.NTT.encode(p.slice())); + const t1 = []; + const tmp = newPoly(N); + for (let i = 0; i < K; i++) { + tmp.fill(0); + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); + polyAdd(tmp, MultiplyNTTs(aij, s1Hat[j])); + } + crystals.NTT.decode(tmp); + polyAdd(tmp, s2[i]); + const { r1 } = polyPowerRound(tmp); + t1.push(r1); + } + xof.clean(); + cleanBytes(tmp, s1Hat, _t0, s1, s2); + return publicCoder.encode([rho, t1]); + }, + // NOTE: random is optional. + sign: (msg, secretKey, opts3 = {}) => { + validateSigOpts2(opts3); + validateInternalOpts(opts3); + let { extraEntropy: random, externalMu = false } = opts3; + const [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey); + const A = []; + const xof = XOF1282(rho); + for (let i = 0; i < K; i++) { + const pv = []; + for (let j = 0; j < L; j++) + pv.push(RejNTTPoly(xof.get(j, i))); + A.push(pv); + } + xof.clean(); + for (let i = 0; i < L; i++) + crystals.NTT.encode(s1[i]); + for (let i = 0; i < K; i++) { + crystals.NTT.encode(s2[i]); + crystals.NTT.encode(t0[i]); + } + const mu = externalMu ? msg : ( + // 6: µ ← H(tr||M, 512) + // ▷ Compute message representative µ + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest() + ); + const rnd = random === false ? new Uint8Array(32) : random === void 0 ? randomBytes3(signRandBytes) : random; + abytesDoc(rnd, 32, "extraEntropy"); + const rhoprime = shake256.create({ dkLen: CRH_BYTES }).update(_K).update(rnd).update(mu).digest(); + abytesDoc(rhoprime, CRH_BYTES); + const x256 = XOF2562(rhoprime, ZCoder.bytesLen); + main_loop: for (let kappa = 0; ; ) { + const y = []; + for (let i = 0; i < L; i++, kappa++) + y.push(ZCoder.decode(x256.get(kappa & 255, kappa >> 8)())); + const z = y.map((i) => crystals.NTT.encode(i.slice())); + const w = []; + for (let i = 0; i < K; i++) { + const wi = newPoly(N); + for (let j = 0; j < L; j++) + polyAdd(wi, MultiplyNTTs(A[i][j], z[j])); + crystals.NTT.decode(wi); + w.push(wi); + } + const w1 = w.map((j) => j.map(HighBits)); + const cTilde = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(w1)).digest(); + const cHat = crystals.NTT.encode(SampleInBall(cTilde)); + const cs1 = s1.map((i) => MultiplyNTTs(i, cHat)); + for (let i = 0; i < L; i++) { + polyAdd(crystals.NTT.decode(cs1[i]), y[i]); + if (polyChknorm(cs1[i], GAMMA1 - BETA)) + continue main_loop; + } + let cnt = 0; + const h = []; + for (let i = 0; i < K; i++) { + const cs2 = crystals.NTT.decode(MultiplyNTTs(s2[i], cHat)); + const r0 = polySub(w[i], cs2).map(LowBits); + if (polyChknorm(r0, GAMMA2 - BETA)) + continue main_loop; + const ct0 = crystals.NTT.decode(MultiplyNTTs(t0[i], cHat)); + if (polyChknorm(ct0, GAMMA2)) + continue main_loop; + polyAdd(r0, ct0); + const hint = polyMakeHint(r0, w1[i]); + h.push(hint.v); + cnt += hint.cnt; + } + if (cnt > OMEGA) + continue; + x256.clean(); + const res = sigCoder.encode([cTilde, cs1, h]); + cleanBytes(cTilde, cs1, h, cHat, w1, w, z, y, rhoprime, s1, s2, t0, ...A); + if (!externalMu) + cleanBytes(mu); + return res; + } + throw new Error("Unreachable code path reached, report this error"); + }, + verify: (sig, msg, publicKey, opts3 = {}) => { + validateInternalOpts(opts3); + const { externalMu = false } = opts3; + const [rho, t1] = publicCoder.decode(publicKey); + const tr = shake256(publicKey, { dkLen: TR_BYTES }); + if (sig.length !== sigCoder.bytesLen) + return false; + const [cTilde, z, h] = sigCoder.decode(sig); + if (h === false) + return false; + for (let i = 0; i < L; i++) + if (polyChknorm(z[i], GAMMA1 - BETA)) + return false; + const mu = externalMu ? msg : ( + // 7: µ ← H(tr||M, 512) + shake256.create({ dkLen: CRH_BYTES }).update(tr).update(msg).digest() + ); + const c = crystals.NTT.encode(SampleInBall(cTilde)); + const zNtt = z.map((i) => i.slice()); + for (let i = 0; i < L; i++) + crystals.NTT.encode(zNtt[i]); + const wTick1 = []; + const xof = XOF1282(rho); + for (let i = 0; i < K; i++) { + const ct12d = MultiplyNTTs(crystals.NTT.encode(polyShiftl(t1[i])), c); + const Az = newPoly(N); + for (let j = 0; j < L; j++) { + const aij = RejNTTPoly(xof.get(j, i)); + polyAdd(Az, MultiplyNTTs(aij, zNtt[j])); + } + const wApprox = crystals.NTT.decode(polySub(Az, ct12d)); + wTick1.push(polyUseHint(wApprox, h[i])); + } + xof.clean(); + const c2 = shake256.create({ dkLen: C_TILDE_BYTES }).update(mu).update(W1Vec.encode(wTick1)).digest(); + for (const t of h) { + const sum = t.reduce((acc, i) => acc + i, 0); + if (!(sum <= OMEGA)) + return false; + } + for (const t of z) + if (polyChknorm(t, GAMMA1 - BETA)) + return false; + return equalBytes(cTilde, c2); + } + }); + return Object.freeze({ + info: Object.freeze({ type: "ml-dsa" }), + internal, + securityLevel, + keygen: internal.keygen, + lengths: internal.lengths, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts3 = {}) => { + validateSigOpts2(opts3); + const M = getMessage(msg, opts3.context); + const res = internal.sign(M, secretKey, opts3); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts3 = {}) => { + validateVerOpts(opts3); + return internal.verify(sig, getMessage(msg, opts3.context), publicKey); + }, + prehash: (hash) => { + checkHash(hash, securityLevel); + return Object.freeze({ + info: Object.freeze({ type: "hashml-dsa" }), + securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts3 = {}) => { + validateSigOpts2(opts3); + const M = getMessagePrehash(hash, msg, opts3.context); + const res = internal.sign(M, secretKey, opts3); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts3 = {}) => { + validateVerOpts(opts3); + return internal.verify(sig, getMessagePrehash(hash, msg, opts3.context), publicKey); + } + }); + } + }); +} +var ml_dsa65 = /* @__PURE__ */ (() => getDilithium({ + ...PARAMS[3], + CRH_BYTES: 64, + TR_BYTES: 64, + C_TILDE_BYTES: 48, + XOF128, + XOF256, + securityLevel: 192 +}))(); + +// node_modules/@noble/post-quantum/slh-dsa.js +var PARAMS2 = /* @__PURE__ */ (() => Object.freeze({ + "128f": Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }), + "128s": Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }), + "192f": Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }), + "192s": Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }), + "256f": Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }), + "256s": Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }) +}))(); +var AddressType = { + WOTS: 0, + WOTSPK: 1, + HASHTREE: 2, + FORSTREE: 3, + FORSPK: 4, + WOTSPRF: 5, + FORSPRF: 6 +}; +function hexToNumber2(hex) { + if (typeof hex !== "string") + throw new Error("hex string expected, got " + typeof hex); + return BigInt(hex === "" ? "0" : "0x" + hex); +} +function bytesToNumberBE2(bytes) { + return hexToNumber2(bytesToHex(bytes)); +} +function numberToBytesBE2(n, len) { + return hexToBytes(n.toString(16).padStart(len * 2, "0")); +} +var base2b = (outLen, b) => { + const mask = getMask(b); + return (bytes) => { + const baseB = new Uint32Array(outLen); + for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) { + while (bits < b) { + total = total << 8 | bytes[pos++]; + bits += 8; + } + bits -= b; + baseB[out] = total >>> bits & mask; + } + return baseB; + }; +}; +function getMaskBig(bits) { + return (1n << BigInt(bits)) - 1n; +} +function gen(opts2, hashOpts_) { + const hashOpts = hashOpts_; + const { N: N3, W, H, D: D2, K, A, securityLevel } = opts2; + const getContext = hashOpts.getContext(opts2); + if (W !== 16) + throw new Error("Unsupported Winternitz parameter"); + const WOTS_LOGW = 4; + const WOTS_LEN1 = Math.floor(8 * N3 / WOTS_LOGW); + const WOTS_LEN2 = N3 <= 8 ? 2 : N3 <= 136 ? 3 : 4; + const TREE_HEIGHT = Math.floor(H / D2); + const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2; + let ADDR_BYTES = 22; + let OFFSET_LAYER = 0; + let OFFSET_TREE = 1; + let OFFSET_TYPE = 9; + let OFFSET_KP_ADDR2 = 12; + let OFFSET_KP_ADDR1 = 13; + let OFFSET_CHAIN_ADDR = 17; + let OFFSET_TREE_INDEX = 18; + let OFFSET_HASH_ADDR = 21; + if (!hashOpts.isCompressed) { + ADDR_BYTES = 32; + OFFSET_LAYER += 3; + OFFSET_TREE += 7; + OFFSET_TYPE += 10; + OFFSET_KP_ADDR2 += 10; + OFFSET_KP_ADDR1 += 10; + OFFSET_CHAIN_ADDR += 10; + OFFSET_TREE_INDEX += 10; + OFFSET_HASH_ADDR += 10; + } + const setAddr = (opts3, addr = new Uint8Array(ADDR_BYTES)) => { + const { type, height, tree, layer, index, chain: chain2, hash, keypair } = opts3; + const { subtreeAddr, keypairAddr } = opts3; + const v = createView(addr); + if (height !== void 0) + addr[OFFSET_CHAIN_ADDR] = height; + if (layer !== void 0) + addr[OFFSET_LAYER] = layer; + if (type !== void 0) + addr[OFFSET_TYPE] = type; + if (chain2 !== void 0) + addr[OFFSET_CHAIN_ADDR] = chain2; + if (hash !== void 0) + addr[OFFSET_HASH_ADDR] = hash; + if (index !== void 0) + v.setUint32(OFFSET_TREE_INDEX, index, false); + if (subtreeAddr) + addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8)); + if (tree !== void 0) + v.setBigUint64(OFFSET_TREE, tree, false); + if (keypair !== void 0) { + addr[OFFSET_KP_ADDR1] = keypair; + if (TREE_HEIGHT > 8) + addr[OFFSET_KP_ADDR2] = keypair >>> 8; + } + if (keypairAddr) { + addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8)); + addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1]; + if (TREE_HEIGHT > 8) + addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2]; + } + return addr; + }; + const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW); + const chainLengths = (msg) => { + const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg); + let csum = 0; + for (let i = 0; i < W1.length; i++) + csum += W - 1 - W1[i]; + csum <<= (8 - WOTS_LEN2 * WOTS_LOGW % 8) % 8; + const W2 = chainCoder(numberToBytesBE2(csum, Math.ceil(WOTS_LEN2 * WOTS_LOGW / 8))); + const lengths = new Uint32Array(WOTS_LEN); + lengths.set(W1); + lengths.set(W2, W1.length); + return lengths; + }; + const messageToIndices = base2b(K, A); + const TREE_BITS = TREE_HEIGHT * (D2 - 1); + const LEAF_BITS = TREE_HEIGHT; + const hashMsgCoder = splitCoder("hashedMessage", Math.ceil(A * K / 8), Math.ceil(TREE_BITS / 8), Math.ceil(TREE_HEIGHT / 8)); + const hashMessage = (R, pkSeed, msg, context) => { + const rawContext = context; + const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen); + const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest); + const tree = bytesToNumberBE2(tmpIdxTree) & getMaskBig(TREE_BITS); + const leafIdx = Number(bytesToNumberBE2(tmpIdxLeaf)) & getMask(LEAF_BITS); + return { tree, leafIdx, md }; + }; + const treehash = (height, fn) => function treehash_i(context, leafIdx, idxOffset, treeAddr, info) { + const rawContext = context; + const leafFn = fn; + const maxIdx = (1 << height) - 1; + const stack = new Uint8Array(height * N3); + const authPath = new Uint8Array(height * N3); + for (let idx = 0; ; idx++) { + const current = new Uint8Array(2 * N3); + const cur0 = current.subarray(0, N3); + const cur1 = current.subarray(N3); + const addrOffset = idx + idxOffset; + cur1.set(leafFn(leafIdx, addrOffset, rawContext, info)); + let h = 0; + for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) { + if (h === height) + return { root: cur1, authPath }; + if ((i ^ l) === 1) + authPath.subarray(h * N3).set(cur1); + if ((i & 1) === 0 && idx < maxIdx) + break; + setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr); + cur0.set(stack.subarray(h * N3).subarray(0, N3)); + cur1.set(rawContext.thashN(2, current, treeAddr)); + } + stack.subarray(h * N3).set(cur1); + } + throw new Error("Unreachable code path reached, report this error"); + }; + const wotsTreehash = treehash(TREE_HEIGHT, (leafIdx, addrOffset, context, info) => { + const rawContext = context; + const wotsPk = new Uint8Array(WOTS_LEN * N3); + const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0; + setAddr({ keypair: addrOffset }, info.leafAddr); + setAddr({ keypair: addrOffset }, info.pkAddr); + for (let i = 0; i < WOTS_LEN; i++) { + const wotsK = info.wotsSteps[i] | wotsKmask; + const pk = wotsPk.subarray(i * N3, (i + 1) * N3); + setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr); + pk.set(rawContext.PRFaddr(info.leafAddr)); + setAddr({ type: AddressType.WOTS }, info.leafAddr); + for (let k = 0; ; k++) { + if (k === wotsK) + info.wotsSig.subarray(i * N3).set(pk); + if (k === W - 1) + break; + setAddr({ hash: k }, info.leafAddr); + pk.set(rawContext.thash1(pk, info.leafAddr)); + } + } + return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr); + }); + const forsTreehash = treehash(A, (_, addrOffset, context, forsLeafAddr) => { + const rawContext = context; + setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr); + const prf = rawContext.PRFaddr(forsLeafAddr); + setAddr({ type: AddressType.FORSTREE }, forsLeafAddr); + return rawContext.thash1(prf, forsLeafAddr); + }); + const merkleSign = (context, wotsAddr, treeAddr, leafIdx, prevRoot = new Uint8Array(N3)) => { + setAddr({ type: AddressType.HASHTREE }, treeAddr); + const info = { + wotsSig: new Uint8Array(wotsCoder.bytesLen), + wotsSteps: chainLengths(prevRoot), + leafAddr: setAddr({ subtreeAddr: wotsAddr }), + pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }) + }; + const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info); + return { + root, + sigWots: info.wotsSig.subarray(0, WOTS_LEN * N3), + sigAuth: authPath + }; + }; + const computeRoot = (leaf, leafIdx, idxOffset, authPath, treeHeight, context, addr) => { + const rawContext = context; + const buffer = new Uint8Array(2 * N3); + const b0 = buffer.subarray(0, N3); + const b1 = buffer.subarray(N3, 2 * N3); + if ((leafIdx & 1) !== 0) { + b1.set(leaf.subarray(0, N3)); + b0.set(authPath.subarray(0, N3)); + } else { + b0.set(leaf.subarray(0, N3)); + b1.set(authPath.subarray(0, N3)); + } + leafIdx >>>= 1; + idxOffset >>>= 1; + for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) { + setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr); + const a = authPath.subarray((i + 1) * N3, (i + 2) * N3); + if ((leafIdx & 1) !== 0) { + b1.set(rawContext.thashN(2, buffer, addr)); + b0.set(a); + } else { + buffer.set(rawContext.thashN(2, buffer, addr)); + b1.set(a); + } + } + setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr); + return rawContext.thashN(2, buffer, addr); + }; + const seedCoder = splitCoder("seed", N3, N3, N3); + const publicCoder = splitCoder("publicKey", N3, N3); + const secretCoder = splitCoder("secretKey", N3, N3, publicCoder.bytesLen); + const forsCoder = vecCoder(splitCoder("fors", N3, N3 * A), K); + const wotsCoder = vecCoder(splitCoder("wots", WOTS_LEN * N3, TREE_HEIGHT * N3), D2); + const sigCoder = splitCoder("signature", N3, forsCoder, wotsCoder); + const internal = Object.freeze({ + info: Object.freeze({ type: "internal-slh-dsa" }), + lengths: Object.freeze({ + publicKey: publicCoder.bytesLen, + secretKey: secretCoder.bytesLen, + signature: sigCoder.bytesLen, + seed: seedCoder.bytesLen, + signRand: N3 + }), + keygen(seed) { + if (seed !== void 0) + abytesDoc(seed, seedCoder.bytesLen, "seed"); + seed = seed === void 0 ? randomBytes3(seedCoder.bytesLen) : copyBytes2(seed); + const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed); + const context = getContext(publicSeed, secretSeed); + const topTreeAddr = setAddr({ layer: D2 - 1 }); + const wotsAddr = setAddr({ layer: D2 - 1 }); + const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0); + const publicKey = publicCoder.encode([publicSeed, root]); + const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]); + context.clean(); + cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr); + return { + publicKey, + secretKey + }; + }, + getPublicKey: (secretKey) => { + const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey); + return Uint8Array.from(pk); + }, + sign: (msg, sk, opts3 = {}) => { + validateSigOpts2(opts3); + let { extraEntropy: random } = opts3; + const [skSeed, skPRF, pk] = secretCoder.decode(sk); + const [pkSeed, _] = publicCoder.decode(pk); + if (random === false) + random = copyBytes2(pkSeed); + else if (random === void 0) + random = randomBytes3(N3); + else + random = copyBytes2(random); + abytesDoc(random, N3); + const context = getContext(pkSeed, skSeed); + const R = context.PRFmsg(skPRF, random, msg); + let { tree, leafIdx, md } = hashMessage(R, pk, msg, context); + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx + }); + const roots = []; + const forsLeaf = setAddr({ keypairAddr: wotsAddr }); + const forsTreeAddr = setAddr({ keypairAddr: wotsAddr }); + const indices = messageToIndices(md); + const fors = []; + for (let i = 0; i < indices.length; i++) { + const idxOffset = i << A; + setAddr({ + type: AddressType.FORSPRF, + height: 0, + index: indices[i] + idxOffset + }, forsTreeAddr); + const prf = context.PRFaddr(forsTreeAddr); + setAddr({ type: AddressType.FORSTREE }, forsTreeAddr); + const { root: root2, authPath } = forsTreehash(context, indices[i], idxOffset, forsTreeAddr, forsLeaf); + roots.push(root2); + fors.push([prf, authPath]); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr + }); + const root = context.thashN(K, concatBytes(...roots), forsPkAddr); + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wots = []; + for (let i = 0; i < D2; i++, tree >>= BigInt(TREE_HEIGHT)) { + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + const { sigWots, sigAuth, root: r } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root); + root.set(r); + cleanBytes(r); + wots.push([sigWots, sigAuth]); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + context.clean(); + const SIG = sigCoder.encode([R, fors, wots]); + cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots); + return SIG; + }, + verify: (sig, msg, publicKey) => { + const [pkSeed, pubRoot] = publicCoder.decode(publicKey); + const [random, forsVec, wotsVec] = sigCoder.decode(sig); + const pk = publicKey; + if (sig.length !== sigCoder.bytesLen) + return false; + const context = getContext(pkSeed); + let { tree, leafIdx, md } = hashMessage(random, pk, msg, context); + const wotsAddr = setAddr({ + type: AddressType.WOTS, + tree, + keypair: leafIdx + }); + const roots = []; + const forsTreeAddr = setAddr({ + type: AddressType.FORSTREE, + keypairAddr: wotsAddr + }); + const indices = messageToIndices(md); + for (let i = 0; i < forsVec.length; i++) { + const [prf, authPath] = forsVec[i]; + const idxOffset = i << A; + setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr); + const leaf = context.thash1(prf, forsTreeAddr); + roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr)); + } + const forsPkAddr = setAddr({ + type: AddressType.FORSPK, + keypairAddr: wotsAddr + }); + let root = context.thashN(K, concatBytes(...roots), forsPkAddr); + const treeAddr = setAddr({ type: AddressType.HASHTREE }); + const wotsPkAddr = setAddr({ type: AddressType.WOTSPK }); + const wotsPk = new Uint8Array(WOTS_LEN * N3); + for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) { + const [wots, sigAuth] = wotsVec[i]; + setAddr({ tree, layer: i }, treeAddr); + setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr); + setAddr({ keypairAddr: wotsAddr }, wotsPkAddr); + const lengths = chainLengths(root); + for (let i2 = 0; i2 < WOTS_LEN; i2++) { + setAddr({ chain: i2 }, wotsAddr); + const steps = W - 1 - lengths[i2]; + const start = lengths[i2]; + const out = wotsPk.subarray(i2 * N3); + out.set(wots.subarray(i2 * N3, (i2 + 1) * N3)); + for (let j = start; j < start + steps && j < W; j++) { + setAddr({ hash: j }, wotsAddr); + out.set(context.thash1(out, wotsAddr)); + } + } + const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr); + root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr); + leafIdx = Number(tree & getMaskBig(TREE_HEIGHT)); + } + return equalBytes(root, pubRoot); + } + }); + return Object.freeze({ + info: Object.freeze({ type: "slh-dsa" }), + internal, + securityLevel, + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts3 = {}) => { + validateSigOpts2(opts3); + const M = getMessage(msg, opts3.context); + const res = internal.sign(M, secretKey, opts3); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts3 = {}) => { + validateVerOpts(opts3); + return internal.verify(sig, getMessage(msg, opts3.context), publicKey); + }, + prehash: (hash) => { + checkHash(hash, securityLevel); + const rawHash = hash; + return Object.freeze({ + info: Object.freeze({ type: "hashslh-dsa" }), + lengths: internal.lengths, + keygen: internal.keygen, + getPublicKey: internal.getPublicKey, + sign: (msg, secretKey, opts3 = {}) => { + validateSigOpts2(opts3); + const M = getMessagePrehash(rawHash, msg, opts3.context); + const res = internal.sign(M, secretKey, opts3); + cleanBytes(M); + return res; + }, + verify: (sig, msg, publicKey, opts3 = {}) => { + validateVerOpts(opts3); + return internal.verify(sig, getMessagePrehash(rawHash, msg, opts3.context), publicKey); + } + }); + } + }); +} +var genSha = (h0, h1) => (opts2) => (pub_seed, sk_seed) => { + const { N: N3 } = opts2; + const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 }; + const counterB = new Uint8Array(4); + const counterV = createView(counterB); + const h0ps = h0.create().update(pub_seed).update(new Uint8Array(h0.blockLen - N3)); + const h1ps = h1.create().update(pub_seed).update(new Uint8Array(h1.blockLen - N3)); + const h0tmp = h0ps.clone(); + const h1tmp = h1ps.clone(); + function mgf1(seed, length, hash) { + stats.mgf1++; + const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen); + if (length > 2 ** 32) + throw new Error("mask too long"); + for (let counter = 0, o = out; o.length; counter++) { + counterV.setUint32(0, counter, false); + hash.create().update(seed).update(counterB).digestInto(o); + o = o.subarray(hash.outputLen); + } + cleanBytes(out.subarray(length)); + return out.subarray(0, length); + } + const thash = (_, h, hTmp) => (blocks, input, addr) => { + stats.thash++; + const d = h._cloneInto(hTmp).update(addr).update(input.subarray(0, blocks * N3)).digest(); + return d.subarray(0, N3); + }; + return { + PRFaddr: (addr) => { + if (!sk_seed) + throw new Error("No sk seed"); + stats.prf++; + const res = h0ps._cloneInto(h0tmp).update(addr).update(sk_seed).digest().subarray(0, N3); + return res; + }, + PRFmsg: (skPRF, random, msg) => { + stats.gen_message_random++; + return hmac.create(h1, skPRF).update(random).update(msg).digest().subarray(0, N3); + }, + Hmsg: (R, pk, m, outLen) => { + stats.hmsg++; + const seed = concatBytes(R.subarray(0, N3), pk.subarray(0, N3), h1.create().update(R.subarray(0, N3)).update(pk).update(m).digest()); + return mgf1(seed, outLen, h1); + }, + thash1: thash(h0, h0ps, h0tmp).bind(null, 1), + thashN: thash(h1, h1ps, h1tmp), + clean: () => { + h0ps.destroy(); + h1ps.destroy(); + h0tmp.destroy(); + h1tmp.destroy(); + } + }; +}; +var SHA256_SIMPLE = /* @__PURE__ */ (() => ({ + isCompressed: true, + getContext: genSha(sha256, sha256) +}))(); +var slh_dsa_sha2_128s = /* @__PURE__ */ (() => gen(PARAMS2["128s"], SHA256_SIMPLE))(); + +// node_modules/@noble/post-quantum/ml-kem.js +var N2 = 256; +var Q2 = 3329; +var F2 = 3303; +var ROOT_OF_UNITY2 = 17; +var crystals2 = /* @__PURE__ */ genCrystals({ + N: N2, + Q: Q2, + F: F2, + ROOT_OF_UNITY: ROOT_OF_UNITY2, + newPoly: (n) => new Uint16Array(n), + brvBits: 7, + isKyber: true +}); +var PARAMS3 = /* @__PURE__ */ (() => Object.freeze({ + 512: Object.freeze({ N: N2, Q: Q2, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }), + 768: Object.freeze({ N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }), + 1024: Object.freeze({ N: N2, Q: Q2, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 }) +}))(); +var compress = (d) => { + if (d >= 12) + return { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i }; + const a = 2 ** (d - 1); + return { + // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d). + encode: (i) => ((i << d) + Q2 / 2) / Q2, + // const decompress = (i: number) => round((Q / 2 ** d) * i); + decode: (i) => i * Q2 + a >>> d + }; +}; +var byteCoder = (d) => crystals2.bitsCoder(d, d === 12 ? { encode: (i) => i, decode: (i) => i >= Q2 ? i - Q2 : i } : { encode: (i) => i, decode: (i) => i }); +var polyCoder2 = (d) => d === 12 ? byteCoder(12) : crystals2.bitsCoder(d, compress(d)); +function polyAdd2(a_, b_) { + const a = a_; + const b = b_; + for (let i = 0; i < N2; i++) + a[i] = crystals2.mod(a[i] + b[i]); +} +function polySub2(a_, b_) { + const a = a_; + const b = b_; + for (let i = 0; i < N2; i++) + a[i] = crystals2.mod(a[i] - b[i]); +} +function BaseCaseMultiply(a0, a1, b0, b1, zeta) { + const c0 = crystals2.mod(a1 * b1 * zeta + a0 * b0); + const c1 = crystals2.mod(a0 * b1 + a1 * b0); + return { c0, c1 }; +} +function MultiplyNTTs2(f_, g_) { + const f = f_; + const g = g_; + for (let i = 0; i < N2 / 2; i++) { + let z = crystals2.nttZetas[64 + (i >> 1)]; + if (i & 1) + z = -z; + const { c0, c1 } = BaseCaseMultiply(f[2 * i + 0], f[2 * i + 1], g[2 * i + 0], g[2 * i + 1], z); + f[2 * i + 0] = c0; + f[2 * i + 1] = c1; + } + return f; +} +function SampleNTT(xof_) { + const xof = xof_; + const r = new Uint16Array(N2); + for (let j = 0; j < N2; ) { + const b = xof(); + if (b.length % 3) + throw new Error("SampleNTT: unaligned block"); + for (let i = 0; j < N2 && i + 3 <= b.length; i += 3) { + const d1 = (b[i + 0] >> 0 | b[i + 1] << 8) & 4095; + const d2 = (b[i + 1] >> 4 | b[i + 2] << 4) & 4095; + if (d1 < Q2) + r[j++] = d1; + if (j < N2 && d2 < Q2) + r[j++] = d2; + } + } + return r; +} +var sampleCBDBytes = (buf, eta) => { + const r = new Uint16Array(N2); + const b32 = u32(buf); + swap32IfBE(b32); + let len = 0; + for (let i = 0, p = 0, bb = 0, t0 = 0; i < b32.length; i++) { + let b = b32[i]; + for (let j = 0; j < 32; j++) { + bb += b & 1; + b >>= 1; + len += 1; + if (len === eta) { + t0 = bb; + bb = 0; + } else if (len === 2 * eta) { + r[p++] = crystals2.mod(t0 - bb); + bb = 0; + len = 0; + } + } + } + swap32IfBE(b32); + if (len) + throw new Error(`sampleCBD: leftover bits: ${len}`); + return r; +}; +function sampleCBD(PRF_, seed, nonce, eta) { + const PRF = PRF_; + return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta); +} +var genKPKE = (opts_) => { + const opts2 = opts_; + const { K, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2; + const poly1 = polyCoder2(1); + const polyV = polyCoder2(dv); + const polyU = polyCoder2(du); + const publicCoder = splitCoder("publicKey", vecCoder(polyCoder2(12), K), 32); + const secretCoder = vecCoder(polyCoder2(12), K); + const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K), polyV); + const seedCoder = splitCoder("seed", 32, 32); + return { + secretCoder, + lengths: { + secretKey: secretCoder.bytesLen, + publicKey: publicCoder.bytesLen, + cipherText: cipherCoder.bytesLen + }, + keygen: (seed) => { + abytesDoc(seed, 32, "seed"); + const seedDst = new Uint8Array(33); + seedDst.set(seed); + seedDst[32] = K; + const seedHash = HASH512(seedDst); + const [rho, sigma] = seedCoder.decode(seedHash); + const sHat = []; + const tHat = []; + for (let i = 0; i < K; i++) + sHat.push(crystals2.NTT.encode(sampleCBD(PRF, sigma, i, ETA1))); + const x = XOF(rho); + for (let i = 0; i < K; i++) { + const e = crystals2.NTT.encode(sampleCBD(PRF, sigma, K + i, ETA1)); + for (let j = 0; j < K; j++) { + const aji = SampleNTT(x.get(j, i)); + polyAdd2(e, MultiplyNTTs2(aji, sHat[j])); + } + tHat.push(e); + } + x.clean(); + const res = { + publicKey: publicCoder.encode([tHat, rho]), + secretKey: secretCoder.encode(sHat) + }; + cleanBytes(rho, sigma, sHat, tHat, seedDst, seedHash); + return res; + }, + encrypt: (publicKey, msg, seed) => { + const [tHat, rho] = publicCoder.decode(publicKey); + const rHat = []; + for (let i = 0; i < K; i++) + rHat.push(crystals2.NTT.encode(sampleCBD(PRF, seed, i, ETA1))); + const x = XOF(rho); + const tmp2 = new Uint16Array(N2); + const u = []; + for (let i = 0; i < K; i++) { + const e1 = sampleCBD(PRF, seed, K + i, ETA2); + const tmp = new Uint16Array(N2); + for (let j = 0; j < K; j++) { + const aij = SampleNTT(x.get(i, j)); + polyAdd2(tmp, MultiplyNTTs2(aij, rHat[j])); + } + polyAdd2(e1, crystals2.NTT.decode(tmp)); + u.push(e1); + polyAdd2(tmp2, MultiplyNTTs2(tHat[i], rHat[i])); + cleanBytes(tmp); + } + x.clean(); + const e2 = sampleCBD(PRF, seed, 2 * K, ETA2); + polyAdd2(e2, crystals2.NTT.decode(tmp2)); + const v = poly1.decode(msg); + polyAdd2(v, e2); + cleanBytes(tHat, rHat, tmp2, e2); + return cipherCoder.encode([u, v]); + }, + decrypt: (cipherText, privateKey) => { + const [u, v] = cipherCoder.decode(cipherText); + const sk = secretCoder.decode(privateKey); + const tmp = new Uint16Array(N2); + for (let i = 0; i < K; i++) + polyAdd2(tmp, MultiplyNTTs2(sk[i], crystals2.NTT.encode(u[i]))); + polySub2(v, crystals2.NTT.decode(tmp)); + cleanBytes(tmp, sk, u); + return poly1.encode(v); + } + }; +}; +function createKyber(opts2) { + const rawOpts = opts2; + const KPKE = genKPKE(rawOpts); + const { HASH256, HASH512, KDF } = rawOpts; + const { secretCoder: KPKESecretCoder, lengths } = KPKE; + const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32); + const msgLen = 32; + const seedLen = 64; + const kemLengths = Object.freeze({ + ...lengths, + seed: 64, + msg: msgLen, + msgRand: msgLen, + secretKey: secretCoder.bytesLen + }); + return Object.freeze({ + info: Object.freeze({ type: "ml-kem" }), + lengths: kemLengths, + keygen: (seed = randomBytes3(seedLen)) => { + abytesDoc(seed, seedLen, "seed"); + const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32)); + const publicKeyHash = HASH256(publicKey); + const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]); + cleanBytes(sk, publicKeyHash); + return { + publicKey, + secretKey + }; + }, + getPublicKey: (secretKey) => { + const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey); + return Uint8Array.from(publicKey); + }, + encapsulate: (publicKey, msg = randomBytes3(msgLen)) => { + abytesDoc(publicKey, lengths.publicKey, "publicKey"); + abytesDoc(msg, msgLen, "message"); + const eke = publicKey.subarray(0, 384 * opts2.K); + const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes2(eke))); + if (!equalBytes(ek, eke)) { + cleanBytes(ek); + throw new Error("ML-KEM.encapsulate: wrong publicKey modulus"); + } + cleanBytes(ek); + const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest(); + const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + cleanBytes(kr.subarray(32)); + return { + cipherText, + sharedSecret: kr.subarray(0, 32) + }; + }, + decapsulate: (cipherText, secretKey) => { + abytesDoc(secretKey, secretCoder.bytesLen, "secretKey"); + abytesDoc(cipherText, lengths.cipherText, "cipherText"); + const k768 = secretCoder.bytesLen - 96; + const start = k768 + 32; + const test = HASH256(secretKey.subarray(k768 / 2, start)); + if (!equalBytes(test, secretKey.subarray(start, start + 32))) + throw new Error("invalid secretKey: hash check failed"); + const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey); + const msg = KPKE.decrypt(cipherText, sk); + const kr = HASH512.create().update(msg).update(publicKeyHash).digest(); + const Khat = kr.subarray(0, 32); + const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64)); + const isValid = equalBytes(cipherText, cipherText2); + const Kbar = KDF.create({ dkLen: 32 }).update(z).update(cipherText).digest(); + cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar); + return isValid ? Khat : Kbar; + } + }); +} +function shakePRF(dkLen, key, nonce) { + return shake256.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest(); +} +var opts = /* @__PURE__ */ (() => ({ + HASH256: sha3_256, + HASH512: sha3_512, + KDF: shake256, + XOF: XOF128, + PRF: shakePRF +}))(); +var mk = (params) => createKyber({ + ...opts, + ...params +}); +var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS3[768]))(); + +// www/js/pq-crypto.mjs +function generateSeedPhrase() { + return generateMnemonic(wordlist, 128); +} +function mnemonicToSeed(mnemonic, passphrase = "") { + if (!validateMnemonic(mnemonic, wordlist)) { + throw new Error("Invalid mnemonic"); + } + return mnemonicToSeedSync(mnemonic, passphrase); +} +function isValidMnemonic(mnemonic) { + return validateMnemonic(mnemonic, wordlist); +} +function deriveSecp256k1FromSeed(seed, accountIndex = 0) { + const hdKey = HDKey.fromMasterSeed(seed); + const path = `m/44'/1237'/${accountIndex}'/0/0`; + const child = hdKey.derive(path); + if (!child.privateKey) { + throw new Error("Failed to derive private key"); + } + return { + privateKey: child.privateKey, + publicKey: child.publicKey + }; +} +function derivePQSeed(bip39Seed, label, length) { + const info = new TextEncoder().encode(label); + return hkdf(sha512, bip39Seed, void 0, info, length); +} +function derivePQKeysFromSeed(bip39Seed) { + const mlDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-dsa-65", 32); + const mlDsa = ml_dsa65.keygen(mlDsaSeed); + const slhDsaSeed = derivePQSeed(bip39Seed, "nostr-pq-slh-dsa-128s", 48); + const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed); + const mlKemSeed = derivePQSeed(bip39Seed, "nostr-pq-ml-kem-768", 64); + const mlKem = ml_kem768.keygen(mlKemSeed); + return { mlDsa, slhDsa, mlKem }; +} +function signWithMLDSA(message, secretKey) { + return ml_dsa65.sign(message, secretKey); +} +function verifyMLDSA(signature, message, publicKey) { + return ml_dsa65.verify(signature, message, publicKey); +} +function signWithSLHDSA(message, secretKey) { + return slh_dsa_sha2_128s.sign(message, secretKey); +} +function verifySLHDSA(signature, message, publicKey) { + return slh_dsa_sha2_128s.verify(signature, message, publicKey); +} +function bytesToBase64(bytes) { + let binary = ""; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +function base64ToBytes(base64) { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} +function bytesToHex3(bytes) { + return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join(""); +} +function hexToBytes3(hex) { + const bytes = new Uint8Array(hex.length / 2); + for (let i = 0; i < hex.length; i += 2) { + bytes[i / 2] = parseInt(hex.substr(i, 2), 16); + } + return bytes; +} +function buildNIPQRContent(npub, successorNpub, pqKeys) { + let statement; + if (successorNpub) { + statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`; + } else { + statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`; + } + const statementBytes = new TextEncoder().encode(statement); + const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey); + const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey); + const content = { + statement, + pq_keys: [ + { + algorithm: "ml-dsa-65", + public_key: bytesToBase64(pqKeys.mlDsa.publicKey), + signature: bytesToBase64(mlDsaSig) + }, + { + algorithm: "slh-dsa-128s", + public_key: bytesToBase64(pqKeys.slhDsa.publicKey), + signature: bytesToBase64(slhDsaSig) + }, + { + algorithm: "ml-kem-768", + public_key: bytesToBase64(pqKeys.mlKem.publicKey), + note: "KEM key for encryption; ownership asserted by secp256k1 signature over this content" + } + ] + }; + if (successorNpub) { + content.successor_pubkey = successorNpub; + } + return { statement, content, statementBytes }; +} +function verifyNIPQRContent(content) { + const results = []; + for (const keyEntry of content.pq_keys) { + if (keyEntry.algorithm === "ml-kem-768") { + results.push({ algorithm: keyEntry.algorithm, valid: true, note: "KEM (no signature to verify)" }); + continue; + } + const pubKey = base64ToBytes(keyEntry.public_key); + const sig = base64ToBytes(keyEntry.signature); + const msg = new TextEncoder().encode(content.statement); + let valid = false; + if (keyEntry.algorithm === "ml-dsa-65") { + valid = verifyMLDSA(sig, msg, pubKey); + } else if (keyEntry.algorithm === "slh-dsa-128s") { + valid = verifySLHDSA(sig, msg, pubKey); + } + results.push({ algorithm: keyEntry.algorithm, valid }); + } + return { + valid: results.every((r) => r.valid), + results + }; +} +var PQ_KEY_INFO = { + "ml-dsa-65": { + name: "ML-DSA-65 (Dilithium)", + publicKeySize: 1952, + signatureSize: 3309, + fips: "FIPS 204", + type: "signature" + }, + "slh-dsa-128s": { + name: "SLH-DSA-128s (SPHINCS+)", + publicKeySize: 32, + signatureSize: 7856, + fips: "FIPS 205", + type: "signature" + }, + "ml-kem-768": { + name: "ML-KEM-768 (Kyber)", + publicKeySize: 1184, + ciphertextSize: 1088, + fips: "FIPS 203", + type: "kem" + } +}; +export { + PQ_KEY_INFO, + base64ToBytes, + buildNIPQRContent, + bytesToBase64, + bytesToHex3 as bytesToHex, + derivePQKeysFromSeed, + deriveSecp256k1FromSeed, + generateSeedPhrase, + hexToBytes3 as hexToBytes, + isValidMnemonic, + mnemonicToSeed, + signWithMLDSA, + signWithSLHDSA, + verifyMLDSA, + verifyNIPQRContent, + verifySLHDSA +}; +/*! Bundled license information: + +@scure/base/index.js: + (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@scure/bip39/index.js: + (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) + +@noble/curves/utils.js: +@noble/curves/abstract/modular.js: +@noble/curves/abstract/curve.js: +@noble/curves/abstract/weierstrass.js: +@noble/curves/secp256k1.js: + (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *) + +@scure/bip32/index.js: + (*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *) + +@noble/post-quantum/utils.js: +@noble/post-quantum/_crystals.js: +@noble/post-quantum/ml-dsa.js: +@noble/post-quantum/slh-dsa.js: +@noble/post-quantum/ml-kem.js: + (*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) *) +*/ +//# sourceMappingURL=pq-crypto.bundle.js.map diff --git a/www/pq-crypto.bundle.js.map b/www/pq-crypto.bundle.js.map new file mode 100644 index 0000000..b56a767 --- /dev/null +++ b/www/pq-crypto.bundle.js.map @@ -0,0 +1,7 @@ +{ + "version": 3, + "sources": ["../node_modules/@noble/hashes/src/utils.ts", "../node_modules/@noble/hashes/src/hmac.ts", "../node_modules/@noble/hashes/src/pbkdf2.ts", "../node_modules/@noble/hashes/src/_md.ts", "../node_modules/@noble/hashes/src/_u64.ts", "../node_modules/@noble/hashes/src/sha2.ts", "../node_modules/@scure/base/index.ts", "../node_modules/@scure/bip39/index.js", "../node_modules/@scure/bip39/wordlists/english.js", "../node_modules/@noble/curves/src/utils.ts", "../node_modules/@noble/curves/src/abstract/modular.ts", "../node_modules/@noble/curves/src/abstract/curve.ts", "../node_modules/@noble/curves/src/abstract/fft.ts", "../node_modules/@noble/curves/src/abstract/weierstrass.ts", "../node_modules/@noble/curves/src/secp256k1.ts", "../node_modules/@noble/hashes/src/legacy.ts", "../node_modules/@scure/bip32/index.ts", "../node_modules/@noble/hashes/src/hkdf.ts", "../node_modules/@noble/hashes/src/sha3.ts", "../node_modules/@noble/post-quantum/src/utils.ts", "../node_modules/@noble/post-quantum/src/_crystals.ts", "../node_modules/@noble/post-quantum/src/ml-dsa.ts", "../node_modules/@noble/post-quantum/src/slh-dsa.ts", "../node_modules/@noble/post-quantum/src/ml-kem.ts", "js/pq-crypto.mjs"], + "sourcesContent": ["/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg
, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\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: unknown): a is Uint8Array {\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 (\n 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}\n\n/**\n * Asserts something is a non-negative integer.\n * @param n - number to validate\n * @param title - label included in thrown errors\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: number, title: string = ''): void {\n if (typeof n !== 'number') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(`${prefix}expected number, got ${typeof n}`);\n }\n if (!Number.isSafeInteger(n) || n < 0) {\n const prefix = title && `\"${title}\" `;\n throw new RangeError(`${prefix}expected integer >= 0, got ${n}`);\n }\n}\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(\n value: TArg,\n length?: number,\n title: string = ''\n): TRet {\n const bytes = isBytes(value);\n const len = value?.length;\n const needsLen = length !== undefined;\n if (!bytes || (needsLen && len !== length)) {\n const prefix = title && `\"${title}\" `;\n const ofLen = needsLen ? ` of length ${length}` : '';\n const got = bytes ? `length=${len}` : `type=${typeof value}`;\n const message = prefix + 'expected Uint8Array' + ofLen + ', got ' + got;\n if (!bytes) throw new TypeError(message);\n throw new RangeError(message);\n }\n return value as TRet;\n}\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: TArg): TRet {\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)) as TRet;\n}\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: TArg): void {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new TypeError('Hash must 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) throw new Error('\"outputLen\" must be >= 1');\n if (h.blockLen < 1) throw new Error('\"blockLen\" must be >= 1');\n}\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: any, checkFinished = true): void {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\n\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: any, instance: any): void {\n abytes(out, undefined, 'digestInto() output');\n const min = instance.outputLen;\n if (out.length < min) {\n throw new RangeError('\"digestInto() output\" expected to be of length >=' + min);\n }\n}\n\n/** Generic type encompassing 8/16/32-byte array views, but not 64-bit variants. */\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\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: TArg): TRet {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength) as TRet;\n}\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: TArg): TRet {\n return new Uint32Array(\n arr.buffer,\n arr.byteOffset,\n Math.floor(arr.byteLength / 4)\n ) as TRet;\n}\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: TArg): void {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\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: TArg): DataView {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\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: number, shift: number): number {\n return (word << (32 - shift)) | (word >>> shift);\n}\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: number, shift: number): number {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n\n/** Whether the current platform is little-endian. */\nexport const isLE: boolean = /* @__PURE__ */ (() =>\n new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n\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: number): number {\n return (\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff)\n );\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: (n: number) => number = isLE\n ? (n: number) => n\n : (n: number) => byteSwap(n) >>> 0;\n\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: TArg): TRet {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr as TRet;\n}\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: (u: TArg) => TRet = isLE\n ? (u: TArg) => u as TRet\n : byteSwap32;\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // @ts-ignore\n typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n\n/**\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: TArg): string {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin) 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\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const;\nfunction asciiToBase16(ch: number): number | undefined {\n if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\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: string): TRet {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n if (hasHexBuiltin) {\n try {\n return (Uint8Array as any).fromHex(hex);\n } catch (error) {\n if (error instanceof SyntaxError) throw new RangeError(error.message);\n throw error;\n }\n }\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) 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));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new RangeError(\n 'hex string expected, got non-hex character \"' + char + '\" at index ' + hi\n );\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * This yields to the Promise/microtask scheduler queue, not to timers or the\n * full macrotask event loop.\n * @example\n * Yield to the next scheduler tick.\n * ```ts\n * await nextTick();\n * ```\n */\nexport const nextTick = async (): Promise => {};\n\n/**\n * Returns control to the Promise/microtask scheduler every `tick`\n * 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 * @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(\n iters: number,\n tick: number,\n cb: (i: number) => void\n): Promise {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols, but ts doesn't see them: https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\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: string): TRet {\n if (typeof str !== 'string') throw new TypeError('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n/** KDFs can accept string or Uint8Array for user convenience. */\nexport type KDFInput = string | Uint8Array;\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: TArg, errorTitle = ''): TRet {\n if (typeof data === 'string') return utf8ToBytes(data);\n return abytes(data, undefined, errorTitle);\n}\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: TArg): TRet {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\ntype EmptyObj = {};\n/**\n * Merges default options and passed options.\n * @param defaults - base option object\n * @param opts - user overrides\n * @returns Merged option object. The merge mutates `defaults` in place.\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(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new TypeError('options must be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\n/** Common interface for all hash instances. */\nexport interface Hash {\n /** Bytes processed per compression block. */\n blockLen: number;\n /** Bytes produced by `digest()`. */\n outputLen: number;\n /** Whether the instance supports XOF-style variable-length output via `xof()` / `xofInto()`. */\n canXOF: boolean;\n /**\n * Absorbs more message bytes into the running hash state.\n * @param buf - message chunk to absorb\n * @returns The same hash instance for chaining.\n */\n update(buf: TArg): this;\n /**\n * Finalizes the hash into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Nothing. Implementations write into `buf` in place.\n */\n digestInto(buf: TArg): void;\n /**\n * Finalizes the hash and returns a freshly allocated digest.\n * @returns Digest bytes.\n */\n digest(): TRet;\n /** Wipes internal state and makes the instance unusable. */\n destroy(): void;\n /**\n * Copies the current hash state into an existing or new instance.\n * @param to - Optional destination instance to reuse.\n * @returns Cloned hash state.\n */\n _cloneInto(to?: T): T;\n /**\n * Creates an independent copy of the current hash state.\n * @returns Cloned hash instance.\n */\n clone(): T;\n}\n\n/** Pseudorandom generator interface. */\nexport interface PRG {\n /**\n * Mixes more entropy into the generator state.\n * @param seed - fresh entropy bytes\n * @returns Nothing. Implementations update internal state in place.\n */\n addEntropy(seed: TArg): void;\n /**\n * Generates pseudorandom output bytes.\n * @param length - number of bytes to generate\n * @returns Generated pseudorandom bytes.\n */\n randomBytes(length: number): TRet;\n /** Wipes generator state and makes the instance unusable. */\n clean(): void;\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF> = Hash & {\n /**\n * Reads more bytes from the XOF stream.\n * @param bytes - number of bytes to read\n * @returns Requested digest bytes.\n */\n xof(bytes: number): TRet;\n /**\n * Reads more bytes from the XOF stream into a caller-provided buffer.\n * @param buf - destination buffer\n * @returns Filled output buffer.\n */\n xofInto(buf: TArg): TRet;\n};\n\n/** Hash constructor or factory type. */\nexport type HasherCons = Opts extends undefined ? () => T : (opts?: Opts) => T;\n/** Optional hash metadata. */\nexport type HashInfo = {\n /** DER-encoded object identifier bytes for the hash algorithm. */\n oid?: TRet;\n};\n/** Callable hash function type. */\nexport type CHash = Hash, Opts = undefined> = {\n /** Digest size in bytes. */\n outputLen: number;\n /** Input block size in bytes. */\n blockLen: number;\n /** Whether `.create()` returns a hash instance that can be used as an XOF stream. */\n canXOF: boolean;\n} & HashInfo &\n (Opts extends undefined\n ? {\n (msg: TArg): TRet;\n create(): T;\n }\n : {\n (msg: TArg, opts?: TArg): TRet;\n create(opts?: Opts): T;\n });\n/** Callable extendable-output hash function type. */\nexport type CHashXOF = HashXOF, Opts = undefined> = CHash;\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 * @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, Opts = undefined>(\n hashCons: HasherCons,\n info: TArg = {}\n): TRet> {\n const hashC: any = (msg: TArg, opts?: TArg) =>\n hashCons(opts as 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?: Opts) => hashCons(opts);\n Object.assign(hashC, info);\n return Object.freeze(hashC) as TRet>;\n}\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): TRet {\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 as any).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/**\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: number): TRet> => ({\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 * HMAC: RFC2104 message authentication code.\n * @module\n */\nimport {\n abytes,\n aexists,\n ahash,\n aoutput,\n clean,\n type CHash,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\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> implements Hash<_HMAC> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n canXOF = false;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: TArg, key: TArg) {\n ahash(hash);\n abytes(key, undefined, 'key');\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of the first block) of the outer hash here,\n // we can re-use it between multiple calls via clone.\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n clean(pad);\n }\n update(buf: TArg): this {\n aexists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: TArg): void {\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(): TRet {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n _cloneInto(to?: _HMAC): _HMAC {\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 } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n clone(): _HMAC {\n return this._cloneInto();\n }\n destroy(): void {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - authentication key bytes\n * @param message - message bytes to authenticate\n * @returns Authentication tag bytes.\n * @example\n * Compute an RFC 2104 HMAC.\n * ```ts\n * import { hmac } from '@noble/hashes/hmac.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const mac = hmac(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));\n * ```\n */\ntype HmacFn = {\n (hash: TArg, key: TArg, message: TArg): TRet;\n create(hash: TArg, key: TArg): TRet<_HMAC>;\n};\nexport const hmac: TRet = /* @__PURE__ */ (() => {\n const hmac_ = ((\n hash: TArg,\n key: TArg,\n message: TArg\n ): TRet => new _HMAC(hash, key).update(message).digest()) as TRet;\n hmac_.create = (hash: TArg, key: TArg): TRet<_HMAC> =>\n new _HMAC(hash, key) as TRet<_HMAC>;\n return hmac_;\n})();\n", "/**\n * PBKDF (RFC 2898). Can be used to create a key from password and salt.\n * @module\n */\nimport { hmac } from './hmac.ts';\n// prettier-ignore\nimport {\n ahash, anumber,\n asyncLoop, checkOpts, clean, createView, kdfInputToBytes,\n type CHash,\n type Hash,\n type KDFInput,\n type TArg,\n type TRet\n} from './utils.ts';\n\n/**\n * PBKDF2 options:\n * * c: iterations, should probably be higher than 100_000\n * * dkLen: desired length of derived key in bytes, must be `>= 1` per RFC 8018 \u00A75.2\n * * asyncTick: max time in ms for which async function can block execution\n */\nexport type Pbkdf2Opt = {\n /** Iteration count. Higher values increase CPU cost. */\n c: number;\n /** Desired derived key length in bytes, must be `>= 1` per RFC 8018 \u00A75.2. */\n dkLen?: number;\n /** Max scheduler block time in milliseconds for the async variant. */\n asyncTick?: number;\n};\n// Common start and end for sync/async functions\nfunction pbkdf2Init(\n hash: TArg,\n _password: TArg,\n _salt: TArg,\n _opts: TArg\n) {\n ahash(hash);\n const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);\n const { c, dkLen, asyncTick } = opts;\n anumber(c, 'c');\n anumber(dkLen, 'dkLen');\n anumber(asyncTick, 'asyncTick');\n if (c < 1) throw new Error('iterations (c) must be >= 1');\n // RFC 8018 \u00A75.2 defines `dkLen` as \"a positive integer\".\n if (dkLen < 1) throw new Error('\"dkLen\" must be >= 1');\n // RFC 8018 \u00A75.2 step 1 requires rejecting oversize `dkLen`\n // before allocating the destination buffer.\n if (dkLen > (2 ** 32 - 1) * hash.outputLen) throw new Error('derived key too long');\n const password = kdfInputToBytes(_password, 'password');\n const salt = kdfInputToBytes(_salt, 'salt');\n // DK = PBKDF2(PRF, Password, Salt, c, dkLen);\n const DK = new Uint8Array(dkLen);\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n const PRF = hmac.create(hash, password);\n // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).\n const PRFSalt = PRF._cloneInto().update(salt);\n return { c, dkLen, asyncTick, DK, PRF, PRFSalt };\n}\n\nfunction pbkdf2Output>(\n PRF: TArg>,\n PRFSalt: TArg>,\n DK: TArg,\n prfW: TArg | undefined>,\n u: TArg\n): TRet {\n // Shared sync/async cleanup point: wipe transient PRF state\n // while preserving the derived key buffer.\n PRF.destroy();\n PRFSalt.destroy();\n if (prfW) prfW.destroy();\n clean(u);\n return DK as TRet;\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. See {@link Pbkdf2Opt}.\n * @returns Derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2 } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });\n * ```\n */\nexport function pbkdf2(\n hash: TArg,\n password: TArg,\n salt: TArg,\n opts: TArg\n): TRet {\n const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n for (let ui = 1; ui < c; ui++) {\n // Uc = PRF(Password, Uc\u22121)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n }\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n\n/**\n * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.\n * @param hash - hash function that would be used e.g. sha256\n * @param password - password from which a derived key is generated;\n * JS string inputs are UTF-8 encoded first\n * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first\n * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,\n * must be `>= 1` per RFC 8018 \u00A75.2. `asyncTick` is only a local\n * scheduler-yield knob for this JS wrapper, not part of RFC 8018.\n * See {@link Pbkdf2Opt}.\n * @returns Promise resolving to derived key bytes.\n * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}\n * @example\n * PBKDF2-HMAC: RFC 2898 key derivation function.\n * ```ts\n * import { pbkdf2Async } from '@noble/hashes/pbkdf2.js';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });\n * ```\n */\nexport async function pbkdf2Async(\n hash: TArg,\n password: TArg,\n salt: TArg,\n opts: TArg\n): Promise> {\n const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);\n let prfW: any; // Working copy\n const arr = new Uint8Array(4);\n const view = createView(arr);\n const u = new Uint8Array(PRF.outputLen);\n // DK = T1 + T2 + \u22EF + Tdklen/hlen\n for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {\n // Ti = F(Password, Salt, c, i)\n // The last Ti view can be shorter than hLen, which applies\n // RFC 8018 \u00A75.2 step 4's T_l<0..r-1> truncation without extra copies.\n const Ti = DK.subarray(pos, pos + PRF.outputLen);\n view.setInt32(0, ti, false);\n // F(Password, Salt, c, i) = U1 ^ U2 ^ \u22EF ^ Uc\n // U1 = PRF(Password, Salt + INT_32_BE(i))\n (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);\n Ti.set(u.subarray(0, Ti.length));\n await asyncLoop(c - 1, asyncTick, () => {\n // Uc = PRF(Password, Uc\u22121)\n PRF._cloneInto(prfW).update(u).digestInto(u);\n for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];\n });\n }\n return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);\n}\n", "/**\n * Internal Merkle-Damgard hash utils.\n * @module\n */\nimport {\n abytes,\n aexists,\n aoutput,\n clean,\n createView,\n type Hash,\n type TArg,\n type TRet,\n} from './utils.ts';\n\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: number, b: number, c: number): number {\n return (a & b) ^ (~a & c);\n}\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: number, b: number, c: number): number {\n return (a & b) ^ (a & c) ^ (b & c);\n}\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 abstract class HashMD> implements Hash {\n // Subclasses must treat `buf` as read-only: `update()` may pass a direct view over caller input\n // when it can process whole blocks without buffering first.\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n\n readonly blockLen: number;\n readonly outputLen: number;\n readonly canXOF = false;\n readonly padOffset: number;\n readonly isLE: boolean;\n\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(blockLen: number, outputLen: number, padOffset: number, isLE: boolean) {\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: TArg): this {\n aexists(this);\n abytes(data);\n const { view, 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 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) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: TArg): void {\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\n buffer[pos++] = 0b10000000;\n clean(this.buffer.subarray(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 pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\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.\n view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen must be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest(): TRet {\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 as TRet;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.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 (length % blockLen) to.buffer.set(buffer);\n return to as unknown as any;\n }\n clone(): T {\n return this._cloneInto();\n }\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\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: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n]);\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: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4,\n]);\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: TRet = /* @__PURE__ */ Uint32Array.from([\n 0xcbbb9d5d, 0xc1059ed8, 0x629a292a, 0x367cd507, 0x9159015a, 0x3070dd17, 0x152fecd8, 0xf70e5939,\n 0x67332667, 0xffc00b31, 0x8eb44a87, 0x68581511, 0xdb0c2e0d, 0x64f98fa7, 0x47b5481d, 0xbefa4fa4,\n]);\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: TRet = /* @__PURE__ */ Uint32Array.from([\n 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1,\n 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179,\n]);\n", "/**\n * Internal helpers for u64.\n * BigUint64Array is too slow as per 2026, so we implement it using\n * Uint32Array.\n * @privateRemarks TODO: re-check {@link https://issues.chromium.org/issues/42212588}\n * @module\n */\nimport type { TRet } from './utils.ts';\n\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\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 n: bigint,\n le = false\n): {\n h: number;\n l: number;\n} {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\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: bigint[], le = false): TRet {\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] as TRet;\n}\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: number, l: number): bigint => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// High 32-bit half of a 64-bit logical right shift for `s` in `0..31`.\nconst shrSH = (h: number, _l: number, s: number): number => h >>> s;\n// Low 32-bit half of a 64-bit logical right shift, valid for `s` in `1..31`.\nconst shrSL = (h: number, l: number, s: number): number => (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: number, l: number, s: number): number => (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: number, l: number, s: number): number => (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: number, l: number, s: number): number => (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: number, l: number, s: number): number => (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: number, l: number): number => 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: number, _l: number): number => h;\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSH = (h: number, l: number, s: number): number => (h << s) | (l >>> (32 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `1..31`.\nconst rotlSL = (h: number, l: number, s: number): number => (l << s) | (h >>> (32 - s));\n// High 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBH = (h: number, l: number, s: number): number => (l << (s - 32)) | (h >>> (64 - s));\n// Low 32-bit half of a 64-bit left rotate, valid for `s` in `33..63`; `32` uses `rotr32*`.\nconst rotlBL = (h: number, l: number, s: number): number => (h << (s - 32)) | (l >>> (64 - s));\n\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(\n Ah: number,\n Al: number,\n Bh: number,\n Bl: number\n): {\n h: number;\n l: number;\n} {\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: number, Bl: number, Cl: number): number => (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: number, Ah: number, Bh: number, Ch: number): number =>\n (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: number, Bl: number, Cl: number, Dl: number): number =>\n (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: number, Ah: number, Bh: number, Ch: number, Dh: number): number =>\n (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: number, Bl: number, Cl: number, Dl: number, El: number): number =>\n (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: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number): number =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig\n};\n// Canonical grouped namespace for callers that prefer one object.\n// Named exports stay for direct imports.\n// prettier-ignore\nconst u64: { fromBig: typeof fromBig; split: typeof split; toBig: (h: number, l: number) => bigint; shrSH: (h: number, _l: number, s: number) => number; shrSL: (h: number, l: number, s: number) => number; rotrSH: (h: number, l: number, s: number) => number; rotrSL: (h: number, l: number, s: number) => number; rotrBH: (h: number, l: number, s: number) => number; rotrBL: (h: number, l: number, s: number) => number; rotr32H: (_h: number, l: number) => number; rotr32L: (h: number, _l: number) => number; rotlSH: (h: number, l: number, s: number) => number; rotlSL: (h: number, l: number, s: number) => number; rotlBH: (h: number, l: number, s: number) => number; rotlBL: (h: number, l: number, s: number) => number; add: typeof add; add3L: (Al: number, Bl: number, Cl: number) => number; add3H: (low: number, Ah: number, Bh: number, Ch: number) => number; add4L: (Al: number, Bl: number, Cl: number, Dl: number) => number; add4H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number) => number; add5H: (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) => number; add5L: (Al: number, Bl: number, Cl: number, Dl: number, El: number) => number; } = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// Default export mirrors named `u64` for compatibility with object-style imports.\nexport default u64;\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.ts';\nimport * as u64 from './_u64.ts';\nimport { type CHash, clean, createHasher, oidNist, rotr, type TRet } from './utils.ts';\n\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\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\n/** Internal SHA-224 / SHA-256 compression engine from RFC 6234 \u00A76.2. */\nabstract class 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 protected abstract A: number;\n protected abstract B: number;\n protected abstract C: number;\n protected abstract D: number;\n protected abstract E: number;\n protected abstract F: number;\n protected abstract G: number;\n protected abstract H: number;\n\n constructor(outputLen: number) {\n super(64, outputLen, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean(): void {\n clean(SHA256_W);\n }\n destroy(): void {\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\n/** Internal SHA-256 hash class grounded in RFC 6234 \u00A76.2. */\nexport class _SHA256 extends SHA2_32B<_SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n protected A: number = SHA256_IV[0] | 0;\n protected B: number = SHA256_IV[1] | 0;\n protected C: number = SHA256_IV[2] | 0;\n protected D: number = SHA256_IV[3] | 0;\n protected E: number = SHA256_IV[4] | 0;\n protected F: number = SHA256_IV[5] | 0;\n protected G: number = SHA256_IV[6] | 0;\n protected H: number = SHA256_IV[7] | 0;\n constructor() {\n super(32);\n }\n}\n\n/** Internal SHA-224 hash class grounded in RFC 6234 \u00A76.2 and \u00A78.5. */\nexport class _SHA224 extends SHA2_32B<_SHA224> {\n protected A: number = SHA224_IV[0] | 0;\n protected B: number = SHA224_IV[1] | 0;\n protected C: number = SHA224_IV[2] | 0;\n protected D: number = SHA224_IV[3] | 0;\n protected E: number = SHA224_IV[4] | 0;\n protected F: number = SHA224_IV[5] | 0;\n protected G: number = SHA224_IV[6] | 0;\n protected H: number = SHA224_IV[7] | 0;\n constructor() {\n super(28);\n }\n}\n\n// SHA2-512 is slower than sha256 in js because u64 operations are slow.\n\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\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\n/** Internal SHA-384 / SHA-512 compression engine from RFC 6234 \u00A76.4. */\nabstract class 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 protected abstract Ah: number;\n protected abstract Al: number;\n protected abstract Bh: number;\n protected abstract Bl: number;\n protected abstract Ch: number;\n protected abstract Cl: number;\n protected abstract Dh: number;\n protected abstract Dl: number;\n protected abstract Eh: number;\n protected abstract El: number;\n protected abstract Fh: number;\n protected abstract Fl: number;\n protected abstract Gh: number;\n protected abstract Gl: number;\n protected abstract Hh: number;\n protected abstract Hl: number;\n\n constructor(outputLen: number) {\n super(128, outputLen, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ): void {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number): void {\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 protected roundClean(): void {\n clean(SHA512_W_H, SHA512_W_L);\n }\n destroy(): void {\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\n/** Internal SHA-512 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA512 extends SHA2_64B<_SHA512> {\n protected Ah: number = SHA512_IV[0] | 0;\n protected Al: number = SHA512_IV[1] | 0;\n protected Bh: number = SHA512_IV[2] | 0;\n protected Bl: number = SHA512_IV[3] | 0;\n protected Ch: number = SHA512_IV[4] | 0;\n protected Cl: number = SHA512_IV[5] | 0;\n protected Dh: number = SHA512_IV[6] | 0;\n protected Dl: number = SHA512_IV[7] | 0;\n protected Eh: number = SHA512_IV[8] | 0;\n protected El: number = SHA512_IV[9] | 0;\n protected Fh: number = SHA512_IV[10] | 0;\n protected Fl: number = SHA512_IV[11] | 0;\n protected Gh: number = SHA512_IV[12] | 0;\n protected Gl: number = SHA512_IV[13] | 0;\n protected Hh: number = SHA512_IV[14] | 0;\n protected Hl: number = SHA512_IV[15] | 0;\n\n constructor() {\n super(64);\n }\n}\n\n/** Internal SHA-384 hash class grounded in RFC 6234 \u00A76.3 and \u00A76.4. */\nexport class _SHA384 extends SHA2_64B<_SHA384> {\n protected Ah: number = SHA384_IV[0] | 0;\n protected Al: number = SHA384_IV[1] | 0;\n protected Bh: number = SHA384_IV[2] | 0;\n protected Bl: number = SHA384_IV[3] | 0;\n protected Ch: number = SHA384_IV[4] | 0;\n protected Cl: number = SHA384_IV[5] | 0;\n protected Dh: number = SHA384_IV[6] | 0;\n protected Dl: number = SHA384_IV[7] | 0;\n protected Eh: number = SHA384_IV[8] | 0;\n protected El: number = SHA384_IV[9] | 0;\n protected Fh: number = SHA384_IV[10] | 0;\n protected Fl: number = SHA384_IV[11] | 0;\n protected Gh: number = SHA384_IV[12] | 0;\n protected Gl: number = SHA384_IV[13] | 0;\n protected Hh: number = SHA384_IV[14] | 0;\n protected Hl: number = SHA384_IV[15] | 0;\n\n constructor() {\n super(48);\n }\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\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\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\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<_SHA512_224> {\n protected Ah: number = T224_IV[0] | 0;\n protected Al: number = T224_IV[1] | 0;\n protected Bh: number = T224_IV[2] | 0;\n protected Bl: number = T224_IV[3] | 0;\n protected Ch: number = T224_IV[4] | 0;\n protected Cl: number = T224_IV[5] | 0;\n protected Dh: number = T224_IV[6] | 0;\n protected Dl: number = T224_IV[7] | 0;\n protected Eh: number = T224_IV[8] | 0;\n protected El: number = T224_IV[9] | 0;\n protected Fh: number = T224_IV[10] | 0;\n protected Fl: number = T224_IV[11] | 0;\n protected Gh: number = T224_IV[12] | 0;\n protected Gl: number = T224_IV[13] | 0;\n protected Hh: number = T224_IV[14] | 0;\n protected Hl: number = T224_IV[15] | 0;\n\n constructor() {\n super(28);\n }\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<_SHA512_256> {\n protected Ah: number = T256_IV[0] | 0;\n protected Al: number = T256_IV[1] | 0;\n protected Bh: number = T256_IV[2] | 0;\n protected Bl: number = T256_IV[3] | 0;\n protected Ch: number = T256_IV[4] | 0;\n protected Cl: number = T256_IV[5] | 0;\n protected Dh: number = T256_IV[6] | 0;\n protected Dl: number = T256_IV[7] | 0;\n protected Eh: number = T256_IV[8] | 0;\n protected El: number = T256_IV[9] | 0;\n protected Fh: number = T256_IV[10] | 0;\n protected Fl: number = T256_IV[11] | 0;\n protected Gh: number = T256_IV[12] | 0;\n protected Gl: number = T256_IV[13] | 0;\n protected Hh: number = T256_IV[14] | 0;\n protected Hl: number = T256_IV[15] | 0;\n\n constructor() {\n super(32);\n }\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 * @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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA256(),\n /* @__PURE__ */ oidNist(0x01)\n);\n/**\n * SHA2-224 hash function from RFC 4634.\n * @param msg - message bytes to hash\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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA224(),\n /* @__PURE__ */ oidNist(0x04)\n);\n\n/**\n * SHA2-512 hash function from RFC 4634.\n * @param msg - message bytes to hash\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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512(),\n /* @__PURE__ */ oidNist(0x03)\n);\n/**\n * SHA2-384 hash function from RFC 4634.\n * @param msg - message bytes to hash\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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA384(),\n /* @__PURE__ */ oidNist(0x02)\n);\n\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 * @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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_256(),\n /* @__PURE__ */ oidNist(0x06)\n);\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 * @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: TRet> = /* @__PURE__ */ createHasher(\n () => new _SHA512_224(),\n /* @__PURE__ */ oidNist(0x05)\n);\n", "/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n/** Transforms values between two representations. */\nexport interface Coder {\n /**\n * Converts a value from the input representation to the output representation.\n * @param from - Value in the source representation.\n * @returns Converted value.\n */\n encode(from: F): T;\n /**\n * Converts a value from the output representation back to the input representation.\n * @param to - Value in the target representation.\n * @returns Converted value.\n */\n decode(to: T): F;\n}\n\n/** Coder that works with byte arrays and strings. */\nexport interface BytesCoder extends Coder {\n /**\n * Encodes bytes into a string representation.\n * @param data - Bytes to encode.\n * @returns Encoded string.\n */\n encode: (data: Uint8Array) => string;\n /**\n * Decodes a string representation into raw bytes.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n */\n decode: (str: string) => Uint8Array;\n}\n\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\n\nfunction isBytes(a: unknown): a is Uint8Array {\n // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases. The\n // fallback still requires a real ArrayBuffer view, so plain JSON-deserialized\n // `{ constructor: ... }` spoofing is rejected. `BYTES_PER_ELEMENT === 1` keeps the\n // fallback on byte-oriented views.\n return (\n 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}\n/** Asserts something is Uint8Array. */\nfunction abytes(b: TArg): void {\n if (!isBytes(b)) throw new TypeError('Uint8Array expected');\n}\n\nfunction isArrayOf(isString: boolean, arr: any[]) {\n if (!Array.isArray(arr)) return false;\n if (arr.length === 0) return true;\n if (isString) {\n return arr.every((item) => typeof item === 'string');\n } else {\n return arr.every((item) => Number.isSafeInteger(item));\n }\n}\n\nfunction afn(input: Function): input is Function {\n if (typeof input !== 'function') throw new TypeError('function expected');\n return true;\n}\n\nfunction astr(label: string, input: unknown): input is string {\n if (typeof input !== 'string') throw new TypeError(`${label}: string expected`);\n return true;\n}\n\nfunction anumber(n: number): void {\n if (typeof n !== 'number') throw new TypeError(`number expected, got ${typeof n}`);\n if (!Number.isSafeInteger(n)) throw new RangeError(`invalid integer: ${n}`);\n}\n\nfunction aArr(input: any[]) {\n if (!Array.isArray(input)) throw new TypeError('array expected');\n}\nfunction astrArr(label: string, input: string[]) {\n if (!isArrayOf(true, input)) throw new TypeError(`${label}: array of strings expected`);\n}\nfunction anumArr(label: string, input: number[]) {\n if (!isArrayOf(false, input)) throw new TypeError(`${label}: array of numbers expected`);\n}\n\n// TODO: some recusive type inference so it would check correct order of input/output inside rest?\n// like , , \ntype Chain = [Coder, ...Coder[]];\n// Extract info from Coder type\ntype Input = F extends Coder ? T : never;\ntype Output = F extends Coder ? T : never;\n// Generic function for arrays\ntype First = T extends [infer U, ...any[]] ? U : never;\ntype Last = T extends [...any[], infer U] ? U : never;\ntype Tail = T extends [any, ...infer U] ? U : never;\n\ntype AsChain> = {\n // C[K] = Coder, Input>\n [K in keyof C]: Coder, Input>;\n};\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction chain>(...args: T): Coder>, Output>> {\n const id = (a: any) => a;\n // Wrap call in closure so JIT can inline calls\n const wrap = (a: any, b: any) => (c: any) => a(b(c));\n // Construct chain of args[-1].encode(args[-2].encode([...]))\n const encode = args.map((x) => x.encode).reduceRight(wrap, id);\n // Construct chain of args[0].decode(args[1].decode(...))\n const decode = args.map((x) => x.decode).reduce(wrap, id);\n return { encode, decode };\n}\n\n/**\n * Encodes integer radix representation to array of strings using alphabet and back.\n * Could also be array of strings.\n * @__NO_SIDE_EFFECTS__\n */\nfunction alphabet(letters: string | string[]): Coder {\n // mapping 1 to \"b\"\n const lettersA = typeof letters === 'string' ? letters.split('') : letters;\n const len = lettersA.length;\n astrArr('alphabet', lettersA);\n\n // mapping \"b\" to 1\n const indexes = new Map(lettersA.map((l, i) => [l, i]));\n return {\n encode: (digits: number[]) => {\n aArr(digits);\n return digits.map((i) => {\n if (!Number.isSafeInteger(i) || i < 0 || i >= len)\n throw new Error(\n `alphabet.encode: digit index outside alphabet \"${i}\". Allowed: ${letters}`\n );\n return lettersA[i]!;\n });\n },\n decode: (input: string[]): number[] => {\n aArr(input);\n return input.map((letter) => {\n astr('alphabet.decode', letter);\n const i = indexes.get(letter);\n if (i === undefined) throw new Error(`Unknown letter: \"${letter}\". Allowed: ${letters}`);\n return i;\n });\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction join(separator = ''): Coder {\n astr('join', separator);\n // join('') is only lossless when each chunk is already unambiguous, such as single-symbol alphabets.\n // Multi-character tokens need a separator that cannot appear inside the chunks.\n return {\n encode: (from) => {\n astrArr('join.decode', from);\n return from.join(separator);\n },\n decode: (to) => {\n astr('join.decode', to);\n return to.split(separator);\n },\n };\n}\n\n/**\n * Pad strings array so it has integer number of bits\n * @__NO_SIDE_EFFECTS__\n */\nfunction padding(bits: number, chr = '='): Coder {\n anumber(bits);\n astr('padding', chr);\n return {\n encode(data: string[]): string[] {\n astrArr('padding.encode', data);\n // Mutates the intermediate token array in place while appending pad chars.\n // utils.padding callers that need to preserve their input should pass a copy.\n while ((data.length * bits) % 8) data.push(chr);\n return data;\n },\n decode(input: string[]): string[] {\n astrArr('padding.decode', input);\n let end = input.length;\n if ((end * bits) % 8)\n throw new Error('padding: invalid, string should have whole number of bytes');\n for (; end > 0 && input[end - 1] === chr; end--) {\n const last = end - 1;\n const byte = last * bits;\n if (byte % 8 === 0) throw new Error('padding: invalid, string has too much padding');\n }\n return input.slice(0, end);\n },\n };\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction normalize(fn: (val: T) => T): Coder {\n afn(fn);\n return { encode: (from: T) => from, decode: (to: T) => fn(to) };\n}\n\n/**\n * Slow: O(n^2) time complexity\n */\nfunction convertRadix(data: number[], from: number, to: number): number[] {\n // base 1 is impossible\n if (from < 2)\n throw new RangeError(`convertRadix: invalid from=${from}, base cannot be less than 2`);\n if (to < 2) throw new RangeError(`convertRadix: invalid to=${to}, base cannot be less than 2`);\n aArr(data);\n if (!data.length) return [];\n let pos = 0;\n const res = [];\n const digits = Array.from(data, (d) => {\n anumber(d);\n if (d < 0 || d >= from) throw new Error(`invalid integer: ${d}`);\n return d;\n });\n const dlen = digits.length;\n while (true) {\n let carry = 0;\n let done = true;\n for (let i = pos; i < dlen; i++) {\n const digit = digits[i]!;\n const fromCarry = from * carry;\n const digitBase = fromCarry + digit;\n if (\n !Number.isSafeInteger(digitBase) ||\n fromCarry / from !== carry ||\n digitBase - digit !== fromCarry\n ) {\n throw new Error('convertRadix: carry overflow');\n }\n const div = digitBase / to;\n carry = digitBase % to;\n const rounded = Math.floor(div);\n digits[i] = rounded;\n if (!Number.isSafeInteger(rounded) || rounded * to + carry !== digitBase)\n throw new Error('convertRadix: carry overflow');\n if (!done) continue;\n else if (!rounded) pos = i;\n else done = false;\n }\n res.push(carry);\n if (done) break;\n }\n // Preserve explicit leading zero digits so callers like base58 keep zero-prefix semantics.\n for (let i = 0; i < data.length - 1 && data[i] === 0; i++) res.push(0);\n return res.reverse();\n}\n\nconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));\n// Maximum carry width before the `pos` cycle repeats.\n// Residues advance in gcd(from, to) steps, so the largest pre-drain width is from + (to - gcd).\nconst radix2carry = /* @__NO_SIDE_EFFECTS__ */ (from: number, to: number) =>\n from + (to - gcd(from, to));\nconst powers: number[] = /* @__PURE__ */ (() => {\n let res = [];\n for (let i = 0; i < 40; i++) res.push(2 ** i);\n return res;\n})();\n/**\n * Implemented with numbers, because BigInt is 5x slower\n */\nfunction convertRadix2(data: number[], from: number, to: number, padding: boolean): number[] {\n aArr(data);\n if (from <= 0 || from > 32) throw new RangeError(`convertRadix2: wrong from=${from}`);\n if (to <= 0 || to > 32) throw new RangeError(`convertRadix2: wrong to=${to}`);\n if (radix2carry(from, to) > 32) {\n throw new Error(\n `convertRadix2: carry overflow from=${from} to=${to} carryBits=${radix2carry(from, to)}`\n );\n }\n let carry = 0;\n let pos = 0; // bitwise position in current element\n const max = powers[from]!;\n const mask = powers[to]! - 1;\n const res: number[] = [];\n for (const n of data) {\n anumber(n);\n if (n >= max) throw new Error(`convertRadix2: invalid data word=${n} from=${from}`);\n carry = (carry << from) | n;\n if (pos + from > 32) throw new Error(`convertRadix2: carry overflow pos=${pos} from=${from}`);\n pos += from;\n for (; pos >= to; pos -= to) res.push(((carry >> (pos - to)) & mask) >>> 0);\n const pow = powers[pos];\n if (pow === undefined) throw new Error('invalid carry');\n carry &= pow - 1; // clean carry, otherwise it will cause overflow\n }\n carry = (carry << (to - pos)) & mask;\n // Canonical decode paths reject leftover whole input words and non-zero pad bits.\n // For Bech32 5->8 regrouping, this is the \"4 bits or less, all zeroes\" tail rule.\n if (!padding && pos >= from) throw new Error('Excess padding');\n if (!padding && carry > 0) throw new Error(`Non-zero padding: ${carry}`);\n if (padding && pos > 0) res.push(carry >>> 0);\n return res;\n}\n\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix(num: number): TRet> {\n anumber(num);\n const _256 = 2 ** 8;\n // Base-range and carry-overflow checks live in convertRadix so encode/decode reject unsupported bases symmetrically.\n return {\n encode: (bytes: TArg) => {\n if (!isBytes(bytes)) throw new TypeError('radix.encode input should be Uint8Array');\n return convertRadix(Array.from(bytes), _256, num);\n },\n decode: (digits: number[]) => {\n anumArr('radix.decode', digits);\n return Uint8Array.from(convertRadix(digits, num, _256));\n },\n };\n}\n\n/**\n * If both bases are power of same number (like `2**8 <-> 2**64`),\n * there is a linear algorithm. For now we have implementation for power-of-two bases only.\n * @__NO_SIDE_EFFECTS__\n */\nfunction radix2(bits: number, revPadding = false): TRet> {\n anumber(bits);\n if (bits <= 0 || bits > 32) throw new RangeError('radix2: bits should be in (0..32]');\n if (radix2carry(8, bits) > 32 || radix2carry(bits, 8) > 32)\n throw new RangeError('radix2: carry overflow');\n // revPadding flips which direction allows a partial zero tail.\n // Default pads 8->bits and rejects extra bits on bits->8; `true` does the opposite.\n return {\n encode: (bytes: TArg) => {\n if (!isBytes(bytes)) throw new TypeError('radix2.encode input should be Uint8Array');\n return convertRadix2(Array.from(bytes), 8, bits, !revPadding);\n },\n decode: (digits: number[]) => {\n anumArr('radix2.decode', digits);\n return Uint8Array.from(convertRadix2(digits, bits, 8, revPadding));\n },\n };\n}\n\ntype ArgumentTypes = F extends (...args: infer A) => any ? A : never;\ntype BytesFn = (data: TArg) => TRet;\nfunction unsafeWrapper any>(fn: T) {\n afn(fn);\n return function (...args: ArgumentTypes): ReturnType | void {\n // Only for *Unsafe APIs that intentionally collapse validation failures to `undefined`.\n // Do not wrap code that needs to preserve exception details.\n try {\n return fn.apply(null, args);\n } catch (e) {}\n };\n}\n\nfunction checksum(len: number, fn: TArg): TRet> {\n anumber(len);\n // Reject degenerate zero-byte checksums up front so callers don't accidentally\n // build a no-op checksum stage.\n if (len <= 0) throw new RangeError(`checksum length must be positive: ${len}`);\n afn(fn);\n const _fn = fn as BytesFn;\n // Uses the first `len` bytes of fn(data) in both directions.\n // Current call sites rely on `len > 0` and checksum functions that return at least that many bytes.\n return {\n encode(data: TArg) {\n if (!isBytes(data)) throw new TypeError('checksum.encode: input should be Uint8Array');\n const sum = _fn(data).slice(0, len);\n const res = new Uint8Array(data.length + len);\n res.set(data);\n res.set(sum, data.length);\n return res;\n },\n decode(data: TArg) {\n if (!isBytes(data)) throw new TypeError('checksum.decode: input should be Uint8Array');\n const payload = data.slice(0, -len);\n const oldChecksum = data.slice(-len);\n const newChecksum = _fn(payload).slice(0, len);\n for (let i = 0; i < len; i++)\n if (newChecksum[i] !== oldChecksum[i]) throw new Error('Invalid checksum');\n return payload;\n },\n };\n}\n\n// prettier-ignore\n/**\n * Low-level building blocks used by the exported codecs.\n * @example\n * Build a radix-32 coder from the low-level helpers.\n * ```ts\n * import { utils } from '@scure/base';\n * utils.radix2(5).encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const utils: { alphabet: typeof alphabet; chain: typeof chain; checksum: typeof checksum; convertRadix: typeof convertRadix; convertRadix2: typeof convertRadix2; radix: typeof radix; radix2: typeof radix2; join: typeof join; padding: typeof padding; } = /* @__PURE__ */ Object.freeze({\n alphabet, chain, checksum, convertRadix, convertRadix2, radix, radix2, join, padding,\n});\n\n// RFC 4648 aka RFC 3548\n// ---------------------\n\n/**\n * base16 encoding from RFC 4648.\n * This codec uses RFC 4648 Table 5's uppercase alphabet directly.\n * RFC 4648 \u00A78 calls base16 \"case-insensitive hex encoding\", but we intentionally do not case-fold decode input here.\n * Use `hex` for case-insensitive hex decoding.\n * @example\n * ```js\n * base16.encode(Uint8Array.from([0x12, 0xab]));\n * // => '12AB'\n * ```\n */\nexport const base16: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(4), alphabet('0123456789ABCDEF'), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. Has padding.\n * RFC 4648 \u00A76 Table 3 uses uppercase letters, and RFC 4648 \u00A73.4 allows applications to choose\n * upper- or lowercase alphabets. We keep the published uppercase table and do not case-fold decode input.\n * Use `base32nopad` for unpadded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ===='\n * base32.decode('CKVQ====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding.\n * This variant inherits RFC 4648 base32's uppercase table and intentionally does not case-fold decode input.\n * Use `base32` for padded version.\n * Also check out `base32hex`, `base32hexnopad`, `base32crockford`.\n * @example\n * ```js\n * base32nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'CKVQ'\n * base32nopad.decode('CKVQ');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Padded. Compared to ordinary `base32`, slightly different alphabet.\n * RFC 4648 \u00A77 Table 4 uses uppercase letters, and we intentionally keep that table without case-folding decode input.\n * Use `base32hexnopad` for unpadded version.\n * @example\n * ```js\n * base32hex.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG===='\n * base32hex.decode('2ALG====');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), padding(5), join(''))\n);\n\n/**\n * base32 encoding from RFC 4648. No padding. Compared to ordinary `base32`, slightly different alphabet.\n * This variant inherits RFC 4648 base32hex's uppercase table and intentionally does not case-fold decode input.\n * Use `base32hex` for padded version.\n * @example\n * ```js\n * base32hexnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ALG'\n * base32hexnopad.decode('2ALG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32hexnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(radix2(5), alphabet('0123456789ABCDEFGHIJKLMNOPQRSTUV'), join(''))\n);\n/**\n * base32 encoding from RFC 4648. Doug Crockford's version.\n * See {@link https://www.crockford.com/base32.html | Douglas Crockford's Base32}.\n * @example\n * ```js\n * base32crockford.encode(Uint8Array.from([0x12, 0xab]));\n * // => '2ANG'\n * base32crockford.decode('2ANG');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base32crockford: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(5),\n alphabet('0123456789ABCDEFGHJKMNPQRSTVWXYZ'),\n join(''),\n normalize((s: string) => s.toUpperCase().replace(/O/g, '0').replace(/[IL]/g, '1'))\n )\n);\n\n// Built-in base64 conversion https://caniuse.com/mdn-javascript_builtins_uint8array_frombase64\n// Require both directions before taking the native fast path, so base64/base64url don't mix native and JS behavior.\n// prettier-ignore\nconst hasBase64Builtin: boolean = /* @__PURE__ */ (() =>\n typeof (Uint8Array as any).from([]).toBase64 === 'function' &&\n typeof (Uint8Array as any).fromBase64 === 'function')();\n\n// Native `Uint8Array.fromBase64()` accepts these ASCII whitespace chars.\n// Reject them first so the native base64 path still follows RFC 4648 \u00A73.3.\n// ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 SPACE\nconst ASCII_WHITESPACE = /[\\t\\n\\f\\r ]/;\n\nconst decodeBase64Builtin = (s: string, isUrl: boolean) => {\n astr('base64', s);\n const alphabet = isUrl ? 'base64url' : 'base64';\n // Per spec, .fromBase64 already throws on any other non-alphabet symbols except ASCII whitespace\n // And checking just for whitespace makes decoding about 3x faster than a full range check.\n // lastChunkHandling: 'strict' rejects loose tails and non-zero pad bits so native decoding stays canonical.\n if (s.length > 0 && ASCII_WHITESPACE.test(s)) throw new Error('invalid base64');\n return (Uint8Array as any).fromBase64(s, { alphabet, lastChunkHandling: 'strict' });\n};\n\n/**\n * base64 from RFC 4648. Padded.\n * Use `base64nopad` for unpadded version.\n * Also check out `base64url`, `base64urlnopad`.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64(); },\n decode(s) { return decodeBase64Builtin(s, false); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n padding(6),\n join('')\n));\n/**\n * base64 from RFC 4648. No padding.\n * Use `base64` for padded version.\n * @example\n * ```js\n * base64nopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64nopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64nopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'),\n join('')\n )\n);\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. Padded.\n * Use `base64urlnopad` for unpadded version.\n * Falls back to built-in function, when available.\n * @example\n * ```js\n * base64url.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs='\n * base64url.decode('Eqs=');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\n// prettier-ignore\nexport const base64url: BytesCoder = /* @__PURE__ */ Object.freeze(hasBase64Builtin ? {\n encode(b) { abytes(b); return (b as any).toBase64({ alphabet: 'base64url' }); },\n decode(s) { return decodeBase64Builtin(s, true); },\n} : chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n padding(6),\n join('')\n));\n\n/**\n * base64 from RFC 4648, using URL-safe alphabet. No padding.\n * Use `base64url` for padded version.\n * @example\n * ```js\n * base64urlnopad.encode(Uint8Array.from([0x12, 0xab]));\n * // => 'Eqs'\n * base64urlnopad.decode('Eqs');\n * // => Uint8Array.from([0x12, 0xab])\n * ```\n */\nexport const base64urlnopad: BytesCoder = /* @__PURE__ */ Object.freeze(\n chain(\n radix2(6),\n alphabet('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'),\n join('')\n )\n);\n\n// base58 code\n// -----------\nconst genBase58 = /* @__NO_SIDE_EFFECTS__ */ (abc: string) =>\n chain(radix(58), alphabet(abc), join(''));\n\n/**\n * base58: base64 without ambigous characters +, /, 0, O, I, l.\n * Quadratic (O(n^2)) - so, can't be used on large inputs.\n * @example\n * ```js\n * const text = base58.encode(Uint8Array.from([0, 1, 2]));\n * base58.decode(text);\n * // => Uint8Array.from([0, 1, 2])\n * ```\n */\nexport const base58: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz')\n);\n/**\n * base58: flickr version. Check out `base58`.\n * @example\n * Round-trip bytes with the Flickr alphabet.\n * ```ts\n * const text = base58flickr.encode(Uint8Array.from([0, 1, 2]));\n * base58flickr.decode(text);\n * ```\n */\nexport const base58flickr: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ')\n);\n/**\n * base58: XRP version. Check out `base58`.\n * @example\n * Round-trip bytes with the XRP alphabet.\n * ```ts\n * const text = base58xrp.encode(Uint8Array.from([0, 1, 2]));\n * base58xrp.decode(text);\n * ```\n */\nexport const base58xrp: BytesCoder = /* @__PURE__ */ Object.freeze(\n genBase58('rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz')\n);\n\n// Data len (index) -> encoded block len.\n// Monero pads each 1..8-byte block to this fixed base58 width so decode can recover the tail length.\nconst XMR_BLOCK_LEN = [0, 2, 3, 5, 6, 7, 9, 10, 11];\n\n/**\n * base58: XMR version. Check out `base58`.\n * Done in 8-byte blocks (which equals 11 chars in decoding). Last (non-full) block padded with '1' to size in XMR_BLOCK_LEN.\n * Block encoding significantly reduces quadratic complexity of base58.\n * @example\n * Round-trip bytes with the Monero block codec.\n * ```ts\n * const text = base58xmr.encode(Uint8Array.from([0, 1, 2]));\n * base58xmr.decode(text);\n * ```\n */\nexport const base58xmr: BytesCoder = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i += 8) {\n const block = data.subarray(i, i + 8);\n res += base58.encode(block).padStart(XMR_BLOCK_LEN[block.length]!, '1');\n }\n return res;\n },\n decode(str: string) {\n astr('base58xmr.decode', str);\n let res: number[] = [];\n for (let i = 0; i < str.length; i += 11) {\n const slice = str.slice(i, i + 11);\n const blockLen = XMR_BLOCK_LEN.indexOf(slice.length);\n const block = base58.decode(slice);\n for (let j = 0; j < block.length - blockLen; j++) {\n if (block[j] !== 0) throw new Error('base58xmr: wrong padding');\n }\n res = res.concat(Array.from(block.slice(block.length - blockLen)));\n }\n return Uint8Array.from(res);\n },\n});\n\n/**\n * Method, which creates base58check encoder.\n * Requires function, calculating sha256.\n * Callers must include any version bytes in `data`; this helper only applies the\n * 4-byte double-SHA256 checksum used by Bitcoin Base58Check.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Create a base58check codec from a SHA-256 implementation.\n * ```ts\n * import { createBase58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = createBase58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const createBase58check = (sha256: TArg): BytesCoder => {\n // Validate the hash function at construction time so wrong inputs fail before returning a coder.\n afn(sha256);\n const _sha256 = sha256 as BytesFn;\n return chain(\n checksum(4, (data: TArg) => _sha256(_sha256(data))),\n base58\n );\n};\n\n/**\n * Use `createBase58check` instead.\n * @deprecated Use {@link createBase58check} instead.\n * Callers must include any version bytes in `data`; this alias keeps the same\n * 4-byte double-SHA256 checksum behavior as `createBase58check`.\n * @param sha256 - Function used to calculate the checksum hash.\n * @returns base58check codec using 4 checksum bytes.\n * @example\n * Create a base58check codec with the deprecated alias.\n * ```ts\n * import { base58check } from '@scure/base';\n * import { sha256 } from '@noble/hashes/sha2.js';\n * const coder = base58check(sha256);\n * coder.encode(Uint8Array.from([1, 2, 3]));\n * ```\n */\nexport const base58check: (sha256: TArg) => BytesCoder = createBase58check;\n\n// Bech32 code\n// -----------\n/** Result of bech32 decoding. */\nexport interface Bech32Decoded {\n /** Human-readable bech32 prefix. */\n prefix: Prefix;\n /** Decoded 5-bit word payload. */\n words: number[];\n}\n/** Result of bech32 decoding with original bytes attached. */\nexport interface Bech32DecodedWithArray {\n /** Human-readable bech32 prefix. */\n prefix: Prefix;\n /** Decoded 5-bit word payload. */\n words: number[];\n /** Decoded payload converted back into raw bytes. */\n bytes: Uint8Array;\n}\n\n// BIP 173 character table: data values 0..31 map to `qpzry9x8gf2tvdw0s3jn54khce6mua7l`.\nconst BECH_ALPHABET: Coder = chain(\n alphabet('qpzry9x8gf2tvdw0s3jn54khce6mua7l'),\n join('')\n);\n\n// BIP 173 `bech32_polymod` GEN coefficients.\nconst POLYMOD_GENERATORS = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];\n// BIP 173 step split: this applies the polymod state transition before callers xor in the next 5-bit value.\nfunction bech32Polymod(pre: number): number {\n const b = pre >> 25;\n let chk = (pre & 0x1ffffff) << 5;\n for (let i = 0; i < POLYMOD_GENERATORS.length; i++) {\n if (((b >> i) & 1) === 1) chk ^= POLYMOD_GENERATORS[i]!;\n }\n return chk;\n}\n\nfunction bechChecksum(prefix: string, words: number[], encodingConst = 1): string {\n const len = prefix.length;\n let chk = 1;\n for (let i = 0; i < len; i++) {\n const c = prefix.charCodeAt(i);\n if (c < 33 || c > 126) throw new Error(`Invalid prefix (${prefix})`);\n chk = bech32Polymod(chk) ^ (c >> 5);\n }\n chk = bech32Polymod(chk);\n for (let i = 0; i < len; i++) chk = bech32Polymod(chk) ^ (prefix.charCodeAt(i) & 0x1f);\n for (let v of words) chk = bech32Polymod(chk) ^ v;\n for (let i = 0; i < 6; i++) chk = bech32Polymod(chk);\n // BIP 173/BIP 350: xor the final checksum constant, then emit the 30-bit state as six 5-bit symbols.\n chk ^= encodingConst;\n return BECH_ALPHABET.encode(convertRadix2([chk % powers[30]!], 30, 5, false));\n}\n\n/** bech32 codec surface. */\nexport interface Bech32 {\n /**\n * Encodes a human-readable prefix and 5-bit words into a bech32 string.\n * @param prefix - Human-readable prefix.\n * @param words - 5-bit words or raw bytes.\n * @param limit - Maximum accepted output length, or `false` to disable the limit.\n * @returns Encoded bech32 string.\n */\n encode(\n prefix: Prefix,\n words: number[] | Uint8Array,\n limit?: number | false\n ): `${Lowercase}1${string}`;\n /**\n * Decodes a bech32 string into prefix and words.\n * @param str - Encoded bech32 string.\n * @param limit - Maximum accepted input length, or `false` to disable the limit.\n * @returns Decoded prefix and 5-bit words.\n */\n decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n decode(str: string, limit?: number | false): Bech32Decoded;\n /**\n * Encodes raw bytes by first converting them to 5-bit words.\n * @param prefix - Human-readable prefix.\n * @param bytes - Raw bytes to encode.\n * @returns Encoded bech32 string.\n */\n encodeFromBytes(prefix: string, bytes: Uint8Array): string;\n /**\n * Decodes a bech32 string and converts the payload back into bytes.\n * @param str - Encoded bech32 string.\n * @returns Decoded prefix, words, and bytes.\n */\n decodeToBytes(str: string): Bech32DecodedWithArray;\n /**\n * Decodes a bech32 string, returning `undefined` instead of throwing on invalid input.\n * @param str - Encoded bech32 string.\n * @param limit - Maximum accepted input length, or `false` to disable the limit.\n * @returns Decoded prefix and words, or `undefined` for invalid input.\n */\n decodeUnsafe(str: string, limit?: number | false): void | Bech32Decoded;\n /**\n * Converts 5-bit words back into raw bytes.\n * @param to - 5-bit words to decode.\n * @returns Decoded bytes.\n */\n fromWords(to: number[]): Uint8Array;\n /**\n * Converts 5-bit words back into raw bytes, returning `undefined` instead of throwing.\n * @param to - 5-bit words to decode.\n * @returns Decoded bytes, or `undefined` for invalid input.\n */\n fromWordsUnsafe(to: number[]): void | Uint8Array;\n /**\n * Converts raw bytes into 5-bit words for bech32 encoding.\n * @param from - Raw bytes to convert.\n * @returns 5-bit words.\n */\n toWords(from: Uint8Array): number[];\n}\n/**\n * @__NO_SIDE_EFFECTS__\n */\nfunction genBech32(encoding: 'bech32' | 'bech32m'): TRet {\n // BIP 173 uses final xor constant 1; BIP 350 swaps in 0x2bc830a3 for Bech32m.\n const ENCODING_CONST = encoding === 'bech32' ? 1 : 0x2bc830a3;\n const _words = radix2(5);\n const fromWords = _words.decode;\n const toWords = _words.encode;\n const fromWordsUnsafe = unsafeWrapper(fromWords);\n\n function encode(\n prefix: Prefix,\n words: TArg,\n limit: number | false = 90\n ): `${Lowercase}1${string}` {\n astr('bech32.encode prefix', prefix);\n if (isBytes(words)) words = Array.from(words);\n anumArr('bech32.encode', words);\n const plen = prefix.length;\n if (plen === 0) throw new TypeError(`Invalid prefix length ${plen}`);\n // Total output is hrp + `1` separator + payload words + 6 checksum chars.\n const actualLength = plen + 7 + words.length;\n if (limit !== false && actualLength > limit)\n throw new TypeError(`Length ${actualLength} exceeds limit ${limit}`);\n const lowered = prefix.toLowerCase();\n const sum = bechChecksum(lowered, words, ENCODING_CONST);\n return `${lowered}1${BECH_ALPHABET.encode(words)}${sum}` as `${Lowercase}1${string}`;\n }\n\n function decode(\n str: `${Prefix}1${string}`,\n limit?: number | false\n ): Bech32Decoded;\n function decode(str: string, limit?: number | false): Bech32Decoded;\n function decode(str: string, limit: number | false = 90): Bech32Decoded {\n astr('bech32.decode input', str);\n const slen = str.length;\n // Minimum length is 1-char hrp + `1` separator + 6-char checksum.\n if (slen < 8 || (limit !== false && slen > limit))\n throw new TypeError(`invalid string length: ${slen} (${str}). Expected (8..${limit})`);\n // don't allow mixed case\n const lowered = str.toLowerCase();\n if (str !== lowered && str !== str.toUpperCase())\n throw new Error(`String must be lowercase or uppercase`);\n const sepIndex = lowered.lastIndexOf('1');\n if (sepIndex === 0 || sepIndex === -1)\n throw new Error(`Letter \"1\" must be present between prefix and data only`);\n const prefix = lowered.slice(0, sepIndex);\n const data = lowered.slice(sepIndex + 1);\n if (data.length < 6) throw new Error('Data must be at least 6 characters long');\n const words = BECH_ALPHABET.decode(data).slice(0, -6);\n const sum = bechChecksum(prefix, words, ENCODING_CONST);\n if (!data.endsWith(sum)) throw new Error(`Invalid checksum in ${str}: expected \"${sum}\"`);\n return { prefix, words };\n }\n\n const decodeUnsafe = unsafeWrapper(decode);\n\n function decodeToBytes(str: string): TRet {\n // Keep the byte helper unbounded; callers that need the default BIP 173 length cap should use decode(str).\n const { prefix, words } = decode(str, false);\n return {\n prefix,\n words,\n bytes: fromWords(words) as TRet,\n } as TRet;\n }\n\n function encodeFromBytes(prefix: string, bytes: TArg) {\n // Keep the convenience wrapper on encode()'s default 90-char cap; custom limits should call encode(prefix, toWords(bytes), limit).\n return encode(prefix, toWords(bytes));\n }\n\n return {\n encode,\n decode,\n encodeFromBytes,\n decodeToBytes,\n decodeUnsafe,\n fromWords,\n fromWordsUnsafe,\n toWords,\n };\n}\n\n/**\n * bech32 from BIP 173. Operates on words.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them, then decode back.\n * ```ts\n * const words = bech32.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32.encode('bc', words);\n * bech32.decode(text);\n * ```\n */\nexport const bech32: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32'));\n\n/**\n * bech32m from BIP 350. Operates on words.\n * It was to mitigate `bech32` weaknesses.\n * For high-level helpers, check out {@link https://github.com/paulmillr/scure-btc-signer | scure-btc-signer}.\n * @example\n * Convert bytes to words, encode them with bech32m, then decode back.\n * ```ts\n * const words = bech32m.toWords(Uint8Array.from([1, 2, 3]));\n * const text = bech32m.encode('bc', words);\n * bech32m.decode(text);\n * ```\n */\nexport const bech32m: TRet = /* @__PURE__ */ Object.freeze(genBech32('bech32m'));\n\ndeclare const TextEncoder: any;\ndeclare const TextDecoder: any;\n\n/**\n * ASCII-to-byte decoder. Rejects non-ASCII text and bytes instead of doing UTF-8 replacement.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and `decode(string)` returns bytes.\n * @example\n * ```js\n * const b = ascii.decode(\"ABC\"); // => new Uint8Array([ 65, 66, 67 ])\n * const str = ascii.encode(b); // \"ABC\"\n * ```\n */\nexport const ascii: TRet = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; i++) {\n const byte = data[i]!;\n // ASCII is 7-bit; reject bytes outside 0x00..0x7f instead of silently widening to\n // Latin-1/UTF-8.\n if (byte > 127) throw new RangeError(`bytes contain non-ASCII byte ${byte} at position ${i}`);\n res += String.fromCharCode(byte);\n }\n return res;\n },\n decode(str: string) {\n if (typeof str !== 'string') throw new TypeError('ascii string expected, got ' + typeof str);\n const res = new Uint8Array(str.length);\n for (let i = 0; i < str.length; i++) {\n // Indexed access is much faster than Uint8Array.from(str, mapFn) here and keeps\n // exact error positions.\n const charCode = str.charCodeAt(i);\n if (charCode > 127) {\n throw new RangeError(\n `string contains non-ASCII character \"${str[i]}\" with code ${charCode} at position ${i}`\n );\n }\n res[i] = charCode;\n }\n return res;\n },\n});\n\nconst _isWellFormedShim = (str: string): boolean => {\n // encodeURI rejects malformed UTF-16, giving a compact fallback that matches native\n // isWellFormed on our tests/fuzz corpus.\n try {\n return encodeURI(str) !== null;\n } catch {\n return false;\n }\n};\nconst _isWellFormed: (str: string) => boolean = /* @__PURE__ */ (() =>\n // Pick the native check once so utf8.decode doesn't re-probe String.prototype on every call.\n typeof ('' as any).isWellFormed === 'function'\n ? (str) => (str as any).isWellFormed()\n : _isWellFormedShim)();\n// This fallback stays small because strict UTF-8 only needs fatal decoding plus well-formed\n// UTF-16 checks, not the replacement, streaming, or legacy-encoding behavior of full platform\n// text codecs.\nconst utf8Fallback: BytesCoder = /* @__PURE__ */ Object.freeze({\n encode(data: TArg) {\n abytes(data);\n let res = '';\n for (let i = 0; i < data.length; ) {\n const a = data[i++]!;\n if (a < 0b1000_0000) {\n res += String.fromCharCode(a);\n continue;\n }\n if (a < 0b1100_0010 || i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const b = data[i++]!;\n if ((b & 0b1100_0000) !== 0b1000_0000) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n let cp = ((a & 0b0001_1111) << 6) | (b & 0b0011_1111);\n if (a >= 0b1110_0000) {\n if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const c = data[i++]!;\n if (\n (c & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1110_0000 && b < 0b1010_0000) ||\n (a === 0xed && b >= 0b1010_0000)\n )\n throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n cp = ((a & 0b0000_1111) << 12) | ((b & 0b0011_1111) << 6) | (c & 0b0011_1111);\n if (a >= 0b1111_0000) {\n if (i >= data.length) throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n const d = data[i++]!;\n if (\n a > 0b1111_0100 ||\n (d & 0b1100_0000) !== 0b1000_0000 ||\n (a === 0b1111_0000 && b < 0b1001_0000) ||\n (a === 0b1111_0100 && b >= 0b1001_0000)\n )\n throw new TypeError(`invalid utf8 at byte ${i - 1}`);\n cp =\n ((a & 7) << 18) |\n ((b & 0b0011_1111) << 12) |\n ((c & 0b0011_1111) << 6) |\n (d & 0b0011_1111);\n }\n }\n if (cp < 0x10000) res += String.fromCharCode(cp);\n else {\n cp -= 0x10000;\n res += String.fromCharCode((cp >> 10) + 0xd800, (cp & 0x3ff) + 0xdc00);\n }\n }\n return res;\n },\n decode(str: string) {\n astr('utf8', str);\n if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n // Direct Uint8Array writes are much faster than number[] + Uint8Array.from on Hermes and\n // large Node inputs.\n const res = new Uint8Array(str.length * 3);\n let pos = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 0b1000_0000) {\n res[pos++] = c;\n continue;\n }\n if (c >= 0xd800 && c <= 0xdfff) {\n const d = str.charCodeAt(++i);\n c = 0x10000 + ((c - 0xd800) << 10) + d - 0xdc00;\n }\n if (c >= 0x10000) {\n res[pos++] = (c >> 18) | 0b1111_0000;\n res[pos++] = ((c >> 12) & 0b0011_1111) | 0b1000_0000;\n } else if (c >= 0x800) res[pos++] = (c >> 12) | 0b1110_0000;\n else res[pos++] = (c >> 6) | 0b1100_0000;\n if (c >= 0x800) res[pos++] = ((c >> 6) & 0b0011_1111) | 0b1000_0000;\n res[pos++] = (c & 0b0011_1111) | 0b1000_0000;\n }\n return res.subarray(0, pos);\n },\n});\n\n/**\n * Strict UTF-8-to-byte decoder. Uses built-in TextDecoder / TextEncoder when available.\n * Method names follow `BytesCoder`, so `encode(bytes)` returns a string and\n * `decode(string)` returns bytes.\n * `encode(bytes)` requires Uint8Array input, preserves an explicit leading BOM, and\n * throws on invalid UTF-8 bytes.\n * `decode(string)` requires a primitive string and throws on malformed UTF-16 strings with\n * lone surrogates.\n * @example\n * ```js\n * const b = utf8.decode(\"hey\"); // => new Uint8Array([ 104, 101, 121 ])\n * const str = utf8.encode(b); // \"hey\"\n * ```\n */\nexport const utf8: BytesCoder = /* @__PURE__ */ (() => {\n let _utf8Encoder: any;\n let _utf8Decoder: any;\n const utf8Builtin: BytesCoder = {\n // ignoreBOM preserves an explicit leading U+FEFF;\n // fatal rejects invalid UTF-8 bytes instead of replacing them.\n encode(data) {\n abytes(data);\n return (\n _utf8Decoder || (_utf8Decoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }))\n ).decode(data);\n },\n decode(str) {\n astr('utf8', str);\n if (!_isWellFormed(str)) throw new TypeError('utf8 expected well-formed string');\n return (_utf8Encoder || (_utf8Encoder = new TextEncoder())).encode(str);\n },\n };\n return Object.freeze({\n // Select each direction once at module init, since\n // TextEncoder and TextDecoder can exist independently.\n encode: typeof TextDecoder === 'function' ? utf8Builtin.encode : utf8Fallback.encode,\n decode: typeof TextEncoder === 'function' ? utf8Builtin.decode : utf8Fallback.decode,\n });\n})();\n// Keep fallback parity probes behind a test-only export until runtime fallback behavior is decided.\nexport const __TESTS: {\n utf8Fallback: BytesCoder;\n _isWellFormedShim: (str: string) => boolean;\n} = /* @__PURE__ */ Object.freeze({\n utf8Fallback: utf8Fallback,\n _isWellFormedShim: _isWellFormedShim,\n});\n\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\n// prettier-ignore\nconst hasHexBuiltin: boolean = /* @__PURE__ */ (() =>\n // Require both directions before enabling the native hex path so encode/decode stay symmetric.\n typeof (Uint8Array as any).from([]).toHex === 'function' &&\n typeof (Uint8Array as any).fromHex === 'function')();\n// prettier-ignore\nconst hexBuiltin: BytesCoder = {\n // Keep local type guards so the native path preserves library-level input errors.\n // Native toHex emits lowercase hex, matching the fallback alphabet and Node's hex strings.\n encode(data) { abytes(data); return (data as any).toHex(); },\n // Native fromHex accepts either hex case and rejects odd-length / non-hex syntax.\n decode(s) { astr('hex', s); return (Uint8Array as any).fromHex(s); },\n};\n/**\n * hex string decoder. Uses built-in function, when available.\n * Lowercase codec; unlike `base16`, this variant accepts either hex case and emits lowercase.\n * @example\n * ```js\n * const b = hex.decode(\"0102ff\"); // => new Uint8Array([ 1, 2, 255 ])\n * const str = hex.encode(b); // \"0102ff\"\n * ```\n */\nexport const hex: BytesCoder = /* @__PURE__ */ Object.freeze(\n hasHexBuiltin\n ? hexBuiltin\n : chain(\n radix2(4),\n alphabet('0123456789abcdef'),\n join(''),\n normalize((s: string) => {\n if (typeof s !== 'string' || s.length % 2 !== 0)\n throw new TypeError(\n `hex.decode: expected string, got ${typeof s} with length ${s.length}`\n );\n return s.toLowerCase();\n })\n )\n);\n\n/** Built-in codecs exposed through the deprecated string conversion helpers. */\nexport type SomeCoders = {\n /** UTF-8 string codec. */\n utf8: BytesCoder;\n /** Hex codec. */\n hex: BytesCoder;\n /** Uppercase RFC 4648 base16 codec. */\n base16: BytesCoder;\n /** RFC 4648 base32 codec with padding. */\n base32: BytesCoder;\n /** RFC 4648 base64 codec with padding. */\n base64: BytesCoder;\n /** URL-safe base64 codec without `+` or `/`. */\n base64url: BytesCoder;\n /** Bitcoin-style base58 codec. */\n base58: BytesCoder;\n /** Monero-style base58 codec. */\n base58xmr: BytesCoder;\n};\n// prettier-ignore\n// Keep this registry aligned with CoderType/coderTypeError; only byte<->string codecs belong here.\nconst CODERS: SomeCoders = {\n utf8, hex, base16, base32, base64, base64url, base58, base58xmr\n};\ntype CoderType = keyof SomeCoders;\nconst coderTypeError =\n 'Invalid encoding type. Available types: utf8, hex, base16, base32, base64, base64url, base58, base58xmr';\n\n/**\n * Encodes bytes with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.encode(bytes)`.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * bytesToString('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const bytesToString = (type: CoderType, bytes: TArg): string => {\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (!isBytes(bytes)) throw new TypeError('bytesToString() expects Uint8Array');\n return CODERS[type].encode(bytes);\n};\n\n/**\n * Alias for `bytesToString`.\n * @deprecated Use {@link bytesToString} or the codec directly instead.\n * @param type - Codec name.\n * @param bytes - Bytes to encode.\n * @returns Encoded string.\n * @example\n * ```ts\n * str('hex', Uint8Array.from([1, 2, 255]));\n * ```\n */\nexport const str: (type: CoderType, bytes: TArg) => string = bytesToString; // as in python, but for bytes only\n\n/**\n * Decodes a string with one of the built-in codecs.\n * @deprecated Use the codec directly, for example `hex.decode(text)`.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * ```ts\n * stringToBytes('hex', '0102ff');\n * ```\n */\nexport const stringToBytes = (type: CoderType, str: string): TRet => {\n // Match bytesToString's selector validation so hostile `toString()` coercions can't leak custom errors.\n if (typeof type !== 'string' || !CODERS.hasOwnProperty(type)) throw new TypeError(coderTypeError);\n if (typeof str !== 'string') throw new TypeError('stringToBytes() expects string');\n return CODERS[type].decode(str) as TRet;\n};\n/**\n * Alias for `stringToBytes`.\n * @deprecated Use {@link stringToBytes} or the codec directly instead.\n * @param type - Codec name.\n * @param str - Encoded string.\n * @returns Decoded bytes.\n * @example\n * ```ts\n * bytes('hex', '0102ff');\n * ```\n */\nexport const bytes: (type: CoderType, str: string) => TRet = stringToBytes;\n", "/*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { pbkdf2, pbkdf2Async } from '@noble/hashes/pbkdf2.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, anumber, randomBytes } from '@noble/hashes/utils.js';\nimport { pbkdf2 as pbkdf2web, sha512 as sha512web } from '@noble/hashes/webcrypto.js';\nimport { utils as baseUtils } from '@scure/base';\n// Japanese wordlist\n// The canonical BIP-39 Japanese wordlist starts with \u3042\u3044\u3053\u304F\u3057\u3093.\n// Use that sentinel so generated phrases use U+3000 ideographic spaces.\nconst isJapanese = (wordlist) => wordlist[0] === '\\u3042\\u3044\\u3053\\u304f\\u3057\\u3093';\n// Normalization replaces equivalent sequences of characters\n// so that any two texts that are equivalent will be reduced\n// to the same sequence of code points, called the normal form of the original text.\n// https://tonsky.me/blog/unicode/#why-is-a----\n// BIP-39 requires UTF-8 NFKD for localized wordlists and mnemonic sentences.\n// It also applies NFKD to the \"mnemonic\" + passphrase salt.\nfunction nfkd(str) {\n if (typeof str !== 'string')\n throw new TypeError('invalid mnemonic type: ' + typeof str);\n return str.normalize('NFKD');\n}\n// BIP-39 mnemonics are consumed in NFKD form.\n// They must contain 12, 15, 18, 21, or 24 words before checksum validation.\nfunction normalize(str) {\n const norm = nfkd(str);\n const words = norm.split(' ');\n if (![12, 15, 18, 21, 24].includes(words.length))\n throw new Error('Invalid mnemonic');\n return { nfkd: norm, words };\n}\n// BIP-39 entropy payloads are 128-256 bits in 32-bit increments, i.e. 16/20/24/28/32 bytes.\nfunction aentropy(ent) {\n abytes(ent);\n if (![16, 20, 24, 28, 32].includes(ent.length))\n throw new RangeError('invalid entropy length');\n}\n/**\n * Generate x random words. Uses Cryptographically-Secure Random Number Generator.\n * @param wordlist - Imported wordlist for a specific language.\n * @param strength - Mnemonic strength, from 128 to 256 bits.\n * @returns 12-24 word mnemonic phrase.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Generate a new English mnemonic.\n * ```ts\n * import { generateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnemonic = generateMnemonic(wordlist, 128);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function generateMnemonic(wordlist, strength = 128) {\n anumber(strength);\n if (strength % 32 !== 0 || strength > 256)\n throw new RangeError('Invalid entropy');\n return entropyToMnemonic(randomBytes(strength / 8), wordlist);\n}\nconst calcChecksum = (entropy) => {\n // Checksum is ent.length/4 bits long\n const bitsLeft = 8 - entropy.length / 4;\n // Zero rightmost \"bitsLeft\" bits in byte\n // For example: bitsLeft=4 val=10111101 -> 10110000\n return new Uint8Array([(sha256(entropy)[0] >> bitsLeft) << bitsLeft]);\n};\nfunction getCoder(wordlist) {\n if (!Array.isArray(wordlist) || wordlist.length !== 2048 || typeof wordlist[0] !== 'string')\n throw new TypeError('Wordlist: expected array of 2048 strings');\n wordlist.forEach((i) => {\n if (typeof i !== 'string')\n throw new TypeError('wordlist: non-string element: ' + i);\n });\n // BIP-39 appends checksum bits to entropy.\n // It then splits the bitstream into 11-bit indexes for a 2048-word list.\n return baseUtils.chain(baseUtils.checksum(1, calcChecksum), baseUtils.radix2(11, true), baseUtils.alphabet(wordlist));\n}\n/**\n * Reversible: Converts mnemonic string to raw entropy in form of byte array.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns Raw entropy bytes.\n * @throws If the mnemonic shape or checksum is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Decode a mnemonic back into its original entropy bytes.\n * ```ts\n * import { mnemonicToEntropy } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const entropy = mnemonicToEntropy(mnem, wordlist);\n * // Produces the original 16-byte entropy payload.\n * new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ])\n * ```\n */\nexport function mnemonicToEntropy(mnemonic, wordlist) {\n const { words } = normalize(mnemonic);\n const entropy = getCoder(wordlist).decode(words);\n aentropy(entropy);\n return entropy;\n}\n/**\n * Reversible: Converts raw entropy in form of byte array to mnemonic string.\n * @param entropy - Byte array.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns 12-24 words.\n * @throws On wrong argument types. {@link TypeError}\n * @throws On wrong argument ranges or values. {@link RangeError}\n * @example\n * Convert raw entropy into an English mnemonic.\n * ```ts\n * import { entropyToMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ent = new Uint8Array([\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f,\n * 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f, 0x7f\n * ]);\n * const mnemonic = entropyToMnemonic(ent, wordlist);\n * // 'legal winner thank year wave sausage worth useful legal winner thank yellow'\n * ```\n */\nexport function entropyToMnemonic(entropy, wordlist) {\n aentropy(entropy);\n const words = getCoder(wordlist).encode(entropy);\n return words.join(isJapanese(wordlist) ? '\\u3000' : ' ');\n}\n/**\n * Validates mnemonic for being 12-24 words contained in `wordlist`.\n * @param mnemonic - 12-24 words.\n * @param wordlist - Imported wordlist for a specific language.\n * @returns `true` when mnemonic checksum and words are valid.\n * @example\n * Validate one English mnemonic.\n * ```ts\n * import { validateMnemonic } from '@scure/bip39';\n * import { wordlist } from '@scure/bip39/wordlists/english.js';\n * const ok = validateMnemonic(\n * 'legal winner thank year wave sausage worth useful legal winner thank yellow',\n * wordlist\n * );\n * // => true\n * ```\n */\nexport function validateMnemonic(mnemonic, wordlist) {\n try {\n mnemonicToEntropy(mnemonic, wordlist);\n }\n catch (e) {\n return false;\n }\n return true;\n}\n// BIP-39 salts PBKDF2 with the UTF-8 NFKD string \"mnemonic\" + passphrase.\nconst psalt = (passphrase) => nfkd('mnemonic' + passphrase);\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the async PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeed(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\n// BIP-39 seed derivation is independent from mnemonic generation.\n// These helpers normalize the phrase but do not verify checksum or wordlist membership.\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n return pbkdf2Async(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed from a mnemonic with the sync PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = mnemonicToSeedSync(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedSync(mnemonic, passphrase = '') {\n return pbkdf2(sha512, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n/**\n * Uses native, built-in functionality, provided by globalThis.crypto.\n * Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password.\n * @param mnemonic - 12-24 words.\n * @param passphrase - String that will additionally protect the key.\n * @returns 64 bytes of key data.\n * @throws If the mnemonic shape is invalid. {@link Error}\n * @throws On wrong argument types. {@link TypeError}\n * @example\n * Derive a seed with the native WebCrypto PBKDF2 helper.\n * ```ts\n * const mnem = 'legal winner thank year wave sausage worth useful legal winner thank yellow';\n * const seed = await mnemonicToSeedWebcrypto(mnem, 'password');\n * // => new Uint8Array([...64 bytes])\n * ```\n */\nexport function mnemonicToSeedWebcrypto(mnemonic, passphrase = '') {\n return pbkdf2web(sha512web, normalize(mnemonic).nfkd, psalt(passphrase), {\n c: 2048,\n dkLen: 64,\n });\n}\n//# sourceMappingURL=index.js.map", "/** English BIP39 wordlist. */\nexport const wordlist = /* @__PURE__ */ Object.freeze(`abandon\nability\nable\nabout\nabove\nabsent\nabsorb\nabstract\nabsurd\nabuse\naccess\naccident\naccount\naccuse\nachieve\nacid\nacoustic\nacquire\nacross\nact\naction\nactor\nactress\nactual\nadapt\nadd\naddict\naddress\nadjust\nadmit\nadult\nadvance\nadvice\naerobic\naffair\nafford\nafraid\nagain\nage\nagent\nagree\nahead\naim\nair\nairport\naisle\nalarm\nalbum\nalcohol\nalert\nalien\nall\nalley\nallow\nalmost\nalone\nalpha\nalready\nalso\nalter\nalways\namateur\namazing\namong\namount\namused\nanalyst\nanchor\nancient\nanger\nangle\nangry\nanimal\nankle\nannounce\nannual\nanother\nanswer\nantenna\nantique\nanxiety\nany\napart\napology\nappear\napple\napprove\napril\narch\narctic\narea\narena\nargue\narm\narmed\narmor\narmy\naround\narrange\narrest\narrive\narrow\nart\nartefact\nartist\nartwork\nask\naspect\nassault\nasset\nassist\nassume\nasthma\nathlete\natom\nattack\nattend\nattitude\nattract\nauction\naudit\naugust\naunt\nauthor\nauto\nautumn\naverage\navocado\navoid\nawake\naware\naway\nawesome\nawful\nawkward\naxis\nbaby\nbachelor\nbacon\nbadge\nbag\nbalance\nbalcony\nball\nbamboo\nbanana\nbanner\nbar\nbarely\nbargain\nbarrel\nbase\nbasic\nbasket\nbattle\nbeach\nbean\nbeauty\nbecause\nbecome\nbeef\nbefore\nbegin\nbehave\nbehind\nbelieve\nbelow\nbelt\nbench\nbenefit\nbest\nbetray\nbetter\nbetween\nbeyond\nbicycle\nbid\nbike\nbind\nbiology\nbird\nbirth\nbitter\nblack\nblade\nblame\nblanket\nblast\nbleak\nbless\nblind\nblood\nblossom\nblouse\nblue\nblur\nblush\nboard\nboat\nbody\nboil\nbomb\nbone\nbonus\nbook\nboost\nborder\nboring\nborrow\nboss\nbottom\nbounce\nbox\nboy\nbracket\nbrain\nbrand\nbrass\nbrave\nbread\nbreeze\nbrick\nbridge\nbrief\nbright\nbring\nbrisk\nbroccoli\nbroken\nbronze\nbroom\nbrother\nbrown\nbrush\nbubble\nbuddy\nbudget\nbuffalo\nbuild\nbulb\nbulk\nbullet\nbundle\nbunker\nburden\nburger\nburst\nbus\nbusiness\nbusy\nbutter\nbuyer\nbuzz\ncabbage\ncabin\ncable\ncactus\ncage\ncake\ncall\ncalm\ncamera\ncamp\ncan\ncanal\ncancel\ncandy\ncannon\ncanoe\ncanvas\ncanyon\ncapable\ncapital\ncaptain\ncar\ncarbon\ncard\ncargo\ncarpet\ncarry\ncart\ncase\ncash\ncasino\ncastle\ncasual\ncat\ncatalog\ncatch\ncategory\ncattle\ncaught\ncause\ncaution\ncave\nceiling\ncelery\ncement\ncensus\ncentury\ncereal\ncertain\nchair\nchalk\nchampion\nchange\nchaos\nchapter\ncharge\nchase\nchat\ncheap\ncheck\ncheese\nchef\ncherry\nchest\nchicken\nchief\nchild\nchimney\nchoice\nchoose\nchronic\nchuckle\nchunk\nchurn\ncigar\ncinnamon\ncircle\ncitizen\ncity\ncivil\nclaim\nclap\nclarify\nclaw\nclay\nclean\nclerk\nclever\nclick\nclient\ncliff\nclimb\nclinic\nclip\nclock\nclog\nclose\ncloth\ncloud\nclown\nclub\nclump\ncluster\nclutch\ncoach\ncoast\ncoconut\ncode\ncoffee\ncoil\ncoin\ncollect\ncolor\ncolumn\ncombine\ncome\ncomfort\ncomic\ncommon\ncompany\nconcert\nconduct\nconfirm\ncongress\nconnect\nconsider\ncontrol\nconvince\ncook\ncool\ncopper\ncopy\ncoral\ncore\ncorn\ncorrect\ncost\ncotton\ncouch\ncountry\ncouple\ncourse\ncousin\ncover\ncoyote\ncrack\ncradle\ncraft\ncram\ncrane\ncrash\ncrater\ncrawl\ncrazy\ncream\ncredit\ncreek\ncrew\ncricket\ncrime\ncrisp\ncritic\ncrop\ncross\ncrouch\ncrowd\ncrucial\ncruel\ncruise\ncrumble\ncrunch\ncrush\ncry\ncrystal\ncube\nculture\ncup\ncupboard\ncurious\ncurrent\ncurtain\ncurve\ncushion\ncustom\ncute\ncycle\ndad\ndamage\ndamp\ndance\ndanger\ndaring\ndash\ndaughter\ndawn\nday\ndeal\ndebate\ndebris\ndecade\ndecember\ndecide\ndecline\ndecorate\ndecrease\ndeer\ndefense\ndefine\ndefy\ndegree\ndelay\ndeliver\ndemand\ndemise\ndenial\ndentist\ndeny\ndepart\ndepend\ndeposit\ndepth\ndeputy\nderive\ndescribe\ndesert\ndesign\ndesk\ndespair\ndestroy\ndetail\ndetect\ndevelop\ndevice\ndevote\ndiagram\ndial\ndiamond\ndiary\ndice\ndiesel\ndiet\ndiffer\ndigital\ndignity\ndilemma\ndinner\ndinosaur\ndirect\ndirt\ndisagree\ndiscover\ndisease\ndish\ndismiss\ndisorder\ndisplay\ndistance\ndivert\ndivide\ndivorce\ndizzy\ndoctor\ndocument\ndog\ndoll\ndolphin\ndomain\ndonate\ndonkey\ndonor\ndoor\ndose\ndouble\ndove\ndraft\ndragon\ndrama\ndrastic\ndraw\ndream\ndress\ndrift\ndrill\ndrink\ndrip\ndrive\ndrop\ndrum\ndry\nduck\ndumb\ndune\nduring\ndust\ndutch\nduty\ndwarf\ndynamic\neager\neagle\nearly\nearn\nearth\neasily\neast\neasy\necho\necology\neconomy\nedge\nedit\neducate\neffort\negg\neight\neither\nelbow\nelder\nelectric\nelegant\nelement\nelephant\nelevator\nelite\nelse\nembark\nembody\nembrace\nemerge\nemotion\nemploy\nempower\nempty\nenable\nenact\nend\nendless\nendorse\nenemy\nenergy\nenforce\nengage\nengine\nenhance\nenjoy\nenlist\nenough\nenrich\nenroll\nensure\nenter\nentire\nentry\nenvelope\nepisode\nequal\nequip\nera\nerase\nerode\nerosion\nerror\nerupt\nescape\nessay\nessence\nestate\neternal\nethics\nevidence\nevil\nevoke\nevolve\nexact\nexample\nexcess\nexchange\nexcite\nexclude\nexcuse\nexecute\nexercise\nexhaust\nexhibit\nexile\nexist\nexit\nexotic\nexpand\nexpect\nexpire\nexplain\nexpose\nexpress\nextend\nextra\neye\neyebrow\nfabric\nface\nfaculty\nfade\nfaint\nfaith\nfall\nfalse\nfame\nfamily\nfamous\nfan\nfancy\nfantasy\nfarm\nfashion\nfat\nfatal\nfather\nfatigue\nfault\nfavorite\nfeature\nfebruary\nfederal\nfee\nfeed\nfeel\nfemale\nfence\nfestival\nfetch\nfever\nfew\nfiber\nfiction\nfield\nfigure\nfile\nfilm\nfilter\nfinal\nfind\nfine\nfinger\nfinish\nfire\nfirm\nfirst\nfiscal\nfish\nfit\nfitness\nfix\nflag\nflame\nflash\nflat\nflavor\nflee\nflight\nflip\nfloat\nflock\nfloor\nflower\nfluid\nflush\nfly\nfoam\nfocus\nfog\nfoil\nfold\nfollow\nfood\nfoot\nforce\nforest\nforget\nfork\nfortune\nforum\nforward\nfossil\nfoster\nfound\nfox\nfragile\nframe\nfrequent\nfresh\nfriend\nfringe\nfrog\nfront\nfrost\nfrown\nfrozen\nfruit\nfuel\nfun\nfunny\nfurnace\nfury\nfuture\ngadget\ngain\ngalaxy\ngallery\ngame\ngap\ngarage\ngarbage\ngarden\ngarlic\ngarment\ngas\ngasp\ngate\ngather\ngauge\ngaze\ngeneral\ngenius\ngenre\ngentle\ngenuine\ngesture\nghost\ngiant\ngift\ngiggle\nginger\ngiraffe\ngirl\ngive\nglad\nglance\nglare\nglass\nglide\nglimpse\nglobe\ngloom\nglory\nglove\nglow\nglue\ngoat\ngoddess\ngold\ngood\ngoose\ngorilla\ngospel\ngossip\ngovern\ngown\ngrab\ngrace\ngrain\ngrant\ngrape\ngrass\ngravity\ngreat\ngreen\ngrid\ngrief\ngrit\ngrocery\ngroup\ngrow\ngrunt\nguard\nguess\nguide\nguilt\nguitar\ngun\ngym\nhabit\nhair\nhalf\nhammer\nhamster\nhand\nhappy\nharbor\nhard\nharsh\nharvest\nhat\nhave\nhawk\nhazard\nhead\nhealth\nheart\nheavy\nhedgehog\nheight\nhello\nhelmet\nhelp\nhen\nhero\nhidden\nhigh\nhill\nhint\nhip\nhire\nhistory\nhobby\nhockey\nhold\nhole\nholiday\nhollow\nhome\nhoney\nhood\nhope\nhorn\nhorror\nhorse\nhospital\nhost\nhotel\nhour\nhover\nhub\nhuge\nhuman\nhumble\nhumor\nhundred\nhungry\nhunt\nhurdle\nhurry\nhurt\nhusband\nhybrid\nice\nicon\nidea\nidentify\nidle\nignore\nill\nillegal\nillness\nimage\nimitate\nimmense\nimmune\nimpact\nimpose\nimprove\nimpulse\ninch\ninclude\nincome\nincrease\nindex\nindicate\nindoor\nindustry\ninfant\ninflict\ninform\ninhale\ninherit\ninitial\ninject\ninjury\ninmate\ninner\ninnocent\ninput\ninquiry\ninsane\ninsect\ninside\ninspire\ninstall\nintact\ninterest\ninto\ninvest\ninvite\ninvolve\niron\nisland\nisolate\nissue\nitem\nivory\njacket\njaguar\njar\njazz\njealous\njeans\njelly\njewel\njob\njoin\njoke\njourney\njoy\njudge\njuice\njump\njungle\njunior\njunk\njust\nkangaroo\nkeen\nkeep\nketchup\nkey\nkick\nkid\nkidney\nkind\nkingdom\nkiss\nkit\nkitchen\nkite\nkitten\nkiwi\nknee\nknife\nknock\nknow\nlab\nlabel\nlabor\nladder\nlady\nlake\nlamp\nlanguage\nlaptop\nlarge\nlater\nlatin\nlaugh\nlaundry\nlava\nlaw\nlawn\nlawsuit\nlayer\nlazy\nleader\nleaf\nlearn\nleave\nlecture\nleft\nleg\nlegal\nlegend\nleisure\nlemon\nlend\nlength\nlens\nleopard\nlesson\nletter\nlevel\nliar\nliberty\nlibrary\nlicense\nlife\nlift\nlight\nlike\nlimb\nlimit\nlink\nlion\nliquid\nlist\nlittle\nlive\nlizard\nload\nloan\nlobster\nlocal\nlock\nlogic\nlonely\nlong\nloop\nlottery\nloud\nlounge\nlove\nloyal\nlucky\nluggage\nlumber\nlunar\nlunch\nluxury\nlyrics\nmachine\nmad\nmagic\nmagnet\nmaid\nmail\nmain\nmajor\nmake\nmammal\nman\nmanage\nmandate\nmango\nmansion\nmanual\nmaple\nmarble\nmarch\nmargin\nmarine\nmarket\nmarriage\nmask\nmass\nmaster\nmatch\nmaterial\nmath\nmatrix\nmatter\nmaximum\nmaze\nmeadow\nmean\nmeasure\nmeat\nmechanic\nmedal\nmedia\nmelody\nmelt\nmember\nmemory\nmention\nmenu\nmercy\nmerge\nmerit\nmerry\nmesh\nmessage\nmetal\nmethod\nmiddle\nmidnight\nmilk\nmillion\nmimic\nmind\nminimum\nminor\nminute\nmiracle\nmirror\nmisery\nmiss\nmistake\nmix\nmixed\nmixture\nmobile\nmodel\nmodify\nmom\nmoment\nmonitor\nmonkey\nmonster\nmonth\nmoon\nmoral\nmore\nmorning\nmosquito\nmother\nmotion\nmotor\nmountain\nmouse\nmove\nmovie\nmuch\nmuffin\nmule\nmultiply\nmuscle\nmuseum\nmushroom\nmusic\nmust\nmutual\nmyself\nmystery\nmyth\nnaive\nname\nnapkin\nnarrow\nnasty\nnation\nnature\nnear\nneck\nneed\nnegative\nneglect\nneither\nnephew\nnerve\nnest\nnet\nnetwork\nneutral\nnever\nnews\nnext\nnice\nnight\nnoble\nnoise\nnominee\nnoodle\nnormal\nnorth\nnose\nnotable\nnote\nnothing\nnotice\nnovel\nnow\nnuclear\nnumber\nnurse\nnut\noak\nobey\nobject\noblige\nobscure\nobserve\nobtain\nobvious\noccur\nocean\noctober\nodor\noff\noffer\noffice\noften\noil\nokay\nold\nolive\nolympic\nomit\nonce\none\nonion\nonline\nonly\nopen\nopera\nopinion\noppose\noption\norange\norbit\norchard\norder\nordinary\norgan\norient\noriginal\norphan\nostrich\nother\noutdoor\nouter\noutput\noutside\noval\noven\nover\nown\nowner\noxygen\noyster\nozone\npact\npaddle\npage\npair\npalace\npalm\npanda\npanel\npanic\npanther\npaper\nparade\nparent\npark\nparrot\nparty\npass\npatch\npath\npatient\npatrol\npattern\npause\npave\npayment\npeace\npeanut\npear\npeasant\npelican\npen\npenalty\npencil\npeople\npepper\nperfect\npermit\nperson\npet\nphone\nphoto\nphrase\nphysical\npiano\npicnic\npicture\npiece\npig\npigeon\npill\npilot\npink\npioneer\npipe\npistol\npitch\npizza\nplace\nplanet\nplastic\nplate\nplay\nplease\npledge\npluck\nplug\nplunge\npoem\npoet\npoint\npolar\npole\npolice\npond\npony\npool\npopular\nportion\nposition\npossible\npost\npotato\npottery\npoverty\npowder\npower\npractice\npraise\npredict\nprefer\nprepare\npresent\npretty\nprevent\nprice\npride\nprimary\nprint\npriority\nprison\nprivate\nprize\nproblem\nprocess\nproduce\nprofit\nprogram\nproject\npromote\nproof\nproperty\nprosper\nprotect\nproud\nprovide\npublic\npudding\npull\npulp\npulse\npumpkin\npunch\npupil\npuppy\npurchase\npurity\npurpose\npurse\npush\nput\npuzzle\npyramid\nquality\nquantum\nquarter\nquestion\nquick\nquit\nquiz\nquote\nrabbit\nraccoon\nrace\nrack\nradar\nradio\nrail\nrain\nraise\nrally\nramp\nranch\nrandom\nrange\nrapid\nrare\nrate\nrather\nraven\nraw\nrazor\nready\nreal\nreason\nrebel\nrebuild\nrecall\nreceive\nrecipe\nrecord\nrecycle\nreduce\nreflect\nreform\nrefuse\nregion\nregret\nregular\nreject\nrelax\nrelease\nrelief\nrely\nremain\nremember\nremind\nremove\nrender\nrenew\nrent\nreopen\nrepair\nrepeat\nreplace\nreport\nrequire\nrescue\nresemble\nresist\nresource\nresponse\nresult\nretire\nretreat\nreturn\nreunion\nreveal\nreview\nreward\nrhythm\nrib\nribbon\nrice\nrich\nride\nridge\nrifle\nright\nrigid\nring\nriot\nripple\nrisk\nritual\nrival\nriver\nroad\nroast\nrobot\nrobust\nrocket\nromance\nroof\nrookie\nroom\nrose\nrotate\nrough\nround\nroute\nroyal\nrubber\nrude\nrug\nrule\nrun\nrunway\nrural\nsad\nsaddle\nsadness\nsafe\nsail\nsalad\nsalmon\nsalon\nsalt\nsalute\nsame\nsample\nsand\nsatisfy\nsatoshi\nsauce\nsausage\nsave\nsay\nscale\nscan\nscare\nscatter\nscene\nscheme\nschool\nscience\nscissors\nscorpion\nscout\nscrap\nscreen\nscript\nscrub\nsea\nsearch\nseason\nseat\nsecond\nsecret\nsection\nsecurity\nseed\nseek\nsegment\nselect\nsell\nseminar\nsenior\nsense\nsentence\nseries\nservice\nsession\nsettle\nsetup\nseven\nshadow\nshaft\nshallow\nshare\nshed\nshell\nsheriff\nshield\nshift\nshine\nship\nshiver\nshock\nshoe\nshoot\nshop\nshort\nshoulder\nshove\nshrimp\nshrug\nshuffle\nshy\nsibling\nsick\nside\nsiege\nsight\nsign\nsilent\nsilk\nsilly\nsilver\nsimilar\nsimple\nsince\nsing\nsiren\nsister\nsituate\nsix\nsize\nskate\nsketch\nski\nskill\nskin\nskirt\nskull\nslab\nslam\nsleep\nslender\nslice\nslide\nslight\nslim\nslogan\nslot\nslow\nslush\nsmall\nsmart\nsmile\nsmoke\nsmooth\nsnack\nsnake\nsnap\nsniff\nsnow\nsoap\nsoccer\nsocial\nsock\nsoda\nsoft\nsolar\nsoldier\nsolid\nsolution\nsolve\nsomeone\nsong\nsoon\nsorry\nsort\nsoul\nsound\nsoup\nsource\nsouth\nspace\nspare\nspatial\nspawn\nspeak\nspecial\nspeed\nspell\nspend\nsphere\nspice\nspider\nspike\nspin\nspirit\nsplit\nspoil\nsponsor\nspoon\nsport\nspot\nspray\nspread\nspring\nspy\nsquare\nsqueeze\nsquirrel\nstable\nstadium\nstaff\nstage\nstairs\nstamp\nstand\nstart\nstate\nstay\nsteak\nsteel\nstem\nstep\nstereo\nstick\nstill\nsting\nstock\nstomach\nstone\nstool\nstory\nstove\nstrategy\nstreet\nstrike\nstrong\nstruggle\nstudent\nstuff\nstumble\nstyle\nsubject\nsubmit\nsubway\nsuccess\nsuch\nsudden\nsuffer\nsugar\nsuggest\nsuit\nsummer\nsun\nsunny\nsunset\nsuper\nsupply\nsupreme\nsure\nsurface\nsurge\nsurprise\nsurround\nsurvey\nsuspect\nsustain\nswallow\nswamp\nswap\nswarm\nswear\nsweet\nswift\nswim\nswing\nswitch\nsword\nsymbol\nsymptom\nsyrup\nsystem\ntable\ntackle\ntag\ntail\ntalent\ntalk\ntank\ntape\ntarget\ntask\ntaste\ntattoo\ntaxi\nteach\nteam\ntell\nten\ntenant\ntennis\ntent\nterm\ntest\ntext\nthank\nthat\ntheme\nthen\ntheory\nthere\nthey\nthing\nthis\nthought\nthree\nthrive\nthrow\nthumb\nthunder\nticket\ntide\ntiger\ntilt\ntimber\ntime\ntiny\ntip\ntired\ntissue\ntitle\ntoast\ntobacco\ntoday\ntoddler\ntoe\ntogether\ntoilet\ntoken\ntomato\ntomorrow\ntone\ntongue\ntonight\ntool\ntooth\ntop\ntopic\ntopple\ntorch\ntornado\ntortoise\ntoss\ntotal\ntourist\ntoward\ntower\ntown\ntoy\ntrack\ntrade\ntraffic\ntragic\ntrain\ntransfer\ntrap\ntrash\ntravel\ntray\ntreat\ntree\ntrend\ntrial\ntribe\ntrick\ntrigger\ntrim\ntrip\ntrophy\ntrouble\ntruck\ntrue\ntruly\ntrumpet\ntrust\ntruth\ntry\ntube\ntuition\ntumble\ntuna\ntunnel\nturkey\nturn\nturtle\ntwelve\ntwenty\ntwice\ntwin\ntwist\ntwo\ntype\ntypical\nugly\numbrella\nunable\nunaware\nuncle\nuncover\nunder\nundo\nunfair\nunfold\nunhappy\nuniform\nunique\nunit\nuniverse\nunknown\nunlock\nuntil\nunusual\nunveil\nupdate\nupgrade\nuphold\nupon\nupper\nupset\nurban\nurge\nusage\nuse\nused\nuseful\nuseless\nusual\nutility\nvacant\nvacuum\nvague\nvalid\nvalley\nvalve\nvan\nvanish\nvapor\nvarious\nvast\nvault\nvehicle\nvelvet\nvendor\nventure\nvenue\nverb\nverify\nversion\nvery\nvessel\nveteran\nviable\nvibrant\nvicious\nvictory\nvideo\nview\nvillage\nvintage\nviolin\nvirtual\nvirus\nvisa\nvisit\nvisual\nvital\nvivid\nvocal\nvoice\nvoid\nvolcano\nvolume\nvote\nvoyage\nwage\nwagon\nwait\nwalk\nwall\nwalnut\nwant\nwarfare\nwarm\nwarrior\nwash\nwasp\nwaste\nwater\nwave\nway\nwealth\nweapon\nwear\nweasel\nweather\nweb\nwedding\nweekend\nweird\nwelcome\nwest\nwet\nwhale\nwhat\nwheat\nwheel\nwhen\nwhere\nwhip\nwhisper\nwide\nwidth\nwife\nwild\nwill\nwin\nwindow\nwine\nwing\nwink\nwinner\nwinter\nwire\nwisdom\nwise\nwish\nwitness\nwolf\nwoman\nwonder\nwood\nwool\nword\nwork\nworld\nworry\nworth\nwrap\nwreck\nwrestle\nwrist\nwrite\nwrong\nyard\nyear\nyellow\nyou\nyoung\nyouth\nzebra\nzero\nzone\nzoo`.split('\\n'));\n//# sourceMappingURL=english.js.map", "/**\n * Hex, bytes and number utilities.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport {\n abytes as abytes_,\n anumber as anumber_,\n bytesToHex as bytesToHex_,\n concatBytes as concatBytes_,\n hexToBytes as hexToBytes_,\n isBytes as isBytes_,\n randomBytes as randomBytes_,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\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: T, length?: number, title?: string): T =>\n abytes_(value, length, title) as T;\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 * @example\n * Validate a numeric length before allocating buffers.\n *\n * ```ts\n * anumber(1);\n * ```\n */\nexport const anumber: typeof anumber_ = anumber_;\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: typeof 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: TArg): TRet =>\n concatBytes_(...arrays) as TRet;\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: string): TRet => hexToBytes_(hex) as TRet;\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: typeof 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?: number): TRet =>\n randomBytes_(bytesLength) as TRet;\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Callable hash interface with metadata and optional extendable output support. */\nexport type CHash = {\n /**\n * Hash one message.\n * @param message - Message bytes to hash.\n * @returns Digest bytes.\n */\n (message: TArg): TRet;\n /** Hash block length in bytes. */\n blockLen: number;\n /** Default output length in bytes. */\n outputLen: number;\n /** Whether `.create()` can be used as an XOF stream. */\n canXOF: boolean;\n /**\n * Create one stateful hash or XOF instance, for example SHAKE with a custom output length.\n * @param opts - Optional extendable-output configuration:\n * - `dkLen` (optional): Optional output length for XOF-style hashes.\n * @returns Hash instance.\n */\n create(opts?: { dkLen?: number }): any;\n};\n/** Plain callable hash interface. */\nexport type FHash = (message: TArg) => TRet;\n/** HMAC callback signature. */\nexport type HmacFn = (key: TArg, message: TArg) => TRet;\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: boolean, title: string = ''): boolean {\n if (typeof value !== 'boolean') {\n const prefix = title && `\"${title}\" `;\n throw new TypeError(prefix + 'expected boolean, got type=' + typeof value);\n }\n return value;\n}\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: T): T {\n if (typeof n === 'bigint') {\n if (!isPosBig(n)) throw new RangeError('positive bigint expected, got ' + n);\n } else anumber(n);\n return n;\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: number, title: string = ''): void {\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/**\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: number | bigint): string {\n const hex = abignumber(num).toString(16);\n return hex.length & 1 ? '0' + hex : hex;\n}\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: string): bigint {\n if (typeof hex !== 'string') throw new TypeError('hex string expected, got ' + typeof hex);\n return hex === '' ? _0n : BigInt('0x' + hex); // Big Endian\n}\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: TArg): bigint {\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: TArg): bigint {\n return hexToNumber(bytesToHex_(copyBytes(abytes_(bytes)).reverse()));\n}\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 * @example\n * Serialize a scalar into a 32-byte field element.\n *\n * ```ts\n * numberToBytesBE(255n, 2);\n * ```\n */\nexport function numberToBytesBE(n: number | bigint, len: number): TRet {\n anumber_(len);\n if (len === 0) throw new RangeError('zero length');\n n = abignumber(n);\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 > len * 2) throw new RangeError('number too large');\n return hexToBytes_(hex.padStart(len * 2, '0')) as TRet;\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 * @example\n * Serialize a scalar for little-endian protocols.\n *\n * ```ts\n * numberToBytesLE(255n, 2);\n * ```\n */\nexport function numberToBytesLE(n: number | bigint, len: number): TRet {\n return numberToBytesBE(n, len).reverse() as TRet;\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: number | bigint): TRet {\n return hexToBytes_(numberToHexUnpadded(abignumber(n))) as TRet;\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: TArg, b: TArg): boolean {\n a = abytes(a);\n b = abytes(b);\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\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: TArg): TRet {\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)) as TRet;\n}\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: string): TRet {\n if (typeof ascii !== 'string') 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(\n `string contains non-ASCII character \"${ascii[i]}\" with code ${charCode} at position ${i}`\n );\n }\n return charCode;\n }) as TRet;\n}\n\n// Historical name: this accepts non-negative bigints, including zero.\nconst isPosBig = (n: bigint) => 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: bigint, min: bigint, max: bigint): boolean {\n return isPosBig(n) && isPosBig(min) && isPosBig(max) && min <= n && n < max;\n}\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: string, n: bigint, min: bigint, max: bigint): void {\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\n// Bit operations\n\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: bigint): number {\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) throw new Error('expected non-negative bigint, got ' + n);\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n * @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: bigint, pos: number): bigint {\n return (n >> BigInt(pos)) & _1n;\n}\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: bigint, pos: number, value: boolean): bigint {\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/**\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: number): bigint => (_1n << BigInt(n)) - _1n;\n\n// DRBG\n\ntype Pred = (v: TArg) => T | undefined;\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 drbg = createHmacDrbg(32, 32, (key, msg) => hmac(sha256, key, msg));\n * const seed = new Uint8Array(32);\n * drbg(seed, (bytes) => bytes);\n * ```\n */\nexport function createHmacDrbg(\n hashLen: number,\n qByteLen: number,\n hmacFn: TArg\n): TRet<(seed: Uint8Array, predicate: Pred) => T> {\n anumber_(hashLen, 'hashLen');\n anumber_(qByteLen, 'qByteLen');\n if (typeof hmacFn !== 'function') throw new TypeError('hmacFn must be a function');\n // creates Uint8Array\n const u8n = (len: number): TRet => new Uint8Array(len) as TRet;\n const NULL = Uint8Array.of();\n const byte0 = Uint8Array.of(0x00);\n const byte1 = Uint8Array.of(0x01);\n const _maxDrbgIters = 1000;\n\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: Uint8Array = u8n(hashLen);\n // Steps B and C of RFC6979 3.2.\n let k: Uint8Array = 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: TArg) => (hmacFn as HmacFn)(k, concatBytes(v, ...msgs));\n const reseed = (seed: TArg = 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) 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) throw new Error('drbg: tried max amount of iterations');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: TArg, pred: TArg>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until the predicate accepts a candidate.\n // Falsy values like 0 are valid outputs.\n while ((res = (pred as Pred)(gen())) === undefined) reseed();\n reset();\n return res;\n };\n return genUntil as TRet<(seed: Uint8Array, predicate: Pred) => T>;\n}\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 * @param object - Object to validate.\n * @param fields - Required field types.\n * @param optFields - Optional field types.\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(\n object: Record,\n fields: Record = {},\n optFields: Record = {}\n): void {\n if (Object.prototype.toString.call(object) !== '[object Object]')\n throw new TypeError('expected valid options object');\n type Item = keyof typeof object;\n function checkField(fieldName: Item, expectedType: string, isOpt: boolean) {\n // Config/data fields must be explicit own properties, but runtime objects such as Field\n // instances intentionally satisfy required method slots via their shared prototype.\n if (!isOpt && expectedType !== 'function' && !Object.hasOwn(object, fieldName))\n throw new TypeError(`param \"${fieldName}\" is invalid: expected own property`);\n const val = object[fieldName];\n if (isOpt && val === undefined) return;\n const current = typeof val;\n if (current !== expectedType || val === null)\n throw new TypeError(\n `param \"${fieldName}\" is invalid: expected ${expectedType}, got ${current}`\n );\n }\n const iter = (f: typeof fields, isOpt: boolean) =>\n Object.entries(f).forEach(([k, v]) => checkField(k, v, isOpt));\n iter(fields, false);\n iter(optFields, true);\n}\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 = (): never => {\n throw new Error('not implemented');\n};\n\n/** Generic keygen/getPublicKey interface shared by curve helpers. */\nexport interface CryptoKeys {\n /** Public byte lengths for keys and optional seeds. */\n lengths: { seed?: number; public?: number; secret?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: Uint8Array) => { secretKey: Uint8Array; publicKey: Uint8Array };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: Uint8Array) => Uint8Array;\n}\n\n/** Generic interface for signatures. Has keygen, sign and verify. */\nexport interface Signer extends CryptoKeys {\n // Interfaces are fun. We cannot just add new fields without copying old ones.\n /** Public byte lengths for keys, signatures, and optional signing randomness. */\n lengths: {\n seed?: number;\n public?: number;\n secret?: number;\n signRand?: number;\n signature?: number;\n };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @returns Signature bytes.\n */\n sign: (msg: Uint8Array, secretKey: Uint8Array) => Uint8Array;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: (sig: Uint8Array, msg: Uint8Array, publicKey: Uint8Array) => boolean;\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 {\n abool,\n abytes,\n anumber,\n asafenumber,\n bitLen,\n bytesToNumberBE,\n bytesToNumberLE,\n numberToBytesBE,\n numberToBytesLE,\n validateObject,\n type TArg,\n type TRet,\n} from '../utils.ts';\n\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 _16n = /* @__PURE__ */ BigInt(16);\n\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: bigint, b: bigint): bigint {\n if (b <= _0n) 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: bigint, power: bigint, modulo: bigint): bigint {\n return FpPow(Field(modulo), num, power);\n}\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: bigint, power: bigint, modulo: bigint): bigint {\n if (power < _0n) 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/**\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 - Positive modulus.\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: bigint, modulo: bigint): bigint {\n if (number === _0n) throw new Error('invert: expected non-zero number');\n if (modulo <= _0n) throw new Error('invert: expected positive modulus, got ' + modulo);\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n const q = b / a;\n const r = b - a * q;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\nfunction assertIsSquare(Fp: TArg>, root: T, n: T): void {\n const F = Fp as IField;\n if (!F.eql(F.sqr(root), n)) throw new Error('Cannot find square root');\n}\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: TArg>, n: T) {\n const F = Fp as IField;\n const p1div4 = (F.ORDER + _1n) / _4n;\n const root = F.pow(n, p1div4);\n assertIsSquare(F, root, n);\n return root;\n}\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: TArg>, n: T) {\n const F = Fp as IField;\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\n// Based on RFC9380, Kong algorithm\n// prettier-ignore\nfunction sqrt9mod16(P: bigint): TRet<(Fp: IField, n: T) => T> {\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: TArg>, n: T): T => {\n const F = Fp as IField;\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 }) as TRet<(Fp: IField, n: T) => T>;\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: bigint): TRet<(Fp: IField, n: T) => T> {\n // Initialization (precomputation).\n // Caching initialization could boost perf by 7%.\n if (P < _3n) throw new Error('sqrt is not defined for small field');\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\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) 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) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>;\n\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: TArg>, n: T): T {\n const F = Fp as IField;\n if (F.is0(n)) return n;\n // Check if n is a quadratic residue using Legendre symbol\n if (FpLegendre(F, n) !== 1) throw new Error('Cannot find square root');\n\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\n // Main loop\n // while t != 1\n while (!F.eql(t, F.ONE)) {\n if (F.is0(t)) return F.ZERO; // if t=0 return R=0\n let i = 1;\n\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) throw new Error('Cannot find square root');\n }\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\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 } as TRet<(Fp: IField, n: T) => T>;\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: bigint): TRet<(Fp: IField, n: T) => T> {\n // P \u2261 3 (mod 4) => \u221An = n^((P+1)/4)\n if (P % _4n === _3n) return sqrt3mod4 as TRet<(Fp: IField, n: T) => T>;\n // P \u2261 5 (mod 8) => Atkin algorithm, page 10 of https://eprint.iacr.org/2012/685.pdf\n if (P % _8n === _5n) return sqrt5mod8 as TRet<(Fp: IField, n: T) => T>;\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) return sqrt9mod16(P);\n // Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\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: bigint, modulo: bigint): boolean =>\n (mod(num, modulo) & _1n) === _1n;\n\n/** Generic field interface used by prime and extension fields alike.\n * Generic helpers treat field operations as pure functions: implementations MUST treat provided\n * values/byte buffers as read-only and return detached results instead of mutating arguments.\n */\nexport interface IField {\n /** Field order `q`, which may be prime or a prime power. */\n ORDER: bigint;\n /** Canonical encoded byte length. */\n BYTES: number;\n /** Canonical encoded bit length. */\n BITS: number;\n /** Whether encoded field elements use little-endian bytes. */\n isLE: boolean;\n /** Additive identity. */\n ZERO: T;\n /** Multiplicative identity. */\n ONE: T;\n // 1-arg\n /**\n * Normalize one value into the field.\n * @param num - Input value.\n * @returns Normalized field value.\n */\n create: (num: T) => T;\n /**\n * Check whether one value already belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value already belongs to the field.\n */\n isValid: (num: T) => boolean;\n /**\n * Check whether one value is zero.\n * @param num - Input value.\n * @returns Whether the value is zero.\n */\n is0: (num: T) => boolean;\n /**\n * Check whether one value is non-zero and belongs to the field.\n * @param num - Input value.\n * Implementations may throw `TypeError` on malformed input types instead of returning `false`.\n * @returns Whether the value is non-zero and valid.\n */\n isValidNot0: (num: T) => boolean;\n /**\n * Negate one value.\n * @param num - Input value.\n * @returns Negated value.\n */\n neg(num: T): T;\n /**\n * Invert one value multiplicatively.\n * @param num - Input value.\n * @returns Multiplicative inverse.\n */\n inv(num: T): T;\n /**\n * Compute one square root when it exists.\n * @param num - Input value.\n * @returns Square root.\n */\n sqrt(num: T): T;\n /**\n * Square one value.\n * @param num - Input value.\n * @returns Squared value.\n */\n sqr(num: T): T;\n // 2-args\n /**\n * Compare two field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Whether both values are equal.\n */\n eql(lhs: T, rhs: T): boolean;\n /**\n * Add two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Sum value.\n */\n add(lhs: T, rhs: T): T;\n /**\n * Subtract two normalized field values.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Difference value.\n */\n sub(lhs: T, rhs: T): T;\n /**\n * Multiply two field values.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Product value.\n */\n mul(lhs: T, rhs: T | bigint): T;\n /**\n * Raise one field value to a power.\n * @param lhs - Base value.\n * @param power - Exponent.\n * @returns Power value.\n */\n pow(lhs: T, power: bigint): T;\n /**\n * Divide one field value by another.\n * @param lhs - Dividend.\n * @param rhs - Divisor or scalar.\n * @returns Quotient value.\n */\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n /**\n * Add two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized sum.\n */\n addN(lhs: T, rhs: T): T;\n /**\n * Subtract two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value.\n * @returns Non-normalized difference.\n */\n subN(lhs: T, rhs: T): T;\n /**\n * Multiply two values without re-normalizing the result.\n * @param lhs - Left value.\n * @param rhs - Right value or scalar.\n * @returns Non-normalized product.\n */\n mulN(lhs: T, rhs: T | bigint): T;\n /**\n * Square one value without re-normalizing the result.\n * @param num - Input value.\n * @returns Non-normalized square.\n */\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is \"negative in LE\", which is the same as odd.\n // Negative in LE is a somewhat strange definition anyway.\n /**\n * Return the RFC 9380 `sgn0`-style oddness bit when supported.\n * This uses oddness instead of evenness so extension fields like Fp2 can expose the same hook.\n * Returns whether the value is odd under the field encoding.\n */\n isOdd?(num: T): boolean;\n // legendre?(num: T): T;\n /**\n * Invert many field elements in one batch.\n * @param lst - Values to invert.\n * @returns Batch of inverses.\n */\n invertBatch: (lst: T[]) => T[];\n /**\n * Encode one field value into fixed-width bytes.\n * Callers that need canonical encodings MUST supply a valid field element.\n * Low-level protocols may also use this to serialize raw / non-canonical residues.\n * @param num - Input value.\n * @returns Fixed-width byte encoding.\n */\n toBytes(num: T): Uint8Array;\n /**\n * Decode one field value from fixed-width bytes.\n * @param bytes - Fixed-width byte encoding.\n * @param skipValidation - Whether to skip range validation.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Decoded field value.\n */\n fromBytes(bytes: Uint8Array, skipValidation?: boolean): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n /**\n * Constant-time conditional move.\n * @param a - Value used when the condition is false.\n * @param b - Value used when the condition is true.\n * @param c - Selection bit.\n * @returns Selected value.\n */\n cmov(a: T, b: T, c: boolean): T;\n}\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] as const;\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: TArg>): TRet> {\n const initial = {\n ORDER: 'bigint',\n BYTES: 'number',\n BITS: 'number',\n } as Record;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n validateObject(field, opts);\n // Runtime field implementations must expose real integer byte/bit sizes; fractional / NaN /\n // infinite metadata leaks through validateObject(type='number') but breaks encoders and caches.\n asafenumber(field.BYTES, 'BYTES');\n asafenumber(field.BITS, 'BITS');\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) throw new Error('invalid field: expected BYTES/BITS > 0');\n if (field.ORDER <= _1n) throw new Error('invalid field: expected ORDER > 1, got ' + field.ORDER);\n return field as TRet>;\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @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: TArg>, num: T, power: bigint): T {\n const F = Fp as IField;\n if (power < _0n) throw new Error('invalid exponent, negatives unsupported');\n if (power === _0n) return F.ONE;\n if (power === _1n) return num;\n let p = F.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = F.mul(p, d);\n d = F.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * Exception-free. Zero-valued field elements stay `undefined` unless `passZero` is enabled.\n * @param Fp - Field implementation.\n * @param nums - Values to invert.\n * @param passZero - map 0 to 0 (instead of undefined)\n * @returns Inverted values.\n * @example\n * Invert several field elements with one shared inversion.\n *\n * ```ts\n * import { Field, FpInvertBatch } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const inv = FpInvertBatch(Fp, [1n, 2n, 4n]);\n * ```\n */\nexport function FpInvertBatch(Fp: TArg>, nums: T[], passZero = false): T[] {\n const F = Fp as IField;\n const inverted = new Array(nums.length).fill(passZero ? F.ZERO : undefined) as T[];\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)) 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)) return acc;\n inverted[i] = F.mul(acc, inverted[i]);\n return F.mul(acc, num);\n }, invertedAcc);\n return inverted;\n}\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: TArg>, lhs: T, rhs: T | bigint): T {\n const F = Fp as IField;\n return F.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, F.ORDER) : F.inv(rhs));\n}\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 field returns an invalid Legendre symbol value. {@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: TArg>, n: T): -1 | 0 | 1 {\n const F = Fp as IField;\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) throw new Error('invalid Legendre symbol result');\n return yes ? 1 : zero ? 0 : -1;\n}\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: TArg>, n: T): boolean {\n const l = FpLegendre(Fp as IField, n);\n // Zero is a square too: 0 = 0^2, and Fp.sqrt(0) already returns 0.\n return l !== -1;\n}\n\n/** Byte and bit lengths derived from one scalar order. */\nexport type NLength = {\n /** Canonical byte length. */\n nByteLength: number;\n /** Canonical bit length. */\n nBitLength: number;\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: bigint, nBitLength?: number): NLength {\n // Bit size, byte size of CURVE.n\n if (nBitLength !== undefined) anumber(nBitLength);\n if (n <= _0n) 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 bit length (${bits}) >= n.length (${nBitLength})`);\n const _nBitLength = nBitLength !== undefined ? nBitLength : bits;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField & Required, 'isOdd'>>;\ntype SqrtFn = (n: bigint) => bigint;\ntype FieldOpts = Partial<{\n isLE: boolean;\n BITS: number;\n sqrt: SqrtFn;\n allowedLengths?: readonly number[]; // for P521 (adds padding for smaller sizes); must stay > 0\n modFromBytes: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\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 implements IField {\n readonly ORDER: bigint;\n readonly BITS: number;\n readonly BYTES: number;\n readonly isLE: boolean;\n readonly ZERO = _0n;\n readonly ONE = _1n;\n readonly _lengths?: readonly number[];\n private readonly _mod?: boolean;\n constructor(ORDER: bigint, opts: FieldOpts = {}) {\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) throw new Error('invalid field: expected ORDER > 1, got ' + ORDER);\n let _nbitLength: number | undefined = 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') _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') this.isLE = opts.isLE;\n if (opts.allowedLengths) this._lengths = Object.freeze(opts.allowedLengths.slice());\n if (typeof opts.modFromBytes === 'boolean') this._mod = opts.modFromBytes;\n }\n const { nBitLength, nByteLength } = nLength(ORDER, _nbitLength);\n if (nByteLength > 2048) 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\n create(num: bigint) {\n return mod(num, this.ORDER);\n }\n isValid(num: bigint) {\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: bigint) {\n return num === _0n;\n }\n // is valid and invertible\n isValidNot0(num: bigint) {\n return !this.is0(num) && this.isValid(num);\n }\n isOdd(num: bigint) {\n return (num & _1n) === _1n;\n }\n neg(num: bigint) {\n return mod(-num, this.ORDER);\n }\n eql(lhs: bigint, rhs: bigint) {\n return lhs === rhs;\n }\n\n sqr(num: bigint) {\n return mod(num * num, this.ORDER);\n }\n add(lhs: bigint, rhs: bigint) {\n return mod(lhs + rhs, this.ORDER);\n }\n sub(lhs: bigint, rhs: bigint) {\n return mod(lhs - rhs, this.ORDER);\n }\n mul(lhs: bigint, rhs: bigint) {\n return mod(lhs * rhs, this.ORDER);\n }\n pow(num: bigint, power: bigint): bigint {\n return FpPow(this, num, power);\n }\n div(lhs: bigint, rhs: bigint) {\n return mod(lhs * invert(rhs, this.ORDER), this.ORDER);\n }\n\n // Same as above, but doesn't normalize\n sqrN(num: bigint) {\n return num * num;\n }\n addN(lhs: bigint, rhs: bigint) {\n return lhs + rhs;\n }\n subN(lhs: bigint, rhs: bigint) {\n return lhs - rhs;\n }\n mulN(lhs: bigint, rhs: bigint) {\n return lhs * rhs;\n }\n\n inv(num: bigint) {\n return invert(num, this.ORDER);\n }\n sqrt(num: bigint): bigint {\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) FIELD_SQRT.set(this, (sqrt = FpSqrt(this.ORDER)));\n return sqrt(this, num);\n }\n toBytes(num: bigint) {\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: Uint8Array, 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(\n 'Field.fromBytes: expected ' + allowedLengths + ' bytes, got ' + bytes.length\n );\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) 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: bigint[]): bigint[] {\n return FpInvertBatch(this, lst);\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: bigint, b: bigint, condition: boolean) {\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// Freeze the shared method surface too; otherwise callers can still poison every Field instance by\n// monkey-patching `_Field.prototype` even if each instance is frozen.\nObject.freeze(_Field.prototype);\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: bigint, opts: FieldOpts = {}): TRet> {\n return new _Field(ORDER, opts);\n}\n\n// Generic random scalar, we can do same for other fields if via Fp2.mul(Fp2.ONE, Fp2.random)?\n// This allows unsafe methods like ignore bias or zero. These unsafe, but often used in different protocols (if deterministic RNG).\n// which mean we cannot force this via opts.\n// Not sure what to do with randomBytes, we can accept it inside opts if wanted.\n// Probably need to export getMinHashLength somewhere?\n// random(bytes?: Uint8Array, unsafeAllowZero = false, unsafeAllowBias = false) {\n// const LEN = !unsafeAllowBias ? getMinHashLength(ORDER) : BYTES;\n// if (bytes === undefined) bytes = randomBytes(LEN); // _opts.randomBytes?\n// const num = isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n// // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n// const reduced = unsafeAllowZero ? mod(num, ORDER) : mod(num, ORDER - _1n) + _1n;\n// return reduced;\n// },\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: TArg>, elm: T): T {\n const F = Fp as IField;\n if (!F.isOdd) 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/**\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: TArg>, elm: T): T {\n const F = Fp as IField;\n if (!F.isOdd) 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/**\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: bigint): number {\n if (typeof fieldOrder !== 'bigint') 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) 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/**\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: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key. 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(\n key: TArg,\n fieldOrder: bigint,\n isLE = false\n): TRet {\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 // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/**\n * Methods for elliptic curve multiplication by scalars.\n * Contains wNAF, pippenger.\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { bitLen, bitMask, validateObject, type Signer, type TArg, type TRet } from '../utils.ts';\nimport { Field, FpInvertBatch, validateField, type IField } from './modular.ts';\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\n\n/** Affine point coordinates without projective fields. */\nexport type AffinePoint = {\n /** Affine x coordinate. */\n x: T;\n /** Affine y coordinate. */\n y: T;\n} & { Z?: never };\n\n// We can't \"abstract out\" coordinates (X, Y, Z; and T in Edwards): argument names of constructor\n// are not accessible. See Typescript gh-56093, gh-41594.\n//\n// We have to use recursive types, so it will return actual point, not constained `CurvePoint`.\n// If, at any point, P is `any`, it will erase all types and replace it\n// with `any`, because of recursion, `any implements CurvePoint`,\n// but we lose all constrains on methods.\n\n/** Base interface for all elliptic-curve point instances. */\nexport interface CurvePoint> {\n /** Affine x coordinate. Different from projective / extended X coordinate. */\n x: F;\n /** Affine y coordinate. Different from projective / extended Y coordinate. */\n y: F;\n /** Projective Z coordinate when the point keeps projective state. */\n Z?: F;\n /**\n * Double the point.\n * @returns Doubled point.\n */\n double(): P;\n /**\n * Negate the point.\n * @returns Negated point.\n */\n negate(): P;\n /**\n * Add another point from the same curve.\n * @param other - Point to add.\n * @returns Sum point.\n */\n add(other: P): P;\n /**\n * Subtract another point from the same curve.\n * @param other - Point to subtract.\n * @returns Difference point.\n */\n subtract(other: P): P;\n /**\n * Compare two points for equality.\n * @param other - Point to compare.\n * @returns Whether the points are equal.\n */\n equals(other: P): boolean;\n /**\n * Multiply the point by a scalar in constant time.\n * Implementations keep the subgroup-scalar contract strict and may reject\n * `0` instead of returning the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiply(scalar: bigint): P;\n /** Assert that the point satisfies the curve equation and subgroup checks. */\n assertValidity(): void;\n /**\n * Map the point into the prime-order subgroup when the curve requires it.\n * @returns Prime-order point.\n */\n clearCofactor(): P;\n /**\n * Check whether the point is the point at infinity.\n * @returns Whether the point is zero.\n */\n is0(): boolean;\n /**\n * Check whether the point belongs to the prime-order subgroup.\n * @returns Whether the point is torsion-free.\n */\n isTorsionFree(): boolean;\n /**\n * Check whether the point lies in a small torsion subgroup.\n * @returns Whether the point has small order.\n */\n isSmallOrder(): boolean;\n /**\n * Multiply the point by a scalar without constant-time guarantees.\n * Public-scalar callers that need `0` should use this method instead of\n * relying on `multiply(...)` to return the identity point.\n * @param scalar - Scalar multiplier.\n * @returns Product point.\n */\n multiplyUnsafe(scalar: bigint): P;\n /**\n * Massively speeds up `p.multiply(n)` by using precompute tables (caching). See {@link wNAF}.\n * Cache state lives in internal WeakMaps keyed by point identity, not on the point object.\n * Repeating `precompute(...)` for the same point identity replaces the remembered window size\n * and forces table regeneration for that point.\n * @param windowSize - Precompute window size.\n * @param isLazy - calculate cache now. Default (true) ensures it's deferred to first `multiply()`\n * @returns Same point instance with precompute tables attached.\n */\n precompute(windowSize?: number, isLazy?: boolean): P;\n /**\n * Converts point to 2D xy affine coordinates.\n * @param invertedZ - Optional inverted Z coordinate for batch normalization.\n * @returns Affine x/y coordinates.\n */\n toAffine(invertedZ?: F): AffinePoint;\n /**\n * Encode the point into the curve's canonical byte form.\n * @returns Encoded point bytes.\n */\n toBytes(): Uint8Array;\n /**\n * Encode the point into the curve's canonical hex form.\n * @returns Encoded point hex.\n */\n toHex(): string;\n}\n\n/** Base interface for elliptic-curve point constructors. */\nexport interface CurvePointCons

> {\n /**\n * Runtime brand check for points created by this constructor.\n * @param item - Value to test.\n * @returns Whether the value is a point from this constructor.\n */\n [Symbol.hasInstance]: (item: unknown) => boolean;\n /** Canonical subgroup generator. */\n BASE: P;\n /** Point at infinity. */\n ZERO: P;\n /** Field for basic curve math */\n Fp: IField>;\n /** Scalar field, for scalars in multiply and others */\n Fn: IField;\n /**\n * Create one point from affine coordinates.\n * Does NOT validate curve, subgroup, or wrapper invariants.\n * Use `.assertValidity()` on adversarial inputs.\n * @param p - Affine point coordinates.\n * @returns Point instance.\n */\n fromAffine(p: AffinePoint>): P;\n /**\n * Decode a point from the canonical byte encoding.\n * @param bytes - Encoded point bytes.\n * Implementations MUST treat `bytes` as read-only.\n * @returns Point instance.\n */\n fromBytes(bytes: Uint8Array): P;\n /**\n * Decode a point from the canonical hex encoding.\n * @param hex - Encoded point hex.\n * @returns Point instance.\n */\n fromHex(hex: string): P;\n}\n\n// Type inference helpers: PC - PointConstructor, P - Point, Fp - Field element\n// Short names, because we use them a lot in result types:\n// * we can't do 'P = GetCurvePoint': this is default value and doesn't constrain anything\n// * we can't do 'type X = GetCurvePoint': it won't be accesible for arguments/return types\n// * `CurvePointCons

>` constraints from interface definition\n// won't propagate, if `PC extends CurvePointCons`: the P would be 'any', which is incorrect\n// * PC could be super specific with super specific P, which implements CurvePoint.\n// this means we need to do stuff like\n// `function test

, PC extends CurvePointCons

>(`\n// if we want type safety around P, otherwise PC_P will be any\n\n/** Returns the affine field type for a point instance (`P_F

== P.F`). */\nexport type P_F

> = P extends CurvePoint ? F : never;\n/** Returns the affine field type for a point constructor (`PC_F == PC.P.F`). */\nexport type PC_F>> = PC['Fp']['ZERO'];\n/** Returns the point instance type for a point constructor (`PC_P == PC.P`). */\nexport type PC_P>> = PC['ZERO'];\n\n// Ugly hack to get proper type inference, because in typescript fails to infer resursively.\n// The hack allows to do up to 10 chained operations without applying type erasure.\n//\n// Types which won't work:\n// * `CurvePointCons>`, will return `any` after 1 operation\n// * `CurvePointCons: WeierstrassPointCons extends CurvePointCons = false`\n// * `P extends CurvePoint, PC extends CurvePointCons

`\n// * It can't infer P from PC alone\n// * Too many relations between F, P & PC\n// * It will infer P/F if `arg: CurvePointCons`, but will fail if PC is generic\n// * It will work correctly if there is an additional argument of type P\n// * But generally, we don't want to parametrize `CurvePointCons` over `F`: it will complicate\n// types, making them un-inferable\n// prettier-ignore\n/** Wide point-constructor type used when the concrete curve is not important. */\nexport type PC_ANY = CurvePointCons<\n CurvePoint\n >>>>>>>>>\n>;\n\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: CurvePointCons

): void {\n const pc = Point as unknown as CurvePointCons;\n if (typeof (pc as unknown) !== 'function') throw new TypeError('Point must be a constructor');\n // validateObject only accepts plain objects, so copy the constructor statics into one bag first.\n validateObject(\n {\n Fp: pc.Fp,\n Fn: pc.Fn,\n fromAffine: pc.fromAffine,\n fromBytes: pc.fromBytes,\n fromHex: pc.fromHex,\n },\n {\n Fp: 'object',\n Fn: 'object',\n fromAffine: 'function',\n fromBytes: 'function',\n fromHex: 'function',\n }\n );\n validateField(pc.Fp);\n validateField(pc.Fn);\n}\n\n/** Byte lengths used by one curve implementation. */\nexport interface CurveLengths {\n /** Secret-key length in bytes. */\n secretKey?: number;\n /** Compressed public-key length in bytes. */\n publicKey?: number;\n /** Uncompressed public-key length in bytes. */\n publicKeyUncompressed?: number;\n /** Whether public-key encodings include a format prefix byte. */\n publicKeyHasPrefix?: boolean;\n /** Signature length in bytes. */\n signature?: number;\n /** Seed length in bytes when the curve exposes deterministic keygen from seed. */\n seed?: number;\n}\n\n/** Reorders or otherwise remaps a batch while preserving its element type. */\nexport type Mapper = (i: T[]) => T[];\n\n/**\n * Computes both candidates first, but the final selection still branches on `condition`, so this\n * is not a strict constant-time CMOV primitive.\n * @param condition - Whether to negate the point.\n * @param item - Point-like value.\n * @returns Original or negated value.\n * @example\n * Keep the point or return its negation based on one boolean branch.\n *\n * ```ts\n * import { negateCt } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const maybeNegated = negateCt(true, p256.Point.BASE);\n * ```\n */\nexport function negateCt T }>(condition: boolean, item: T): T {\n const neg = item.negate();\n return condition ? neg : item;\n}\n\n/**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n * 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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[]\n): P[] {\n const invertedZs = FpInvertBatch(\n c.Fp,\n points.map((p) => p.Z!)\n );\n return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));\n}\n\nfunction validateW(W: number, bits: number) {\n if (!Number.isSafeInteger(W) || W <= 0 || W > bits)\n throw new Error('invalid window size, expected [1..' + bits + '], got W=' + W);\n}\n\n/** Internal wNAF opts for specific W and scalarBits.\n * Zero digits are skipped, so tables store only the positive half-window and callers reserve one\n * extra carry window.\n */\ntype WOpts = {\n windows: number;\n windowSize: number;\n mask: bigint;\n maxNumber: number;\n shiftBy: bigint;\n};\n\nfunction calcWOpts(W: number, scalarBits: number): WOpts {\n validateW(W, scalarBits);\n const windows = Math.ceil(scalarBits / W) + 1; // W=8 33. Not 32, because we skip zero\n const windowSize = 2 ** (W - 1); // W=8 128. Not 256, because we skip zero\n const maxNumber = 2 ** W; // W=8 256\n const mask = bitMask(W); // W=8 255 == mask 0b11111111\n const shiftBy = BigInt(W); // W=8 8\n return { windows, windowSize, mask, maxNumber, shiftBy };\n}\n\nfunction calcOffsets(n: bigint, window: number, wOpts: WOpts) {\n const { windowSize, mask, maxNumber, shiftBy } = wOpts;\n let wbits = Number(n & mask); // extract W bits.\n let nextN = n >> shiftBy; // shift number by W bits.\n\n // What actually happens here:\n // const highestBit = Number(mask ^ (mask >> 1n));\n // let wbits2 = wbits - 1; // skip zero\n // if (wbits2 & highestBit) { wbits2 ^= Number(mask); // (~);\n\n // split if bits > max: +224 => 256-32\n if (wbits > windowSize) {\n // we skip zero, which means instead of `>= size-1`, we do `> size`\n wbits -= maxNumber; // -32, can be maxNumber - wbits, but then we need to set isNeg here.\n nextN += _1n; // +256 (carry)\n }\n const offsetStart = window * windowSize;\n const offset = offsetStart + Math.abs(wbits) - 1; // -1 because we skip zero; ignore when isZero\n const isZero = wbits === 0; // is current window slice a 0?\n const isNeg = wbits < 0; // is current window slice negative?\n const isNegF = window % 2 !== 0; // fake branch noise only\n const offsetF = offsetStart; // fake branch noise only\n return { nextN, offset, isZero, isNeg, isNegF, offsetF };\n}\n\nfunction validateMSMPoints(points: any[], c: any) {\n if (!Array.isArray(points)) throw new Error('array expected');\n points.forEach((p, i) => {\n if (!(p instanceof c)) throw new Error('invalid point at index ' + i);\n });\n}\nfunction validateMSMScalars(scalars: any[], field: any) {\n if (!Array.isArray(scalars)) throw new Error('array of scalars expected');\n scalars.forEach((s, i) => {\n if (!field.isValid(s)) throw new Error('invalid scalar at index ' + i);\n });\n}\n\n// Since points in different groups cannot be equal (different object constructor),\n// we can have single place to store precomputes.\n// Allows to make points frozen / immutable.\nconst pointPrecomputes = new WeakMap();\nconst pointWindowSizes = new WeakMap();\n\nfunction getW(P: any): number {\n // To disable precomputes:\n // return 1;\n // `1` is also the uncached sentinel: use the ladder / non-precomputed path.\n return pointWindowSizes.get(P) || 1;\n}\n\nfunction assert0(n: bigint): void {\n // Internal invariant: a non-zero remainder here means the wNAF window decomposition or loop\n // count is inconsistent, not that the original caller provided a bad scalar.\n if (n !== _0n) throw new Error('invalid wNAF');\n}\n\n/**\n * Elliptic curve multiplication of Point by scalar. Fragile.\n * Table generation takes **30MB of ram and 10ms on high-end CPU**,\n * but may take much longer on slow devices. Actual generation will happen on\n * first call of `multiply()`. By default, `BASE` point is precomputed.\n *\n * Scalars should always be less than curve order: this should be checked inside of a curve itself.\n * Creates precomputation tables for fast multiplication:\n * - private scalar is split by fixed size windows of W bits\n * - every window point is collected from window's table & added to accumulator\n * - since windows are different, same point inside tables won't be accessed more than once per calc\n * - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n * - +1 window is neccessary for wNAF\n * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n *\n * TODO: research returning a 2d JS array of windows instead of a single window.\n * This would allow windows to be in different memory locations.\n * @param Point - Point constructor.\n * @param bits - Scalar bit length.\n * @example\n * Elliptic curve multiplication of Point by scalar.\n *\n * ```ts\n * import { wNAF } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);\n * ```\n */\nexport class wNAF {\n private readonly BASE: PC_P;\n private readonly ZERO: PC_P;\n private readonly Fn: PC['Fn'];\n readonly bits: number;\n\n // Parametrized with a given Point class (not individual point)\n constructor(Point: PC, bits: number) {\n this.BASE = Point.BASE;\n this.ZERO = Point.ZERO;\n this.Fn = Point.Fn;\n this.bits = bits;\n }\n\n // non-const time multiplication ladder\n _unsafeLadder(elm: PC_P, n: bigint, p: PC_P = this.ZERO): PC_P {\n let d: PC_P = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n }\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @param point - Point instance\n * @param W - window size\n * @returns precomputed point tables flattened to a single array\n */\n private precomputeWindow(point: PC_P, W: number): PC_P[] {\n const { windows, windowSize } = calcWOpts(W, this.bits);\n const points: PC_P[] = [];\n let p: PC_P = point;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // i=1, bc we skip 0\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n }\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * More compact implementation:\n * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541\n * @returns real and fake (for const-time) points\n */\n private wNAF(W: number, precomputes: PC_P[], n: bigint): { p: PC_P; f: PC_P } {\n // Scalar should be smaller than field order\n if (!this.Fn.isValid(n)) throw new Error('invalid scalar');\n // Accumulators\n let p = this.ZERO;\n let f = this.BASE;\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n // (n === _0n) is handled and not early-exited. isEven and offsetF are used for noise\n const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // bits are 0: add garbage to fake point\n // Important part for const-time getPublicKey: add random \"noise\" point to f.\n f = f.add(negateCt(isNegF, precomputes[offsetF]));\n } else {\n // bits are 1: add to result point\n p = p.add(negateCt(isNeg, precomputes[offset]));\n }\n }\n assert0(n);\n // Return both real and fake points so JIT keeps the noise path alive.\n // Known caveat: negate/carry interactions can still drive `f` to infinity even when `p` is not,\n // which weakens the noise path and leaves this only \"less const-time\" by about one bigint mul.\n return { p, f };\n }\n\n /**\n * Implements unsafe EC multiplication using precomputed tables\n * and w-ary non-adjacent form.\n * @param acc - accumulator point to add result of multiplication\n * @returns point\n */\n private wNAFUnsafe(\n W: number,\n precomputes: PC_P[],\n n: bigint,\n acc: PC_P = this.ZERO\n ): PC_P {\n const wo = calcWOpts(W, this.bits);\n for (let window = 0; window < wo.windows; window++) {\n if (n === _0n) break; // Early-exit, skip 0 value\n const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);\n n = nextN;\n if (isZero) {\n // Window bits are 0: skip processing.\n // Move to next window.\n continue;\n } else {\n const item = precomputes[offset];\n acc = acc.add(isNeg ? item.negate() : item); // Re-using acc allows to save adds in MSM\n }\n }\n assert0(n);\n return acc;\n }\n\n private getPrecomputes(W: number, point: PC_P, transform?: Mapper>): PC_P[] {\n // Cache key is only point identity plus the remembered window size; callers must not reuse the\n // same point with incompatible `transform(...)` layouts and expect a separate cache entry.\n let comp = pointPrecomputes.get(point);\n if (!comp) {\n comp = this.precomputeWindow(point, W) as PC_P[];\n if (W !== 1) {\n // Doing transform outside of if brings 15% perf hit\n if (typeof transform === 'function') comp = transform(comp);\n pointPrecomputes.set(point, comp);\n }\n }\n return comp;\n }\n\n cached(\n point: PC_P,\n scalar: bigint,\n transform?: Mapper>\n ): { p: PC_P; f: PC_P } {\n const W = getW(point);\n return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);\n }\n\n unsafe(point: PC_P, scalar: bigint, transform?: Mapper>, prev?: PC_P): PC_P {\n const W = getW(point);\n if (W === 1) return this._unsafeLadder(point, scalar, prev); // For W=1 ladder is ~x2 faster\n return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n createCache(P: PC_P, W: number): void {\n validateW(W, this.bits);\n pointWindowSizes.set(P, W);\n pointPrecomputes.delete(P);\n }\n\n hasCache(elm: PC_P): boolean {\n return getW(elm) !== 1;\n }\n}\n\n/**\n * Endomorphism-specific multiplication for Koblitz curves.\n * Cost: 128 dbl, 0-256 adds.\n * @param Point - Point constructor.\n * @param point - Input point.\n * @param k1 - First non-negative absolute scalar chunk.\n * @param k2 - Second non-negative absolute scalar chunk.\n * @returns Partial multiplication results.\n * @example\n * Endomorphism-specific multiplication for Koblitz curves.\n *\n * ```ts\n * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);\n * ```\n */\nexport function mulEndoUnsafe

, PC extends CurvePointCons

>(\n Point: PC,\n point: P,\n k1: bigint,\n k2: bigint\n): { p1: P; p2: P } {\n let acc = point;\n let p1 = Point.ZERO;\n let p2 = Point.ZERO;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) p1 = p1.add(acc);\n if (k2 & _1n) p2 = p2.add(acc);\n acc = acc.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n return { p1, p2 };\n}\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 * Algorithmically constant-time (for same L), even when 1 point + scalar, or when scalar = 0.\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

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n scalars: bigint[]\n): P {\n // If we split scalars by some window (let's say 8 bits), every chunk will only\n // take 256 buckets even if there are 4096 scalars, also re-uses double.\n // TODO:\n // - https://eprint.iacr.org/2024/750.pdf\n // - https://tches.iacr.org/index.php/TCHES/article/view/10287\n // 0 is accepted in scalars\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) throw new Error('arrays of points and scalars must have equal length');\n // if (plength === 0) throw new Error('array must be of length >= 2');\n const zero = c.ZERO;\n const wbits = bitLen(BigInt(plength));\n let windowSize = 1; // bits\n if (wbits > 12) windowSize = wbits - 3;\n else if (wbits > 4) windowSize = wbits - 2;\n else if (wbits > 0) 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) for (let j = 0; j < windowSize; j++) sum = sum.double();\n }\n return sum as P;\n}\n/**\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n * @param c - Curve Point constructor\n * @param points - array of L curve points\n * @param windowSize - Precompute window size.\n * @returns Function which multiplies points with scalars. The closure accepts\n * `scalars.length <= points.length`, and omitted trailing scalars are treated as zero.\n * @throws If the point set or precompute window is invalid. {@link Error}\n * @example\n * Precomputed multi-scalar multiplication (MSM, Pa + Qb + Rc + ...).\n *\n * ```ts\n * import { precomputeMSMUnsafe } from '@noble/curves/abstract/curve.js';\n * import { p256 } from '@noble/curves/nist.js';\n * const msm = precomputeMSMUnsafe(p256.Point, [p256.Point.BASE], 4);\n * const point = msm([3n]);\n * ```\n */\nexport function precomputeMSMUnsafe

, PC extends CurvePointCons

>(\n c: PC,\n points: P[],\n windowSize: number\n): (scalars: bigint[]) => P {\n /**\n * Performance Analysis of Window-based Precomputation\n *\n * Base Case (256-bit scalar, 8-bit window):\n * - Standard precomputation requires:\n * - 31 additions per scalar \u00D7 256 scalars = 7,936 ops\n * - Plus 255 summary additions = 8,191 total ops\n * Note: Summary additions can be optimized via accumulator\n *\n * Chunked Precomputation Analysis:\n * - Using 32 chunks requires:\n * - 255 additions per chunk\n * - 256 doublings\n * - Total: (255 \u00D7 32) + 256 = 8,416 ops\n *\n * Memory Usage Comparison:\n * Window Size | Standard Points | Chunked Points\n * ------------|-----------------|---------------\n * 4-bit | 520 | 15\n * 8-bit | 4,224 | 255\n * 10-bit | 13,824 | 1,023\n * 16-bit | 557,056 | 65,535\n *\n * Key Advantages:\n * 1. Enables larger window sizes due to reduced memory overhead\n * 2. More efficient for smaller scalar counts:\n * - 16 chunks: (16 \u00D7 255) + 256 = 4,336 ops\n * - ~2x faster than standard 8,191 ops\n *\n * Limitations:\n * - Not suitable for plain precomputes (requires 256 constant doublings)\n * - Performance degrades with larger scalar counts:\n * - Optimal for ~256 scalars\n * - Less efficient for 4096+ scalars (Pippenger preferred)\n */\n const fieldN = c.Fn;\n validateW(windowSize, fieldN.BITS);\n validateMSMPoints(points, c);\n const zero = c.ZERO;\n const tableSize = 2 ** windowSize - 1; // table size (without zero)\n const chunks = Math.ceil(fieldN.BITS / windowSize); // chunks of item\n const MASK = bitMask(windowSize);\n const tables = points.map((p: P) => {\n const res = [];\n for (let i = 0, acc = p; i < tableSize; i++) {\n res.push(acc);\n acc = acc.add(p);\n }\n return res;\n });\n return (scalars: bigint[]): P => {\n validateMSMScalars(scalars, fieldN);\n if (scalars.length > points.length)\n throw new Error('array of scalars must be smaller than array of points');\n let res = zero;\n for (let i = 0; i < chunks; i++) {\n // No need to double if accumulator is still zero.\n if (res !== zero) for (let j = 0; j < windowSize; j++) res = res.double();\n const shiftBy = BigInt(chunks * windowSize - (i + 1) * windowSize);\n for (let j = 0; j < scalars.length; j++) {\n const n = scalars[j];\n const curr = Number((n >> shiftBy) & MASK);\n if (!curr) continue; // skip zero scalars chunks\n res = res.add(tables[j][curr - 1]);\n }\n }\n return res;\n };\n}\n\n/** Minimal curve parameters needed to construct a Weierstrass or Edwards curve. */\nexport type ValidCurveParams = {\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Cofactor. */\n h: bigint;\n /** Curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b?: T;\n /** Edwards curve parameter `d`. */\n d?: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n};\n\nfunction createField(order: bigint, field?: TArg>, isLE?: boolean): TRet> {\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) throw new Error('Field.ORDER must match order: Fp == p, Fn == n');\n validateField(field);\n return field as TRet>;\n } else {\n return Field(order, { isLE }) as unknown as TRet>;\n }\n}\n/** Pair of fields used by curve constructors. */\nexport type FpFn = {\n /** Base field used for curve coordinates. */\n Fp: IField;\n /** Scalar field used for secret scalars and subgroup arithmetic. */\n Fn: IField;\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:\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(\n type: 'weierstrass' | 'edwards',\n CURVE: ValidCurveParams,\n curveOpts: TArg>> = {},\n FpFnLE?: boolean\n): TRet & { CURVE: ValidCurveParams }> {\n if (FpFnLE === undefined) FpFnLE = type === 'edwards';\n if (!CURVE || typeof CURVE !== 'object') throw new Error(`expected valid ${type} CURVE object`);\n for (const p of ['p', 'n', 'h'] as const) {\n const val = CURVE[p];\n if (!(typeof val === 'bigint' && 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: 'b' | 'd' = type === 'weierstrass' ? 'b' : 'd';\n const params = ['Gx', 'Gy', 'a', _b] as const;\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 } as TRet & { CURVE: ValidCurveParams }>;\n}\n\ntype KeygenFn = (\n seed?: Uint8Array,\n isCompressed?: boolean\n) => { secretKey: Uint8Array; publicKey: Uint8Array };\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(\n randomSecretKey: Function,\n getPublicKey: TArg\n): TRet {\n return function keygen(seed?: TArg) {\n const secretKey = randomSecretKey(seed) as TRet;\n return { secretKey, publicKey: getPublicKey(secretKey) as TRet };\n };\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 type { TArg } from '../utils.ts';\nimport type { IField } from './modular.ts';\n\n/** Array-like coefficient storage that can be mutated in place. */\nexport interface MutableArrayLike {\n /** Element access by numeric index. */\n [index: number]: T;\n /** Current amount of stored coefficients. */\n length: number;\n /**\n * Return a sliced copy using the same storage shape.\n * @param start - Inclusive start index.\n * @param end - Exclusive end index.\n * @returns Sliced copy.\n */\n slice(start?: number, end?: number): this;\n /**\n * Iterate over stored coefficients in order.\n * @returns Coefficient iterator.\n */\n [Symbol.iterator](): Iterator;\n}\n\n/**\n * Concrete polynomial containers accepted by the high-level `poly(...)` helpers.\n * Lower-level FFT helpers can work with structural `MutableArrayLike`, but `poly(...)`\n * intentionally keeps runtime dispatch on plain arrays and typed-array views.\n */\nexport type PolyStorage = T[] | (MutableArrayLike & ArrayBufferView);\n\nfunction checkU32(n: number) {\n // 0xff_ff_ff_ff\n if (!Number.isSafeInteger(n) || n < 0 || n > 0xffffffff)\n throw new Error('wrong u32 integer:' + n);\n return n;\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 * @throws If `x` is not a valid unsigned 32-bit integer. {@link Error}\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: number): boolean {\n checkU32(x);\n return (x & (x - 1)) === 0 && x !== 0;\n}\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: number): number {\n checkU32(n);\n if (n <= 1) 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) throw new Error('nextPowerOfTwo overflow: result does not fit u32');\n return (1 << (log2(n - 1) + 1)) >>> 0;\n}\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: number, bits: number): number {\n checkU32(n);\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) 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/**\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 * @throws If `n` is not a valid unsigned 32-bit integer. {@link Error}\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: number): number {\n checkU32(n);\n return 31 - Math.clz32(n);\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: T): T {\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)) 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/**\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: T[]): T[] {\n return bitReversalInplace(values.slice()) as T[];\n}\n\nconst _1n = /** @__PURE__ */ BigInt(1);\nfunction findGenerator(field: TArg>) {\n let G = BigInt(2);\n for (; field.eql(field.pow(G, field.ORDER >> _1n), field.ONE); G++);\n return G;\n}\n\n/** Cached roots-of-unity tables derived from one finite field. */\nexport type RootsOfUnity = {\n /** Generator and 2-adicity metadata for the cached field. */\n info: { G: bigint; oddFactor: bigint; powerOfTwo: number };\n /**\n * Return the natural-order roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Natural-order roots for that size.\n */\n roots: (bits: number) => bigint[];\n /**\n * Return the bit-reversal permutation of the roots for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Bit-reversed roots.\n */\n brp(bits: number): bigint[];\n /**\n * Return the inverse roots of unity for one radix-2 size.\n * @param bits - Transform size as `log2(N)`.\n * @returns Inverse roots.\n */\n inverse(bits: number): bigint[];\n /**\n * Return one primitive root used by a radix-2 stage.\n * @param bits - Transform size as `log2(N)`.\n * @returns Primitive root for that stage.\n */\n omega: (bits: number) => bigint;\n /**\n * Drop all cached root tables.\n * @returns Nothing.\n */\n clear: () => void;\n};\n/**\n * We limit roots up to 2**31, which is a lot: 2-billion polynomimal should be rare.\n * @param field - Field implementation.\n * @param generator - Optional generator override.\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: TArg>, generator?: bigint): RootsOfUnity {\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: bigint[] = new Array(powerOfTwo + 1);\n omegas[powerOfTwo] = field.pow(G, oddFactor);\n for (let i = powerOfTwo; i > 0; i--) omegas[i - 1] = field.sqr(omegas[i]);\n // Compute all roots of unity for powers up to maxPower\n const rootsCache: bigint[][] = [];\n const checkBits = (bits: number) => {\n checkU32(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: number) => {\n checkBits(maxPower);\n for (let power = maxPower; power >= 0; power--) {\n if (rootsCache[power]) continue; // Skip if we've already computed roots for this power\n const rootsAtPower: bigint[] = [];\n for (let j = 0, cur = field.ONE; j < 2 ** power; j++, cur = field.mul(cur, omegas[power]))\n rootsAtPower.push(cur);\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\n // NOTE: we use bits instead of power, because power = 2**bits,\n // but power is not neccesary isPowerOfTwo(power)!\n return {\n info: { G, powerOfTwo, oddFactor },\n roots: (bits: number): bigint[] => {\n const b = checkBits(bits);\n return precomputeRoots(b);\n },\n brp(bits: number): bigint[] {\n const b = checkBits(bits);\n if (brpCache.has(b)) 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: number): bigint[] {\n const b = checkBits(bits);\n if (inverseCache.has(b)) return inverseCache.get(b)!;\n else {\n const res = field.invertBatch(this.roots(b));\n inverseCache.set(b, res);\n return res;\n }\n },\n omega: (bits: number): bigint => omegas[checkBits(bits)],\n clear: (): void => {\n rootsCache.splice(0, rootsCache.length);\n brpCache.clear();\n inverseCache.clear();\n },\n };\n}\n\n/** Polynomial coefficient container used by the FFT helpers. */\nexport type Polynomial = MutableArrayLike;\n\n/**\n * Arithmetic operations used by the generic FFT implementation.\n *\n * Maps great to Field, but not to Group (EC points):\n * - inv from scalar field\n * - we need multiplyUnsafe here, instead of multiply for speed\n * - multiplyUnsafe is safe in the context: we do mul(rootsOfUnity), which are public and sparse\n */\nexport type FFTOpts = {\n /**\n * Add two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Sum coefficient.\n */\n add: (a: T, b: T) => T;\n /**\n * Subtract two coefficients.\n * @param a - Left coefficient.\n * @param b - Right coefficient.\n * @returns Difference coefficient.\n */\n sub: (a: T, b: T) => T;\n /**\n * Multiply one coefficient by a scalar/root factor.\n * @param a - Coefficient value.\n * @param scalar - Scalar/root factor.\n * @returns Scaled coefficient.\n */\n mul: (a: T, scalar: R) => T;\n /**\n * Invert one scalar/root factor.\n * @param a - Scalar/root factor.\n * @returns Inverse factor.\n */\n inv: (a: R) => R;\n};\n\n/** Configuration for one low-level FFT loop. */\nexport type FFTCoreOpts = {\n /** Transform size. Must be a power of two. */\n N: number;\n /** Stage roots for the selected transform size. */\n roots: Polynomial;\n /** Whether to run the DIT variant instead of DIF. */\n dit: boolean;\n /** Whether to invert butterfly placement for decode-oriented layouts. */\n invertButterflies?: boolean;\n /** Number of initial stages to skip. */\n skipStages?: number;\n /** Whether to apply bit-reversal permutation at the boundary. */\n brp?: boolean;\n};\n\n/**\n * Callable low-level FFT loop over one polynomial storage shape.\n * @param values - Polynomial coefficients to transform in place.\n * @returns The mutated input polynomial.\n */\nexport type FFTCoreLoop =

>(values: P) => P;\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), Cool-Turkey\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 * @param F - Field operations.\n * @param coreOpts - FFT configuration:\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: FFTOpts, coreOpts: FFTCoreOpts): FFTCoreLoop => {\n const { N, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;\n const bits = log2(N);\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\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 isDit;\n return

>(values: P): P => {\n if (values.length !== N) throw new Error('FFT: wrong Polynomial length');\n if (dit && brp) 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 } 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 } 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) bitReversalInplace(values);\n return values;\n };\n};\n\n/** Forward and inverse FFT helpers for one coefficient domain. */\nexport type FFTMethods = {\n /**\n * Apply the forward transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Transformed copy.\n */\n direct

>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\n /**\n * Apply the inverse transform.\n * @param values - Polynomial coefficients to transform.\n * @param brpInput - Whether the input is already bit-reversed.\n * @param brpOutput - Whether to keep the output bit-reversed.\n * @returns Inverse-transformed copy.\n */\n inverse

>(values: P, brpInput?: boolean, brpOutput?: boolean): P;\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: RootsOfUnity, opts: FFTOpts): FFTMethods {\n const getLoop = (\n N: number,\n roots: Polynomial,\n brpInput = false,\n brpOutput = false\n ): (

>(values: P) => P) => {\n if (brpInput && brpOutput) {\n // we cannot optimize this case, but lets support it anyway\n return (values) =>\n FFTCore(opts, { N, roots, dit: false, brp: false })(bitReversalInplace(values));\n }\n if (brpInput) return FFTCore(opts, { N, roots, dit: true, brp: false });\n if (brpOutput) return FFTCore(opts, { N, roots, dit: false, brp: false });\n return FFTCore(opts, { N, roots, dit: true, brp: true }); // all natural\n };\n return {\n direct

>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n return getLoop(N, roots.roots(bits), brpInput, brpOutput)

(values.slice());\n },\n inverse

>(values: P, brpInput = false, brpOutput = false): P {\n const N = values.length;\n if (!isPowerOfTwo(N)) throw new Error('FFT: Polynomial size should be power of two');\n const bits = log2(N);\n const res = getLoop(N, roots.inverse(bits), brpInput, brpOutput)(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++) 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}\n\n/**\n * Factory that allocates one polynomial storage container.\n * Callers must ensure `_create(len)` returns field-zero-filled storage when `elm` is omitted,\n * because the quadratic `mul()` / `convolve()` paths and the Kronecker-\u03B4 shortcut in\n * `lagrange.basis()` rely on that default instead of always passing `field.ZERO` explicitly.\n * @param len - Requested amount of coefficients.\n * @param elm - Optional fill value.\n * @returns Newly allocated polynomial container.\n */\nexport type CreatePolyFn

, T> = (len: number, elm?: T) => P;\n\n/** High-level polynomial helpers layered on top of FFT and field arithmetic. */\nexport type PolyFn

, T> = {\n /** Roots-of-unity cache used by the helper namespace. */\n roots: RootsOfUnity;\n /** Factory used to allocate new polynomial containers. */\n create: CreatePolyFn;\n /** Optional enforced polynomial length. */\n length?: number;\n\n /**\n * Compute the polynomial degree.\n * @param a - Polynomial coefficients.\n * @returns Polynomial degree.\n */\n degree: (a: P) => number;\n /**\n * Extend or truncate one polynomial to a requested length.\n * @param a - Polynomial coefficients.\n * @param len - Target length.\n * @returns Resized polynomial.\n */\n extend: (a: P, len: number) => P;\n /**\n * Add two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Sum polynomial.\n */\n add: (a: P, b: P) => P;\n /**\n * Subtract two polynomials coefficient-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Difference polynomial.\n */\n sub: (a: P, b: P) => P;\n /**\n * Multiply by another polynomial or by one scalar.\n * @param a - Left polynomial.\n * @param b - Right polynomial or scalar.\n * @returns Product polynomial.\n */\n mul: (a: P, b: P | T) => P;\n /**\n * Multiply coefficients point-wise.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Point-wise product polynomial.\n */\n dot: (a: P, b: P) => P;\n /**\n * Multiply two polynomials with convolution.\n * @param a - Left polynomial.\n * @param b - Right polynomial.\n * @returns Convolution product.\n */\n convolve: (a: P, b: P) => P;\n /**\n * Apply a point-wise coefficient shift by powers of one factor.\n * @param p - Polynomial coefficients.\n * @param factor - Shift factor.\n * @returns Shifted polynomial.\n */\n shift: (p: P, factor: bigint) => P;\n /**\n * Clone one polynomial container.\n * @param a - Polynomial coefficients.\n * @returns Cloned polynomial.\n */\n clone: (a: P) => P;\n /**\n * Evaluate one polynomial on a basis vector.\n * @param a - Polynomial coefficients.\n * @param basis - Basis vector.\n * @returns Evaluated field element.\n */\n eval: (a: P, basis: P) => T;\n /** Helpers for monomial-basis polynomials. */\n monomial: {\n /** Build the monomial basis vector for one evaluation point. */\n basis: (x: T, n: number) => P;\n /** Evaluate a polynomial in the monomial basis. */\n eval: (a: P, x: T) => T;\n };\n /** Helpers for Lagrange-basis polynomials. */\n lagrange: {\n /** Build the Lagrange basis vector for one evaluation point. */\n basis: (x: T, n: number, brp?: boolean) => P;\n /** Evaluate a polynomial in the Lagrange basis. */\n eval: (a: P, x: T, brp?: boolean) => T;\n };\n /**\n * Build the vanishing polynomial for a root set.\n * @param roots - Root set.\n * @returns Vanishing polynomial.\n */\n vanishing: (roots: P) => P;\n};\n\n/**\n * Poly wants a cracker.\n *\n * Polynomials are functions like `y=f(x)`, which means when we multiply two polynomials, result is\n * function `f3(x) = f1(x) * f2(x)`, we don't multiply values. Key takeaways:\n *\n * - **Polynomial** is an array of coefficients: `f(x) = sum(coeff[i] * basis[i](x))`\n * - **Basis** is array of functions\n * - **Monominal** is Polynomial where `basis[i](x) == x**i` (powers)\n * - **Array size** is domain size\n * - **Lattice** is matrix (Polynomial of Polynomials)\n * @param field - Field implementation.\n * @param roots - Roots-of-unity cache.\n * @param create - Optional polynomial factory. Runtime input validation accepts only plain `Array`\n * and typed-array polynomial containers; arbitrary structural wrappers are intentionally rejected.\n * @param fft - Optional FFT implementation.\n * @param length - Optional fixed polynomial length.\n * @returns Polynomial helper namespace.\n * @example\n * Build polynomial helpers, then convolve two coefficient arrays.\n *\n * ```ts\n * import { poly, rootsOfUnity } from '@noble/curves/abstract/fft.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const poly17 = poly(Fp, rootsOfUnity(Fp));\n * const product = poly17.convolve([1n, 2n], [3n, 4n]);\n * ```\n */\nexport function poly(\n field: TArg>,\n roots: RootsOfUnity,\n create?: undefined,\n fft?: FFTMethods,\n length?: number\n): PolyFn;\nexport function poly>(\n field: TArg>,\n roots: RootsOfUnity,\n create: CreatePolyFn,\n fft?: FFTMethods,\n length?: number\n): PolyFn;\nexport function poly>(\n field: TArg>,\n roots: RootsOfUnity,\n create?: CreatePolyFn,\n fft?: FFTMethods,\n length?: number\n): PolyFn {\n const F = field as IField;\n const _create =\n create ||\n (((len: number, elm?: T): T[] => new Array(len).fill(elm ?? F.ZERO)) as CreatePolyFn);\n\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: any): x is P => {\n if (Array.isArray(x)) return true;\n if (!ArrayBuffer.isView(x)) return false;\n const v = x as unknown as ArrayLike & { slice?: unknown; [Symbol.iterator]?: unknown };\n return (\n typeof v.length === 'number' &&\n typeof v.slice === 'function' &&\n typeof v[Symbol.iterator] === 'function'\n );\n };\n const checkLength = (...lst: P[]): number => {\n if (!lst.length) return 0;\n for (const i of lst) if (!isPoly(i)) throw new Error('poly: not polynomial: ' + i);\n const L = lst[0].length;\n for (let i = 1; i < lst.length; i++)\n if (lst[i].length !== L) throw new Error(`poly: mismatched lengths ${L} vs ${lst[i].length}`);\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: T, n: number, brp = false): number {\n const bits = log2(n);\n const omega = brp ? roots.brp(bits) : roots.roots(bits);\n for (let i = 0; i < n; i++) if (F.eql(x, omega[i] as T)) 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: P, len: number): P => {\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++) out[i] = a[i];\n return out;\n },\n degree: (a: P): number => {\n checkLength(a);\n for (let i = a.length - 1; i >= 0; i--) if (!F.is0(a[i])) return i;\n return -1;\n },\n add: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.add(a[i], b[i]);\n return out;\n },\n sub: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.sub(a[i], b[i]);\n return out;\n },\n dot: (a: P, b: P): P => {\n const len = checkLength(a, b);\n const out = _create(len);\n for (let i = 0; i < len; i++) out[i] = F.mul(a[i], b[i]);\n return out;\n },\n mul: (a: P, b: P | T): P => {\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++) A[i] = F.mul(A[i], B[i]);\n return fft.inverse(A, true, false) as P;\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 } else {\n const out = _create(checkLength(a));\n for (let i = 0; i < out.length; i++) out[i] = F.mul(a[i], b);\n return out;\n }\n },\n convolve(a: P, b: P): P {\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: P, factor: bigint): P {\n const out = _create(checkLength(p));\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: P): P => {\n checkLength(a);\n const out = _create(a.length);\n for (let i = 0; i < a.length; i++) out[i] = a[i];\n return out;\n },\n eval: (a: P, basis: P): T => {\n checkLength(a, basis);\n let acc = F.ZERO;\n for (let i = 0; i < a.length; i++) acc = F.add(acc, F.mul(a[i], basis[i]));\n return acc;\n },\n monomial: {\n basis: (x: T, n: number): P => {\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: P, x: T): T => {\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--) acc = F.add(F.mul(acc, x), a[i]);\n return acc;\n },\n },\n lagrange: {\n basis: (x: T, n: number, brp = false, weights?: P): P => {\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);\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) as T)); // c = (x\u207F - 1)/n\n const denom = _create(n);\n for (let i = 0; i < n; i++) denom[i] = F.sub(x, cache[i] as T);\n const inv = F.invertBatch(denom as any as T[]);\n for (let i = 0; i < n; i++) out[i] = F.mul(c, F.mul(cache[i] as T, inv[i]));\n return out;\n },\n eval(a: P, x: T, brp = false): T {\n checkLength(a);\n const idx = findOmegaIndex(x, a.length, brp);\n if (idx !== -1) 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++) if (!F.is0(a[i])) acc = F.add(acc, F.mul(a[i], L[i]));\n return acc;\n },\n },\n vanishing(roots: P): P {\n checkLength(roots);\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--) 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 * 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 {\n abignumber,\n abool,\n abytes,\n aInRange,\n asafenumber,\n bitLen,\n bitMask,\n bytesToHex,\n bytesToNumberBE,\n concatBytes,\n createHmacDrbg,\n hexToBytes,\n isBytes,\n numberToHexUnpadded,\n validateObject,\n randomBytes as wcRandomBytes,\n type CHash,\n type HmacFn,\n type Signer,\n type TArg,\n type TRet,\n} from '../utils.ts';\nimport {\n createCurveFields,\n createKeygen,\n mulEndoUnsafe,\n negateCt,\n normalizeZ,\n wNAF,\n type AffinePoint,\n type CurveLengths,\n type CurvePoint,\n type CurvePointCons,\n} from './curve.ts';\nimport {\n FpInvertBatch,\n FpIsSquare,\n getMinHashLength,\n mapHashToField,\n validateField,\n type IField,\n} from './modular.ts';\n\n/** Shared affine point shape used by Weierstrass helpers. */\nexport type { AffinePoint };\n\ntype EndoBasis = [[bigint, bigint], [bigint, bigint]];\n/**\n * When Weierstrass curve has `a=0`, it becomes Koblitz curve.\n * Koblitz curves allow using **efficiently-computable GLV endomorphism \u03C8**.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n *\n * Endomorphism consists of beta, lambda and splitScalar:\n *\n * 1. GLV endomorphism \u03C8 transforms a point: `P = (x, y) \u21A6 \u03C8(P) = (\u03B2\u00B7x mod p, y)`\n * 2. GLV scalar decomposition transforms a scalar: `k \u2261 k\u2081 + k\u2082\u00B7\u03BB (mod n)`\n * 3. Then these are combined: `k\u00B7P = k\u2081\u00B7P + k\u2082\u00B7\u03C8(P)`\n * 4. Two 128-bit point-by-scalar multiplications + one point addition is faster than\n * one 256-bit multiplication.\n *\n * where\n * * beta: \u03B2 \u2208 F\u209A with \u03B2\u00B3 = 1, \u03B2 \u2260 1\n * * lambda: \u03BB \u2208 F\u2099 with \u03BB\u00B3 = 1, \u03BB \u2260 1\n * * splitScalar decomposes k \u21A6 k\u2081, k\u2082, by using reduced basis vectors.\n * Gauss lattice reduction calculates them from initial basis vectors `(n, 0), (-\u03BB, 0)`\n *\n * Check out `test/misc/endomorphism.js` and\n * {@link https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066 | this endomorphism gist}.\n */\nexport type EndomorphismOpts = {\n /** Cube root of unity used by the GLV endomorphism. */\n beta: bigint;\n /** Reduced lattice basis used for scalar splitting. */\n basises?: EndoBasis;\n /**\n * Optional custom scalar-splitting helper.\n * Receives one scalar and returns two half-sized scalar components.\n */\n splitScalar?: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\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: bigint, den: bigint) => (num + (num >= 0 ? den : -den) / _2n) / den;\n\n/** Two half-sized scalar components returned by endomorphism splitting. */\nexport type ScalarEndoParts = {\n /** Whether the first split scalar should be negated. */\n k1neg: boolean;\n /** Absolute value of the first split scalar. */\n k1: bigint;\n /** Whether the second split scalar should be negated. */\n k2neg: boolean;\n /** Absolute value of the second split scalar. */\n k2: bigint;\n};\n\n/** Splits scalar for GLV endomorphism. */\nexport function _splitEndoScalar(k: bigint, basis: EndoBasis, n: bigint): ScalarEndoParts {\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) k1 = -k1;\n if (k2neg) k2 = -k2;\n // Double check that resulting scalar less than half bits of N: otherwise wNAF will fail.\n // 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}\n\n/**\n * Option to enable hedged signatures with improved security.\n *\n * * Randomly generated k is bad, because broken CSPRNG would leak private keys.\n * * Deterministic k (RFC6979) is better; but is suspectible to fault attacks.\n *\n * We allow using technique described in RFC6979 3.6: additional k', a.k.a. adding randomness\n * to deterministic sig. If CSPRNG is broken & randomness is weak, it would STILL be as secure\n * as ordinary sig without ExtraEntropy.\n *\n * * `true` means \"fetch data, from CSPRNG, incorporate it into k generation\"\n * * `false` means \"disable extra entropy, use purely deterministic k\"\n * * `Uint8Array` passed means \"incorporate following data into k generation\"\n *\n * See {@link https://paulmillr.com/posts/deterministic-signatures/ | deterministic signatures}.\n */\nexport type ECDSAExtraEntropy = boolean | Uint8Array;\n/**\n * - `compact` is the default format\n * - `recovered` is the same as compact, but with an extra byte indicating recovery byte\n * - `der` is ASN.1 DER encoding\n */\nexport type ECDSASignatureFormat = 'compact' | 'recovered' | 'der';\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n */\nexport type ECDSARecoverOpts = {\n /** Whether to hash the message before signature recovery. */\n prehash?: boolean;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n */\nexport type ECDSAVerifyOpts = {\n /** Whether to hash the message before verification. */\n prehash?: boolean;\n /** Whether to reject high-S signatures. */\n lowS?: boolean;\n /** Signature encoding to accept. */\n format?: ECDSASignatureFormat;\n};\n/**\n * - `prehash`: (default: true) indicates whether to do sha256(message).\n * When a custom hash is used, it must be set to `false`.\n * - `lowS`: (default: true) prohibits signatures with `sig.s >= CURVE.n/2n`.\n * Compatible with BTC/ETH. Setting `lowS: false` allows to create malleable signatures,\n * which is default openssl behavior.\n * Non-malleable signatures can still be successfully verified in openssl.\n * - `format`: (default: 'compact') 'compact' or 'recovered' with recovery byte\n * - `extraEntropy`: (default: false) creates signatures with increased\n * security, see {@link ECDSAExtraEntropy}\n */\nexport type ECDSASignOpts = {\n /** Whether to hash the message before signing. */\n prehash?: boolean;\n /** Whether to normalize signatures into the low-S half-order. */\n lowS?: boolean;\n /** Signature encoding to produce. */\n format?: ECDSASignatureFormat;\n /** Optional hedging input for deterministic k generation. */\n extraEntropy?: ECDSAExtraEntropy;\n};\n\nfunction validateSigFormat(format: string): ECDSASignatureFormat {\n if (!['compact', 'recovered', 'der'].includes(format))\n throw new Error('Signature format must be \"compact\", \"recovered\", or \"der\"');\n return format as ECDSASignatureFormat;\n}\n\nfunction validateSigOpts>(\n opts: T,\n def: D\n): D {\n validateObject(opts);\n const optsn = {} as D;\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) as (keyof D)[]) {\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) validateSigFormat(optsn.format);\n return optsn;\n}\n\n/** Projective XYZ point used by short Weierstrass curves. */\nexport interface WeierstrassPoint extends CurvePoint> {\n /** projective X coordinate. Different from affine x. */\n readonly X: T;\n /** projective Y coordinate. Different from affine y. */\n readonly Y: T;\n /** projective z coordinate */\n readonly Z: T;\n /** affine x coordinate. Different from projective X. */\n get x(): T;\n /** affine y coordinate. Different from projective Y. */\n get y(): T;\n /**\n * Encode the point into compressed or uncompressed SEC1 bytes.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point bytes.\n */\n toBytes(isCompressed?: boolean): TRet;\n /**\n * Encode the point into compressed or uncompressed SEC1 hex.\n * @param isCompressed - Whether to use the compressed form.\n * @returns Encoded point hex.\n */\n toHex(isCompressed?: boolean): string;\n}\n\n/** Constructor and metadata helpers for Weierstrass points. */\nexport interface WeierstrassPointCons extends CurvePointCons> {\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n new (X: T, Y: T, Z: T): WeierstrassPoint;\n /**\n * Return the curve parameters captured by this point constructor.\n * @returns Curve parameters.\n */\n CURVE(): WeierstrassOpts;\n}\n\n/**\n * Weierstrass curve options.\n *\n * * p: prime characteristic (order) of finite field, in which arithmetics is done\n * * n: order of prime subgroup a.k.a total amount of valid curve points\n * * h: cofactor, usually 1. h*n is group order; n is subgroup order\n * * a: formula param, must be in field of p\n * * b: formula param, must be in field of p\n * * Gx: x coordinate of generator point a.k.a. base point\n * * Gy: y coordinate of generator point\n */\nexport type WeierstrassOpts = Readonly<{\n /** Base-field modulus. */\n p: bigint;\n /** Prime subgroup order. */\n n: bigint;\n /** Curve cofactor. */\n h: bigint;\n /** Weierstrass curve parameter `a`. */\n a: T;\n /** Weierstrass curve parameter `b`. */\n b: T;\n /** Generator x coordinate. */\n Gx: T;\n /** Generator y coordinate. */\n Gy: T;\n}>;\n\n/**\n * Optional helpers and overrides for a Weierstrass point constructor.\n *\n * When a cofactor != 1, there can be effective methods to:\n * 1. Determine whether a point is torsion-free\n * 2. Clear torsion component\n */\nexport type WeierstrassExtraOpts = Partial<{\n /** Optional base-field override. */\n Fp: IField;\n /** Optional scalar-field override. */\n Fn: IField;\n /** Whether the point constructor accepts infinity points. */\n allowInfinityPoint: boolean;\n /** Optional GLV endomorphism data. */\n endo: EndomorphismOpts;\n /** Optional torsion-check override. */\n isTorsionFree: (c: WeierstrassPointCons, point: WeierstrassPoint) => boolean;\n /** Optional cofactor-clearing override. */\n clearCofactor: (c: WeierstrassPointCons, point: WeierstrassPoint) => WeierstrassPoint;\n /** Optional custom point decoder. */\n fromBytes: (bytes: TArg) => AffinePoint;\n /** Optional custom point encoder. */\n toBytes: (\n c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ) => TRet;\n}>;\n\n/**\n * Options for ECDSA signatures over a Weierstrass curve.\n *\n * * lowS: (default: true) whether produced or verified signatures occupy the\n * low half of `ecdsaOpts.n`. Prevents malleability.\n * * hmac: (default: noble-hashes hmac) function, would be used to init hmac-drbg for k generation.\n * * randomBytes: (default: webcrypto os-level CSPRNG) custom method for fetching secure randomness.\n * * bits2int, bits2int_modN: used in sigs, sometimes overridden by curves. Custom hooks are\n * treated as pure functions over validated bytes and MUST NOT mutate caller-owned buffers or\n * closure-captured option bags. `bits2int_modN` must also return a canonical scalar in\n * `[0..Point.Fn.ORDER-1]`.\n */\nexport type ECDSAOpts = Partial<{\n /** Default low-S policy for this ECDSA instance. */\n lowS: boolean;\n /** HMAC implementation used by RFC6979 DRBG. */\n hmac: HmacFn;\n /** RNG override used by helper constructors. */\n randomBytes: (bytesLength?: number) => TRet;\n /** Hash-to-integer conversion override. */\n bits2int: (bytes: TArg) => bigint;\n /** Hash-to-integer-mod-n conversion override. Returns a canonical scalar in `[0..Fn.ORDER-1]`. */\n bits2int_modN: (bytes: TArg) => bigint;\n}>;\n\n/** Elliptic Curve Diffie-Hellman helper namespace. */\nexport interface ECDH {\n /**\n * Generate a secret/public key pair.\n * @param seed - Optional seed material.\n * @returns Secret/public key pair.\n */\n keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet };\n /**\n * Derive the public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded public key.\n */\n getPublicKey: (secretKey: TArg, isCompressed?: boolean) => TRet;\n /**\n * Compute the shared secret point from a secret key and peer public key.\n * @param secretKeyA - Local secret key bytes.\n * @param publicKeyB - Peer public key bytes.\n * @param isCompressed - Whether to emit compressed SEC1 bytes.\n * @returns Encoded shared point.\n */\n getSharedSecret: (\n secretKeyA: TArg,\n publicKeyB: TArg,\n isCompressed?: boolean\n ) => TRet;\n /** Point constructor used by this ECDH instance. */\n Point: WeierstrassPointCons;\n /** Validation and random-key helpers. */\n utils: {\n /** Check whether a secret key has the expected encoding. */\n isValidSecretKey: (secretKey: TArg) => boolean;\n /** Check whether a public key decodes to a valid point. */\n isValidPublicKey: (publicKey: TArg, isCompressed?: boolean) => boolean;\n /** Generate a valid random secret key. */\n randomSecretKey: (seed?: TArg) => TRet;\n };\n /** Byte lengths for keys and signatures exposed by this curve. */\n lengths: CurveLengths;\n}\n\n/**\n * ECDSA interface.\n * Only supported for prime fields, not Fp2 (extension fields).\n */\nexport interface ECDSA extends ECDH {\n /**\n * Sign a message with the given secret key.\n * @param message - Message bytes.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing tweaks. See {@link ECDSASignOpts}.\n * @returns Encoded signature bytes.\n */\n sign: (\n message: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n /**\n * Verify a signature against a message and public key.\n * @param signature - Encoded signature bytes.\n * @param message - Message bytes.\n * @param publicKey - Encoded public key.\n * @param opts - Optional verification tweaks. See {@link ECDSAVerifyOpts}.\n * @returns Whether the signature is valid.\n */\n verify: (\n signature: TArg,\n message: TArg,\n publicKey: TArg,\n opts?: TArg\n ) => boolean;\n /**\n * Recover the public key encoded into a recoverable signature.\n * @param signature - Recoverable signature bytes.\n * @param message - Message bytes.\n * @param opts - Optional recovery tweaks. See {@link ECDSARecoverOpts}.\n * @returns Encoded recovered public key.\n */\n recoverPublicKey(\n signature: TArg,\n message: TArg,\n opts?: TArg\n ): TRet;\n /** Signature constructor and parser helpers. */\n Signature: ECDSASignatureCons;\n}\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/** DER helper namespace used by ECDSA signature parsing and encoding. */\nexport type IDER = {\n // asn.1 DER encoding utils\n /**\n * DER-specific error constructor.\n * @param m - Error message.\n * @returns DER-specific error instance.\n */\n Err: typeof DERErr;\n // Basic building block is TLV (Tag-Length-Value)\n /** Low-level tag-length-value helpers used by DER encoders. */\n _tlv: {\n /**\n * Encode one TLV record.\n * @param tag - ASN.1 tag byte.\n * @param data - Hex-encoded value payload.\n * @returns Encoded TLV string.\n */\n encode: (tag: number, data: string) => string;\n // v - value, l - left bytes (unparsed)\n /**\n * Decode one TLV record and return the value plus leftover bytes.\n * @param tag - Expected ASN.1 tag byte.\n * @param data - Remaining DER bytes.\n * @returns Parsed value plus leftover bytes.\n */\n decode(tag: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }>;\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 /** Positive-integer DER helpers used by ECDSA signature encoding. */\n _int: {\n /**\n * Encode one positive bigint as a DER INTEGER.\n * @param num - Positive integer to encode.\n * @returns Encoded DER INTEGER.\n */\n encode(num: bigint): string;\n /**\n * Decode one DER INTEGER into a bigint.\n * @param data - DER INTEGER bytes.\n * @returns Decoded bigint.\n */\n decode(data: TArg): bigint;\n };\n /**\n * Parse a DER signature into `{ r, s }`.\n * @param bytes - DER signature bytes.\n * @returns Parsed signature components.\n */\n toSig(bytes: TArg): { r: bigint; s: bigint };\n /**\n * Encode `{ r, s }` as a DER signature.\n * @param sig - Signature components.\n * @returns DER-encoded signature hex.\n */\n hexFromSig(sig: { r: bigint; s: bigint }): string;\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: IDER = {\n // asn.1 DER encoding utils\n Err: DERErr,\n // Basic building block is TLV (Tag-Length-Value)\n _tlv: {\n encode: (tag: number, data: string): string => {\n const { Err: E } = DER;\n asafenumber(tag, 'tag');\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (typeof data !== 'string')\n throw new TypeError('\"data\" expected string, got type=' + typeof 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) 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) 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: number, data: TArg): TRet<{ v: Uint8Array; l: Uint8Array }> {\n const { Err: E } = DER;\n data = abytes(data, undefined, 'DER data');\n let pos = 0;\n if (tag < 0 || tag > 255) throw new E('tlv.encode: wrong tag');\n if (data.length < 2 || data[pos++] !== tag) 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) length = first;\n else {\n // Long form: [longFlag(1bit), lengthLength(7bit), length (BE)]\n const lenLen = first & 0b0111_1111;\n if (!lenLen) throw new E('tlv.decode(long): indefinite length not supported');\n // This would overflow u32 in JS.\n if (lenLen > 4) throw new E('tlv.decode(long): byte length is too big');\n const lengthBytes = data.subarray(pos, pos + lenLen);\n if (lengthBytes.length !== lenLen) throw new E('tlv.decode: length bytes not complete');\n if (lengthBytes[0] === 0) throw new E('tlv.decode(long): zero leftmost byte');\n for (const b of lengthBytes) length = (length << 8) | b;\n pos += lenLen;\n if (length < 128) throw new E('tlv.decode(long): not minimal encoding');\n }\n const v = data.subarray(pos, pos + length);\n if (v.length !== length) throw new E('tlv.decode: wrong value length');\n return { v, l: data.subarray(pos + length) } as TRet<{ v: Uint8Array; l: Uint8Array }>;\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: bigint): string {\n const { Err: E } = DER;\n abignumber(num);\n if (num < _0n) 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) hex = '00' + hex;\n if (hex.length & 1) throw new E('unexpected DER parsing assertion: unpadded hex');\n return hex;\n },\n decode(data: TArg): bigint {\n const { Err: E } = DER;\n if (data.length < 1) throw new E('invalid signature integer: empty');\n if (data[0] & 0b1000_0000) 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: TArg): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E, _int: int, _tlv: tlv } = DER;\n const data = abytes(bytes, undefined, 'signature');\n const { v: seqBytes, l: seqLeftBytes } = tlv.decode(0x30, data);\n if (seqLeftBytes.length) 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) throw new E('invalid signature: left bytes after parsing');\n return { r: int.decode(rBytes), s: int.decode(sBytes) };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n const { _tlv: tlv, _int: int } = DER;\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};\nObject.freeze(DER._tlv);\nObject.freeze(DER._int);\nObject.freeze(DER);\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/**\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(\n params: WeierstrassOpts,\n extraOpts: WeierstrassExtraOpts = {}\n): WeierstrassPointCons {\n const validated = createCurveFields('weierstrass', params, extraOpts);\n const Fp = validated.Fp as IField;\n const Fn = validated.Fn as IField;\n let CURVE = validated.CURVE as WeierstrassOpts;\n const { h: cofactor, n: CURVE_ORDER } = CURVE;\n validateObject(\n extraOpts,\n {},\n {\n allowInfinityPoint: 'boolean',\n clearCofactor: 'function',\n isTorsionFree: 'function',\n fromBytes: 'function',\n toBytes: 'function',\n endo: 'object',\n }\n );\n\n // Snapshot constructor-time flags whose later mutation would otherwise change\n // validity semantics of an already-built point type.\n const { endo, allowInfinityPoint } = extraOpts;\n if (endo) {\n // validateObject(endo, { beta: 'bigint', splitScalar: 'function' });\n if (!Fp.is0(CURVE.a) || typeof endo.beta !== 'bigint' || !Array.isArray(endo.basises)) {\n throw new Error('invalid endo: expected \"beta\": bigint and \"basises\": array');\n }\n }\n\n const lengths = getWLengths(Fp as TArg>, Fn);\n\n function assertCompressionIsSupported() {\n if (!Fp.isOdd) throw new Error('compression is not supported: Field does not have .isOdd()');\n }\n\n // Implements IEEE P1363 point encoding\n function pointToBytes(\n _c: WeierstrassPointCons,\n point: WeierstrassPoint,\n isCompressed: boolean\n ): TRet {\n // SEC 1 v2.0 \u00A72.3.3 encodes infinity as the single octet 0x00. Only curves\n // that opt into infinity as a public point value should expose that byte form.\n if (allowInfinityPoint && point.is0()) return Uint8Array.of(0) as TRet;\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) as TRet;\n } else {\n return concatBytes(Uint8Array.of(0x04), bx, Fp.toBytes(y)) as TRet;\n }\n }\n function pointFromBytes(bytes: TArg) {\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 if (allowInfinityPoint && length === 1 && head === 0x00) return { x: Fp.ZERO, y: Fp.ZERO };\n // SEC 1 v2.0 \u00A72.3.4 decodes 0x00 as infinity, but \u00A73.2.2 public-key validation\n // rejects infinity. We therefore keep 0x00 rejected by default because callers\n // reuse this parser as the strict public-key boundary, and only admit it when\n // the curve explicitly opts into infinity as a public point value. secp256k1\n // crosstests show OpenSSL raw point codecs accept 0x00 too.\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)) 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: T;\n try {\n y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\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) y = Fp.neg(y);\n return { x, y };\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)) throw new Error('bad point: is not on curve');\n return { x, y };\n } else {\n throw new Error(\n `bad point: got length ${length}, expected compressed=${comp} or uncompressed=${uncomp}`\n );\n }\n }\n\n const encodePoint = extraOpts.toBytes === undefined ? pointToBytes : extraOpts.toBytes;\n const decodePoint = extraOpts.fromBytes === undefined ? pointFromBytes : extraOpts.fromBytes;\n function weierstrassEquation(x: T): T {\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x\u00B2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, CURVE.a)), CURVE.b); // x\u00B3 + a * x + b\n }\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: T, y: T): boolean {\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n return Fp.eql(left, right);\n }\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)) throw new Error('bad curve params: generator point');\n\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))) throw new Error('bad curve params: a or b');\n\n /** Asserts coordinate is valid: 0 <= n < Fp.ORDER. */\n function acoord(title: string, n: T, banZero = false) {\n if (!Fp.isValid(n) || (banZero && Fp.is0(n))) throw new Error(`bad point coordinate ${title}`);\n return n;\n }\n\n function aprjpoint(other: unknown): asserts other is Point {\n if (!(other instanceof Point)) throw new Error('Weierstrass Point expected');\n }\n\n function splitEndoScalarN(k: bigint) {\n if (!endo || !endo.basises) throw new Error('no endo');\n return _splitEndoScalar(k, endo.basises, Fn.ORDER);\n }\n\n function finishEndo(\n endoBeta: EndomorphismOpts['beta'],\n k1p: Point,\n k2p: Point,\n k1neg: boolean,\n k2neg: boolean\n ) {\n k2p = new Point(Fp.mul(k2p.X, endoBeta), k2p.Y, k2p.Z);\n k1p = negateCt(k1neg, k1p);\n k2p = negateCt(k2neg, k2p);\n return k1p.add(k2p);\n }\n\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates:(X, Y, Z) \u220B (x=X/Z, y=Y/Z).\n * Default Point works in 2d / affine coordinates: (x, y).\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements WeierstrassPoint {\n // base / generator point\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n // zero / infinity / identity point\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO); // 0, 1, 0\n // math field\n static readonly Fp = Fp;\n // scalar field\n static readonly Fn = Fn;\n\n readonly X: T;\n readonly Y: T;\n readonly Z: T;\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n constructor(X: T, Y: T, Z: T) {\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\n static CURVE(): WeierstrassOpts {\n return CURVE;\n }\n\n /** Does NOT validate if the point is valid. Use `.assertValidity()`. */\n static fromAffine(p: AffinePoint): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n // (0, 0) would've produced (0, 0, 1) - instead, we need (0, 1, 0)\n if (Fp.is0(x) && Fp.is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n static fromBytes(bytes: TArg): Point {\n const P = Point.fromAffine(decodePoint(abytes(bytes, undefined, 'point')));\n P.assertValidity();\n return P;\n }\n\n static fromHex(hex: string): Point {\n return Point.fromBytes(hexToBytes(hex));\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n *\n * @param windowSize\n * @param isLazy - true will defer table computation until the first multiplication\n * @returns\n */\n precompute(windowSize: number = 8, isLazy = true): Point {\n wnaf.createCache(this, windowSize);\n if (!isLazy) this.multiply(_3n); // random number\n return this;\n }\n\n // TODO: return `this`\n /** A point on curve is valid if it conforms to equation. */\n assertValidity(): void {\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 (extraOpts.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 // 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)) throw new Error('bad point: x or y not field elements');\n if (!isValidXY(x, y)) throw new Error('bad point: equation left != right');\n if (!p.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (!Fp.isOdd) throw new Error(\"Field doesn't support isOdd\");\n return !Fp.isOdd(y);\n }\n\n /** Compare one point to another. */\n equals(other: WeierstrassPoint): boolean {\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\n /** Flips point to one corresponding to (x, -y) in Affine coordinates. */\n negate(): Point {\n return new Point(this.X, Fp.neg(this.Y), this.Z);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { 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 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: WeierstrassPoint): Point {\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 const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: WeierstrassPoint) {\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\n is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar - by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n const { endo } = extraOpts;\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)) throw new RangeError('invalid scalar: out of range'); // 0 is invalid\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const mul = (n: bigint) => wnaf.cached(this, n, (p) => normalizeZ(Point, p));\n /** See docs for {@link EndomorphismOpts} */\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(scalar);\n const { p: k1p, f: k1f } = mul(k1);\n const { p: k2p, f: k2f } = mul(k2);\n fake = k1f.add(k2f);\n point = finishEndo(endo.beta, k1p, k2p, k1neg, k2neg);\n } else {\n const { p, f } = mul(scalar);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return normalizeZ(Point, [point, fake])[0];\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed secret key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(scalar: bigint): Point {\n const { endo } = extraOpts;\n const p = this as Point;\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)) throw new RangeError('invalid scalar: out of range'); // 0 is valid\n if (sc === _0n || p.is0()) return Point.ZERO; // 0\n if (sc === _1n) return p; // 1\n if (wnaf.hasCache(this)) return this.multiply(sc); // precomputes\n // We don't have method for double scalar multiplication (aP + bQ):\n // Even with using Strauss-Shamir trick, it's 35% slower than na\u00EFve mul+add.\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = splitEndoScalarN(sc);\n const { p1, p2 } = mulEndoUnsafe(Point, p, k1, k2); // 30% faster vs wnaf.unsafe\n return finishEndo(endo.beta, p1, p2, k1neg, k2neg);\n } else {\n return wnaf.unsafe(p, sc);\n }\n }\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?: T): AffinePoint {\n const p = this;\n let iz = invertedZ;\n const { X, Y, Z } = p;\n // Fast-path for normalized points\n if (Fp.eql(Z, Fp.ONE)) 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) 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) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x, y };\n }\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(): boolean {\n const { isTorsionFree } = extraOpts;\n if (cofactor === _1n) return true;\n if (isTorsionFree) return isTorsionFree(Point, this);\n return wnaf.unsafe(this, CURVE_ORDER).is0();\n }\n\n clearCofactor(): Point {\n const { clearCofactor } = extraOpts;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\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\n isSmallOrder(): boolean {\n if (cofactor === _1n) return this.is0(); // Fast-path\n return this.clearCofactor().is0();\n }\n\n toBytes(isCompressed = true): TRet {\n abool(isCompressed, 'isCompressed');\n // Same policy as pointFromBytes(): keep ZERO out of the default byte surface because\n // callers use these encodings as public keys, where SEC 1 validation rejects infinity.\n this.assertValidity();\n return encodePoint(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return bytesToHex(this.toBytes(isCompressed));\n }\n\n toString() {\n return ``;\n }\n }\n const bits = Fn.BITS;\n const wnaf = new wNAF(Point, extraOpts.endo ? Math.ceil(bits / 2) : bits);\n // Tiny toy curves can have scalar fields narrower than 8 bits. Skip the\n // eager W=8 cache there instead of rejecting an otherwise valid constructor.\n if (bits >= 8) Point.BASE.precompute(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n Object.freeze(Point.prototype);\n Object.freeze(Point);\n return Point;\n}\n\n/** Parsed ECDSA signature with helpers for recovery and re-encoding. */\nexport interface ECDSASignature {\n /** Signature component `r`. */\n readonly r: bigint;\n /** Signature component `s`. */\n readonly s: bigint;\n /** Optional recovery bit for recoverable signatures. */\n readonly recovery?: number;\n /**\n * Return a copy of the signature with a recovery bit attached.\n * @param recovery - Recovery bit to attach.\n * @returns Signature with an attached recovery bit.\n */\n addRecoveryBit(recovery: number): ECDSASignature & { readonly recovery: number };\n /**\n * Check whether the signature uses the high-S half-order.\n * @returns Whether the signature uses the high-S half-order.\n */\n hasHighS(): boolean;\n /**\n * Recover the public key from the hashed message and recovery bit.\n * @param messageHash - Hashed message bytes.\n * @returns Recovered public-key point.\n */\n recoverPublicKey(messageHash: TArg): WeierstrassPoint;\n /**\n * Encode the signature into bytes.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature bytes.\n */\n toBytes(format?: string): TRet;\n /**\n * Encode the signature into hex.\n * @param format - Signature encoding to produce.\n * @returns Encoded signature hex.\n */\n toHex(format?: string): string;\n}\n/** Constructor and decoding helpers for ECDSA signatures. */\nexport type ECDSASignatureCons = {\n /** Create a signature from `r`, `s`, and an optional recovery bit. */\n new (r: bigint, s: bigint, recovery?: number): ECDSASignature;\n /**\n * Decode a signature from bytes.\n * @param bytes - Encoded signature bytes.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromBytes(bytes: TArg, format?: ECDSASignatureFormat): ECDSASignature;\n /**\n * Decode a signature from hex.\n * @param hex - Encoded signature hex.\n * @param format - Signature encoding to parse.\n * @returns Parsed signature.\n */\n fromHex(hex: string, format?: ECDSASignatureFormat): ECDSASignature;\n};\n\n// Points start with byte 0x02 when y is even; otherwise 0x03\nfunction pprefix(hasEvenY: boolean): TRet {\n return Uint8Array.of(hasEvenY ? 0x02 : 0x03) as TRet;\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * RFC 9380 expects callers to provide `v != 0`; this helper does not enforce it.\n * @param Fp - Field implementation.\n * @param Z - Simplified SWU map parameter.\n * @returns Square-root ratio helper.\n * @example\n * Build the square-root ratio helper used by SWU map implementations.\n *\n * ```ts\n * import { SWUFpSqrtRatio } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const sqrtRatio = SWUFpSqrtRatio(Fp, 3n);\n * const out = sqrtRatio(4n, 1n);\n * ```\n */\nexport function SWUFpSqrtRatio(\n Fp: TArg>,\n Z: T\n): (u: T, v: T) => { isValid: boolean; value: T } {\n // Fail with the usual field-shape error before touching pow/cmov on malformed field shims.\n const F = validateField(Fp as IField) as IField;\n // Generic implementation\n const q = F.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = F.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = F.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) only for v != 0.\n // We keep v=0 on the regular result path with isValid=false instead of\n // throwing so the helper stays closer to the RFC's fixed control flow.\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = F.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = F.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = F.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = F.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = F.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = F.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = F.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = F.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = F.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = F.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = F.eql(tv5, F.ONE); // 12. isQR = tv5 == 1\n tv2 = F.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = F.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = F.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = F.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = F.eql(tvv5, F.ONE); // 21. e1 = tv5 == 1\n tv2 = F.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = F.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = F.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = F.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = F.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n // RFC 9380 Appendix F.2.1.1 defines sqrt_ratio(u, v) for v != 0.\n // When u = 0 and v != 0, u / v = 0 is square and the computed root is\n // still 0, so widen only the final flag and keep the full control flow.\n return { isValid: !F.is0(v) && (isQR || F.is0(u)), value: tv3 };\n };\n if (F.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (F.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = F.sqrt(F.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = F.sqr(v); // 1. tv1 = v^2\n const tv2 = F.mul(u, v); // 2. tv2 = u * v\n tv1 = F.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = F.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = F.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = F.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = F.mul(F.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = F.eql(tv3, u); // 9. isQR = tv3 == u\n let y = F.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: !F.is0(v) && isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * See {@link https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2 | RFC 9380 section 6.6.2}.\n * @param Fp - Field implementation.\n * @param opts - SWU parameters:\n * - `A`: Curve parameter `A`.\n * - `B`: Curve parameter `B`.\n * - `Z`: Simplified SWU map parameter.\n * @returns Deterministic map-to-curve function.\n * @throws If the SWU parameters are invalid or the field lacks the required helpers. {@link Error}\n * @example\n * Map one field element to a Weierstrass curve point with the SWU recipe.\n *\n * ```ts\n * import { mapToCurveSimpleSWU } from '@noble/curves/abstract/weierstrass.js';\n * import { Field } from '@noble/curves/abstract/modular.js';\n * const Fp = Field(17n);\n * const map = mapToCurveSimpleSWU(Fp, { A: 1n, B: 2n, Z: 3n });\n * const point = map(5n);\n * ```\n */\nexport function mapToCurveSimpleSWU(\n Fp: TArg>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n): (u: T) => { x: T; y: T } {\n const F = validateField(Fp as IField) as IField;\n const { A, B, Z } = opts;\n if (!F.isValidNot0(A) || !F.isValidNot0(B) || !F.isValid(Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 \u00A76.6.2 and Appendix H.2 require:\n // 1. Z is non-square in F\n // 2. Z != -1 in F\n // 3. g(x) - Z is irreducible over F\n // 4. g(B / (Z * A)) is square in F\n // We can enforce 1, 2, and 4 with the current field API.\n // Criterion 3 is not checked here because generic `IField` does not expose\n // polynomial-ring / irreducibility operations, and this helper is used for\n // both prime and extension fields.\n if (F.eql(Z, F.neg(F.ONE)) || FpIsSquare(F, Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n // RFC 9380 Appendix H.2 criterion 4: g(B / (Z * A)) is square in F.\n // x = B / (Z * A)\n const x = F.mul(B, F.inv(F.mul(Z, A)));\n // g(x) = x^3 + A*x + B\n const gx = F.add(F.add(F.mul(F.sqr(x), x), F.mul(A, x)), B);\n if (!FpIsSquare(F, gx)) throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(F, Z);\n if (!F.isOdd) throw new Error('Field does not have .isOdd()');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = F.sqr(u); // 1. tv1 = u^2\n tv1 = F.mul(tv1, Z); // 2. tv1 = Z * tv1\n tv2 = F.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = F.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = F.add(tv2, F.ONE); // 5. tv3 = tv2 + 1\n tv3 = F.mul(tv3, B); // 6. tv3 = B * tv3\n tv4 = F.cmov(Z, F.neg(tv2), !F.eql(tv2, F.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = F.mul(tv4, A); // 8. tv4 = A * tv4\n tv2 = F.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = F.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = F.mul(tv6, A); // 11. tv5 = A * tv6\n tv2 = F.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = F.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = F.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = F.mul(tv6, B); // 15. tv5 = B * tv6\n tv2 = F.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = F.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = F.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = F.mul(y, value); // 20. y = y * y1\n x = F.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = F.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = F.isOdd!(u) === F.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = F.cmov(F.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n const tv4_inv = FpInvertBatch(F, [tv4], true)[0];\n x = F.mul(x, tv4_inv); // 25. x = x / tv4\n return { x, y };\n };\n}\n\nfunction getWLengths(Fp: TArg>, Fn: TArg>) {\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/**\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(\n Point: WeierstrassPointCons,\n ecdhOpts: TArg<{ randomBytes?: (bytesLength?: number) => TRet }> = {}\n): ECDH {\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\n function isValidSecretKey(secretKey: TArg) {\n try {\n const num = Fn.fromBytes(secretKey);\n return Fn.isValidNot0(num);\n } catch (error) {\n return false;\n }\n }\n\n function isValidPublicKey(publicKey: TArg, isCompressed?: boolean): boolean {\n const { publicKey: comp, publicKeyUncompressed } = lengths;\n try {\n const l = publicKey.length;\n if (isCompressed === true && l !== comp) return false;\n if (isCompressed === false && l !== publicKeyUncompressed) return false;\n return !!Point.fromBytes(publicKey);\n } catch (error) {\n return false;\n }\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?: TArg): TRet {\n seed = seed === undefined ? randomBytes_(lengths.seed) : seed;\n return mapHashToField(abytes(seed, lengths.seed, 'seed'), Fn.ORDER) as TRet;\n }\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: TArg, isCompressed = true): TRet {\n return Point.BASE.multiply(Fn.fromBytes(secretKey)).toBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: TArg): boolean | undefined {\n const { secretKey, publicKey, publicKeyUncompressed } = lengths;\n const allowedLengths = (Fn as { _lengths?: readonly number[] })._lengths;\n if (!isBytes(item)) 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) return undefined;\n return isPub;\n }\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(\n secretKeyA: TArg,\n publicKeyB: TArg,\n isCompressed = true\n ): TRet {\n if (isProbPub(secretKeyA) === true) throw new Error('first arg must be private key');\n if (isProbPub(publicKeyB) === false) 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 return b.multiply(s).toBytes(isCompressed);\n }\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\n return Object.freeze({ getPublicKey, getSharedSecret, keygen, Point, utils, lengths });\n}\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(\n Point: WeierstrassPointCons,\n hash: TArg,\n ecdsaOpts: TArg = {}\n): ECDSA {\n // Custom hash / bits2int hooks are treated as pure functions over validated caller-owned bytes.\n const hash_ = hash as CHash;\n ahash(hash_);\n validateObject(\n ecdsaOpts,\n {},\n {\n hmac: 'function',\n lowS: 'boolean',\n randomBytes: 'function',\n bits2int: 'function',\n bits2int_modN: 'function',\n }\n );\n ecdsaOpts = Object.assign({}, ecdsaOpts);\n const randomBytes = ecdsaOpts.randomBytes === undefined ? wcRandomBytes : ecdsaOpts.randomBytes;\n const hmac =\n ecdsaOpts.hmac === undefined\n ? (key: TArg, msg: TArg) => nobleHmac(hash_, key, msg)\n : (ecdsaOpts.hmac as HmacFn);\n\n const { Fp, Fn } = Point;\n const { ORDER: CURVE_ORDER, BITS: fnBits } = Fn;\n const { keygen, getPublicKey, getSharedSecret, utils, lengths } = ecdh(Point, ecdsaOpts);\n const defaultSigOpts: Required = {\n prehash: true,\n lowS: typeof ecdsaOpts.lowS === 'boolean' ? ecdsaOpts.lowS : true,\n format: 'compact' as ECDSASignatureFormat,\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\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n function validateRS(title: string, num: bigint): bigint {\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 assertRecoverableCurve(): void {\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: TArg, format: ECDSASignatureFormat) {\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 /**\n * ECDSA signature with its (r, s) properties. Supports compact, recovered & DER representations.\n */\n class Signature implements ECDSASignature {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n\n constructor(r: bigint, s: bigint, recovery?: number) {\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)) throw new Error('invalid recovery id');\n this.recovery = recovery;\n }\n Object.freeze(this);\n }\n\n static fromBytes(\n bytes: TArg,\n format: ECDSASignatureFormat = defaultSigOpts.format\n ): Signature {\n validateSigLength(bytes, format);\n let recid: number | undefined;\n if (format === 'der') {\n const { r, s } = DER.toSig(abytes(bytes));\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\n static fromHex(hex: string, format?: ECDSASignatureFormat) {\n return this.fromBytes(hexToBytes(hex), format);\n }\n\n private assertRecovery(): number {\n const { recovery } = this;\n if (recovery == null) throw new Error('invalid recovery id: must be present');\n return recovery;\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\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: TArg): WeierstrassPoint {\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)) 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.multiplyUnsafe(u1).add(R.multiplyUnsafe(u2));\n if (Q.is0()) throw new Error('invalid recovery: point at infinify');\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n toBytes(format: ECDSASignatureFormat = defaultSigOpts.format): TRet {\n validateSigFormat(format);\n if (format === 'der') return hexToBytes(DER.hexFromSig(this)) as TRet;\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) as TRet;\n }\n return concatBytes(rb, sb) as TRet;\n }\n\n toHex(format?: ECDSASignatureFormat) {\n return bytesToHex(this.toBytes(format));\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n Object.freeze(Signature.prototype);\n Object.freeze(Signature);\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int: (bytes: TArg) => bigint =\n ecdsaOpts.bits2int === undefined\n ? function bits2int_def(bytes: TArg): bigint {\n // Our custom check \"just in case\", for protection against DoS\n if (bytes.length > 8192) 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 : (ecdsaOpts.bits2int as (bytes: TArg) => bigint);\n const bits2int_modN: (bytes: TArg) => bigint =\n ecdsaOpts.bits2int_modN === undefined\n ? function bits2int_modN_def(bytes: TArg): bigint {\n return Fn.create(bits2int(bytes)); // can't use bytesToNumberBE here\n }\n : (ecdsaOpts.bits2int_modN as (bytes: TArg) => bigint);\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: bigint): TRet {\n aInRange('num < 2^' + fnBits, num, _0n, ORDER_MASK);\n return Fn.toBytes(num) as TRet;\n }\n\n function validateMsgAndHash(message: TArg, prehash: boolean): TRet {\n abytes(message, undefined, 'message');\n return (\n prehash ? abytes(hash_(message), undefined, 'prehashed message') : message\n ) as TRet;\n }\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(\n message: TArg,\n secretKey: TArg,\n opts: TArg\n ) {\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)) throw new Error('invalid private key');\n const seedArgs: TArg[] = [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) as TRet; // 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 // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n function k2sig(kBytes: TArg): Signature | undefined {\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)) return; // Valid scalars (including k) must be in 1..N-1\n const ik = Fn.inv(k); // k^-1 mod n\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) return;\n const s = Fn.create(ik * Fn.create(m + r * d)); // s = k^-1(m + rd) mod n\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3 when q.x>n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = 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 /**\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(\n message: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet {\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 /**\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(\n signature: TArg,\n message: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ): boolean {\n const { lowS, prehash, format } = validateSigOpts(opts, defaultSigOpts);\n publicKey = abytes(publicKey, undefined, 'publicKey');\n message = validateMsgAndHash(message, prehash);\n if (!isBytes(signature as any)) {\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 if (lowS && sig.hasHighS()) 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.multiplyUnsafe(u1).add(P.multiplyUnsafe(u2)); // u1\u22C5G + u2\u22C5P\n if (R.is0()) return false;\n const v = Fn.create(R.x); // v = r.x mod n\n return v === r;\n } catch (e) {\n return false;\n }\n }\n\n function recoverPublicKey(\n signature: TArg,\n message: TArg,\n opts: TArg = {}\n ): TRet {\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\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 }) satisfies Signer;\n}\n", "/**\n * SECG secp256k1. See [pdf](https://www.secg.org/sec2-v2.pdf).\n *\n * Belongs to Koblitz curves: it has efficiently-computable GLV endomorphism \u03C8,\n * check out {@link EndomorphismOpts}. Seems to be rigid (not backdoored).\n * @module\n */\n/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha2.js';\nimport { randomBytes } from '@noble/hashes/utils.js';\nimport { createKeygen, type CurveLengths } from './abstract/curve.ts';\nimport {\n createFROST,\n type FROST,\n type FrostPublic,\n type FrostSecret,\n type Nonces,\n} from './abstract/frost.ts';\nimport { createHasher, type H2CHasher, isogenyMap } from './abstract/hash-to-curve.ts';\nimport { Field, mapHashToField, pow2 } from './abstract/modular.ts';\nimport {\n type ECDSA,\n ecdsa,\n type EndomorphismOpts,\n mapToCurveSimpleSWU,\n type WeierstrassPoint as PointType,\n weierstrass,\n type WeierstrassOpts,\n type WeierstrassPointCons,\n} from './abstract/weierstrass.ts';\nimport {\n abytes,\n asciiToBytes,\n bytesToNumberBE,\n concatBytes,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n// Seems like generator was produced from some seed:\n// `Pointk1.BASE.multiply(Pointk1.Fn.inv(2n, N)).toAffine().x`\n// // gives short x 0x3b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63n\nconst secp256k1_CURVE: WeierstrassOpts = {\n p: BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f'),\n n: BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141'),\n h: BigInt(1),\n a: BigInt(0),\n b: BigInt(7),\n Gx: BigInt('0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798'),\n Gy: BigInt('0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8'),\n};\n\nconst secp256k1_ENDO: EndomorphismOpts = {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n basises: [\n [BigInt('0x3086d221a7d46bcde86c90e49284eb15'), -BigInt('0xe4437ed6010e88286f547fa90abfe4c3')],\n [BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8'), BigInt('0x3086d221a7d46bcde86c90e49284eb15')],\n ],\n};\n\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _2n = /* @__PURE__ */ BigInt(2);\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1_CURVE.p;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fpk1.eql(Fpk1.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fpk1 = Field(secp256k1_CURVE.p, { sqrt: sqrtMod });\nconst Pointk1 = /* @__PURE__ */ weierstrass(secp256k1_CURVE, {\n Fp: Fpk1,\n endo: secp256k1_ENDO,\n});\n\n/**\n * secp256k1 curve: ECDSA and ECDH methods.\n *\n * Uses sha256 to hash messages. To use a different hash,\n * pass `{ prehash: false }` to sign / verify.\n *\n * @example\n * Generate one secp256k1 keypair, sign a message, and verify it.\n *\n * ```js\n * import { secp256k1 } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = secp256k1.keygen();\n * // const publicKey = secp256k1.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello noble');\n * const sig = secp256k1.sign(msg, secretKey);\n * const isValid = secp256k1.verify(sig, msg, publicKey);\n * // const sigKeccak = secp256k1.sign(keccak256(msg), secretKey, { prehash: false });\n * ```\n */\nexport const secp256k1: ECDSA = /* @__PURE__ */ ecdsa(Pointk1, sha256);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\n// BIP-340 phrases tags as UTF-8, but all current standardized names here are 7-bit ASCII.\nfunction taggedHash(tag: string, ...messages: TArg): TRet {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(asciiToBytes(tag));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages)) as TRet;\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: TArg>): TRet =>\n point.toBytes(true).slice(1) as TRet;\nconst hasEven = (y: bigint) => y % _2n === _0n;\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: TArg) {\n const { Fn, BASE } = Pointk1;\n const d_ = Fn.fromBytes(priv);\n const p = BASE.multiply(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = hasEven(p.y) ? d_ : Fn.neg(d_);\n return { scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType {\n const Fp = Fpk1;\n if (!Fp.isValidNot0(x)) throw new Error('invalid x: Fail if x \u2265 p');\n const xx = Fp.create(x * x);\n const c = Fp.create(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = Fp.sqrt(c); // Let y = c^(p+1)/4 mod p. Same as sqrt().\n // Return the unique point P such that x(P) = x and\n // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n if (!hasEven(y)) y = Fp.neg(y);\n const p = Pointk1.fromAffine({ x, y });\n p.assertValidity();\n return p;\n}\n// BIP-340 callers still need to supply canonical 32-byte inputs where required; this alias only\n// parses big-endian bytes and does not enforce the fixed-width contract itself.\nconst num = bytesToNumberBE;\n/** Create tagged hash, convert it to bigint, reduce modulo-n. */\nfunction challenge(...args: TArg): bigint {\n return Pointk1.Fn.create(num(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/** Schnorr public key is just `x` coordinate of Point as per BIP340. */\nfunction schnorrGetPublicKey(secretKey: TArg): TRet {\n return schnorrGetExtPubKey(secretKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * `auxRand` is optional and is not the sole source of `k` generation: bad CSPRNG output will not\n * be catastrophic, but BIP-340 still recommends fresh auxiliary randomness when available to harden\n * deterministic signing against side-channel and fault-injection attacks.\n */\nfunction schnorrSign(\n message: TArg,\n secretKey: TArg,\n auxRand: TArg = randomBytes(32)\n): TRet {\n const { Fn, BASE } = Pointk1;\n const m = abytes(message, undefined, 'message');\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(secretKey); // checks for isWithinCurveOrder\n const a = abytes(auxRand, 32, 'auxRand'); // Auxiliary random data a: a 32-byte array\n // Let t be the byte-wise xor of bytes(d) and hash/aux(a).\n const t = Fn.toBytes(d ^ num(taggedHash('BIP0340/aux', a)));\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n // BIP340 defines k' = int(rand) mod n. We can't reuse schnorrGetExtPubKey(rand)\n // here: that helper parses canonical secret keys and rejects rand >= n instead\n // of reducing the nonce hash modulo the group order.\n const k_ = Fn.create(num(rand));\n // BIP-340: \"Let k' = int(rand) mod n. Fail if k' = 0. Let R = k'\u22C5G.\"\n if (k_ === 0n) throw new Error('sign failed: k is zero');\n const p = BASE.multiply(k_); // Rejects zero; only the raw nonce hash needs reduction.\n const k = hasEven(p.y) ? k_ : Fn.neg(k_);\n const rx = pointToBytes(p);\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(Fn.toBytes(Fn.create(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig as TRet;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(\n signature: TArg,\n message: TArg,\n publicKey: TArg\n): boolean {\n const { Fp, Fn, BASE } = Pointk1;\n const sig = abytes(signature, 64, 'signature');\n const m = abytes(message, undefined, 'message');\n const pub = abytes(publicKey, 32, 'publicKey');\n try {\n const P = lift_x(num(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = num(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!Fp.isValidNot0(r)) return false;\n const s = num(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n // Stricter than BIP-340/libsecp256k1, which only reject s >= n. Honest signing reaches\n // s = 0 only with negligible probability (k + e*d \u2261 0 mod n), so treat zero-s inputs as\n // crafted edge cases and fail closed instead of carrying that extra verification surface.\n if (!Fn.isValidNot0(s)) return false;\n\n // int(challenge(bytes(r) || bytes(P) || m)) % n\n const e = challenge(Fn.toBytes(r), pointToBytes(P), m);\n // R = s\u22C5G - e\u22C5P, where -eP == (n-e)P\n const R = BASE.multiplyUnsafe(s).add(P.multiplyUnsafe(Fn.neg(e)));\n const { x, y } = R.toAffine();\n // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n if (R.is0() || !hasEven(y) || x !== r) return false;\n return true;\n } catch (error) {\n return false;\n }\n}\n\nexport const __TEST: { lift_x: typeof lift_x } = /* @__PURE__ */ Object.freeze({ lift_x });\n\n/** Schnorr-specific secp256k1 API from BIP340. */\nexport type SecpSchnorr = {\n /**\n * Generate one Schnorr secret/public keypair.\n * @param seed - Optional seed for deterministic testing or custom randomness.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg) => { secretKey: TRet; publicKey: TRet };\n /**\n * Derive the x-only public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns X-only public key bytes.\n */\n getPublicKey: typeof schnorrGetPublicKey;\n /**\n * Create one BIP340 Schnorr signature.\n * @param message - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param auxRand - Optional auxiliary randomness.\n * @returns Compact Schnorr signature bytes.\n */\n sign: typeof schnorrSign;\n /**\n * Verify one BIP340 Schnorr signature.\n * @param signature - Compact signature bytes.\n * @param message - Signed message bytes.\n * @param publicKey - X-only public key bytes.\n * @returns `true` when the signature is valid.\n */\n verify: typeof schnorrVerify;\n /** Underlying secp256k1 point constructor. */\n Point: WeierstrassPointCons;\n /** Helper utilities for Schnorr-specific key handling and tagged hashing. */\n utils: {\n /** Generate one Schnorr secret key. */\n randomSecretKey: (seed?: TArg) => TRet;\n /** Convert one point into its x-only BIP340 byte encoding. */\n pointToBytes: (point: TArg>) => TRet;\n /** Lift one x coordinate into the unique even-Y point. */\n lift_x: typeof lift_x;\n /** Compute a BIP340 tagged hash. */\n taggedHash: typeof taggedHash;\n };\n /** Public byte lengths for keys, signatures, and seeds. */\n lengths: CurveLengths;\n};\n/**\n * Schnorr signatures over secp256k1.\n * See {@link https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki | BIP 340}.\n * @example\n * Generate one BIP340 Schnorr keypair, sign a message, and verify it.\n *\n * ```js\n * import { schnorr } from '@noble/curves/secp256k1.js';\n * const { secretKey, publicKey } = schnorr.keygen();\n * // const publicKey = schnorr.getPublicKey(secretKey);\n * const msg = new TextEncoder().encode('hello');\n * const sig = schnorr.sign(msg, secretKey);\n * const isValid = schnorr.verify(sig, msg, publicKey);\n * ```\n */\nexport const schnorr: SecpSchnorr = /* @__PURE__ */ (() => {\n const size = 32;\n const seedLength = 48;\n const randomSecretKey = (seed?: TArg): TRet => {\n seed = seed === undefined ? randomBytes(seedLength) : seed;\n return mapHashToField(seed, secp256k1_CURVE.n);\n };\n return Object.freeze({\n keygen: createKeygen(randomSecretKey, schnorrGetPublicKey),\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n Point: Pointk1,\n utils: Object.freeze({\n randomSecretKey,\n taggedHash,\n lift_x,\n pointToBytes,\n }),\n lengths: Object.freeze({\n secretKey: size,\n publicKey: size,\n publicKeyHasPrefix: false,\n signature: size * 2,\n seed: seedLength,\n }),\n });\n})();\n\n// RFC 9380 Appendix E.1 3-isogeny coefficients for secp256k1, stored in ascending degree order.\n// The final `1` in each denominator array is the explicit monic leading term.\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fpk1,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\n// RFC 9380 \u00A78.7 secp256k1 E' parameters for the SWU-to-isogeny pipeline below.\nlet mapSWU: ((u: bigint) => { x: bigint; y: bigint }) | undefined;\nconst getMapSWU = () =>\n mapSWU ||\n (mapSWU = mapToCurveSimpleSWU(Fpk1, {\n // Building the SWU sqrt-ratio helper eagerly adds noticeable `secp256k1.js` import cost, so\n // defer it to first use; after that the cached mapper is reused directly.\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fpk1.create(BigInt('-11')),\n }));\n\n/**\n * Hashing / encoding to secp256k1 points / field. RFC 9380 methods.\n * @example\n * Hash one message onto secp256k1.\n *\n * ```ts\n * const point = secp256k1_hasher.hashToCurve(new TextEncoder().encode('hello noble'));\n * ```\n */\nexport const secp256k1_hasher: H2CHasher> = /* @__PURE__ */ (() =>\n createHasher(\n Pointk1,\n (scalars: bigint[]) => {\n const { x, y } = getMapSWU()(Fpk1.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fpk1.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\n/**\n * FROST threshold signatures over secp256k1. RFC 9591.\n * @example\n * Create one trusted-dealer package for 2-of-3 secp256k1 signing.\n *\n * ```ts\n * const alice = secp256k1_FROST.Identifier.derive('alice@example.com');\n * const bob = secp256k1_FROST.Identifier.derive('bob@example.com');\n * const carol = secp256k1_FROST.Identifier.derive('carol@example.com');\n * const deal = secp256k1_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const secp256k1_FROST: TRet = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n }))();\n\n// Taproot utils\n// `undefined` means \"disable TapTweak entirely\"; callers that want the BIP-341/BIP-386 empty\n// merkle root must pass `new Uint8Array(0)` explicitly.\nfunction tweak(point: PointType, merkleRoot?: TArg): bigint {\n if (merkleRoot === undefined) return _0n;\n const x = pointToBytes(point);\n const t = bytesToNumberBE(taggedHash('TapTweak', x, merkleRoot));\n // BIP-341 taproot_tweak_pubkey/taproot_tweak_seckey: \"if t >= SECP256K1_ORDER:\n // raise ValueError\". TapTweak must reject overflow instead of reducing modulo n.\n if (!Pointk1.Fn.isValid(t)) throw new Error('invalid TapTweak hash');\n return t;\n}\nfunction frostPubToEvenY(pub: TArg): TRet {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can skip unnecessary cloning.\n if (hasEven(VK.y)) return pub as TRet;\n return {\n signers: { min: pub.signers.min, max: pub.signers.max },\n commitments: pub.commitments.map((i) => Pointk1.fromBytes(i).negate().toBytes()),\n verifyingShares: Object.fromEntries(\n Object.entries(pub.verifyingShares).map(([k, v]) => [\n k,\n Pointk1.fromBytes(v).negate().toBytes(),\n ])\n ),\n } as TRet;\n}\nfunction frostSecretToEvenY(s: TArg, pub: TArg): TRet {\n const VK = Pointk1.fromBytes(pub.commitments[0]);\n // Keep aliasing on the already-even path so wrapper callers can preserve package identity.\n if (hasEven(VK.y)) return s as TRet;\n const Fn = Pointk1.Fn;\n return {\n ...s,\n signingShare: Fn.toBytes(Fn.neg(Fn.fromBytes(s.signingShare))),\n } as TRet;\n}\nfunction frostNoncesToEvenY(PK: PointType, nonces: TArg): TRet {\n if (hasEven(PK.y)) return nonces as TRet;\n const Fn = Pointk1.Fn;\n return {\n binding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.binding))),\n hiding: Fn.toBytes(Fn.neg(Fn.fromBytes(nonces.hiding))),\n } as TRet;\n}\n\nfunction frostTweakSecret(\n s: TArg,\n pub: TArg,\n merkleRoot?: TArg\n): TRet {\n const Fn = Pointk1.Fn;\n const keyPackage = frostSecretToEvenY(s, pub);\n const evenPub = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(evenPub.commitments[0]), merkleRoot);\n const signingShare = Fn.toBytes(Fn.add(Fn.fromBytes(keyPackage.signingShare), t));\n return {\n identifier: keyPackage.identifier,\n signingShare,\n } as TRet;\n}\n\nfunction frostTweakPublic(\n pub: TArg,\n merkleRoot?: TArg\n): TRet {\n const PKPackage = frostPubToEvenY(pub);\n const t = tweak(Pointk1.fromBytes(PKPackage.commitments[0]), merkleRoot);\n const tp = Pointk1.BASE.multiply(t);\n const commitments = PKPackage.commitments.map((c, i) =>\n (i === 0 ? Pointk1.fromBytes(c).add(tp) : Pointk1.fromBytes(c)).toBytes()\n );\n const verifyingShares: Record = {};\n for (const k in PKPackage.verifyingShares) {\n verifyingShares[k] = Pointk1.fromBytes(PKPackage.verifyingShares[k]).add(tp).toBytes();\n }\n return {\n signers: { min: PKPackage.signers.min, max: PKPackage.signers.max },\n commitments,\n verifyingShares,\n } as TRet;\n}\n\n/**\n * FROST threshold signatures over secp256k1-schnorr-taproot. RFC 9591.\n * DKG outputs are auto-tweaked with the empty Taproot merkle root for compatibility, while\n * `trustedDealer()` outputs stay untweaked unless callers apply the Taproot tweak themselves.\n * @example\n * Create one trusted-dealer package for Taproot-compatible FROST signing.\n *\n * ```ts\n * const alice = schnorr_FROST.Identifier.derive('alice@example.com');\n * const bob = schnorr_FROST.Identifier.derive('bob@example.com');\n * const carol = schnorr_FROST.Identifier.derive('carol@example.com');\n * const deal = schnorr_FROST.trustedDealer({ min: 2, max: 3 }, [alice, bob, carol]);\n * ```\n */\nexport const schnorr_FROST: TRet = /* @__PURE__ */ (() =>\n createFROST({\n name: 'FROST-secp256k1-SHA256-TR-v1',\n Point: Pointk1,\n hashToScalar: secp256k1_hasher.hashToScalar,\n hash: sha256,\n // Taproot related hacks\n parsePublicKey(publicKey) {\n // External Taproot keys are x-only, but local key packages still use compressed points.\n if (publicKey.length === 32) return lift_x(bytesToNumberBE(publicKey));\n if (publicKey.length === 33) return Pointk1.fromBytes(publicKey);\n throw new Error(`expected x-only or compressed public key, got length=${publicKey.length}`);\n },\n adjustScalar(n: bigint) {\n const PK = Pointk1.BASE.multiply(n);\n return hasEven(PK.y) ? n : Pointk1.Fn.neg(n);\n },\n adjustPoint: (p) => (hasEven(p.y) ? p : p.negate()),\n challenge(R, PK, msg) {\n return challenge(pointToBytes(R), pointToBytes(PK), msg);\n },\n adjustNonces: frostNoncesToEvenY,\n adjustGroupCommitmentShare: (GC, GCShare) => (!hasEven(GC.y) ? GCShare.negate() : GCShare),\n adjustPublic: frostPubToEvenY,\n adjustSecret: frostSecretToEvenY,\n adjustTx: {\n // Compat with official implementation\n encode: (tx) => tx.subarray(1) as TRet,\n decode: (tx) => concatBytes(Uint8Array.of(0x02), tx) as TRet,\n },\n adjustDKG: (k) => {\n // Compatibility with frost-secp256k1-tr: DKG output is auto-tweaked with the\n // empty Taproot merkle root, while dealer-generated keys stay untweaked.\n const merkleRoot = new Uint8Array(0);\n return {\n public: frostTweakPublic(k.public, merkleRoot),\n secret: frostTweakSecret(k.secret, k.public, merkleRoot),\n };\n },\n }))();\n", "/**\n\nSHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.\nRFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,\nnot the base RIPEMD-160 compression spec.\nDon't use them in a new protocol. What \"weak\" means:\n\n- Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.\n- No practical pre-image attacks (only theoretical, 2^123.4)\n- HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151\n * @module\n */\nimport { Chi, HashMD, Maj } from './_md.ts';\nimport { type CHash, clean, createHasher, rotl, type TRet } from './utils.ts';\n\n/** Initial SHA-1 state from RFC 3174 \u00A76.1. */\nconst SHA1_IV = /* @__PURE__ */ Uint32Array.from([\n 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,\n]);\n\n// Reusable 80-word SHA-1 message schedule buffer.\nconst SHA1_W = /* @__PURE__ */ new Uint32Array(80);\n\n/** Internal SHA1 legacy hash class. */\nexport class _SHA1 extends HashMD<_SHA1> {\n private A = SHA1_IV[0] | 0;\n private B = SHA1_IV[1] | 0;\n private C = SHA1_IV[2] | 0;\n private D = SHA1_IV[3] | 0;\n private E = SHA1_IV[4] | 0;\n\n constructor() {\n super(64, 20, 8, false);\n }\n protected get(): [number, number, number, number, number] {\n const { A, B, C, D, E } = this;\n return [A, B, C, D, E];\n }\n protected set(A: number, B: number, C: number, D: number, E: number): void {\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 }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) SHA1_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 80; i++)\n SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);\n // Compression function main loop, 80 rounds\n let { A, B, C, D, E } = this;\n for (let i = 0; i < 80; i++) {\n let F, K;\n if (i < 20) {\n F = Chi(B, C, D);\n K = 0x5a827999;\n } else if (i < 40) {\n F = B ^ C ^ D;\n K = 0x6ed9eba1;\n } else if (i < 60) {\n F = Maj(B, C, D);\n K = 0x8f1bbcdc;\n } else {\n F = B ^ C ^ D;\n K = 0xca62c1d6;\n }\n const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;\n E = D;\n D = C;\n C = rotl(B, 30);\n B = A;\n A = T;\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 this.set(A, B, C, D, E);\n }\n protected roundClean(): void {\n clean(SHA1_W);\n }\n destroy(): void {\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);\n clean(this.buffer);\n }\n}\n\n/**\n * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with SHA1.\n * ```ts\n * sha1(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const sha1: TRet = /* @__PURE__ */ createHasher(() => new _SHA1());\n\n/** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */\nconst p32 = /* @__PURE__ */ Math.pow(2, 32);\n/** RFC 1321 `T[1..64]` table. */\nconst K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) =>\n Math.floor(p32 * Math.abs(Math.sin(i + 1)))\n);\n\n/** MD5 initial state from RFC 1321, stored as 4 u32 words. */\nconst MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);\n\n// Reusable 16-word MD5 message block buffer.\nconst MD5_W = /* @__PURE__ */ new Uint32Array(16);\n/** Internal MD5 legacy hash class. */\nexport class _MD5 extends HashMD<_MD5> {\n private A = MD5_IV[0] | 0;\n private B = MD5_IV[1] | 0;\n private C = MD5_IV[2] | 0;\n private D = MD5_IV[3] | 0;\n\n constructor() {\n super(64, 16, 8, true);\n }\n protected get(): [number, number, number, number] {\n const { A, B, C, D } = this;\n return [A, B, C, D];\n }\n protected set(A: number, B: number, C: number, D: number): void {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) MD5_W[i] = view.getUint32(offset, true);\n // Compression function main loop, 64 rounds\n let { A, B, C, D } = this;\n for (let i = 0; i < 64; i++) {\n let F, g, s;\n if (i < 16) {\n F = Chi(B, C, D);\n g = i;\n s = [7, 12, 17, 22];\n } else if (i < 32) {\n // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.\n F = Chi(D, B, C);\n g = (5 * i + 1) % 16;\n s = [5, 9, 14, 20];\n } else if (i < 48) {\n F = B ^ C ^ D;\n g = (3 * i + 5) % 16;\n s = [4, 11, 16, 23];\n } else {\n F = C ^ (B | ~D);\n g = (7 * i) % 16;\n s = [6, 10, 15, 21];\n }\n F = F + A + K[i] + MD5_W[g];\n A = D;\n D = C;\n C = B;\n B = B + rotl(F, s[i % 4]);\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 this.set(A, B, C, D);\n }\n protected roundClean(): void {\n clean(MD5_W);\n }\n destroy(): void {\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);\n clean(this.buffer);\n }\n}\n\n/**\n * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.\n * MD5 architecture is similar to SHA1, with some differences:\n * - Reduced output length: 16 bytes (128 bit) instead of 20\n * - 64 rounds, instead of 80\n * - Little-endian: could be faster, but will require more code\n * - Non-linear index selection: huge speed-up for unroll\n * - Per round constants: more memory accesses, additional speed-up for unroll\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with MD5.\n * ```ts\n * md5(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const md5: TRet = /* @__PURE__ */ createHasher(() => new _MD5());\n\n// RIPEMD-160\n\n// Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.\nconst Rho160 = /* @__PURE__ */ Uint8Array.from([\n 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,\n]);\nconst Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();\nconst Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();\n// Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.\nconst idxLR = /* @__PURE__ */ (() => {\n const L = [Id160];\n const R = [Pi160];\n const res = [L, R];\n for (let i = 0; i < 4; i++) for (let j of res) j.push(j[i].map((k) => Rho160[k]));\n return res;\n})();\nconst idxL = /* @__PURE__ */ (() => idxLR[0])();\nconst idxR = /* @__PURE__ */ (() => idxLR[1])();\n// const [idxL, idxR] = idxLR;\n\n// Base per-group shift table before the left/right message-order permutations are applied.\nconst shifts160 = /* @__PURE__ */ [\n [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],\n [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],\n [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],\n [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],\n [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],\n].map((i) => Uint8Array.from(i));\nconst shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));\nconst shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));\n// Five left-lane additive constants for RIPEMD-160.\nconst Kl160 = /* @__PURE__ */ Uint32Array.from([\n 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,\n]);\n// Five right-lane additive constants for RIPEMD-160.\nconst Kr160 = /* @__PURE__ */ Uint32Array.from([\n 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,\n]);\n// Called `f()` in the spec; valid `group` values are 0..4, and out-of-range\n// inputs currently fall through to the group-4 branch.\nfunction ripemd_f(group: number, x: number, y: number, z: number): number {\n if (group === 0) return x ^ y ^ z;\n if (group === 1) return (x & y) | (~x & z);\n if (group === 2) return (x | ~y) ^ z;\n if (group === 3) return (x & z) | (y & ~z);\n return x ^ (y | ~z);\n}\n// Reusable 16-word RIPEMD-160 message block buffer.\nconst BUF_160 = /* @__PURE__ */ new Uint32Array(16);\n/**\n * Internal RIPEMD-160 legacy hash class.\n * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.\n */\nexport class _RIPEMD160 extends HashMD<_RIPEMD160> {\n private h0 = 0x67452301 | 0;\n private h1 = 0xefcdab89 | 0;\n private h2 = 0x98badcfe | 0;\n private h3 = 0x10325476 | 0;\n private h4 = 0xc3d2e1f0 | 0;\n\n constructor() {\n super(64, 20, 8, true);\n }\n protected get(): [number, number, number, number, number] {\n const { h0, h1, h2, h3, h4 } = this;\n return [h0, h1, h2, h3, h4];\n }\n protected set(h0: number, h1: number, h2: number, h3: number, h4: number): void {\n this.h0 = h0 | 0;\n this.h1 = h1 | 0;\n this.h2 = h2 | 0;\n this.h3 = h3 | 0;\n this.h4 = h4 | 0;\n }\n protected process(view: DataView, offset: number): void {\n for (let i = 0; i < 16; i++, offset += 4) BUF_160[i] = view.getUint32(offset, true);\n // prettier-ignore\n let al = this.h0 | 0, ar = al,\n bl = this.h1 | 0, br = bl,\n cl = this.h2 | 0, cr = cl,\n dl = this.h3 | 0, dr = dl,\n el = this.h4 | 0, er = el;\n\n // Instead of iterating 0 to 80, we split it into 5 groups\n // And use the groups in constants, functions, etc. Much simpler\n for (let group = 0; group < 5; group++) {\n const rGroup = 4 - group;\n const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore\n const rl = idxL[group], rr = idxR[group]; // prettier-ignore\n const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore\n for (let i = 0; i < 16; i++) {\n const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;\n al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore\n }\n // 2 loops are 10% faster\n for (let i = 0; i < 16; i++) {\n const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;\n ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore\n }\n }\n // Add the compressed chunk to the current hash value\n // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.\n this.set(\n (this.h1 + cl + dr) | 0,\n (this.h2 + dl + er) | 0,\n (this.h3 + el + ar) | 0,\n (this.h4 + al + br) | 0,\n (this.h0 + bl + cr) | 0\n );\n }\n protected roundClean(): void {\n clean(BUF_160);\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.buffer);\n this.set(0, 0, 0, 0, 0);\n }\n}\n\n/**\n * RIPEMD-160 - a legacy hash function from 1990s.\n * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point\n * at the base RIPEMD-160 references.\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}\n * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}\n * @param msg - message bytes to hash\n * @returns Digest bytes.\n * @example\n * Hash a message with RIPEMD-160.\n * ```ts\n * ripemd160(new Uint8Array([97, 98, 99]));\n * ```\n */\nexport const ripemd160: TRet = /* @__PURE__ */ createHasher(() => new _RIPEMD160());\n", "/**\n * BIP32 hierarchical deterministic (HD) wallets over secp256k1.\n * @module\n * @example\n * ```js\n * import { HDKey } from \"@scure/bip32\";\n * import { sha256 } from '@noble/hashes/sha2.js';\n * import { randomBytes } from '@noble/hashes/utils.js';\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const base58key = root.privateExtendedKey;\n * const restored = HDKey.fromExtendedKey(base58key);\n * const fromJson = HDKey.fromJSON({ xpriv: base58key });\n * const child = fromJson.derive(\"m/0/2147483647'/1\");\n * const msgHash = sha256(new TextEncoder().encode('hello scure-bip32'));\n *\n * // props\n * [root.depth, root.index, root.chainCode];\n * [restored.privateKey, restored.publicKey];\n * const sig = child.sign(msgHash);\n * child.verify(msgHash, sig);\n * ```\n */\n/*! scure-bip32 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) */\nimport { secp256k1 as secp } from '@noble/curves/secp256k1.js';\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { ripemd160 } from '@noble/hashes/legacy.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { abytes, concatBytes, createView, type TArg, type TRet } from '@noble/hashes/utils.js';\nimport { createBase58check } from '@scure/base';\n\nconst Point = /* @__PURE__ */ (() => secp.Point)();\nconst Fn = /* @__PURE__ */ (() => Point.Fn)();\nconst base58check = /* @__PURE__ */ createBase58check(sha256);\nconst MASTER_SECRET = /* @__PURE__ */ (() => {\n return Uint8Array.from('Bitcoin seed'.split(''), (char) => char.charCodeAt(0));\n})();\n\n/** Network-specific BIP32 version bytes. */\nexport interface Versions {\n /** 4-byte version used when serializing private extended keys. */\n private: number;\n /** 4-byte version used when serializing public extended keys. */\n public: number;\n}\n\nconst BITCOIN_VERSIONS: Versions = { private: 0x0488ade4, public: 0x0488b21e };\n/** Hardened child index offset from BIP32. */\nexport const HARDENED_OFFSET: number = 0x80000000;\n\nconst hash160 = (data: TArg) => ripemd160(sha256(data));\nconst fromU32 = (data: TArg) => createView(data).getUint32(0, false);\nconst toU32 = (n: number): TRet => {\n if (typeof n !== 'number')\n throw new TypeError('invalid number, should be from 0 to 2**32-1, got ' + n);\n if (!Number.isSafeInteger(n) || n < 0 || n > 2 ** 32 - 1)\n throw new RangeError('invalid number, should be from 0 to 2**32-1, got ' + n);\n const buf = new Uint8Array(4);\n createView(buf).setUint32(0, n, false);\n return buf;\n};\n\ninterface HDKeyOpt {\n versions?: Versions;\n depth?: number;\n index?: number;\n parentFingerprint?: number;\n chainCode?: Uint8Array;\n publicKey?: Uint8Array;\n privateKey?: Uint8Array;\n}\n\n/**\n * HDKey from BIP32\n * @param opt - Node fields used to construct one HDKey instance.\n * @example\n * ```js\n * import { HDKey } from '@scure/bip32';\n * import { randomBytes } from '@noble/hashes/utils.js';\n *\n * const seed = randomBytes(32);\n * const root = HDKey.fromMasterSeed(seed);\n * const account0 = root.derive(\"m/0/1'\");\n * account0.publicKey;\n * ```\n */\nexport class HDKey {\n get fingerprint(): number {\n if (!this.pubHash) {\n throw new Error('No publicKey set!');\n }\n return fromU32(this.pubHash);\n }\n get identifier(): Uint8Array | undefined {\n return this.pubHash;\n }\n get pubKeyHash(): Uint8Array | undefined {\n return this.pubHash;\n }\n // Returns the live private key buffer for this instance.\n // Copy it first if you need an immutable snapshot.\n get privateKey(): Uint8Array | null {\n return this._privateKey || null;\n }\n get publicKey(): Uint8Array | null {\n return this._publicKey || null;\n }\n get privateExtendedKey(): string {\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('No private key');\n }\n return base58check.encode(\n this.serialize(this.versions.private, concatBytes(Uint8Array.of(0), priv))\n );\n }\n get publicExtendedKey(): string {\n if (!this._publicKey) {\n throw new Error('No public key');\n }\n return base58check.encode(this.serialize(this.versions.public, this._publicKey));\n }\n\n static fromMasterSeed(seed: Uint8Array, versions: Versions = BITCOIN_VERSIONS): HDKey {\n abytes(seed);\n if (8 * seed.length < 128 || 8 * seed.length > 512) {\n throw new RangeError(\n 'HDKey: seed length must be between 128 and 512 bits; 256 bits is advised, got ' +\n seed.length\n );\n }\n const I = hmac(sha512, MASTER_SECRET, seed);\n const privateKey = I.slice(0, 32);\n const chainCode = I.slice(32);\n return new HDKey({ versions, chainCode, privateKey });\n }\n\n static fromExtendedKey(base58key: string, versions: Versions = BITCOIN_VERSIONS): HDKey {\n // => version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n const keyBuffer: Uint8Array = base58check.decode(base58key);\n const keyView = createView(keyBuffer);\n const version = keyView.getUint32(0, false);\n const opt = {\n versions,\n depth: keyBuffer[4],\n parentFingerprint: keyView.getUint32(5, false),\n index: keyView.getUint32(9, false),\n chainCode: keyBuffer.slice(13, 45),\n };\n const key = keyBuffer.slice(45);\n const isPriv = key[0] === 0;\n if (version !== versions[isPriv ? 'private' : 'public']) {\n throw new Error('Version mismatch');\n }\n if (isPriv) {\n return new HDKey({ ...opt, privateKey: key.slice(1) });\n } else {\n return new HDKey({ ...opt, publicKey: key });\n }\n }\n\n public static fromJSON(json: { xpriv: string }): HDKey {\n return HDKey.fromExtendedKey(json.xpriv);\n }\n readonly versions: Versions;\n readonly depth: number = 0;\n readonly index: number = 0;\n readonly chainCode: Uint8Array | null = null;\n readonly parentFingerprint: number = 0;\n private _privateKey?: Uint8Array;\n private _publicKey?: Uint8Array;\n private pubHash: Uint8Array | undefined;\n\n constructor(opt: HDKeyOpt) {\n if (!opt || typeof opt !== 'object') {\n throw new Error('HDKey.constructor must not be called directly');\n }\n this.versions = opt.versions || BITCOIN_VERSIONS;\n this.depth = opt.depth || 0;\n this.chainCode = opt.chainCode ? Uint8Array.from(opt.chainCode) : null;\n this.index = opt.index || 0;\n this.parentFingerprint = opt.parentFingerprint || 0;\n if (!this.depth) {\n if (this.parentFingerprint || this.index) {\n throw new Error('HDKey: zero depth with non-zero index/parent fingerprint');\n }\n }\n if (this.depth > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n if (opt.publicKey && opt.privateKey) {\n throw new Error('HDKey: publicKey and privateKey at same time.');\n }\n if (opt.privateKey) {\n if (!secp.utils.isValidSecretKey(opt.privateKey)) throw new Error('Invalid private key');\n // Don't alias caller-owned secret buffers.\n this._privateKey = Uint8Array.from(opt.privateKey);\n this._publicKey = secp.getPublicKey(this._privateKey, true);\n } else if (opt.publicKey) {\n this._publicKey = Point.fromBytes(opt.publicKey).toBytes(true); // force compressed point\n } else {\n throw new Error('HDKey: no public or private key provided');\n }\n this.pubHash = hash160(this._publicKey);\n }\n\n derive(path: string): HDKey {\n if (!/^[mM]'?/.test(path)) {\n throw new Error('Path must start with \"m\" or \"M\"');\n }\n if (/^[mM]'?$/.test(path)) {\n return this;\n }\n const parts = path.replace(/^[mM]'?\\//, '').split('/');\n // tslint:disable-next-line\n let child: HDKey = this;\n for (const c of parts) {\n const m = /^(\\d+)('?)$/.exec(c);\n const m1 = m && m[1];\n if (!m || m.length !== 3 || typeof m1 !== 'string')\n throw new Error('invalid child index: ' + c);\n let idx = +m1;\n if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET) {\n throw new Error('Invalid index');\n }\n // hardened key\n if (m[2] === \"'\") {\n idx += HARDENED_OFFSET;\n }\n child = child.deriveChild(idx);\n }\n return child;\n }\n\n /**\n * @param _I - Test-only override for the 64-byte HMAC-SHA512 output; normal callers must omit it.\n */\n deriveChild(index: number, _I?: Uint8Array): HDKey {\n if (!this._publicKey || !this.chainCode) {\n throw new Error('No publicKey or chainCode set');\n }\n let data = toU32(index);\n if (index >= HARDENED_OFFSET) {\n // Hardened\n const priv = this._privateKey;\n if (!priv) {\n throw new Error('Could not derive hardened child key');\n }\n // Hardened child: 0x00 || ser256(kpar) || ser32(index)\n data = concatBytes(Uint8Array.of(0), priv, data);\n } else {\n // Normal child: serP(point(kpar)) || ser32(index)\n data = concatBytes(this._publicKey, data);\n }\n const out = _I || hmac(sha512, this.chainCode, data);\n abytes(out, 64);\n const childTweak = out.slice(0, 32);\n const chainCode = out.slice(32);\n const opt: HDKeyOpt = {\n versions: this.versions,\n chainCode,\n depth: this.depth + 1,\n parentFingerprint: this.fingerprint,\n index,\n };\n // Fail early instead of re-trying different index\n if (opt.depth! > 255) {\n throw new Error('HDKey: depth exceeds the serializable value 255');\n }\n try {\n const ctweak = Fn.fromBytes(childTweak);\n // BIP-32 private derivation retries only when parse256(I_L) >= n or k_i = 0.\n // BIP-32 public derivation retries only when parse256(I_L) >= n or K_i is infinity.\n // So I_L = 0 is valid here; Fn.fromBytes still rejects parse256(I_L) >= n.\n if (this._privateKey) {\n const added = Fn.create(Fn.fromBytes(this._privateKey) + ctweak);\n if (!Fn.isValidNot0(added)) {\n throw new Error('The tweak was out of range or the resulted private key is invalid');\n }\n opt.privateKey = Fn.toBytes(added);\n } else {\n const point = Point.fromBytes(this._publicKey);\n const added = ctweak === 0n ? point : point.add(Point.BASE.multiply(ctweak));\n // Cryptographically impossible: hmac-sha512 preimage would need to be found\n if (added.equals(Point.ZERO)) {\n throw new Error('The tweak was equal to negative P, which made the result key invalid');\n }\n opt.publicKey = added.toBytes(true);\n }\n return new HDKey(opt);\n } catch (err) {\n return this.deriveChild(index + 1);\n }\n }\n\n sign(hash: Uint8Array): Uint8Array {\n if (!this._privateKey) {\n throw new Error('No privateKey set!');\n }\n abytes(hash, 32);\n return secp.sign(hash, this._privateKey, { prehash: false });\n }\n\n verify(hash: Uint8Array, signature: Uint8Array): boolean {\n abytes(hash, 32);\n abytes(signature, 64);\n if (!this._publicKey) {\n throw new Error('No publicKey set!');\n }\n return secp.verify(signature, hash, this._publicKey, { prehash: false });\n }\n\n wipePrivateData(): this {\n if (this._privateKey) {\n this._privateKey.fill(0);\n this._privateKey = undefined;\n }\n return this;\n }\n toJSON(): { xpriv: string; xpub: string } {\n return {\n xpriv: this.privateExtendedKey,\n xpub: this.publicExtendedKey,\n };\n }\n\n private serialize(version: number, key: Uint8Array) {\n if (!this.chainCode) {\n throw new Error('No chainCode set');\n }\n abytes(key, 33);\n // version(4) || depth(1) || fingerprint(4) || index(4) || chain(32) || key(33)\n return concatBytes(\n toU32(version),\n new Uint8Array([this.depth]),\n toU32(this.parentFingerprint),\n toU32(this.index),\n this.chainCode,\n key\n );\n }\n}\n\ntype Tests = Readonly<{\n deriveChildWithI(key: TArg, index: number, I: TArg): TRet;\n}>;\n\nexport const __TESTS: TRet = /* @__PURE__ */ Object.freeze({\n deriveChildWithI(key: TArg, index: number, I: TArg): TRet {\n // Bytes wrappers widen the exported test seam, but deriveChild still needs concrete inputs.\n return (key as HDKey).deriveChild(index, I as Uint8Array) as TRet;\n },\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.ts';\nimport { abytes, ahash, anumber, type CHash, clean, type TArg, type TRet } from './utils.ts';\n\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(\n hash: TArg,\n ikm: TArg,\n salt?: TArg\n): TRet {\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) salt = new Uint8Array(hash.outputLen);\n return hmac(hash, salt, ikm);\n}\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/**\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 * @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(\n hash: TArg,\n prk: TArg,\n info?: TArg,\n length: number = 32\n): TRet {\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) 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) throw new Error('Length must be <= 255*HashLen');\n const blocks = Math.ceil(length / olen);\n if (info === undefined) info = EMPTY_BUFFER;\n else abytes(info, undefined, 'info');\n // first L(ength) octets of T\n const okm = new Uint8Array(blocks * olen);\n // Re-use HMAC instance between blocks\n const HMAC = hmac.create(hash, prk);\n const HMACTmp = HMAC._cloneInto();\n const T = new Uint8Array(HMAC.outputLen);\n for (let counter = 0; counter < blocks; counter++) {\n HKDF_COUNTER[0] = counter + 1;\n // T(0) = empty string (zero length)\n // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)\n HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)\n .update(info)\n .update(HKDF_COUNTER)\n .digestInto(T);\n okm.set(T, olen * counter);\n HMAC._cloneInto(HMACTmp);\n }\n HMAC.destroy();\n HMACTmp.destroy();\n clean(T, HKDF_COUNTER);\n return okm.slice(0, length) as TRet;\n}\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 = (\n hash: TArg,\n ikm: TArg,\n salt: TArg,\n info: TArg,\n length: number\n): TRet => expand(hash, extract(hash, ikm, salt), info, length);\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 { rotlBH, rotlBL, rotlSH, rotlSL, split } from './_u64.ts';\n// prettier-ignore\nimport {\n abytes, aexists, anumber, aoutput,\n clean, createHasher,\n oidNist,\n swap32IfBE,\n u32,\n type CHash, type CHashXOF,\n type Hash,\n type HashInfo,\n type HashXOF,\n type TArg,\n type TRet\n} from './utils.ts';\n\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: number[] = [];\nconst SHA3_ROTL: number[] = [];\nconst _SHA3_IOTA: bigint[] = []; // 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) 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\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h: number, l: number, s: number) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h: number, l: number, s: number) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n\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 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: TArg, rounds: number = 24): void {\n anumber(rounds, 'rounds');\n // This implementation precomputes only the standard Keccak-f[1600] 24-round Iota table.\n if (rounds < 1 || rounds > 24) throw new Error('\"rounds\" expected integer 1..24');\n const B = new Uint32Array(5 * 2);\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++) 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],\n b1 = s[y + 1],\n b2 = s[y + 2],\n 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/**\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 implements Hash, HashXOF {\n protected state: Uint8Array;\n protected pos = 0;\n protected posOut = 0;\n protected finished = false;\n protected state32: Uint32Array;\n protected destroyed = false;\n\n public blockLen: number;\n public suffix: number;\n public outputLen: number;\n public canXOF: boolean;\n protected enableXOF = false;\n protected rounds: number;\n\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(\n blockLen: number,\n suffix: number,\n outputLen: number,\n enableXOF = false,\n rounds: number = 24\n ) {\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 // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone(): Keccak {\n return this._cloneInto();\n }\n protected keccak(): void {\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: TArg): this {\n aexists(this);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++) state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen) this.keccak();\n }\n return this;\n }\n protected finish(): void {\n if (this.finished) 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) this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n protected writeInto(out: TArg): TRet {\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) 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 as TRet;\n }\n xofInto(out: TArg): TRet {\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) throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes: number): TRet {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out: TArg): void {\n aoutput(out, this);\n if (this.finished) throw new Error('digest() was already called');\n // `aoutput(...)` allows oversized buffers; digestInto() must fill only the advertised digest.\n this.writeInto(out.subarray(0, this.outputLen));\n this.destroy();\n }\n digest(): TRet {\n const out = new Uint8Array(this.outputLen);\n this.digestInto(out);\n return out as TRet;\n }\n destroy(): void {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to?: Keccak): Keccak {\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 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}\n\nconst genKeccak = (\n suffix: number,\n blockLen: number,\n outputLen: number,\n info: TArg = {}\n) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info);\n\n/**\n * SHA3-224 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 144,\n 28,\n /* @__PURE__ */ oidNist(0x07)\n);\n/**\n * SHA3-256 hash function. Different from keccak-256.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 136,\n 32,\n /* @__PURE__ */ oidNist(0x08)\n);\n/**\n * SHA3-384 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 104,\n 48,\n /* @__PURE__ */ oidNist(0x09)\n);\n/**\n * SHA3-512 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(\n 0x06,\n 72,\n 64,\n /* @__PURE__ */ oidNist(0x0a)\n);\n\n/**\n * Keccak-224 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(0x01, 144, 28);\n/**\n * Keccak-256 hash function. Different from SHA3-256.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(0x01, 136, 32);\n/**\n * Keccak-384 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(0x01, 104, 48);\n/**\n * Keccak-512 hash function.\n * @param msg - message bytes to hash\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: TRet = /* @__PURE__ */ genKeccak(0x01, 72, 64);\n\n/** Options for SHAKE XOF. */\nexport type ShakeOpts = {\n /** Desired number of output bytes. */\n dkLen?: number;\n};\n\nconst genShake = (suffix: number, blockLen: number, outputLen: number, info: TArg = {}) =>\n createHasher(\n (opts: ShakeOpts = {}) =>\n new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true),\n info\n );\n\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: TRet> =\n /* @__PURE__ */\n genShake(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: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 136, 32, /* @__PURE__ */ oidNist(0x0c));\n\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: TRet> =\n /* @__PURE__ */\n genShake(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: TRet> =\n /* @__PURE__ */\n genShake(0x1f, 136, 64, /* @__PURE__ */ oidNist(0x0c));\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 {\n type CHash,\n type TypedArray,\n abytes,\n abytes as abytes_,\n concatBytes,\n isLE,\n randomBytes as randb,\n} from '@noble/hashes/utils.js';\n/**\n * Bytes API type helpers for old + new TypeScript.\n *\n * TS 5.6 has `Uint8Array`, while TS 5.9+ made it generic `Uint8Array`.\n * We can't use specific return type, because TS 5.6 will error.\n * We can't use generic return type, because most TS 5.9 software will expect specific type.\n *\n * Maps typed-array input leaves to broad forms.\n * These are compatibility adapters, not ownership guarantees.\n *\n * - `TArg` keeps byte inputs broad.\n * - `TRet` marks byte outputs for TS 5.6 and TS 5.9+ compatibility.\n */\nexport type TypedArg = T extends BigInt64Array\n ? BigInt64Array\n : T extends BigUint64Array\n ? BigUint64Array\n : T extends Float32Array\n ? Float32Array\n : T extends Float64Array\n ? Float64Array\n : T extends Int16Array\n ? Int16Array\n : T extends Int32Array\n ? Int32Array\n : T extends Int8Array\n ? Int8Array\n : T extends Uint16Array\n ? Uint16Array\n : T extends Uint32Array\n ? Uint32Array\n : T extends Uint8ClampedArray\n ? Uint8ClampedArray\n : T extends Uint8Array\n ? Uint8Array\n : never;\n/** Maps typed-array output leaves to narrow TS-compatible forms. */\nexport type TypedRet = T extends BigInt64Array\n ? ReturnType\n : T extends BigUint64Array\n ? ReturnType\n : T extends Float32Array\n ? ReturnType\n : T extends Float64Array\n ? ReturnType\n : T extends Int16Array\n ? ReturnType\n : T extends Int32Array\n ? ReturnType\n : T extends Int8Array\n ? ReturnType\n : T extends Uint16Array\n ? ReturnType\n : T extends Uint32Array\n ? ReturnType\n : T extends Uint8ClampedArray\n ? ReturnType\n : T extends Uint8Array\n ? ReturnType\n : never;\n/** Recursively adapts byte-carrying API input types. See {@link TypedArg}. */\nexport type TArg =\n | T\n | ([TypedArg] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TRet }) => TArg) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TArg;\n }\n : T extends [infer A, ...infer R]\n ? [TArg, ...{ [K in keyof R]: TArg }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TArg, ...{ [K in keyof R]: TArg }]\n : T extends (infer A)[]\n ? TArg[]\n : T extends readonly (infer A)[]\n ? readonly TArg[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TArg }\n : T\n : TypedArg);\n/** Recursively adapts byte-carrying API output types. See {@link TypedArg}. */\nexport type TRet = T extends unknown\n ? T &\n ([TypedRet] extends [never]\n ? T extends (...args: infer A) => infer R\n ? ((...args: { [K in keyof A]: TArg }) => TRet) & {\n [K in keyof T]: T[K] extends (...args: any) => any ? T[K] : TRet;\n }\n : T extends [infer A, ...infer R]\n ? [TRet, ...{ [K in keyof R]: TRet }]\n : T extends readonly [infer A, ...infer R]\n ? readonly [TRet, ...{ [K in keyof R]: TRet }]\n : T extends (infer A)[]\n ? TRet[]\n : T extends readonly (infer A)[]\n ? readonly TRet[]\n : T extends Promise\n ? Promise>\n : T extends object\n ? { [K in keyof T]: TRet }\n : T\n : TypedRet)\n : never;\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: typeof abytes = 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: typeof concatBytes = 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: typeof randb = randb;\n\n/**\n * Compares two byte arrays in a length-constant way for equal lengths.\n * Unequal lengths return `false` immediately, and there is no runtime type validation.\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: TArg, b: TArg): boolean {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n/**\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: TArg): TRet {\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)) as TRet;\n}\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: T): T {\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: (arr: T) => T = isLE\n ? (arr) => arr\n : byteSwap64;\n\n/** Shared key-generation surface for signers and KEMs. */\nexport type CryptoKeys = {\n /** Optional metadata about the algorithm family or variant. */\n info?: { type?: string };\n /** Public byte lengths for the exported key material. */\n lengths: { seed?: number; publicKey?: number; secretKey?: number };\n /**\n * Generate one secret/public keypair.\n * @param seed - Optional seed bytes for deterministic key generation.\n * @returns Fresh secret/public keypair.\n */\n keygen: (seed?: TArg) => {\n secretKey: TRet;\n publicKey: TRet;\n };\n /**\n * Derive one public key from a secret key.\n * @param secretKey - Secret key bytes.\n * @returns Public key bytes.\n */\n getPublicKey: (secretKey: TArg) => TRet;\n};\n\n/** Verification options shared by the signature APIs. */\nexport type VerOpts = {\n /** Optional application-defined context string. */\n context?: Uint8Array;\n};\n/** Signing options shared by the signature APIs. */\nexport type SigOpts = VerOpts & {\n // Compatibility with @noble/curves: false to disable, enabled by default, user can pass U8A\n /** Optional extra entropy or `false` to disable randomized signing. */\n extraEntropy?: Uint8Array | false;\n};\n\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: object): void {\n // Arrays silently passed here before, but these call sites expect named option-bag fields.\n if (Object.prototype.toString.call(opts) !== '[object Object]')\n throw new TypeError('expected valid options object');\n}\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 * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common verification options.\n * ```ts\n * validateVerOpts({ context: new Uint8Array([1]) });\n * ```\n */\nexport function validateVerOpts(opts: TArg): void {\n validateOpts(opts);\n if (opts.context !== undefined) abytes(opts.context, undefined, 'opts.context');\n}\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 * @throws On wrong argument types. {@link TypeError}\n * @example\n * Validate common signing options.\n * ```ts\n * validateSigOpts({ extraEntropy: new Uint8Array([1]) });\n * ```\n */\nexport function validateSigOpts(opts: TArg): void {\n validateVerOpts(opts);\n if (opts.extraEntropy !== false && opts.extraEntropy !== undefined)\n abytes(opts.extraEntropy, undefined, 'opts.extraEntropy');\n}\n\n/** Generic signature interface with key generation, signing, and verification. */\nexport type Signer = CryptoKeys & {\n /** Public byte lengths for signatures and signing randomness. */\n lengths: { signRand?: number; signature?: number };\n /**\n * Sign one message.\n * @param msg - Message bytes to sign.\n * @param secretKey - Secret key bytes.\n * @param opts - Optional signing options.\n * @returns Signature bytes.\n */\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n /**\n * Verify one signature.\n * @param sig - Signature bytes.\n * @param msg - Signed message bytes.\n * @param publicKey - Public key bytes.\n * @param opts - Optional verification options.\n * @returns `true` when the signature is valid, `false` when all inputs are well-formed but the\n * signature check does not pass. Some implementations also treat malformed signature encodings as\n * a verification failure and return `false`.\n * @throws On malformed API arguments or unsupported verification options.\n */\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts?: TArg\n ) => boolean;\n};\n\n/** Generic key encapsulation mechanism interface. */\nexport type KEM = CryptoKeys & {\n /** Public byte lengths for ciphertexts and optional message randomness. */\n lengths: { cipherText?: number; msg?: number; msgRand?: number };\n /**\n * Encapsulate one shared secret to a recipient public key.\n * @param publicKey - Recipient public key bytes.\n * @param msg - Optional caller-provided randomness/message seed.\n * @returns Ciphertext plus shared secret.\n */\n encapsulate: (\n publicKey: TArg,\n msg?: TArg\n ) => {\n cipherText: TRet;\n sharedSecret: TRet;\n };\n /**\n * Recover the shared secret from a ciphertext and recipient secret key.\n * @param cipherText - Ciphertext bytes.\n * @param secretKey - Recipient secret key bytes.\n * @returns Decapsulated shared secret.\n */\n decapsulate: (cipherText: TArg, secretKey: TArg) => TRet;\n};\n\n/** Bidirectional encoder/decoder interface. */\nexport interface Coder {\n /**\n * Serialize one value.\n * @param from - Value to encode.\n * @returns Encoded representation.\n */\n encode(from: F): T;\n /**\n * Parse one serialized value.\n * @param to - Encoded representation.\n * @returns Decoded value.\n */\n decode(to: T): F;\n}\n\n/** Encoder/decoder interface specialized for byte arrays. */\nexport interface BytesCoder extends Coder {\n /**\n * Serialize one value into bytes.\n * @param data - Value to encode.\n * @returns Encoded bytes.\n */\n encode: (data: T) => Uint8Array;\n /**\n * Parse one byte array into a value.\n * @param bytes - Encoded bytes.\n * @returns Decoded value.\n */\n decode: (bytes: Uint8Array) => T;\n}\n\n/** Fixed-length byte encoder/decoder. */\nexport type BytesCoderLen = BytesCoder & { bytesLen: number };\n\n// nano-packed, because struct encoding is hard.\ntype UnCoder = T extends BytesCoder ? U : never;\ntype SplitOut)[]> = {\n [K in keyof T]: T[K] extends number ? Uint8Array : UnCoder;\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)[]>(\n label: string,\n ...lengths: T\n): TRet> & { bytesLen: number }> {\n const getLength = (c: TArg>) =>\n typeof c === 'number' ? c : (c as BytesCoderLen).bytesLen;\n const bytesLen: number = lengths.reduce((sum: number, a) => sum + getLength(a), 0);\n return {\n bytesLen,\n encode: (bufs: T) => {\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: Uint8Array = typeof c === 'number' ? (bufs[i] as any) : c.encode(bufs[i]);\n abytes_(b, l, label);\n res.set(b, pos);\n if (typeof c !== 'number') b.fill(0); // clean\n pos += l;\n }\n return res;\n },\n decode: (buf: TArg) => {\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 as SplitOut;\n },\n } as any;\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: TArg>, vecLen: number): TRet> {\n const coder = c as BytesCoderLen;\n const bytesLen = vecLen * coder.bytesLen;\n return {\n bytesLen,\n encode: (u: TArg): TRet => {\n if (u.length !== vecLen)\n throw new RangeError(`vecCoder.encode: wrong length=${u.length}. Expected: ${vecLen}`);\n const res = new Uint8Array(bytesLen);\n for (let i = 0, pos = 0; i < u.length; i++) {\n const b = coder.encode(u[i] as T);\n res.set(b, pos);\n b.fill(0); // clean\n pos += b.length;\n }\n return res as TRet;\n },\n decode: (a: TArg): TRet => {\n abytes_(a, bytesLen);\n const r: T[] = [];\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 as TRet;\n },\n } as any;\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: (TypedArray | TypedArray[])[]): void {\n for (const t of list) {\n if (Array.isArray(t)) for (const b of t) b.fill(0);\n else t.fill(0);\n }\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 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: number): number {\n if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)\n throw new RangeError(`expected bits in [0..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\n/** Shared empty byte array used as the default context. */\nexport const EMPTY: TRet = /* @__PURE__ */ Uint8Array.of();\n\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: TArg, ctx: TArg = EMPTY): TRet {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) throw new RangeError('context should be 255 bytes or less');\n return concatBytes(new Uint8Array([0, ctx.length]), ctx, msg);\n}\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/**\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: CHash, requiredStrength: number = 0): void {\n if (!hash.oid || !equalBytes(hash.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 const collisionResistance = (hash.outputLen * 8) / 2;\n if (requiredStrength > collisionResistance) {\n throw new Error(\n 'Pre-hash security strength too low: ' +\n collisionResistance +\n ', required: ' +\n requiredStrength\n );\n }\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(\n hash: CHash,\n msg: TArg,\n ctx: TArg = EMPTY\n): TRet {\n abytes_(msg);\n abytes_(ctx);\n if (ctx.length > 255) 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 * 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 type { TypedArray } from '@noble/hashes/utils.js';\nimport {\n type BytesCoderLen,\n cleanBytes,\n type Coder,\n getMask,\n type TArg,\n type TRet,\n} from './utils.ts';\n\n/** Extendable-output reader used by the CRYSTALS implementations. */\nexport type XOF = (\n seed: Uint8Array,\n blockLen?: number\n) => {\n /**\n * Read diagnostic counters for the current XOF session.\n * @returns Current call and XOF block counters.\n */\n stats: () => { calls: number; xofs: number };\n /**\n * Select one `(x, y)` coordinate pair and get a block reader for it.\n * Only one coordinate stream is live at a time: a later `get(...)` call rebinds the shared\n * SHAKE state and invalidates older readers.\n * Each squeeze aliases one mutable internal output buffer, so callers must copy blocks they\n * want to retain before the next read.\n * @param x - First matrix coordinate.\n * @param y - Second matrix coordinate.\n * @returns Lazy block reader for that coordinate pair.\n */\n get: (x: number, y: number) => () => Uint8Array; // return block aligned to blockLen and 3\n /** Wipe any buffered state once the reader is no longer needed. */\n clean: () => void;\n};\n\n/** CRYSTALS (ml-kem, ml-dsa) options */\n/** Shared polynomial and NTT parameters for CRYSTALS algorithms. */\nexport type CrystalOpts = {\n /**\n * Allocate one zeroed polynomial/vector container.\n * @param n - Number of coefficients to allocate.\n * @returns Fresh typed container.\n */\n newPoly: TypedCons;\n /** Polynomial size, typically `256`. */\n N: number;\n /** Prime modulus used for all coefficient arithmetic. */\n Q: number;\n /** Inverse transform normalization factor:\n * `256**-1 mod q` for Dilithium, `128**-1 mod q` for Kyber.\n */\n F: number;\n /** Principal root of unity for the transform domain. */\n ROOT_OF_UNITY: number;\n /** Number of bits used for bit-reversal ordering. */\n brvBits: number;\n /** `true` for Kyber/ML-KEM mode, `false` for Dilithium/ML-DSA mode. */\n isKyber: boolean;\n};\n\n/** Constructor function for typed polynomial containers. */\nexport type TypedCons = (n: number) => T;\n\ntype Crystals = {\n mod: (a: number, modulo?: number) => number;\n smod: (a: number, modulo?: number) => number;\n nttZetas: T;\n NTT: {\n /** Forward transform in place. Mutates and returns `r`. */\n encode: (r: T) => T;\n /** Inverse transform in place. Mutates and returns `r`. */\n decode: (r: T) => T;\n };\n bitsCoder: (d: number, c: Coder) => BytesCoderLen;\n};\n\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: CrystalOpts): TRet> => {\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: number, modulo = Q): number => {\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: number, modulo = Q): number => {\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\n // Number-Theoretic Transform\n // Explained: https://electricdusk.com/ntt.html\n\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\n const field = {\n add: (a: number, b: number) => mod((a | 0) + (b | 0)) | 0,\n sub: (a: number, b: number) => mod((a | 0) - (b | 0)) | 0,\n mul: (a: number, b: number) => mod((a | 0) * (b | 0)) | 0,\n inv: (_a: number) => {\n throw new Error('not implemented');\n },\n };\n const nttOpts = {\n N,\n roots: nttZetas as any,\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: T): T => {\n return dif(r) as any;\n },\n decode: (r: T): T => {\n dit(r as any);\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++) 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: number, c: Coder): TRet> => {\n const mask = getMask(d);\n const bytesLen = d * (N / 8);\n return {\n bytesLen,\n encode: (poly_: TArg): TRet => {\n const poly = poly_ as T;\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 for (; bufLen >= 8; bufLen -= 8, buf >>= 8) r[pos++] = buf & getMask(bufLen);\n }\n return r as TRet;\n },\n decode: (bytes: TArg): TRet => {\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) r[pos++] = c.decode(buf & mask);\n }\n return r as TRet;\n },\n } as TRet>;\n };\n\n return {\n mod,\n smod,\n nttZetas: nttZetas as TRet,\n NTT: {\n encode: (r: TArg): TRet => NTT.encode(r as T) as TRet,\n decode: (r: TArg): TRet => NTT.decode(r as T) as TRet,\n },\n bitsCoder: bitsCoder as TRet>['bitsCoder'],\n };\n};\n\nconst createXofShake =\n (shake: typeof shake128): TRet =>\n (seed: TArg, blockLen?: number) => {\n if (!blockLen) 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\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: number, y: number) => {\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) as TRet;\n };\n },\n clean: () => {\n h.destroy();\n cleanBytes(buf, _seed);\n },\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: TRet = /* @__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: TRet = /* @__PURE__ */ createXofShake(shake256);\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 type { CHash } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128, XOF256 } from './_crystals.ts';\nimport {\n abytes,\n type BytesCoderLen,\n checkHash,\n cleanBytes,\n type CryptoKeys,\n equalBytes,\n getMessage,\n getMessagePrehash,\n randomBytes,\n type Signer,\n type SigOpts,\n splitCoder,\n type TArg,\n type TRet,\n validateOpts,\n validateSigOpts,\n validateVerOpts,\n vecCoder,\n type VerOpts,\n} from './utils.ts';\n\n/** Internal ML-DSA options. */\nexport type DSAInternalOpts = {\n /**\n * Whether `internal.sign` / `internal.verify` receive a caller-supplied 64-byte `mu`\n * instead of the usual FIPS 204 formatted message `M'` / prehash-formatted message.\n * validateInternalOpts() only checks this flag; callers still must supply the right input length.\n */\n externalMu?: boolean;\n};\nfunction validateInternalOpts(opts: TArg) {\n validateOpts(opts);\n if (opts.externalMu !== undefined) abool(opts.externalMu, 'opts.externalMu');\n}\n\n/** ML-DSA signer surface with access to the internal message formatting mode. */\nexport type DSAInternal = CryptoKeys & {\n lengths: Signer['lengths'];\n sign: (\n msg: TArg,\n secretKey: TArg,\n opts?: TArg\n ) => TRet;\n verify: (\n sig: TArg,\n msg: TArg,\n pubKey: TArg,\n opts?: TArg\n ) => boolean;\n};\n/** Public ML-DSA signer surface. */\nexport type DSA = Signer & { internal: TRet };\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\ntype XofGet = ReturnType['get']>;\n\n/** Various lattice params. */\n/** Public ML-DSA parameter-set description. */\nexport type DSAParam = {\n /** Matrix row count. */\n K: number;\n /** Matrix column count. */\n L: number;\n /** Bit width used when rounding `t`. */\n D: number;\n /** Bound used for the `y` sampling range. */\n GAMMA1: number;\n /** Bound used during decomposition and hints. */\n GAMMA2: number;\n /** Number of non-zero challenge coefficients. */\n TAU: number;\n /** Centered-binomial noise parameter. */\n ETA: number;\n /** Maximum number of hint bits in a signature. */\n OMEGA: number;\n};\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: Record = /* @__PURE__ */ (() =>\n 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 } as const))();\n\n// NOTE: there is a lot cases where negative numbers used (with smod instead of mod).\ntype Poly = Int32Array;\nconst newPoly = (n: number): TRet => new Int32Array(n) as TRet;\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});\n\nconst id = (n: T): T => n;\ntype IdNum = (n: number) => number;\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: number, compress: IdNum = id, verify: IdNum = id) =>\n crystals.bitsCoder(d, {\n encode: (i: number) => compress(verify(i)),\n decode: (i: number) => verify(compress(i)),\n });\n\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polyAdd = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] + b[i]);\n return a as TRet;\n};\n// Mutates `a` in place; callers must pass same-length polynomials.\nconst polySub = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\n for (let i = 0; i < a.length; i++) a[i] = crystals.mod(a[i] - b[i]);\n return a as TRet;\n};\n\n// Mutates `p` in place and assumes it is a decoded `t1`-range polynomial.\nconst polyShiftl = (p_: TArg): TRet => {\n const p = p_ as Poly;\n for (let i = 0; i < N; i++) p[i] <<= D;\n return p as TRet;\n};\n\nconst polyChknorm = (p_: TArg, B: number): boolean => {\n const p = p_ as Poly;\n // FIPS 204 Algorithms 7 and 8 express the same centered-norm check with explicit inequalities.\n for (let i = 0; i < N; i++) if (Math.abs(crystals.smod(p[i])) >= B) return true;\n return false;\n};\n\n// Both inputs must already be in NTT / `T_q` form.\nconst MultiplyNTTs = (a_: TArg, b_: TArg): TRet => {\n const a = a_ as Poly;\n const b = b_ as Poly;\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++) c[i] = crystals.mod(a[i] * b[i]);\n return c as TRet;\n};\n\n// Return poly in NTT representation\nfunction RejNTTPoly(xof_: TArg): TRet {\n const xof = xof_ as XofGet;\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) 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) r[j++] = t;\n }\n }\n return r as TRet;\n}\n\ntype DilithiumOpts = {\n K: number;\n L: number;\n GAMMA1: number;\n GAMMA2: number;\n TAU: number;\n ETA: number;\n OMEGA: number;\n C_TILDE_BYTES: number;\n CRH_BYTES: number;\n TR_BYTES: number;\n XOF128: XOF;\n XOF256: XOF;\n securityLevel: number;\n};\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_: TArg): TRet {\n const opts = opts_ as DilithiumOpts;\n const { K, L, GAMMA1, GAMMA2, TAU, ETA, OMEGA } = opts;\n const { CRH_BYTES, TR_BYTES, C_TILDE_BYTES, XOF128, XOF256, securityLevel } = opts;\n\n if (![2, 4].includes(ETA)) throw new Error('Wrong ETA');\n if (![1 << 17, 1 << 19].includes(GAMMA1)) throw new Error('Wrong GAMMA1');\n if (![GAMMA2_1, GAMMA2_2].includes(GAMMA2)) throw new Error('Wrong GAMMA2');\n const BETA = TAU * ETA;\n\n const decompose = (r: number) => {\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) 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\n const HighBits = (r: number) => decompose(r).r1;\n const LowBits = (r: number) => decompose(r).r0;\n const MakeHint = (z: number, r: number) => {\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\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\n const UseHint = (h: number, r: number) => {\n // Returns the high bits of r adjusted according to hint h\n const m = Math.floor((Q - 1) / (2 * GAMMA2));\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) return r0 > 0 ? crystals.mod(r1 + 1, m) | 0 : crystals.mod(r1 - 1, m) | 0;\n return r1 | 0;\n };\n const Power2Round = (r: number) => {\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\n const hintCoder: BytesCoderLen = {\n bytesLen: OMEGA + K,\n encode: (h_: TArg): TRet => {\n const h = h_ as Poly[] | false;\n if (h === false) 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++) if (h[i][j] !== 0) res[k++] = j;\n res[OMEGA + i] = k;\n }\n return res as TRet;\n },\n decode: (buf: TArg): TRet => {\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) return false as TRet;\n for (let j = k; j < buf[OMEGA + i]; j++) {\n if (j > k && buf[j] <= buf[j - 1]) return false as TRet;\n hi[buf[j]] = 1;\n }\n k = buf[OMEGA + i];\n h.push(hi);\n }\n for (let j = k; j < OMEGA; j++) if (buf[j] !== 0) return false as TRet;\n return h as TRet;\n },\n };\n\n const ETACoder = polyCoder(\n ETA === 2 ? 3 : 4,\n (i: number) => ETA - i,\n (i: number) => {\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 );\n const T0Coder = polyCoder(13, (i: number) => (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: number) => 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(\n 'secretKey',\n 32,\n 32,\n TR_BYTES,\n vecCoder(ETACoder, L),\n vecCoder(ETACoder, K),\n vecCoder(T0Coder, K)\n );\n const sigCoder = splitCoder('signature', C_TILDE_BYTES, vecCoder(ZCoder, L), hintCoder);\n const CoefFromHalfByte =\n ETA === 2\n ? (n: number) => (n < 15 ? 2 - (n % 5) : false)\n : (n: number) => (n < 9 ? 4 - n : false);\n\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_: TArg): TRet {\n const xof = xof_ as XofGet;\n // Samples an element a \u2208 Rq with coeffcients in [\u2212\u03B7, \u03B7] computed via rejection sampling from \u03C1.\n const r: Poly = 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) r[j++] = d1;\n if (j < N && d2 !== false) r[j++] = d2;\n }\n }\n return r as TRet;\n }\n\n const SampleInBall = (seed: TArg): TRet => {\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) 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 as TRet;\n };\n\n const polyPowerRound = (p_: TArg) => {\n const p = p_ as Poly;\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_: TArg, h_: TArg): TRet => {\n const u = u_ as Poly;\n const h = h_ as Poly;\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++) u[i] = UseHint(h[i], u[i]);\n return u as TRet;\n };\n const polyMakeHint = (a_: TArg, b_: TArg) => {\n const a = a_ as Poly;\n const b = b_ as Poly;\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\n const signRandBytes = 32;\n const seedCoder = splitCoder('seed', 32, 64, 32);\n // API & argument positions are exactly as in FIPS204.\n const internal: TRet = 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?: TArg) => {\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) seed = randomBytes(32);\n abytes(seed!, 32, 'seed');\n seedDst.set(seed!);\n if (randSeed) cleanBytes(seed!);\n seedDst[32] = K;\n seedDst[33] = L;\n const [rho, rhoPrime, K_] = seedCoder.decode(\n shake256(seedDst, { dkLen: seedCoder.bytesLen })\n );\n const xofPrime = XOF256(rhoPrime);\n const s1 = [];\n for (let i = 0; i < L; i++) 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 as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\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: Poly[] = [];\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: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n validateInternalOpts(opts);\n let { extraEntropy: random, externalMu = false } = opts;\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 [rho, _K, tr, s1, s2, t0] = secretCoder.decode(secretKey);\n // Cache matrix to avoid re-compute later\n const A: Poly[][] = []; // 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++) pv.push(RejNTTPoly(xof.get(j, i)));\n A.push(pv);\n }\n xof.clean();\n for (let i = 0; i < L; i++) 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\n // Compute private random seed\n const rnd =\n random === false\n ? new Uint8Array(32)\n : random === undefined\n ? randomBytes(signRandBytes)\n : random;\n abytes(rnd, 32, 'extraEntropy');\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\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++) 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)) continue main_loop; // ||z||\u221E \u2265 \u03B31 \u2212 \u03B2\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)) continue main_loop; // ||r0||\u221E \u2265 \u03B32 \u2212 \u03B2\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)) continue main_loop;\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) continue; // the number of 1\u2019s in h is greater than \u03C9\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) cleanBytes(mu);\n return res as TRet;\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateInternalOpts(opts);\n const { externalMu = false } = opts;\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\n if (sig.length !== sigCoder.bytesLen) 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) return false; // if h = \u22A5 then return false\n for (let i = 0; i < L; i++) if (polyChknorm(z[i], GAMMA1 - BETA)) 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++) 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)) return false;\n }\n for (const t of z) if (polyChknorm(t, GAMMA1 - BETA)) 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: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash: CHash) => {\n checkHash(hash, securityLevel);\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: (\n msg: TArg,\n secretKey: TArg,\n opts: TArg = {}\n ): TRet => {\n validateSigOpts(opts);\n const M = getMessagePrehash(hash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessagePrehash(hash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n\n/** ML-DSA-44 for 128-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa44: TRet = /* @__PURE__ */ (() =>\n 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\n/** ML-DSA-65 for 192-bit security level. Not recommended after 2030, as per ASD. */\nexport const ml_dsa65: TRet = /* @__PURE__ */ (() =>\n 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\n/** ML-DSA-87 for 256-bit security level. OK after 2030, as per ASD. */\nexport const ml_dsa87: TRet = /* @__PURE__ */ (() =>\n 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 * SLH-DSA: StateLess Hash-based Digital Signature Standard from\n * [FIPS-205](https://csrc.nist.gov/pubs/fips/205/ipd). A.k.a. Sphincs+ v3.1.\n *\n * There are many different kinds of SLH, but basically `sha2` / `shake` indicate internal hash,\n * `128` / `192` / `256` indicate security level, and `s` /`f` indicate trade-off (Small / Fast).\n *\n * Hashes function similarly to signatures. You hash a private key to get a public key,\n * which can be used to verify the private key. However, this only works once since\n * disclosing the pre-image invalidates the key.\n *\n * To address the \"one-time\" limitation, we can use a Merkle tree root hash:\n * h(h(h(0) || h(1)) || h(h(2) || h(3))))\n *\n * This allows us to have the same public key output from the hash, but disclosing one\n * path in the tree doesn't invalidate the others. By choosing a path related to the\n * message, we can \"sign\" it.\n *\n * Limitation: Only a fixed number of signatures can be made. For instance, a Merkle tree\n * with depth 8 allows 256 distinct messages. Using different trees for each node can\n * prevent forgeries, but the key will still degrade over time.\n *\n * WOTS: One-time signatures (can be forged if same key used twice).\n * FORS: Forest of Random Subsets\n *\n * Check out [official site](https://sphincs.org) & [repo](https://github.com/sphincs/sphincsplus).\n * @module\n */\n/*! noble-post-quantum - MIT License (c) 2024 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac.js';\nimport { sha256, sha512 } from '@noble/hashes/sha2.js';\nimport { shake256 } from '@noble/hashes/sha3.js';\nimport {\n bytesToHex,\n concatBytes,\n createView,\n hexToBytes,\n type CHash,\n} from '@noble/hashes/utils.js';\nimport {\n abytes,\n checkHash,\n cleanBytes,\n copyBytes,\n equalBytes,\n getMask,\n getMessage,\n getMessagePrehash,\n randomBytes,\n splitCoder,\n validateSigOpts,\n validateVerOpts,\n vecCoder,\n type Signer,\n type SigOpts,\n type TArg,\n type TRet,\n type VerOpts,\n} from './utils.ts';\n\n/**\n * * N: Security parameter (in bytes). W: Winternitz parameter\n * * H: Hypertree height. D: Hypertree layers\n * * K: FORS trees numbers. A: FORS trees height\n */\nexport type SphincsOpts = {\n /** Security parameter in bytes. */\n N: number;\n /** Winternitz parameter. */\n W: number;\n /** Total hypertree height. */\n H: number;\n /** Number of hypertree layers. */\n D: number;\n /** Number of FORS trees. */\n K: number;\n /** Height of each FORS tree. */\n A: number;\n /** Target security level in bits. */\n securityLevel: number;\n};\n\n/** Hash customization options for SLH-DSA context creation. */\nexport type SphincsHashOpts = {\n /** Whether to use the compressed-address variant from the standard. */\n isCompressed?: boolean;\n /** Factory that binds one parameter set to one per-key hash context generator. */\n getContext: GetContext;\n};\n\n/** Winternitz signature params. */\n/**\n * Built-in SLH-DSA Table 2 subset keyed by strength/profile.\n * SHA2 and SHAKE pairs share the same numeric rows here, so the hash family is chosen separately.\n * `securityLevel` stores 128/192/256-bit strengths for `checkHash(...)`,\n * not Table 2's category labels 1/3/5.\n * Other Table 2 columns such as `m`, public-key bytes, and signature bytes\n * stay derived at the export layer.\n */\nexport const PARAMS: Record = /* @__PURE__ */ (() =>\n Object.freeze({\n '128f': Object.freeze({ W: 16, N: 16, H: 66, D: 22, K: 33, A: 6, securityLevel: 128 }),\n '128s': Object.freeze({ W: 16, N: 16, H: 63, D: 7, K: 14, A: 12, securityLevel: 128 }),\n '192f': Object.freeze({ W: 16, N: 24, H: 66, D: 22, K: 33, A: 8, securityLevel: 192 }),\n '192s': Object.freeze({ W: 16, N: 24, H: 63, D: 7, K: 17, A: 14, securityLevel: 192 }),\n '256f': Object.freeze({ W: 16, N: 32, H: 68, D: 17, K: 35, A: 9, securityLevel: 256 }),\n '256s': Object.freeze({ W: 16, N: 32, H: 64, D: 8, K: 22, A: 14, securityLevel: 256 }),\n } as const))();\n\n// FIPS 205 `ADRS.setTypeAndClear(...)` selectors. Local names shorten the spec labels\n// (`WOTS_HASH` -> `WOTS`, `TREE` -> `HASHTREE`, `FORS_ROOTS` -> `FORSPK`), and `setAddr({ type })`\n// below only writes the type word; callers still need to preserve or overwrite the trailing words.\nconst AddressType = {\n WOTS: 0,\n WOTSPK: 1,\n HASHTREE: 2,\n FORSTREE: 3,\n FORSPK: 4,\n WOTSPRF: 5,\n FORSPRF: 6,\n} as const;\n\n/** Address byte array of size `ADDR_BYTES`. */\nexport type ADRS = Uint8Array;\n\n/** Hash and tweakable-hash callbacks bound to one SLH-DSA keypair context. */\nexport type Context = {\n /**\n * Derive a PRF output for one address.\n * @param addr - Address bytes.\n * @returns PRF output bytes.\n */\n PRFaddr: (addr: TArg) => TRet;\n /**\n * Derive the randomized message hash prefix.\n * @param skPRF - Secret PRF seed.\n * @param random - Per-signature randomness.\n * @param msg - Message bytes.\n * @returns PRF output bytes.\n */\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ) => TRet;\n /**\n * Hash one randomized message transcript.\n * @param R - Randomized message prefix.\n * @param pk - Public key bytes.\n * @param m - Message bytes.\n * @param outLen - Output length in bytes.\n * @returns Transcript hash bytes.\n */\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen: number\n ) => TRet;\n /**\n * Tweakable hash over one input block.\n * @param input - Input block.\n * @param addr - Address bytes.\n * @returns Hash output bytes.\n */\n thash1: (input: TArg, addr: TArg) => TRet;\n /**\n * Tweakable hash over multiple input blocks.\n * @param blocks - Number of input blocks.\n * @param input - Concatenated input bytes.\n * @param addr - Address bytes.\n * @returns Hash output bytes.\n */\n thashN: (blocks: number, input: TArg, addr: TArg) => TRet;\n /** Wipe any buffered hash state for the current context. */\n clean: () => void;\n};\n/** Factory that creates a context generator for one SLH-DSA parameter set. */\nexport type GetContext = (\n opts: SphincsOpts\n) => (pub_seed: TArg, sk_seed?: TArg) => TRet;\n\nfunction hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n return BigInt(hex === '' ? '0' : '0x' + hex); // Big Endian\n}\n\n// BE: Big Endian, LE: Little Endian. This is the local FIPS 205 `toInt(...)` equivalent.\nfunction bytesToNumberBE(bytes: TArg): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\n\n// Local in-range FIPS 205 `toByte(x, n)` equivalent; callers must keep `n < 256^len`.\nfunction numberToBytesBE(n: number | bigint, len: number): TRet {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\n\n// Local FIPS 205 Algorithm 4 `base_2^b(...)` implementation. Bits are consumed in big-endian\n// order within each input byte, and callers must provide at least `ceil(outLen * b / 8)` bytes;\n// short inputs are not rejected and would zero-extend implicitly.\nconst base2b = (outLen: number, b: number) => {\n const mask = getMask(b);\n return (bytes: TArg): TRet => {\n const baseB = new Uint32Array(outLen);\n for (let out = 0, pos = 0, bits = 0, total = 0; out < outLen; out++) {\n while (bits < b) {\n total = (total << 8) | bytes[pos++];\n bits += 8;\n }\n bits -= b;\n baseB[out] = (total >>> bits) & mask;\n }\n return baseB as TRet;\n };\n};\n\nfunction getMaskBig(bits: number) {\n return (1n << BigInt(bits)) - 1n; // 4 -> 0b1111\n}\n\n/** Public SLH-DSA signer with prehash customization. */\nexport type SphincsSigner = Signer & {\n internal: TRet;\n securityLevel: number;\n prehash: (hash: TArg) => TRet;\n};\n\n/** One parameter/hash instantiation of the public SLH-DSA API.\n * `keygen(seed)` is a deterministic 3N-byte library hook around the internal keygen flow,\n * and `getPublicKey(secretKey)` only extracts the embedded public key\n * instead of recomputing `PK.root`.\n */\nfunction gen(opts: SphincsOpts, hashOpts_: TArg): TRet {\n const hashOpts = hashOpts_ as SphincsHashOpts;\n const { N, W, H, D, K, A, securityLevel: securityLevel } = opts;\n const getContext = hashOpts.getContext(opts);\n if (W !== 16) throw new Error('Unsupported Winternitz parameter');\n const WOTS_LOGW = 4;\n const WOTS_LEN1 = Math.floor((8 * N) / WOTS_LOGW);\n const WOTS_LEN2 = N <= 8 ? 2 : N <= 136 ? 3 : 4;\n const TREE_HEIGHT = Math.floor(H / D);\n const WOTS_LEN = WOTS_LEN1 + WOTS_LEN2;\n\n let ADDR_BYTES = 22;\n let OFFSET_LAYER = 0;\n let OFFSET_TREE = 1;\n let OFFSET_TYPE = 9;\n let OFFSET_KP_ADDR2 = 12;\n let OFFSET_KP_ADDR1 = 13;\n let OFFSET_CHAIN_ADDR = 17;\n let OFFSET_TREE_INDEX = 18;\n let OFFSET_HASH_ADDR = 21;\n if (!hashOpts.isCompressed) {\n ADDR_BYTES = 32;\n OFFSET_LAYER += 3;\n OFFSET_TREE += 7;\n OFFSET_TYPE += 10;\n OFFSET_KP_ADDR2 += 10;\n OFFSET_KP_ADDR1 += 10;\n OFFSET_CHAIN_ADDR += 10;\n OFFSET_TREE_INDEX += 10;\n OFFSET_HASH_ADDR += 10;\n }\n\n // Mutates and returns `addr` in place. For the built-in parameter sets, the layer / chain /\n // hash / height / keypair values fit in the low byte(s), and the tree value fits in 64 bits,\n // so the untouched leading bytes in the wider FIPS 205 ADRS / ADRS_c fields stay zero.\n // `height` / `chain` and `index` / `hash` share the same spec words, so callers must use the\n // address-type-specific combinations instead of mixing both meanings in one call.\n const setAddr = (\n opts: TArg<{\n type?: (typeof AddressType)[keyof typeof AddressType];\n height?: number;\n tree?: bigint;\n index?: number;\n layer?: number;\n chain?: number;\n hash?: number;\n keypair?: number;\n subtreeAddr?: ADRS;\n keypairAddr?: ADRS;\n }>,\n addr: TArg = new Uint8Array(ADDR_BYTES)\n ) => {\n const { type, height, tree, layer, index, chain, hash, keypair } = opts;\n const { subtreeAddr, keypairAddr } = opts;\n const v = createView(addr);\n\n if (height !== undefined) addr[OFFSET_CHAIN_ADDR] = height;\n if (layer !== undefined) addr[OFFSET_LAYER] = layer;\n if (type !== undefined) addr[OFFSET_TYPE] = type;\n if (chain !== undefined) addr[OFFSET_CHAIN_ADDR] = chain;\n if (hash !== undefined) addr[OFFSET_HASH_ADDR] = hash;\n if (index !== undefined) v.setUint32(OFFSET_TREE_INDEX, index, false);\n if (subtreeAddr) addr.set(subtreeAddr.subarray(0, OFFSET_TREE + 8));\n if (tree !== undefined) v.setBigUint64(OFFSET_TREE, tree, false);\n if (keypair !== undefined) {\n addr[OFFSET_KP_ADDR1] = keypair;\n if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypair >>> 8;\n }\n if (keypairAddr) {\n addr.set(keypairAddr.subarray(0, OFFSET_TREE + 8));\n addr[OFFSET_KP_ADDR1] = keypairAddr[OFFSET_KP_ADDR1];\n if (TREE_HEIGHT > 8) addr[OFFSET_KP_ADDR2] = keypairAddr[OFFSET_KP_ADDR2];\n }\n return addr;\n };\n\n const chainCoder = base2b(WOTS_LEN2, WOTS_LOGW);\n const chainLengths = (msg: TArg) => {\n const W1 = base2b(WOTS_LEN1, WOTS_LOGW)(msg);\n let csum = 0;\n for (let i = 0; i < W1.length; i++) csum += W - 1 - W1[i]; // \u25B7 Compute checksum\n // csum \u2190 csum \u226A ((8 \u2212 ((len2 \u00B7 lg(w)) mod 8)) mod 8\n csum <<= (8 - ((WOTS_LEN2 * WOTS_LOGW) % 8)) % 8;\n // Checksum to base(LOG_W)\n const W2 = chainCoder(numberToBytesBE(csum, Math.ceil((WOTS_LEN2 * WOTS_LOGW) / 8)));\n // W1 || W2 (concatBytes cannot concat TypedArrays)\n const lengths = new Uint32Array(WOTS_LEN);\n lengths.set(W1);\n lengths.set(W2, W1.length);\n return lengths;\n };\n const messageToIndices = base2b(K, A);\n\n const TREE_BITS = TREE_HEIGHT * (D - 1);\n const LEAF_BITS = TREE_HEIGHT;\n const hashMsgCoder = splitCoder(\n 'hashedMessage',\n Math.ceil((A * K) / 8),\n Math.ceil(TREE_BITS / 8),\n Math.ceil(TREE_HEIGHT / 8)\n );\n // `pkSeed` is the full public key byte string `PK.seed || PK.root`; after splitting `Hmsg`,\n // mask away any spare high bits so `idx_tree` / `idx_leaf` match the spec's final mod-2^k steps.\n const hashMessage = (\n R: TArg,\n pkSeed: TArg,\n msg: TArg,\n context: TArg\n ) => {\n const rawContext = context as Context;\n // digest \u2190 Hmsg(R, PK.seed, PK.root, M)\n const digest = rawContext.Hmsg(R, pkSeed, msg, hashMsgCoder.bytesLen);\n const [md, tmpIdxTree, tmpIdxLeaf] = hashMsgCoder.decode(digest);\n const tree = bytesToNumberBE(tmpIdxTree) & getMaskBig(TREE_BITS);\n const leafIdx = Number(bytesToNumberBE(tmpIdxLeaf)) & getMask(LEAF_BITS);\n return { tree, leafIdx, md };\n };\n\n // Iterative `xmss_node` / `xmss_sign` core: mutate `treeAddr` in place, collapse completed\n // sibling pairs on `stack`, and record the sibling whenever the current subtree is the auth-path\n // neighbor of the target leaf at that height.\n const treehash = (\n height: number,\n fn: TArg<(leafIdx: number, addrOffset: number, context: Context, info: T) => Uint8Array>\n ) =>\n function treehash_i(\n context: TArg,\n leafIdx: number,\n idxOffset: number,\n treeAddr: TArg,\n info: T\n ) {\n const rawContext = context as Context;\n const leafFn = fn as (\n leafIdx: number,\n addrOffset: number,\n context: Context,\n info: T\n ) => Uint8Array;\n const maxIdx = (1 << height) - 1;\n const stack = new Uint8Array(height * N);\n const authPath = new Uint8Array(height * N);\n for (let idx = 0; ; idx++) {\n const current = new Uint8Array(2 * N);\n const cur0 = current.subarray(0, N);\n const cur1 = current.subarray(N);\n const addrOffset = idx + idxOffset;\n cur1.set(leafFn(leafIdx, addrOffset, rawContext, info));\n let h = 0;\n for (let i = idx, o = idxOffset, l = leafIdx; ; h++, i >>>= 1, l >>>= 1, o >>>= 1) {\n if (h === height) return { root: cur1, authPath }; // Returns from here\n if ((i ^ l) === 1) authPath.subarray(h * N).set(cur1); // authPath.push(cur1)\n if ((i & 1) === 0 && idx < maxIdx) break;\n setAddr({ height: h + 1, index: (i >> 1) + (o >> 1) }, treeAddr);\n cur0.set(stack.subarray(h * N).subarray(0, N));\n cur1.set(rawContext.thashN(2, current, treeAddr));\n }\n stack.subarray(h * N).set(cur1); // stack.push(cur1)\n }\n // @ts-ignore\n throw new Error('Unreachable code path reached, report this error');\n };\n\n type LeafInfo = {\n wotsSig: Uint8Array;\n wotsSteps: Uint32Array;\n leafAddr: ADRS;\n pkAddr: ADRS;\n };\n const wotsTreehash = treehash(\n TREE_HEIGHT,\n (leafIdx: number, addrOffset: number, context: TArg, info: TArg) => {\n const rawContext = context as Context;\n const wotsPk = new Uint8Array(WOTS_LEN * N);\n // `keygen()` passes `leafIdx = ~0 >>> 0`, so no real XMSS leaf matches and this suppresses\n // WOTS signature capture while still hashing every chain to its public-key endpoint.\n const wotsKmask = addrOffset === leafIdx ? 0 : ~0 >>> 0;\n setAddr({ keypair: addrOffset }, info.leafAddr);\n setAddr({ keypair: addrOffset }, info.pkAddr);\n for (let i = 0; i < WOTS_LEN; i++) {\n const wotsK = info.wotsSteps[i] | wotsKmask;\n const pk = wotsPk.subarray(i * N, (i + 1) * N);\n setAddr({ chain: i, hash: 0, type: AddressType.WOTSPRF }, info.leafAddr);\n pk.set(rawContext.PRFaddr(info.leafAddr));\n setAddr({ type: AddressType.WOTS }, info.leafAddr);\n for (let k = 0; ; k++) {\n if (k === wotsK) info.wotsSig.subarray(i * N).set(pk); //wotsSig.push()\n if (k === W - 1) break;\n setAddr({ hash: k }, info.leafAddr);\n pk.set(rawContext.thash1(pk, info.leafAddr));\n }\n }\n return rawContext.thashN(WOTS_LEN, wotsPk, info.pkAddr);\n }\n );\n\n const forsTreehash = treehash(\n A,\n (_: number, addrOffset: number, context: TArg, forsLeafAddr: TArg) => {\n const rawContext = context as Context;\n setAddr({ type: AddressType.FORSPRF, index: addrOffset }, forsLeafAddr);\n const prf = rawContext.PRFaddr(forsLeafAddr);\n setAddr({ type: AddressType.FORSTREE }, forsLeafAddr);\n return rawContext.thash1(prf, forsLeafAddr);\n }\n );\n\n // Fuse `xmss_sign` with the subtree-root computation needed by `ht_sign`, so one tree walk\n // yields both the WOTS/auth-path signature and the root that the next hypertree layer signs.\n const merkleSign = (\n context: TArg,\n wotsAddr: TArg,\n treeAddr: TArg,\n leafIdx: number,\n prevRoot: TArg = new Uint8Array(N)\n ): TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }> => {\n setAddr({ type: AddressType.HASHTREE }, treeAddr);\n // State variables\n const info = {\n wotsSig: new Uint8Array(wotsCoder.bytesLen),\n wotsSteps: chainLengths(prevRoot),\n leafAddr: setAddr({ subtreeAddr: wotsAddr }),\n pkAddr: setAddr({ type: AddressType.WOTSPK, subtreeAddr: wotsAddr }),\n };\n const { root, authPath } = wotsTreehash(context, leafIdx, 0, treeAddr, info);\n return {\n root,\n sigWots: info.wotsSig.subarray(0, WOTS_LEN * N),\n sigAuth: authPath,\n } as TRet<{ root: Uint8Array; sigWots: Uint8Array; sigAuth: Uint8Array }>;\n };\n\n type ForsLeafInfo = ADRS;\n\n const computeRoot = (\n leaf: TArg,\n leafIdx: number,\n idxOffset: number,\n authPath: TArg,\n treeHeight: number,\n context: TArg,\n addr: TArg\n ) => {\n const rawContext = context as Context;\n const buffer = new Uint8Array(2 * N);\n const b0 = buffer.subarray(0, N);\n const b1 = buffer.subarray(N, 2 * N);\n // Algorithm 11 hashes `node || AUTH[k]` for even nodes and `AUTH[k] || node` for odd ones,\n // so reuse one `2N` buffer and just swap which half receives the sibling at each level.\n // `idxOffset` carries the subtree base for the shared FORS path, so `leafIdx + idxOffset`\n // tracks the same tree-global index updates that Algorithms 11 and 17 apply to ADRS.\n // First iter\n if ((leafIdx & 1) !== 0) {\n b1.set(leaf.subarray(0, N));\n b0.set(authPath.subarray(0, N));\n } else {\n b0.set(leaf.subarray(0, N));\n b1.set(authPath.subarray(0, N));\n }\n leafIdx >>>= 1;\n idxOffset >>>= 1;\n // Rest\n for (let i = 0; i < treeHeight - 1; i++, leafIdx >>= 1, idxOffset >>= 1) {\n setAddr({ height: i + 1, index: leafIdx + idxOffset }, addr);\n const a = authPath.subarray((i + 1) * N, (i + 2) * N);\n if ((leafIdx & 1) !== 0) {\n b1.set(rawContext.thashN(2, buffer, addr));\n b0.set(a);\n } else {\n buffer.set(rawContext.thashN(2, buffer, addr));\n b1.set(a);\n }\n }\n // Root\n setAddr({ height: treeHeight, index: leafIdx + idxOffset }, addr);\n return rawContext.thashN(2, buffer, addr);\n };\n\n const seedCoder = splitCoder('seed', N, N, N);\n const publicCoder = splitCoder('publicKey', N, N);\n const secretCoder = splitCoder('secretKey', N, N, publicCoder.bytesLen);\n const forsCoder = vecCoder(splitCoder('fors', N, N * A), K);\n const wotsCoder = vecCoder(splitCoder('wots', WOTS_LEN * N, TREE_HEIGHT * N), D);\n const sigCoder = splitCoder('signature', N, forsCoder, wotsCoder); // random || fors || wots\n const internal: TRet = Object.freeze({\n info: Object.freeze({ type: 'internal-slh-dsa' }),\n lengths: Object.freeze({\n publicKey: publicCoder.bytesLen,\n secretKey: secretCoder.bytesLen,\n signature: sigCoder.bytesLen,\n seed: seedCoder.bytesLen,\n signRand: N,\n }),\n keygen(seed?: TArg) {\n if (seed !== undefined) abytes(seed, seedCoder.bytesLen, 'seed');\n seed = seed === undefined ? randomBytes(seedCoder.bytesLen) : copyBytes(seed);\n // Set SK.seed, SK.prf, and PK.seed to random n-byte\n const [secretSeed, secretPRF, publicSeed] = seedCoder.decode(seed);\n const context = getContext(publicSeed, secretSeed);\n // ADRS.setLayerAddress(d \u2212 1)\n const topTreeAddr = setAddr({ layer: D - 1 });\n const wotsAddr = setAddr({ layer: D - 1 });\n //PK.root \u2190_xmss node(SK.seed, 0, h\u2032, PK.seed, ADRS)\n const { root } = merkleSign(context, wotsAddr, topTreeAddr, ~0 >>> 0);\n const publicKey = publicCoder.encode([publicSeed, root]);\n const secretKey = secretCoder.encode([secretSeed, secretPRF, publicKey]);\n context.clean();\n cleanBytes(secretSeed, secretPRF, root, wotsAddr, topTreeAddr);\n return {\n publicKey: publicKey as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\n const [_skSeed, _skPRF, pk] = secretCoder.decode(secretKey);\n return Uint8Array.from(pk) as TRet;\n },\n sign: (msg: TArg, sk: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n let { extraEntropy: random } = opts;\n const [skSeed, skPRF, pk] = secretCoder.decode(sk); // todo: fix\n const [pkSeed, _] = publicCoder.decode(pk);\n // Set opt_rand to either PK.seed or to a random n-byte string\n if (random === false) random = copyBytes(pkSeed);\n else if (random === undefined) random = randomBytes(N);\n else random = copyBytes(random);\n abytes(random, N);\n const context = getContext(pkSeed, skSeed);\n // Generate randomizer\n const R = context.PRFmsg(skPRF, random, msg); // R \u2190 PRFmsg(SK.prf, opt_rand, M)\n let { tree, leafIdx, md } = hashMessage(R, pk, msg, context);\n // Create FORS signatures\n const wotsAddr = setAddr({\n type: AddressType.WOTS,\n tree,\n keypair: leafIdx,\n });\n const roots = [];\n const forsLeaf = setAddr({ keypairAddr: wotsAddr });\n const forsTreeAddr = setAddr({ keypairAddr: wotsAddr });\n const indices = messageToIndices(md);\n const fors: [Uint8Array, Uint8Array][] = [];\n for (let i = 0; i < indices.length; i++) {\n const idxOffset = i << A;\n setAddr(\n {\n type: AddressType.FORSPRF,\n height: 0,\n index: indices[i] + idxOffset,\n },\n forsTreeAddr\n );\n const prf = context.PRFaddr(forsTreeAddr);\n setAddr({ type: AddressType.FORSTREE }, forsTreeAddr);\n const { root, authPath } = forsTreehash(\n context,\n indices[i],\n idxOffset,\n forsTreeAddr,\n forsLeaf\n );\n roots.push(root);\n fors.push([prf, authPath]);\n }\n const forsPkAddr = setAddr({\n type: AddressType.FORSPK,\n keypairAddr: wotsAddr,\n });\n const root = context.thashN(K, concatBytes(...roots), forsPkAddr);\n // WOTS signatures\n const treeAddr = setAddr({ type: AddressType.HASHTREE });\n const wots: [Uint8Array, Uint8Array][] = [];\n for (let i = 0; i < D; i++, tree >>= BigInt(TREE_HEIGHT)) {\n setAddr({ tree, layer: i }, treeAddr);\n setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);\n const {\n sigWots,\n sigAuth,\n root: r,\n } = merkleSign(context, wotsAddr, treeAddr, leafIdx, root);\n root.set(r);\n cleanBytes(r);\n wots.push([sigWots, sigAuth]);\n leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));\n }\n context.clean();\n const SIG = sigCoder.encode([R, fors, wots]);\n cleanBytes(R, random, treeAddr, wotsAddr, forsLeaf, forsTreeAddr, indices, roots);\n return SIG as TRet;\n },\n verify: (sig: TArg, msg: TArg, publicKey: TArg) => {\n const [pkSeed, pubRoot] = publicCoder.decode(publicKey);\n const [random, forsVec, wotsVec] = sigCoder.decode(sig);\n const pk = publicKey;\n if (sig.length !== sigCoder.bytesLen) return false;\n const context = getContext(pkSeed);\n let { tree, leafIdx, md } = hashMessage(random, pk, msg, context);\n const wotsAddr = setAddr({\n type: AddressType.WOTS,\n tree,\n keypair: leafIdx,\n });\n // FORS signature\n const roots = [];\n const forsTreeAddr = setAddr({\n type: AddressType.FORSTREE,\n keypairAddr: wotsAddr,\n });\n const indices = messageToIndices(md);\n for (let i = 0; i < forsVec.length; i++) {\n const [prf, authPath] = forsVec[i];\n const idxOffset = i << A;\n setAddr({ height: 0, index: indices[i] + idxOffset }, forsTreeAddr);\n const leaf = context.thash1(prf, forsTreeAddr);\n // Compute inplace, because we need all roots in same byte array\n roots.push(computeRoot(leaf, indices[i], idxOffset, authPath, A, context, forsTreeAddr));\n }\n const forsPkAddr = setAddr({\n type: AddressType.FORSPK,\n keypairAddr: wotsAddr,\n });\n let root = context.thashN(K, concatBytes(...roots), forsPkAddr); // root = thash()\n // WOTS signature\n const treeAddr = setAddr({ type: AddressType.HASHTREE });\n const wotsPkAddr = setAddr({ type: AddressType.WOTSPK });\n const wotsPk = new Uint8Array(WOTS_LEN * N);\n for (let i = 0; i < wotsVec.length; i++, tree >>= BigInt(TREE_HEIGHT)) {\n const [wots, sigAuth] = wotsVec[i];\n setAddr({ tree, layer: i }, treeAddr);\n setAddr({ subtreeAddr: treeAddr, keypair: leafIdx }, wotsAddr);\n setAddr({ keypairAddr: wotsAddr }, wotsPkAddr);\n const lengths = chainLengths(root);\n for (let i = 0; i < WOTS_LEN; i++) {\n setAddr({ chain: i }, wotsAddr);\n const steps = W - 1 - lengths[i];\n const start = lengths[i];\n const out = wotsPk.subarray(i * N);\n out.set(wots.subarray(i * N, (i + 1) * N));\n for (let j = start; j < start + steps && j < W; j++) {\n setAddr({ hash: j }, wotsAddr);\n out.set(context.thash1(out, wotsAddr));\n }\n }\n const leaf = context.thashN(WOTS_LEN, wotsPk, wotsPkAddr);\n root = computeRoot(leaf, leafIdx, 0, sigAuth, TREE_HEIGHT, context, treeAddr);\n leafIdx = Number(tree & getMaskBig(TREE_HEIGHT));\n }\n return equalBytes(root, pubRoot);\n },\n });\n return Object.freeze({\n info: Object.freeze({ type: 'slh-dsa' }),\n internal,\n securityLevel: securityLevel,\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n const M = getMessage(msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessage(msg, opts.context), publicKey);\n },\n prehash: (hash: TArg): TRet => {\n checkHash(hash as CHash, securityLevel);\n const rawHash = hash as CHash;\n return Object.freeze({\n info: Object.freeze({ type: 'hashslh-dsa' }),\n lengths: internal.lengths,\n keygen: internal.keygen,\n getPublicKey: internal.getPublicKey,\n sign: (msg: TArg, secretKey: TArg, opts: TArg = {}) => {\n validateSigOpts(opts);\n const M = getMessagePrehash(rawHash, msg, opts.context);\n const res = internal.sign(M, secretKey, opts);\n cleanBytes(M);\n return res as TRet;\n },\n verify: (\n sig: TArg,\n msg: TArg,\n publicKey: TArg,\n opts: TArg = {}\n ) => {\n validateVerOpts(opts);\n return internal.verify(sig, getMessagePrehash(rawHash, msg, opts.context), publicKey);\n },\n });\n },\n });\n}\n\n// FIPS 205 \u00A711.1 SHAKE instantiation: this path hashes the full uncompressed address bytes,\n// unlike the compressed 22-byte SHA2 path in \u00A711.2.\nconst genShake =\n (): TRet =>\n (opts: SphincsOpts) =>\n (pubSeed: TArg, skSeed?: TArg): TRet => {\n const { N } = opts;\n const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0 };\n // \u00A711.1 prefixes PRF/F/H/T_l with `PK.seed`, so cache that absorbed prefix once and clone it\n // for each address-bound call instead of reabsorbing the same seed every time.\n const h0 = shake256.create({}).update(pubSeed);\n const h0tmp = h0.clone();\n const thash = (blocks: number, input: TArg, addr: TArg): TRet => {\n stats.thash++;\n return h0\n ._cloneInto(h0tmp)\n .update(addr)\n .update(input.subarray(0, blocks * N))\n .xof(N) as TRet;\n };\n return {\n PRFaddr: (addr: TArg): TRet => {\n if (!skSeed) throw new Error('no sk seed');\n stats.prf++;\n const res = h0._cloneInto(h0tmp).update(addr).update(skSeed).xof(N);\n return res as TRet;\n },\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ): TRet => {\n stats.gen_message_random++;\n return shake256\n .create({})\n .update(skPRF)\n .update(random)\n .update(msg)\n .digest()\n .subarray(0, N) as TRet;\n },\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen\n ): TRet => {\n stats.hmsg++;\n return shake256.create({}).update(R.subarray(0, N)).update(pk).update(m).xof(outLen);\n },\n thash1: thash.bind(null, 1),\n thashN: thash,\n clean: () => {\n h0.destroy();\n h0tmp.destroy();\n //console.log(stats);\n },\n } as TRet;\n };\n\nconst SHAKE_SIMPLE = /* @__PURE__ */ (() => ({ getContext: genShake() }))();\n\n/**\n * SLH-DSA-SHAKE-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_128f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_128s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128s'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_192f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_192s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192s'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_256f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256f'], SHAKE_SIMPLE))();\n/**\n * SLH-DSA-SHAKE-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_shake_256s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256s'], SHAKE_SIMPLE))();\n\ntype ShaType = typeof sha256 | typeof sha512;\n// FIPS 205 \u00A711.2 SHA2 instantiation. The `h0` / `h1` split is intentional:\n// category-1 keeps everything on SHA-256, while category-3/5 keep `PRFaddr` / `thash1`\n// on SHA-256 but switch `PRFmsg`, `Hmsg`, and multi-block `thashN` to SHA-512.\nconst genSha =\n (h0: ShaType, h1: ShaType): TRet =>\n (opts) =>\n (pub_seed: TArg, sk_seed?: TArg): TRet => {\n const { N } = opts;\n /*\n Perf debug stats, how much hashes we call?\n 128f_simple: { prf: 8305, thash: 96_922, hmsg: 1, gen_message_random: 1, mgf1: 2 }\n 256s_robust: { prf: 497_686, thash: 2_783_203, hmsg: 1, gen_message_random: 1, mgf1: 2_783_205}\n 256f_simple: { prf: 36_179, thash: 309_693, hmsg: 1, gen_message_random: 1, mgf1: 2 }\n */\n const stats = { prf: 0, thash: 0, hmsg: 0, gen_message_random: 0, mgf1: 0 };\n\n const counterB = new Uint8Array(4);\n const counterV = createView(counterB);\n // \u00A711.2 prefixes SHA2 PRF/F/H/T_l with `PK.seed || toByte(0, blockLen-N)`, so cache the\n // zero-padded seed block once for the SHA-256 lane and once for the SHA-512 lane.\n const h0ps = h0\n .create()\n .update(pub_seed)\n .update(new Uint8Array(h0.blockLen - N));\n const h1ps = h1\n .create()\n .update(pub_seed)\n .update(new Uint8Array(h1.blockLen - N));\n\n const h0tmp = h0ps.clone();\n const h1tmp = h1ps.clone();\n\n // https://www.rfc-editor.org/rfc/rfc8017.html#appendix-B.2.1\n // This local helper is intentionally stricter than generic MGF1 reuse: current SLH-DSA callers\n // only request tiny `m`-byte outputs, but the guard below rejects `length > 2^32` instead of\n // RFC 8017's broader `maskLen > 2^32 * hLen` bound.\n function mgf1(seed: TArg, length: number, hash: ShaType): TRet {\n stats.mgf1++;\n const out = new Uint8Array(Math.ceil(length / hash.outputLen) * hash.outputLen);\n // NOT 2^32-1\n if (length > 2 ** 32) throw new Error('mask too long');\n for (let counter = 0, o = out; o.length; counter++) {\n counterV.setUint32(0, counter, false);\n hash.create().update(seed).update(counterB).digestInto(o);\n o = o.subarray(hash.outputLen);\n }\n cleanBytes(out.subarray(length));\n return out.subarray(0, length) as TRet;\n }\n\n const thash =\n (_: ShaType, h: typeof h0ps, hTmp: typeof h0ps) =>\n (blocks: number, input: TArg, addr: TArg): TRet => {\n stats.thash++;\n const d = h\n ._cloneInto(hTmp as any)\n .update(addr)\n .update(input.subarray(0, blocks * N))\n .digest();\n return d.subarray(0, N) as TRet;\n };\n return {\n PRFaddr: (addr: TArg): TRet => {\n if (!sk_seed) throw new Error('No sk seed');\n stats.prf++;\n const res = h0ps\n ._cloneInto(h0tmp as any)\n .update(addr)\n .update(sk_seed)\n .digest()\n .subarray(0, N);\n return res as TRet;\n },\n PRFmsg: (\n skPRF: TArg,\n random: TArg,\n msg: TArg\n ): TRet => {\n stats.gen_message_random++;\n return hmac\n .create(h1, skPRF)\n .update(random)\n .update(msg)\n .digest()\n .subarray(0, N) as TRet;\n },\n Hmsg: (\n R: TArg,\n pk: TArg,\n m: TArg,\n outLen\n ): TRet => {\n stats.hmsg++;\n const seed = concatBytes(\n R.subarray(0, N),\n pk.subarray(0, N),\n h1.create().update(R.subarray(0, N)).update(pk).update(m).digest()\n );\n return mgf1(seed, outLen, h1);\n },\n thash1: thash(h0, h0ps, h0tmp).bind(null, 1),\n thashN: thash(h1, h1ps, h1tmp),\n clean: () => {\n h0ps.destroy();\n h1ps.destroy();\n h0tmp.destroy();\n h1tmp.destroy();\n //console.log(stats);\n },\n } as TRet;\n };\n\nconst SHA256_SIMPLE = /* @__PURE__ */ (() => ({\n isCompressed: true,\n getContext: genSha(sha256, sha256),\n}))();\nconst SHA512_SIMPLE = /* @__PURE__ */ (() => ({\n isCompressed: true,\n getContext: genSha(sha256, sha512),\n}))();\n\n/**\n * SLH-DSA-SHA2-128f: Table 2 row `n=16, h=66, d=22, h'=3, a=6, k=33, lg w=4, m=34`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=17088`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_128f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128f'], SHA256_SIMPLE))();\n/**\n * SLH-DSA-SHA2-128s: Table 2 row `n=16, h=63, d=7, h'=9, a=12, k=14, lg w=4, m=30`;\n * lengths `publicKey=32`, `secretKey=64`, `signature=7856`, `seed=48`, `signRand=16`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_128s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['128s'], SHA256_SIMPLE))();\n/**\n * SLH-DSA-SHA2-192f: Table 2 row `n=24, h=66, d=22, h'=3, a=8, k=33, lg w=4, m=42`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=35664`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_192f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192f'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-192s: Table 2 row `n=24, h=63, d=7, h'=9, a=14, k=17, lg w=4, m=39`;\n * lengths `publicKey=48`, `secretKey=96`, `signature=16224`, `seed=72`, `signRand=24`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_192s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['192s'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-256f: Table 2 row `n=32, h=68, d=17, h'=4, a=9, k=35, lg w=4, m=49`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=49856`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_256f: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256f'], SHA512_SIMPLE))();\n/**\n * SLH-DSA-SHA2-256s: Table 2 row `n=32, h=64, d=8, h'=8, a=14, k=22, lg w=4, m=47`;\n * lengths `publicKey=64`, `secretKey=128`, `signature=29792`, `seed=96`, `signRand=32`.\n * Also exposes `.prehash(...)`.\n */\nexport const slh_dsa_sha2_256s: TRet = /* @__PURE__ */ (() =>\n gen(PARAMS['256s'], SHA512_SIMPLE))();\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 { type CHash, swap32IfBE, u32 } from '@noble/hashes/utils.js';\nimport { genCrystals, type XOF, XOF128 } from './_crystals.ts';\nimport {\n abytes,\n cleanBytes,\n type Coder,\n copyBytes,\n equalBytes,\n getMask,\n type KEM,\n randomBytes,\n splitCoder,\n type TArg,\n type TRet,\n vecCoder,\n} from './utils.ts';\n\n/** Key encapsulation mechanism interface */\n\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: number): TRet => new Uint16Array(n) as TRet,\n brvBits: 7,\n isKyber: true,\n});\n\n/** FIPS 203: 7. Parameter Sets */\n/** Public ML-KEM parameter-set description. */\nexport type KEMParam = {\n /** Polynomial size. */\n N: number;\n /** Module rank. */\n K: number;\n /** Prime modulus. */\n Q: number;\n /** CBD parameter used for secret-key noise. */\n ETA1: number;\n /** CBD parameter used for error noise. */\n ETA2: number;\n /** Compression width for the `u` vector. */\n du: number;\n /** Compression width for the `v` polynomial. */\n dv: number;\n /** Required strength of the randomness source in bits. */\n RBGstrength: number;\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: Record = /* @__PURE__ */ (() =>\n 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 } as const))();\n\n// FIPS-203: compress/decompress\nconst compress = (d: number): Coder => {\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) return { encode: (i: number) => i, decode: (i: number) => (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: number) => ((i << d) + Q / 2) / Q,\n // const decompress = (i: number) => round((Q / 2 ** d) * i);\n decode: (i: number) => (i * Q + a) >>> d,\n };\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: number) =>\n crystals.bitsCoder(\n d,\n d === 12\n ? { encode: (i: number) => i, decode: (i: number) => (i >= Q ? i - Q : i) }\n : { encode: (i: number) => i, decode: (i: number) => i }\n );\n\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: number) => (d === 12 ? byteCoder(12) : crystals.bitsCoder(d, compress(d)));\n\n// Poly is mod Q, so 12 bits\ntype Poly = Uint16Array;\n\nfunction polyAdd(a_: TArg, b_: TArg) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] + b[i]); // a += b\n}\nfunction polySub(a_: TArg, b_: TArg) {\n const a = a_ as Poly;\n const b = b_ as Poly;\n // Mutates `a` in place; callers must pass two N=256 polynomials.\n for (let i = 0; i < N; i++) a[i] = crystals.mod(a[i] - b[i]); // a -= b\n}\n\n// FIPS-203: Computes the product of two degree-one polynomials with respect to a quadratic modulus\nfunction BaseCaseMultiply(a0: number, a1: number, b0: number, b1: number, zeta: number) {\n // `zeta` here is Algorithm 11's \u03B3 = \u03B6^(2BitRev_7(i)+1).\n const c0 = crystals.mod(a1 * b1 * zeta + a0 * b0);\n const c1 = crystals.mod(a0 * b1 + a1 * b0);\n return { c0, c1 };\n}\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_: TArg, g_: TArg): TRet {\n const f = f_ as Poly;\n const g = g_ as Poly;\n for (let i = 0; i < N / 2; i++) {\n let z = crystals.nttZetas[64 + (i >> 1)];\n if (i & 1) 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 as TRet;\n}\n\ntype PRF = (l: number, key: Uint8Array, nonce: number) => Uint8Array;\n\ntype XofGet = ReturnType['get']>;\n\ntype KyberOpts = KEMParam & {\n HASH256: CHash;\n HASH512: CHash;\n KDF: CHash;\n XOF: XOF; // (seed: Uint8Array, len: number, x: number, y: number) => Uint8Array;\n PRF: PRF;\n};\n\n// Return poly in NTT representation\nfunction SampleNTT(xof_: TArg): TRet {\n const xof = xof_ as XofGet;\n // The reader must already bind the Algorithm 7 seed||j||i bytes\n // and return block lengths divisible by 3.\n const r: Poly = new Uint16Array(N);\n for (let j = 0; j < N; ) {\n const b = xof();\n if (b.length % 3) 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) r[j++] = d1;\n if (j < N && d2 < Q) r[j++] = d2;\n }\n }\n return r as TRet;\n}\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: TArg, eta: number): TRet => {\n const r: Poly = 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 } 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) throw new Error(`sampleCBD: leftover bits: ${len}`);\n return r as TRet;\n};\n\nfunction sampleCBD(\n PRF_: TArg,\n seed: TArg,\n nonce: number,\n eta: number\n): TRet {\n const PRF = PRF_ as PRF;\n return sampleCBDBytes(PRF((eta * N) / 4, seed, nonce), eta);\n}\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_: TArg) => {\n const opts = opts_ as KyberOpts;\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 return {\n secretCoder,\n lengths: {\n secretKey: secretCoder.bytesLen,\n publicKey: publicCoder.bytesLen,\n cipherText: cipherCoder.bytesLen,\n },\n keygen: (seed: TArg) => {\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\n const [rho, sigma] = seedCoder.decode(seedHash);\n const sHat: Poly[] = [];\n const tHat: Poly[] = [];\n for (let i = 0; i < K; i++) 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: (\n publicKey: TArg,\n msg: TArg,\n seed: TArg\n ): TRet => {\n const [tHat, rho] = publicCoder.decode(publicKey);\n const rHat = [];\n for (let i = 0; i < K; i++) rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i, ETA1)));\n const x = XOF(rho);\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 = SampleNTT(x.get(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 x.clean();\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]) as TRet;\n },\n decrypt: (cipherText: TArg, privateKey: TArg): TRet => {\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++) polyAdd(tmp, MultiplyNTTs(sk[i], crystals.NTT.encode(u[i])));\n polySub(v, crystals.NTT.decode(tmp)); // w = v' - tmp\n cleanBytes(tmp, sk, u);\n return poly1.encode(v) as TRet;\n },\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 * 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: TArg): TRet {\n const rawOpts = opts as KyberOpts;\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 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: TArg = randomBytes(seedLen)) => {\n abytes(seed, seedLen, 'seed');\n const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));\n const publicKeyHash = HASH256(publicKey);\n // (dkPKE||ek||H(ek)||z)\n const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);\n cleanBytes(sk, publicKeyHash);\n return {\n publicKey: publicKey as TRet,\n secretKey: secretKey as TRet,\n };\n },\n getPublicKey: (secretKey: TArg): TRet => {\n const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);\n return Uint8Array.from(publicKey) as TRet;\n },\n encapsulate: (publicKey: TArg, msg: TArg = randomBytes(msgLen)) => {\n abytes(publicKey, lengths.publicKey, 'publicKey');\n abytes(msg, msgLen, 'message');\n\n // FIPS-203 includes additional verification check for modulus\n const eke = publicKey.subarray(0, 384 * opts.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 if (!equalBytes(ek, eke)) {\n cleanBytes(ek);\n throw new Error('ML-KEM.encapsulate: wrong publicKey modulus');\n }\n cleanBytes(ek);\n // derive randomness\n const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();\n const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));\n cleanBytes(kr.subarray(32));\n return {\n cipherText: cipherText as TRet,\n sharedSecret: kr.subarray(0, 32) as TRet,\n };\n },\n decapsulate: (cipherText: TArg, secretKey: TArg): TRet => {\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 cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);\n return (isValid ? Khat : Kbar) as TRet;\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: number, key: TArg, nonce: number): TRet {\n return shake256\n .create({ dkLen })\n .update(key)\n .update(new Uint8Array([nonce]))\n .digest() as TRet;\n}\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: KEMParam) =>\n createKyber({\n ...opts,\n ...params,\n });\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 */\nexport const ml_kem512: TRet = /* @__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: TRet = /* @__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: TRet = /* @__PURE__ */ (() => mk(PARAMS[1024]))();\n\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: any = /* @__PURE__ */ (() =>\n Object.freeze({\n Compress_d: (x: number, d: number) => {\n if (d < 1 || d > 11) 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: number, d: number) => {\n if (d < 1 || d > 11) throw new Error(`Decompress_d: expected d in [1..11], got ${d}`);\n return compress(d).decode(y);\n },\n ByteEncode_d: (F: TArg, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteEncode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).encode(F as TRet);\n },\n ByteDecode_d: (B: TArg, d: number) => {\n if (d < 1 || d > 12) throw new Error(`ByteDecode_d: expected d in [1..12], got ${d}`);\n return byteCoder(d).decode(B);\n },\n NTT: (f: TArg) => crystals.NTT.encode(Uint16Array.from(f)),\n NTT_inv: (fHat: TArg) => crystals.NTT.decode(Uint16Array.from(fHat)),\n MultiplyNTTs: (fHat: TArg, gHat: TArg) =>\n MultiplyNTTs(Uint16Array.from(fHat), Uint16Array.from(gHat)),\n SamplePolyCBD: (B: TArg, eta: number) => {\n abytes(B, 64 * eta, 'B');\n return sampleCBDBytes(B, eta);\n },\n SampleNTT: (B: TArg) => {\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 } finally {\n xof.clean();\n }\n },\n }))();\n", "/**\n * Post-Quantum Crypto Module for Nostr\n *\n * Provides:\n * - BIP39 seed phrase generation\n * - NIP-06 key derivation (secp256k1 from seed)\n * - PQ key derivation from seed (ML-DSA-65, SLH-DSA-128s, ML-KEM-768)\n * - PQ signing (ML-DSA, SLH-DSA)\n * - NIP-QR event construction\n *\n * Uses @noble/post-quantum (pure JS, no WASM needed)\n */\n\nimport { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';\nimport { wordlist } from '@scure/bip39/wordlists/english.js';\nimport { HDKey } from '@scure/bip32';\nimport { hkdf } from '@noble/hashes/hkdf.js';\nimport { sha256 as sha256Hash, sha512 as sha512Hash } from '@noble/hashes/sha2.js';\nimport { ml_dsa65 } from '@noble/post-quantum/ml-dsa.js';\nimport { slh_dsa_sha2_128s } from '@noble/post-quantum/slh-dsa.js';\nimport { ml_kem768 } from '@noble/post-quantum/ml-kem.js';\n\n// ============================================================================\n// BIP39 SEED PHRASE\n// ============================================================================\n\n/**\n * Generate a new 12-word BIP39 mnemonic.\n * @returns {string} 12-word seed phrase\n */\nexport function generateSeedPhrase() {\n return generateMnemonic(wordlist, 128); // 128 bits = 12 words\n}\n\n/**\n * Convert a mnemonic to a 64-byte BIP39 seed (PBKDF2-HMAC-SHA512).\n * @param {string} mnemonic - 12/24 word seed phrase\n * @param {string} [passphrase=''] - optional BIP39 passphrase\n * @returns {Uint8Array} 64-byte seed\n */\nexport function mnemonicToSeed(mnemonic, passphrase = '') {\n if (!validateMnemonic(mnemonic, wordlist)) {\n throw new Error('Invalid mnemonic');\n }\n return mnemonicToSeedSync(mnemonic, passphrase);\n}\n\n/**\n * Validate a BIP39 mnemonic.\n * @param {string} mnemonic\n * @returns {boolean}\n */\nexport function isValidMnemonic(mnemonic) {\n return validateMnemonic(mnemonic, wordlist);\n}\n\n// ============================================================================\n// NIP-06 KEY DERIVATION (secp256k1 from seed)\n// ============================================================================\n\n/**\n * Derive a secp256k1 keypair from a BIP39 seed using NIP-06.\n * Path: m/44'/1237'/0'/0/0\n *\n * @param {Uint8Array} seed - 64-byte BIP39 seed\n * @param {number} [accountIndex=0] - account index\n * @returns {{privateKey: Uint8Array, publicKey: Uint8Array}} secp256k1 keypair\n */\nexport function deriveSecp256k1FromSeed(seed, accountIndex = 0) {\n const hdKey = HDKey.fromMasterSeed(seed);\n const path = `m/44'/1237'/${accountIndex}'/0/0`;\n const child = hdKey.derive(path);\n if (!child.privateKey) {\n throw new Error('Failed to derive private key');\n }\n return {\n privateKey: child.privateKey,\n publicKey: child.publicKey\n };\n}\n\n// ============================================================================\n// PQ KEY DERIVATION FROM SEED\n// ============================================================================\n\n/**\n * Derive PQ key seeds from a BIP39 seed using HKDF.\n * Each algorithm gets a unique label so keys are independent.\n *\n * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed\n * @param {string} label - algorithm label (e.g. 'nostr-pq-ml-dsa-65')\n * @param {number} length - output length in bytes\n * @returns {Uint8Array} deterministic seed for PQ keygen\n */\nfunction derivePQSeed(bip39Seed, label, length) {\n const info = new TextEncoder().encode(label);\n return hkdf(sha512Hash, bip39Seed, undefined, info, length);\n}\n\n/**\n * Derive all PQ keypairs from a BIP39 seed.\n *\n * @param {Uint8Array} bip39Seed - 64-byte BIP39 seed\n * @returns {{\n * mlDsa: {publicKey: Uint8Array, secretKey: Uint8Array},\n * slhDsa: {publicKey: Uint8Array, secretKey: Uint8Array},\n * mlKem: {publicKey: Uint8Array, secretKey: Uint8Array}\n * }}\n */\nexport function derivePQKeysFromSeed(bip39Seed) {\n // ML-DSA-65 needs 32-byte seed\n const mlDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-dsa-65', 32);\n const mlDsa = ml_dsa65.keygen(mlDsaSeed);\n\n // SLH-DSA-128s needs 48-byte seed (3 * 16 for sk seed, pk seed, etc.)\n const slhDsaSeed = derivePQSeed(bip39Seed, 'nostr-pq-slh-dsa-128s', 48);\n const slhDsa = slh_dsa_sha2_128s.keygen(slhDsaSeed);\n\n // ML-KEM-768 needs 64-byte seed\n const mlKemSeed = derivePQSeed(bip39Seed, 'nostr-pq-ml-kem-768', 64);\n const mlKem = ml_kem768.keygen(mlKemSeed);\n\n return { mlDsa, slhDsa, mlKem };\n}\n\n// ============================================================================\n// PQ SIGNING\n// ============================================================================\n\n/**\n * Sign a message with ML-DSA-65.\n * @param {Uint8Array} message\n * @param {Uint8Array} secretKey\n * @returns {Uint8Array} signature\n */\nexport function signWithMLDSA(message, secretKey) {\n return ml_dsa65.sign(message, secretKey);\n}\n\n/**\n * Verify an ML-DSA-65 signature.\n * @param {Uint8Array} signature\n * @param {Uint8Array} message\n * @param {Uint8Array} publicKey\n * @returns {boolean}\n */\nexport function verifyMLDSA(signature, message, publicKey) {\n return ml_dsa65.verify(signature, message, publicKey);\n}\n\n/**\n * Sign a message with SLH-DSA-128s.\n * @param {Uint8Array} message\n * @param {Uint8Array} secretKey\n * @returns {Uint8Array} signature\n */\nexport function signWithSLHDSA(message, secretKey) {\n return slh_dsa_sha2_128s.sign(message, secretKey);\n}\n\n/**\n * Verify an SLH-DSA-128s signature.\n * @param {Uint8Array} signature\n * @param {Uint8Array} message\n * @param {Uint8Array} publicKey\n * @returns {boolean}\n */\nexport function verifySLHDSA(signature, message, publicKey) {\n return slh_dsa_sha2_128s.verify(signature, message, publicKey);\n}\n\n// ============================================================================\n// UTILITIES\n// ============================================================================\n\n/**\n * Convert Uint8Array to base64 string.\n * @param {Uint8Array} bytes\n * @returns {string}\n */\nexport function bytesToBase64(bytes) {\n let binary = '';\n for (let i = 0; i < bytes.length; i++) {\n binary += String.fromCharCode(bytes[i]);\n }\n return btoa(binary);\n}\n\n/**\n * Convert base64 string to Uint8Array.\n * @param {string} base64\n * @returns {Uint8Array}\n */\nexport function base64ToBytes(base64) {\n const binary = atob(base64);\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\n/**\n * Convert Uint8Array to hex string.\n * @param {Uint8Array} bytes\n * @returns {string}\n */\nexport function bytesToHex(bytes) {\n return Array.from(bytes)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/**\n * Convert hex string to Uint8Array.\n * @param {string} hex\n * @returns {Uint8Array}\n */\nexport function hexToBytes(hex) {\n const bytes = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n bytes[i / 2] = parseInt(hex.substr(i, 2), 16);\n }\n return bytes;\n}\n\n// ============================================================================\n// NIP-QR EVENT CONSTRUCTION\n// ============================================================================\n\n/**\n * Build the NIP-QR event content (the JSON that goes in the event's content field).\n *\n * The content contains:\n * - A link statement\n * - All PQ public keys\n * - PQ signatures over the statement\n * - The ML-KEM public key (no signature \u2014 KEM can't sign)\n *\n * @param {string} npub - The user's Nostr npub (hex pubkey)\n * @param {string} successorNpub - The successor's hex pubkey (for Path B), or null for Path A\n * @param {{mlDsa: *, slhDsa: *, mlKem: *}} pqKeys - PQ keypairs\n * @returns {{statement: string, content: object, statementBytes: Uint8Array}}\n */\nexport function buildNIPQRContent(npub, successorNpub, pqKeys) {\n let statement;\n if (successorNpub) {\n // Path B: migration from old nsec to seed-derived key\n statement = `Identity ${npub} is migrating to successor ${successorNpub}. All PQ keys listed below are derived from the same BIP39 seed as ${successorNpub}. This link is established pre-quantum.`;\n } else {\n // Path A: direct link (identity already seed-derived)\n statement = `Identity ${npub} is linked to the following PQ keys, all derived from the same BIP39 seed. This link is established pre-quantum.`;\n }\n\n const statementBytes = new TextEncoder().encode(statement);\n\n // Sign the statement with each PQ signature scheme\n const mlDsaSig = signWithMLDSA(statementBytes, pqKeys.mlDsa.secretKey);\n const slhDsaSig = signWithSLHDSA(statementBytes, pqKeys.slhDsa.secretKey);\n\n const content = {\n statement,\n pq_keys: [\n {\n algorithm: 'ml-dsa-65',\n public_key: bytesToBase64(pqKeys.mlDsa.publicKey),\n signature: bytesToBase64(mlDsaSig)\n },\n {\n algorithm: 'slh-dsa-128s',\n public_key: bytesToBase64(pqKeys.slhDsa.publicKey),\n signature: bytesToBase64(slhDsaSig)\n },\n {\n algorithm: 'ml-kem-768',\n public_key: bytesToBase64(pqKeys.mlKem.publicKey),\n note: 'KEM key for encryption; ownership asserted by secp256k1 signature over this content'\n }\n ]\n };\n\n // If Path B, include successor info\n if (successorNpub) {\n content.successor_pubkey = successorNpub;\n }\n\n return { statement, content, statementBytes };\n}\n\n/**\n * Verify a NIP-QR event's PQ signatures.\n * @param {object} content - The parsed content object\n * @returns {{valid: boolean, results: Array}} verification results\n */\nexport function verifyNIPQRContent(content) {\n const results = [];\n\n for (const keyEntry of content.pq_keys) {\n if (keyEntry.algorithm === 'ml-kem-768') {\n // KEM can't sign \u2014 skip verification\n results.push({ algorithm: keyEntry.algorithm, valid: true, note: 'KEM (no signature to verify)' });\n continue;\n }\n\n const pubKey = base64ToBytes(keyEntry.public_key);\n const sig = base64ToBytes(keyEntry.signature);\n const msg = new TextEncoder().encode(content.statement);\n\n let valid = false;\n if (keyEntry.algorithm === 'ml-dsa-65') {\n valid = verifyMLDSA(sig, msg, pubKey);\n } else if (keyEntry.algorithm === 'slh-dsa-128s') {\n valid = verifySLHDSA(sig, msg, pubKey);\n }\n\n results.push({ algorithm: keyEntry.algorithm, valid });\n }\n\n return {\n valid: results.every(r => r.valid),\n results\n };\n}\n\n// ============================================================================\n// KEY SIZE INFO (for display)\n// ============================================================================\n\nexport const PQ_KEY_INFO = {\n 'ml-dsa-65': {\n name: 'ML-DSA-65 (Dilithium)',\n publicKeySize: 1952,\n signatureSize: 3309,\n fips: 'FIPS 204',\n type: 'signature'\n },\n 'slh-dsa-128s': {\n name: 'SLH-DSA-128s (SPHINCS+)',\n publicKeySize: 32,\n signatureSize: 7856,\n fips: 'FIPS 205',\n type: 'signature'\n },\n 'ml-kem-768': {\n name: 'ML-KEM-768 (Kyber)',\n publicKeySize: 1184,\n ciphertextSize: 1088,\n fips: 'FIPS 203',\n type: 'kem'\n }\n};\n"], + "mappings": ";;;;;AAwHM,SAAU,QAAQ,GAAU;AAKhC,SACE,aAAa,cACZ,YAAY,OAAO,CAAC,KACnB,EAAE,YAAY,SAAS,gBACvB,uBAAuB,KACvB,EAAE,sBAAsB;AAE9B;AAcM,SAAU,QAAQ,GAAW,QAAgB,IAAE;AACnD,MAAI,OAAO,MAAM,UAAU;AACzB,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,UAAU,GAAG,MAAM,wBAAwB,OAAO,CAAC,EAAE;EACjE;AACA,MAAI,CAAC,OAAO,cAAc,CAAC,KAAK,IAAI,GAAG;AACrC,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,IAAI,WAAW,GAAG,MAAM,8BAA8B,CAAC,EAAE;EACjE;AACF;AAgBM,SAAU,OACd,OACA,QACA,QAAgB,IAAE;AAElB,QAAM,QAAQ,QAAQ,KAAK;AAC3B,QAAM,MAAM,OAAO;AACnB,QAAM,WAAW,WAAW;AAC5B,MAAI,CAAC,SAAU,YAAY,QAAQ,QAAS;AAC1C,UAAM,SAAS,SAAS,IAAI,KAAK;AACjC,UAAM,QAAQ,WAAW,cAAc,MAAM,KAAK;AAClD,UAAM,MAAM,QAAQ,UAAU,GAAG,KAAK,QAAQ,OAAO,KAAK;AAC1D,UAAM,UAAU,SAAS,wBAAwB,QAAQ,WAAW;AACpE,QAAI,CAAC;AAAO,YAAM,IAAI,UAAU,OAAO;AACvC,UAAM,IAAI,WAAW,OAAO;EAC9B;AACA,SAAO;AACT;AAkCM,SAAU,MAAM,GAAc;AAClC,MAAI,OAAO,MAAM,cAAc,OAAO,EAAE,WAA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IACf,eAAe;AAAA,IACf,MAAM;AAAA,IACN,MAAM;AAAA,EACV;AAAA,EACA,gBAAgB;AAAA,IACZ,MAAM;AAAA,IACN,eAAe;AAAA,IACf,eAAe;AAAA,IACf,MAAM;AAAA,IACN,MAAM;AAAA,EACV;AAAA,EACA,cAAc;AAAA,IACV,MAAM;AAAA,IACN,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,MAAM;AAAA,IACN,MAAM;AAAA,EACV;AACJ;", + "names": ["opts", "opts", "isLE", "D", "F", "isBytes", "anumber", "id", "anumber", "padding", "isBytes", "anumber", "isBytes", "sha256", "wordlist", "abytes", "anumber", "bytesToHex", "concatBytes", "hexToBytes", "isBytes", "randomBytes", "abytes", "concatBytes", "gen", "_0n", "_1n", "_0n", "_1n", "gcd", "F", "Q", "opts", "_1n", "F", "_0n", "F", "_1n", "anumber", "_0n", "opts", "_1n", "abytes", "isLE", "_1n", "isLE", "abytes", "_0n", "_1n", "_1n", "_0n", "Point", "_1n", "isLE", "_0n", "Fn", "F", "N", "_2n", "_0n", "_1n", "opts", "abytes", "_3n", "_4n", "Fn", "concatBytes", "Point", "hexToBytes", "endo", "bytesToHex", "Fn", "Point", "randomBytes", "abytes", "isBytes", "utils", "hmac", "_2n", "_1n", "r", "s", "hexToBytes", "concatBytes", "Q", "bytesToHex", "_0n", "opts", "_2n", "_3n", "_0n", "_1n", "_2n", "_7n", "opts", "randomBytes", "copyBytes", "opts", "validateSigOpts", "opts", "newPoly", "N", "Q", "F", "ROOT_OF_UNITY", "mod", "opts", "compress", "XOF128", "XOF256", "randomBytes", "validateSigOpts", "PARAMS", "hexToNumber", "bytesToNumberBE", "numberToBytesBE", "opts", "N", "D", "chain", "randomBytes", "copyBytes", "validateSigOpts", "root", "i", "opts", "N", "PARAMS", "N", "Q", "F", "ROOT_OF_UNITY", "crystals", "PARAMS", "polyCoder", "polyAdd", "polySub", "MultiplyNTTs", "opts", "randomBytes", "copyBytes", "PARAMS", "bytesToHex", "hexToBytes"] +}