diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index dd04373..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,9 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "npm" - directory: "/" - schedule: - interval: "daily" - allow: - - dependency-name: "*" - dependency-type: "production" \ No newline at end of file diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 2504ef9..18f422a 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -10,12 +10,17 @@ jobs: strategy: fail-fast: false matrix: + include: + # @actions/setup-node does not support Node.js v14 for macOS + - node: 14 + os: ubuntu-latest node: + - 16.0.0 + - 16 + - 18.0.0 - 18 - 20 - # TODO: Unpin to `22` once parcel incomaptibility with 22.7+ is resolved - # - https://github.com/nodejs/node/issues/54573 - # - https://github.com/parcel-bundler/parcel/issues/9926 + # TODO: change to `22` once they fix https://github.com/nodejs/node/issues/54573 - 22.6 os: - ubuntu-latest @@ -28,12 +33,9 @@ jobs: node-version: ${{ matrix.node }} registry-url: 'https://registry.npmjs.org' cache: 'npm' + - run: npm install -g npm@9.x - run: npm ci - - name: Build and run tests - run: | - npm run build --if-present - npm test - - name: Run browser tests and lint - run: | - npm run browser-tests - npm run lint + - run: npm run build --if-present + - run: npm test + - run: npm run browser-tests + - run: npm run lint --if-present diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 0accffd..4cec091 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -9,14 +9,15 @@ jobs: contents: read id-token: write steps: - - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4 - - uses: actions/setup-node@1e60f620b9541d16bece96c5465dc8ee9832be0b # v4 - with: - node-version: ${{ matrix.node }} - registry-url: 'https://registry.npmjs.org' - cache: 'npm' - - run: npm ci - - run: npm run build - - run: npm publish --provenance --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} + - uses: actions/checkout@1e31de5234b9f8995739874a8ce0492dc87873e2 # v4 + - uses: actions/setup-node@8f152de45cc393bb48ce5d89d36b731f54556e65 # v4 + with: + node-version: 20 + registry-url: 'https://registry.npmjs.org' + cache: npm + - run: npm install -g npm@9.x + - run: npm ci + - run: npm run build + - run: npm publish --provenance --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} diff --git a/.gitignore b/.gitignore index d968c99..55d0b5b 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ /bip39 /test-builds /node_modules -/.parcel-cache +.parcel-cache /esm /test/node_modules /test/package-lock.json diff --git a/README.md b/README.md index d88429f..649e15d 100644 --- a/README.md +++ b/README.md @@ -1,102 +1,67 @@ # ethereum-cryptography -[![npm version][1]][2] [![license][3]][4] +[Audited](#security) pure JS library containing all Ethereum-related cryptographic primitives. Implemented with 6 [noble & scure](https://paulmillr.com/noble/) dependencies. -[Audited](#security) pure JS library containing all Ethereum-related cryptographic primitives. - -Included algorithms, implemented with just 5 [noble & scure](https://paulmillr.com/noble/) dependencies: - -* [Hashes: SHA256, keccak-256, RIPEMD160, BLAKE2b](#hashes-sha256-keccak-256-ripemd160-blake2b) -* [KDFs: PBKDF2, Scrypt](#kdfs-pbkdf2-scrypt) -* [CSPRNG (Cryptographically Secure Pseudorandom Number Generator)](#csprng-cryptographically-strong-pseudorandom-number-generator) -* [secp256k1 elliptic curve](#secp256k1-curve) -* [BIP32 HD Keygen](#bip32-hd-keygen) -* [BIP39 Mnemonic phrases](#bip39-mnemonic-seed-phrase) -* [AES Encryption](#aes-encryption) - -**April 2023 update:** v2.0 is out, switching -[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1) to -[noble-curves](https://github.com/paulmillr/noble-curves), -which changes re-exported api of `secp256k1` submodule. -There have been no other changes. - -**January 2022 update:** v1.0 has been released. We've rewritten the library from -scratch and [audited](#security) it. It became **6x smaller:** ~5,000 lines of -code instead of ~24,000 (with all deps); 650KB instead of 10.2MB. -5 dependencies by 1 author are now used, instead of 38 by 5 authors. - -Check out [Upgrading](#upgrading) section and an article about the library: +Check out [Changelog / Upgrading](#upgrading) and an article about the library: [A safer, smaller, and faster Ethereum cryptography stack](https://medium.com/nomic-labs-blog/a-safer-smaller-and-faster-ethereum-cryptography-stack-5eeb47f62d79). ## Usage -Use NPM / Yarn in node.js / browser: - -```bash -# NPM -npm install ethereum-cryptography - -# Yarn -yarn add ethereum-cryptography -``` +> npm install ethereum-cryptography -See [browser usage](#browser-usage) for information on using the package with major Javascript bundlers. It is -tested with **Webpack, Rollup, Parcel and Browserify**. +We explicitly support major browsers and Node.js on x86 and arm64. Other major runtimes and platforms are supported on a best-effort basis. +Refer to `engines` field of `package.json` for runtime support information for each version. +Tests are being ran with Webpack, Rollup, Parcel and Browserify. This package has no single entry-point, but submodule for each cryptographic -primitive. Read each primitive's section of this document to learn how to use -them. - -The reason for this is that importing everything from a single file will lead to -huge bundles when using this package for the web. This could be avoided through -tree-shaking, but the possibility of it not working properly on one of -[the supported bundlers](#browser-usage) is too high. - -```js -// Hashes -import { sha256 } from "ethereum-cryptography/sha256.js"; -import { keccak256 } from "ethereum-cryptography/keccak.js"; -import { ripemd160 } from "ethereum-cryptography/ripemd160.js"; -import { blake2b } from "ethereum-cryptography/blake2b.js"; - -// KDFs -import { pbkdf2Sync } from "ethereum-cryptography/pbkdf2.js"; -import { scryptSync } from "ethereum-cryptography/scrypt.js"; - -// Random -import { getRandomBytesSync } from "ethereum-cryptography/random.js"; - -// AES encryption -import { encrypt } from "ethereum-cryptography/aes.js"; - -// secp256k1 elliptic curve operations -import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; - -// BIP32 HD Keygen, BIP39 Mnemonic Phrases -import { HDKey } from "ethereum-cryptography/hdkey.js"; -import { generateMnemonic } from "ethereum-cryptography/bip39/index.js"; -import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; - -// utilities -import { hexToBytes, toHex, utf8ToBytes } from "ethereum-cryptography/utils.js"; -``` - -## Hashes: SHA256, keccak-256, RIPEMD160, BLAKE2b -```typescript -function sha256(msg: Uint8Array): Uint8Array; -function sha512(msg: Uint8Array): Uint8Array; -function keccak256(msg: Uint8Array): Uint8Array; -function ripemd160(msg: Uint8Array): Uint8Array; -function blake2b(msg: Uint8Array, outputLength = 64): Uint8Array; -``` - -Exposes following cryptographic hash functions: - -- SHA2 (SHA256, SHA512) -- keccak-256 variant of SHA3 (also `keccak224`, `keccak384`, -and `keccak512`) -- RIPEMD160 -- BLAKE2b +primitive. The reason for this is that importing everything from a single file will lead to huge bundles when using this package for the web. This could be +avoided through tree-shaking, but the possibility of it not working properly +on one of [the supported bundlers](#browser-usage) is too high. + +* [Usage](#usage) + * [Dependencies](#dependencies) + * [hashes: sha256, sha512, keccak, ripemd160, blake2b](#hashes-sha256-sha512-keccak-ripemd160-blake2b) + * [kdfs: pbkdf2, scrypt](#kdfs-pbkdf2-scrypt) + * [random: secure randomness](#random-secure-randomness) + * [secp256k1: curve operations](#secp256k1-curve-operations) + * [bn: pairing-friendly curve](#bn-pairing-friendly-curve) + * [bls: pairing-friendly curve](#bls-pairing-friendly-curve) + * [aes: encryption](#aes-encryption) + * [hdkey: bip32 HD wallets](#hdkey-bip32-hd-wallets) + * [bip39: mnemonic phrases](#bip39-mnemonic-phrases) + * [math: utilities](#math-utilities) + * [utils: generic utilities](#utils-generic-utilities) + * [secp256k1-compat: compatibility layer with other libraries](#secp256k1-compat-compatibility-layer-with-other-libraries) + * [All imports](#all-imports) +* [Caveats](#caveats) + * [Browser usage: Rollup setup](#browser-usage-rollup-setup) + * [AES](#aes) + * [Encrypting with passwords](#encrypting-with-passwords) + * [Operation modes](#operation-modes) + * [Padding plaintext messages](#padding-plaintext-messages) + * [How to use the IV parameter](#how-to-use-the-iv-parameter) + * [How to handle errors with this module](#how-to-handle-errors-with-this-module) +* [Upgrading](#upgrading) + * [Changelog](#changelog) + * [From v2 to v3](#from-v2-to-v3) + * [From v1 to v2](#from-v1-to-v2) + * [From v0.1 to v1](#from-v01-to-v1) +* [Security](#security) +* [License](#license) + +### Dependencies + +All functionality of the module is simple +re-export of 6 audited [noble & scure libraries](https://paulmillr.com/noble/): + +- noble-curves, noble-ciphers, noble-hashes +- scure-base, scure-bip32, scure-bip39 + +ethereum-cryptography pins versions of the libraries to ensure good +protection against supply chain attacks. Ideally, your app would also +pin version of ethereum-cryptography. That means, no `^3.0.0` - use `3.0.0` instead. + +### hashes: sha256, sha512, keccak, ripemd160, blake2b ```js import { sha256 } from "ethereum-cryptography/sha256.js"; @@ -104,25 +69,34 @@ import { sha512 } from "ethereum-cryptography/sha512.js"; import { keccak256, keccak224, keccak384, keccak512 } from "ethereum-cryptography/keccak.js"; import { ripemd160 } from "ethereum-cryptography/ripemd160.js"; import { blake2b } from "ethereum-cryptography/blake2b.js"; +sha256(Uint8Array.from([1, 2, 3])) // A: buffers -sha256(Uint8Array.from([1, 2, 3])) - -// Can be used with strings import { utf8ToBytes } from "ethereum-cryptography/utils.js"; -sha256(utf8ToBytes("abc")) +sha256(utf8ToBytes("abc")) // B: strings -// If you need hex import { bytesToHex as toHex } from "ethereum-cryptography/utils.js"; -toHex(sha256(utf8ToBytes("abc"))) +toHex(sha256(utf8ToBytes("abc"))) // C: hex ``` -## KDFs: PBKDF2, Scrypt +### kdfs: pbkdf2, scrypt + +```js +import { pbkdf2, pbkdf2Sync } from "ethereum-cryptography/pbkdf2.js"; +import { scrypt, scryptSync } from "ethereum-cryptography/scrypt.js"; +import { utf8ToBytes } from "ethereum-cryptography/utils.js"; -```ts -function pbkdf2(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Promise; -function pbkdf2Sync(password: Uint8Array, salt: Uint8Array, iterations: number, keylen: number, digest: string): Uint8Array; -function scrypt(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void): Promise; -function scryptSync(password: Uint8Array, salt: Uint8Array, N: number, p: number, r: number, dkLen: number, onProgress?: (progress: number) => void)): Uint8Array; +// Pass Uint8Array, or convert strings to Uint8Array +const pass = utf8ToBytes("password") +const salt = utf8ToBytes("salt") +const iters = 131072; +const outLength = 32; +console.log(await pbkdf2(pass, salt, iters, outLength, "sha256")); + +const N = 262144; +const r = 8; +const p = 1; +const outLengths = 32; +console.log(await scrypt(pass, salt, N, r, p, outLengths)); ``` The `pbkdf2` submodule has two functions implementing the PBKDF2 key @@ -136,80 +110,112 @@ very slow, and using the synchronous version in the browser is not recommended, as it will block its main thread and hang your UI. Encoding passwords is a frequent source of errors. Please read -[these notes](https://github.com/ricmoo/scrypt-js/tree/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0#encoding-notes) +[notes](https://github.com/ricmoo/scrypt-js/tree/0eb70873ddf3d24e34b53e0d9a99a0cef06a79c0#encoding-notes) before using these submodules. -```js -import { pbkdf2 } from "ethereum-cryptography/pbkdf2.js"; -import { utf8ToBytes } from "ethereum-cryptography/utils.js"; -// Pass Uint8Array, or convert strings to Uint8Array -console.log(await pbkdf2(utf8ToBytes("password"), utf8ToBytes("salt"), 131072, 32, "sha256")); -``` +### random: secure randomness ```js -import { scrypt } from "ethereum-cryptography/scrypt.js"; -import { utf8ToBytes } from "ethereum-cryptography/utils.js"; -console.log(await scrypt(utf8ToBytes("password"), utf8ToBytes("salt"), 262144, 8, 1, 32)); -``` - -## CSPRNG (Cryptographically strong pseudorandom number generator) - -```ts -function getRandomBytes(bytes: number): Promise; -function getRandomBytesSync(bytes: number): Uint8Array; +import { getRandomBytesSync } from "ethereum-cryptography/random.js"; +console.log(getRandomBytesSync(32)); ``` The `random` submodule has functions to generate cryptographically strong -pseudo-random data in synchronous and asynchronous ways. +pseudo-random data in synchronous and asynchronous ways. Backed by [`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) in browser and by [`crypto.randomBytes`](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) in node.js. If backends are somehow not available, the module would throw an error and won't work, as keeping them working would be insecure. -Backed by [`crypto.getRandomValues`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) in browser and by [`crypto.randomBytes`](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) in node.js. If backends are somehow not available, the module would throw an error and won't work, as keeping them working would be insecure. +### secp256k1: curve operations ```js -import { getRandomBytesSync } from "ethereum-cryptography/random.js"; -console.log(getRandomBytesSync(32)); +import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; +// You pass either a hex string, or Uint8Array +const privateKey = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e"; +const messageHash = "a33321f98e4ff1c283c76998f14f57447545d339b3db534c6d886decb4209f28"; +const publicKey = secp256k1.getPublicKey(privateKey); +const signature = secp256k1.sign(messageHash, privateKey); +const isSigned = secp256k1.verify(signature, messageHash, publicKey); ``` -## secp256k1 curve +Elliptic curve operations on the curve secp256k1. Check out [noble-curves docs](https://github.com/paulmillr/noble-curves) for more info. + +secp256k1 private keys need to be cryptographically secure random numbers with +certain characteristics. If this is not the case, the security of secp256k1 is +compromised. + +### bn: pairing-friendly curve + +```js +import { bn } from "ethereum-cryptography/bls.js"; -```ts -function getPublicKey(privateKey: Uint8Array, isCompressed = true): Uint8Array; -function sign(msgHash: Uint8Array, privateKey: Uint8Array): { r: bigint; s: bigint; recovery: number }; -function verify(signature: Uint8Array, msgHash: Uint8Array, publicKey: Uint8Array): boolean -function getSharedSecret(privateKeyA: Uint8Array, publicKeyB: Uint8Array): Uint8Array; -function utils.randomPrivateKey(): Uint8Array; +console.log( + bn254.G1, + bn254.G2, + bn254.pairing +) ``` -The `secp256k1` submodule provides a library for elliptic curve operations on -the curve secp256k1. For detailed documentation, follow [README of `noble-curves`](https://github.com/paulmillr/noble-curves), which the module uses as a backend. +For example usage, check out [the implementation of bn254 EVM precompiles](https://github.com/paulmillr/noble-curves/blob/3ed792f8ad9932765b84d1064afea8663a255457/test/bn254.test.js#L697). -secp256k1 private keys need to be cryptographically secure random numbers with -certain characteristics. If this is not the case, the security of secp256k1 is -compromised. We strongly recommend using `utils.randomPrivateKey()` to generate them. +### bls: pairing-friendly curve ```js -import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; -(async () => { - // You pass either a hex string, or Uint8Array - const privateKey = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e"; - const messageHash = "a33321f98e4ff1c283c76998f14f57447545d339b3db534c6d886decb4209f28"; - const publicKey = secp256k1.getPublicKey(privateKey); - const signature = secp256k1.sign(messageHash, privateKey); - const isSigned = secp256k1.verify(signature, messageHash, publicKey); -})(); +import { bls12_381 as bls } from "ethereum-cryptography/bls.js"; + +// G1 keys, G2 signatures +const privateKey = '67d53f170b908cabb9eb326c3c337762d59289a8fec79f7bc9254b584b73265c'; +const message = '64726e3da8'; +const publicKey = bls.getPublicKey(privateKey); +const signature = bls.sign(message, privateKey); +const isValid = bls.verify(signature, message, publicKey); +console.log({ publicKey, signature, isValid }); + +// G2 signatures, G1 keys +// getPublicKeyForShortSignatures(privateKey) +// signShortSignature(message, privateKey) +// verifyShortSignature(signature, message, publicKey) +// aggregateShortSignatures(signatures) + +// Custom DST +const htfEthereum = { DST: 'BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_POP_' }; +const signatureEth = bls.sign(message, privateKey, htfEthereum); +const isValidEth = bls.verify(signature, message, publicKey, htfEthereum); + +// Aggregation +const aggregatedKey = bls.aggregatePublicKeys([bls.utils.randomPrivateKey(), bls.utils.randomPrivateKey()]) +// 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.ProjectivePoint.BASE, bls.G2.ProjectivePoint.BASE; +// bls.fields.Fp, bls.fields.Fp2, bls.fields.Fp12, bls.fields.Fr; ``` -We're also providing a compatibility layer for users who want to upgrade -from `tiny-secp256k1` or `secp256k1` modules without hassle. -Check out [secp256k1 compatibility layer](#legacy-secp256k1-compatibility-layer). +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). -## BIP32 HD Keygen +### aes: encryption -Hierarchical deterministic (HD) wallets that conform to BIP32 standard. -Also available as standalone package [scure-bip32](https://github.com/paulmillr/scure-bip32). +```js +import * as aes from "ethereum-cryptography/aes.js"; +import { hexToBytes, utf8ToBytes } from "ethereum-cryptography/utils.js"; -This module exports a single class `HDKey`, which should be used like this: +console.log( + aes.encrypt( + utf8ToBytes("message"), + hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"), + hexToBytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff") + ) +); +// const mode = "aes-128-ctr"; // "aes-128-cbc", "aes-256-ctr", "aes-256-cbc" +// function encrypt(msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Uint8Array; +// function decrypt(cipherText: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Uint8Array; +``` -```ts +### hdkey: bip32 HD wallets + +```js import { HDKey } from "ethereum-cryptography/hdkey.js"; const hdkey1 = HDKey.fromMasterSeed(seed); const hdkey2 = HDKey.fromExtendedKey(base58key); @@ -223,106 +229,134 @@ const sig = hdkey3.sign(hash); hdkey3.verify(hash, 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 `hdkey` submodule provides a library for keys derivation according to +Hierarchical deterministic (HD) wallets that conform to [BIP32](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki). -It has almost the exact same API than the version `1.x` of -[`hdkey` from cryptocoinjs](https://github.com/cryptocoinjs/hdkey), -but it's backed by this package's primitives, and has built-in TypeScript types. -Its only difference is that it has to be used with a named import. -The implementation is [loosely based on hdkey, which has MIT License](#LICENSE). - -## BIP39 Mnemonic Seed Phrase - -```ts -function generateMnemonic(wordlist: string[], strength: number = 128): string; -function mnemonicToEntropy(mnemonic: string, wordlist: string[]): Uint8Array; -function entropyToMnemonic(entropy: Uint8Array, wordlist: string[]): string; -function validateMnemonic(mnemonic: string, wordlist: string[]): boolean; -async function mnemonicToSeed(mnemonic: string, passphrase: string = ""): Promise; -function mnemonicToSeedSync(mnemonic: string, passphrase: string = ""): Uint8Array; +### bip39: mnemonic phrases + +```js +import * as bip39 from "ethereum-cryptography/bip39/index.js"; +import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; + +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/czech.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/french.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/italian.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/japanese.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/korean.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/portuguese.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/simplified-chinese.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/spanish.js"; +// import { wordlist } from "ethereum-cryptography/bip39/wordlists/traditional-chinese.js"; + +// Generate x random words. Uses Cryptographically-Secure Random Number Generator. +const mn = bip39.generateMnemonic(wordlist); +console.log(mn); + +// 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); + +// Irreversible: Uses KDF to derive 64 bytes of key data from mnemonic + optional password. +await bip39.mnemonicToSeed(mn, 'password'); +bip39.mnemonicToSeedSync(mn, 'password'); ``` The `bip39` submodule provides functions to generate, validate and use seed recovery phrases according to [BIP39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki). -Also available as standalone package [scure-bip39](https://github.com/paulmillr/scure-bip39). +Wordlists for different languages are not imported by default, +as that would increase bundle sizes too much. Instead, you should import and use them explicitly. + +### math: utilities + +```js +import { modPow, modInvert } from "ethereum-cryptography/math.js"; +modPow(123n, 456n, 789n); +modInvert(22n, 5n); +``` + +### utils: generic utilities + +```js +import { hexToBytes, toHex, utf8ToBytes } from "ethereum-cryptography/utils.js"; +``` + +### secp256k1-compat: compatibility layer with other libraries + +```js +import { createPrivateKeySync, ecdsaSign } from "ethereum-cryptography/secp256k1-compat"; +const msgHash = Uint8Array.from( + "82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28", + "hex" +); +const privateKey = createPrivateKeySync(); +console.log(Uint8Array.from(ecdsaSign(msgHash, privateKey).signature)); +``` + +**Warning:** use `secp256k1` instead. This module is only for users who upgraded +from ethereum-cryptography v0.1. It could be removed in the future. + +The API of `secp256k1-compat` is the same as [secp256k1-node](https://github.com/cryptocoinjs/secp256k1-node): + +### All imports ```js +import { sha256 } from "ethereum-cryptography/sha256.js"; +import { sha512 } from "ethereum-cryptography/sha512.js"; +import { keccak256, keccak224, keccak384, keccak512 } from "ethereum-cryptography/keccak.js"; +import { ripemd160 } from "ethereum-cryptography/ripemd160.js"; +import { blake2b } from "ethereum-cryptography/blake2b.js"; + +import { pbkdf2Sync } from "ethereum-cryptography/pbkdf2.js"; +import { scryptSync } from "ethereum-cryptography/scrypt.js"; + +import { getRandomBytesSync } from "ethereum-cryptography/random.js"; + +import { encrypt } from "ethereum-cryptography/aes.js"; +import { modPow, modInvert } from "ethereum-cryptography/math.js"; + +import { secp256k1 } from "ethereum-cryptography/secp256k1.js"; +import { bls12_381 } from "ethereum-cryptography/bls.js"; +import { bn254 } from "ethereum-cryptography/bn.js"; + +import { HDKey } from "ethereum-cryptography/hdkey.js"; import { generateMnemonic } from "ethereum-cryptography/bip39/index.js"; import { wordlist } from "ethereum-cryptography/bip39/wordlists/english.js"; -console.log(generateMnemonic(wordlist)); + +import { modPow, modInvert } from "ethereum-cryptography/math.js"; +import { hexToBytes, toHex, utf8ToBytes } from "ethereum-cryptography/utils.js"; ``` -This submodule also contains the word lists defined by BIP39 for Czech, English, -French, Italian, Japanese, Korean, 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. - -The word lists are exported as a `wordlist` variable in each of these submodules: - -* `ethereum-cryptography/bip39/wordlists/czech.js` -* `ethereum-cryptography/bip39/wordlists/english.js` -* `ethereum-cryptography/bip39/wordlists/french.js` -* `ethereum-cryptography/bip39/wordlists/italian.js` -* `ethereum-cryptography/bip39/wordlists/japanese.js` -* `ethereum-cryptography/bip39/wordlists/korean.js` -* `ethereum-cryptography/bip39/wordlists/portuguese.js` -* `ethereum-cryptography/bip39/wordlists/simplified-chinese.js` -* `ethereum-cryptography/bip39/wordlists/spanish.js` -* `ethereum-cryptography/bip39/wordlists/traditional-chinese.js` - -## AES Encryption - -```ts -function encrypt(msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise; -function decrypt(cypherText: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true): Promise; +## Caveats + +### Browser usage: Rollup setup + +Using this library with Rollup requires the following plugins: + +* [`@rollup/plugin-commonjs`](https://www.npmjs.com/package/@rollup/plugin-commonjs) +* [`@rollup/plugin-node-resolve`](https://www.npmjs.com/package/@rollup/plugin-node-resolve) + +These can be used by setting your `plugins` array like this: + +```js + plugins: [ + commonjs(), + resolve({ + browser: true, + preferBuiltins: false, + }), + ] ``` -The `aes` submodule contains encryption and decryption functions implementing -the [Advanced Encryption Standard](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard) -algorithm. +### AES -### Encrypting with passwords +#### Encrypting with passwords AES is not supposed to be used directly with a password. Doing that will compromise your users' security. @@ -332,7 +366,7 @@ keys. If you want to obtain such a key from a password, please use a [key derivation function](https://en.wikipedia.org/wiki/Key_derivation_function) like [pbkdf2](#kdfs-pbkdf2-scrypt) or [scrypt](#kdfs-pbkdf2-scrypt). -### Operation modes +#### Operation modes This submodule works with different [block cipher modes of operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation). If you are using this module in a new application, we recommend using the default. @@ -344,7 +378,7 @@ a warning will be printed in the console. We only recommend using `aes-128-cbc` and `aes-256-cbc` to decrypt already encrypted data. -### Padding plaintext messages +#### Padding plaintext messages Some operation modes require the plaintext message to be a multiple of `16`. If that isn't the case, your message has to be padded. @@ -363,7 +397,7 @@ multiple of `16`. This option is only present to enable the decryption of already encrypted data. To encrypt new data, we recommend using the default. -### How to use the IV parameter +#### How to use the IV parameter The `iv` parameter of the `encrypt` function must be unique, or the security of the encryption algorithm can be compromised. @@ -373,7 +407,7 @@ You can generate a new `iv` using the `random` module. Note that to decrypt a value, you have to provide the same `iv` used to encrypt it. -### How to handle errors with this module +#### How to handle errors with this module Sensitive information can be leaked via error messages when using this module. To avoid this, you should make sure that the errors you return don't @@ -384,75 +418,28 @@ Note that implementing this can mean catching all errors that can be thrown when calling on of this module's functions, and just throwing a new generic exception. -### Example usage - -```js -import { encrypt } from "ethereum-cryptography/aes.js"; -import { hexToBytes, utf8ToBytes } from "ethereum-cryptography/utils.js"; - -console.log( - encrypt( - utf8ToBytes("message"), - hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"), - hexToBytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff") - ) -); -``` - -## Browser usage - -### Rollup setup - -Using this library with Rollup requires the following plugins: - -* [`@rollup/plugin-commonjs`](https://www.npmjs.com/package/@rollup/plugin-commonjs) -* [`@rollup/plugin-node-resolve`](https://www.npmjs.com/package/@rollup/plugin-node-resolve) - -These can be used by setting your `plugins` array like this: - -```js - plugins: [ - commonjs(), - resolve({ - browser: true, - preferBuiltins: false, - }), - ] -``` - -## Legacy secp256k1 compatibility layer - -**Warning:** use `secp256k1` instead. This module is only for users who upgraded -from ethereum-cryptography v0.1. It could be removed in the future. - -The API of `secp256k1-compat` is the same as [secp256k1-node](https://github.com/cryptocoinjs/secp256k1-node): - -```js -import { createPrivateKeySync, ecdsaSign } from "ethereum-cryptography/secp256k1-compat"; -const msgHash = Uint8Array.from( - "82ff40c0a986c6a5cfad4ddf4c3aa6996f1a7837f9c398e17e5de5cbd5a12b28", - "hex" -); -const privateKey = createPrivateKeySync(); -console.log(Uint8Array.from(ecdsaSign(msgHash, privateKey).signature)); -``` - -## Missing cryptographic primitives +## Upgrading -This package intentionally excludes the cryptographic primitives necessary -to implement the following EIPs: +### Changelog -* [EIP 196: Precompiled contracts for addition and scalar multiplication on the elliptic curve alt_bn128](https://eips.ethereum.org/EIPS/eip-196) -* [EIP 197: Precompiled contracts for optimal ate pairing check on the elliptic curve alt_bn128](https://eips.ethereum.org/EIPS/eip-197) -* [EIP 198: Big integer modular exponentiation](https://eips.ethereum.org/EIPS/eip-198) -* [EIP 152: Add Blake2 compression function `F` precompile](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-152.md) +* v3.0 (Sep 2024): new modules `bls`, `bn`, `math` +change async AES to non-native sync, +improve typescript compatibility, new dependency [noble-ciphers](https://github.com/paulmillr/noble-ciphers) +* v2.0 (Apr 2023): switched +[noble-secp256k1](https://github.com/paulmillr/noble-secp256k1) to +[noble-curves](https://github.com/paulmillr/noble-curves), +which changes re-exported api of `secp256k1` submodule. +* v1.0 (Jan 2022): rewritten the library from +scratch and [audited](#security) it. It became **6x smaller:** ~5,000 lines of +code instead of ~24,000 (with all deps); 650KB instead of 10.2MB. +5 dependencies by 1 author are now used, instead of 38 by 5 authors. -Feel free to open an issue if you want this decision to be reconsidered, or if -you found another primitive that is missing. +### From v2 to v3 -## Upgrading +1. utils: `crypto` var had been removed +2. aes: async methods became sync -Upgrading from 1.0 to 2.0: +### From v1 to v2 1. `secp256k1` module was changed massively: before, it was using [noble-secp256k1 1.7](https://github.com/paulmillr/noble-secp256k1); @@ -462,7 +449,9 @@ Upgrading from 1.0 to 2.0: b) `recoverPublicKey` got moved onto a `Signature` instance 2. node.js 14 and older support was dropped. Upgrade to node.js 16 or later. -Upgrading from 0.1 to 1.0: **Same functionality**, all old APIs remain the same except for the breaking changes: +### From v0.1 to v1 + +All old APIs remain the same except for the breaking changes: 1. We return `Uint8Array` from all methods that worked with `Buffer` before. `Buffer` has never been supported in browsers, while `Uint8Array`s are supported natively in both @@ -490,6 +479,8 @@ const hashbo = hashb.toString("hex"); Audited by Cure53 on Jan 5, 2022. Check out the audit [PDF](./audit/2022-01-05-cure53-audit-nbl2.pdf) & [URL](https://cure53.de/pentest-report_hashing-libs.pdf). +Dependencies are having separate regular audits: check out their documentation for more info. + ## License `ethereum-cryptography` is released under The MIT License (MIT) @@ -503,7 +494,5 @@ which had [MIT License](https://github.com/cryptocoinjs/hdkey/blob/3f3c0b5cedb98 Copyright (c) 2018 cryptocoinjs -[1]: https://img.shields.io/npm/v/ethereum-cryptography.svg -[2]: https://www.npmjs.com/package/ethereum-cryptography -[3]: https://img.shields.io/npm/l/ethereum-cryptography -[4]: https://github.com/ethereum/js-ethereum-cryptography/blob/master/packages/ethereum-cryptography/LICENSE +[1]: https://www.npmjs.com/package/ethereum-cryptography +[2]: https://github.com/ethereum/js-ethereum-cryptography/blob/master/packages/ethereum-cryptography/LICENSE diff --git a/package-lock.json b/package-lock.json index 0e02bc4..951e8ed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,11 @@ "version": "2.2.1", "license": "MIT", "dependencies": { - "@noble/curves": "1.5.0", - "@noble/hashes": "1.4.0", - "@scure/bip32": "1.4.0", - "@scure/bip39": "1.3.0" + "@noble/ciphers": "1.0.0", + "@noble/curves": "1.6.0", + "@noble/hashes": "1.5.0", + "@scure/bip32": "1.5.0", + "@scure/bip39": "1.4.0" }, "devDependencies": { "@types/estree": "1.0.0", @@ -31,6 +32,10 @@ "prettier": "2.7.1", "ts-node": "10.9.1", "typescript": "5.5.4" + }, + "engines": { + "node": "^14.21.3 || >=16", + "npm": ">=9" } }, "node_modules/@colors/colors": { @@ -170,23 +175,40 @@ "@jridgewell/sourcemap-codec": "^1.4.10" } }, + "node_modules/@noble/ciphers": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-1.0.0.tgz", + "integrity": "sha512-wH5EHOmLi0rEazphPbecAzmjd12I6/Yv/SiHdkA9LSycsQk7RuuTp7am5/o62qYr0RScE7Pc9icXGBbsr6cesA==", + "license": "MIT", + "engines": { + "node": "^14.21.3 || >=16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@noble/curves": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.5.0.tgz", - "integrity": "sha512-J5EKamIHnKPyClwVrzmaf5wSdQXgdHcPZIZLu3bwnbeCx8/7NPK5q2ZBWF+5FvYGByjiQQsJYX6jfgB2wDPn3A==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.6.0.tgz", + "integrity": "sha512-TlaHRXDehJuRNR9TfZDNQ45mMEd5dwUwmicsafcIX4SsNiqnCHKjE/1alYPd/lDRVhxdhUAlv8uEhMCI5zjIJQ==", + "license": "MIT", "dependencies": { - "@noble/hashes": "1.4.0" + "@noble/hashes": "1.5.0" + }, + "engines": { + "node": "^14.21.3 || >=16" }, "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@noble/hashes": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz", - "integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.5.0.tgz", + "integrity": "sha512-1j6kQFb7QRru7eKN3ZDvRcP13rugwdxZqCjbiAVZfIJwgj2A65UmT4TgARXGlXgnRkORLTDTrO19ZErt7+QXgA==", + "license": "MIT", "engines": { - "node": ">= 16" + "node": "^14.21.3 || >=16" }, "funding": { "url": "https://paulmillr.com/funding/" @@ -228,44 +250,36 @@ } }, "node_modules/@scure/base": { - "version": "1.1.7", - "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.7.tgz", - "integrity": "sha512-PPNYBslrLNNUQ/Yad37MHYsNQtK67EhWb6WtSvNLLPo7SdVZgkUjD6Dg+5On7zNwmskf8OX7I7Nx5oN+MIWE0g==", + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/@scure/base/-/base-1.1.8.tgz", + "integrity": "sha512-6CyAclxj3Nb0XT7GHK6K4zK6k2xJm6E4Ft0Ohjt4WgegiFUHEtFb2CGzmPmGBwoIhrLsqNLYfLr04Y1GePrzZg==", + "license": "MIT", "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@scure/bip32": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.4.0.tgz", - "integrity": "sha512-sVUpc0Vq3tXCkDGYVWGIZTRfnvu8LoTDaev7vbwh0omSvVORONr960MQWdKqJDCReIEmTj3PAr73O3aoxz7OPg==", - "dependencies": { - "@noble/curves": "~1.4.0", - "@noble/hashes": "~1.4.0", - "@scure/base": "~1.1.6" - }, - "funding": { - "url": "https://paulmillr.com/funding/" - } - }, - "node_modules/@scure/bip32/node_modules/@noble/curves": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.4.2.tgz", - "integrity": "sha512-TavHr8qycMChk8UwMld0ZDRvatedkzWfH8IiaeGCfymOP5i0hSCozz9vHOL0nkwk7HRMlFnAiKpS2jrUmSybcw==", + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@scure/bip32/-/bip32-1.5.0.tgz", + "integrity": "sha512-8EnFYkqEQdnkuGBVpCzKxyIwDCBLDVj3oiX0EKUFre/tOjL/Hqba1D6n/8RcmaQy4f95qQFrO2A8Sr6ybh4NRw==", + "license": "MIT", "dependencies": { - "@noble/hashes": "1.4.0" + "@noble/curves": "~1.6.0", + "@noble/hashes": "~1.5.0", + "@scure/base": "~1.1.7" }, "funding": { "url": "https://paulmillr.com/funding/" } }, "node_modules/@scure/bip39": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.3.0.tgz", - "integrity": "sha512-disdg7gHuTDZtY+ZdkmLpPCk7fxZSu3gBiEGuoC1XYxv9cGx3Z6cpTggCgW6odSOOIXCiDjuGejW+aJKCY/pIQ==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.4.0.tgz", + "integrity": "sha512-BEEm6p8IueV/ZTfQLp/0vhw4NPnT9oWf5+28nvmeUICjP99f4vr2d+qc7AVGDDtwRep6ifR43Yed9ERVmiITzw==", + "license": "MIT", "dependencies": { - "@noble/hashes": "~1.4.0", - "@scure/base": "~1.1.6" + "@noble/hashes": "~1.5.0", + "@scure/base": "~1.1.8" }, "funding": { "url": "https://paulmillr.com/funding/" @@ -734,9 +748,9 @@ } }, "node_modules/body-parser": { - "version": "1.20.2", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.2.tgz", - "integrity": "sha512-ml9pReCu3M61kGlqoTm2umSXTlRTuGTx0bfYj+uIUKKYycG5NtSbeetV3faSU6R7ajOPw0g/J1PvK4qNy7s5bA==", + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", + "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", "dev": true, "dependencies": { "bytes": "3.1.2", @@ -747,7 +761,7 @@ "http-errors": "2.0.0", "iconv-lite": "0.4.24", "on-finished": "2.4.1", - "qs": "6.11.0", + "qs": "6.13.0", "raw-body": "2.5.2", "type-is": "~1.6.18", "unpipe": "1.0.0" @@ -3819,12 +3833,12 @@ } }, "node_modules/qs": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", - "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", "dev": true, "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" diff --git a/package.json b/package.json index e712c15..16dc8c2 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,10 @@ "repository": "https://github.com/ethereum/js-ethereum-cryptography", "license": "MIT", "main": "./index.js", + "engines": { + "node": "^14.21.3 || >=16", + "npm": ">=9" + }, "files": [ "bip39/*.js", "bip39/*.d.ts", @@ -15,271 +19,244 @@ "esm" ], "dependencies": { - "@noble/curves": "1.5.0", - "@noble/hashes": "1.4.0", - "@scure/bip32": "1.4.0", - "@scure/bip39": "1.3.0" + "@noble/ciphers": "1.0.0", + "@noble/curves": "1.6.0", + "@noble/hashes": "1.5.0", + "@scure/bip32": "1.5.0", + "@scure/bip39": "1.4.0" }, "exports": { ".": { - "types": "./index.d.ts", "import": "./esm/index.js", - "default": "./index.js" + "require": "./index.js" }, "./aes": { - "types": "./aes.d.ts", "import": "./esm/aes.js", - "default": "./aes.js" + "require": "./aes.js" }, "./bip39": { - "types": "./bip39/index.d.ts", "import": "./esm/bip39/index.js", - "default": "./bip39/index.js" + "require": "./bip39/index.js" }, "./blake2b": { - "types": "./blake2b.d.ts", "import": "./esm/blake2b.js", - "default": "./blake2b.js" + "require": "./blake2b.js" + }, + "./bls": { + "import": "./esm/bls.js", + "require": "./bls.js" + }, + "./bn": { + "import": "./esm/bn.js", + "require": "./bn.js" }, "./hdkey": { - "types": "./hdkey.d.ts", "import": "./esm/hdkey.js", - "default": "./hdkey.js" + "require": "./hdkey.js" }, "./index": { - "types": "./index.d.ts", "import": "./esm/index.js", - "default": "./index.js" + "require": "./index.js" + }, + "./math": { + "import": "./esm/math.js", + "require": "./math.js" }, "./keccak": { - "types": "./keccak.d.ts", "import": "./esm/keccak.js", - "default": "./keccak.js" + "require": "./keccak.js" }, "./pbkdf2": { - "types": "./pbkdf2.d.ts", "import": "./esm/pbkdf2.js", - "default": "./pbkdf2.js" + "require": "./pbkdf2.js" }, "./random": { - "types": "./random.d.ts", "import": "./esm/random.js", - "default": "./random.js" + "require": "./random.js" }, "./ripemd160": { - "types": "./ripemd160.d.ts", "import": "./esm/ripemd160.js", - "default": "./ripemd160.js" + "require": "./ripemd160.js" }, "./scrypt": { - "types": "./scrypt.d.ts", "import": "./esm/scrypt.js", - "default": "./scrypt.js" + "require": "./scrypt.js" }, "./secp256k1-compat": { - "types": "./secp256k1-compat.d.ts", "import": "./esm/secp256k1-compat.js", - "default": "./secp256k1-compat.js" + "require": "./secp256k1-compat.js" }, "./secp256k1": { - "types": "./secp256k1.d.ts", "import": "./esm/secp256k1.js", - "default": "./secp256k1.js" + "require": "./secp256k1.js" }, "./sha256": { - "types": "./sha256.d.ts", "import": "./esm/sha256.js", - "default": "./sha256.js" + "require": "./sha256.js" }, "./sha512": { - "types": "./sha512.d.ts", "import": "./esm/sha512.js", - "default": "./sha512.js" + "require": "./sha512.js" }, "./utils": { - "types": "./utils.d.ts", "import": "./esm/utils.js", - "default": "./utils.js" + "require": "./utils.js" }, "./bip39/index": { - "types": "./bip39/index.d.ts", "import": "./esm/bip39/index.js", - "default": "./bip39/index.js" + "require": "./bip39/index.js" }, "./bip39/wordlists/czech": { - "types": "./bip39/wordlists/czech.d.ts", "import": "./esm/bip39/wordlists/czech.js", - "default": "./bip39/wordlists/czech.js" + "require": "./bip39/wordlists/czech.js" }, "./bip39/wordlists/english": { - "types": "./bip39/wordlists/english.d.ts", "import": "./esm/bip39/wordlists/english.js", - "default": "./bip39/wordlists/english.js" + "require": "./bip39/wordlists/english.js" }, "./bip39/wordlists/french": { - "types": "./bip39/wordlists/french.d.ts", "import": "./esm/bip39/wordlists/french.js", - "default": "./bip39/wordlists/french.js" + "require": "./bip39/wordlists/french.js" }, "./bip39/wordlists/italian": { - "types": "./bip39/wordlists/italian.d.ts", "import": "./esm/bip39/wordlists/italian.js", - "default": "./bip39/wordlists/italian.js" + "require": "./bip39/wordlists/italian.js" }, "./bip39/wordlists/japanese": { - "types": "./bip39/wordlists/japanese.d.ts", "import": "./esm/bip39/wordlists/japanese.js", - "default": "./bip39/wordlists/japanese.js" + "require": "./bip39/wordlists/japanese.js" }, "./bip39/wordlists/korean": { - "types": "./bip39/wordlists/korean.d.ts", "import": "./esm/bip39/wordlists/korean.js", - "default": "./bip39/wordlists/korean.js" + "require": "./bip39/wordlists/korean.js" }, "./bip39/wordlists/portuguese": { - "types": "./bip39/wordlists/portuguese.d.ts", "import": "./esm/bip39/wordlists/portuguese.js", - "default": "./bip39/wordlists/portuguese.js" + "require": "./bip39/wordlists/portuguese.js" }, "./bip39/wordlists/simplified-chinese": { - "types": "./bip39/wordlists/simplified-chinese.d.ts", "import": "./esm/bip39/wordlists/simplified-chinese.js", - "default": "./bip39/wordlists/simplified-chinese.js" + "require": "./bip39/wordlists/simplified-chinese.js" }, "./bip39/wordlists/spanish": { - "types": "./bip39/wordlists/spanish.d.ts", "import": "./esm/bip39/wordlists/spanish.js", - "default": "./bip39/wordlists/spanish.js" + "require": "./bip39/wordlists/spanish.js" }, "./bip39/wordlists/traditional-chinese": { - "types": "./bip39/wordlists/traditional-chinese.d.ts", "import": "./esm/bip39/wordlists/traditional-chinese.js", - "default": "./bip39/wordlists/traditional-chinese.js" + "require": "./bip39/wordlists/traditional-chinese.js" }, "./aes.js": { - "types": "./aes.d.ts", "import": "./esm/aes.js", - "default": "./aes.js" + "require": "./aes.js" }, "./bip39.js": { - "types": "./bip39/index.d.ts", "import": "./esm/bip39/index.js", - "default": "./bip39/index.js" + "require": "./bip39/index.js" }, "./blake2b.js": { - "types": "./blake2b.d.ts", "import": "./esm/blake2b.js", - "default": "./blake2b.js" + "require": "./blake2b.js" + }, + "./bls.js": { + "import": "./esm/bls.js", + "require": "./bls.js" + }, + "./bn.js": { + "import": "./esm/bn.js", + "require": "./bn.js" }, "./hdkey.js": { - "types": "./hdkey.d.ts", "import": "./esm/hdkey.js", - "default": "./hdkey.js" + "require": "./hdkey.js" }, "./index.js": { - "types": "./index.d.ts", "import": "./esm/index.js", - "default": "./index.js" + "require": "./index.js" + }, + "./math.js": { + "import": "./esm/math.js", + "require": "./math.js" }, "./keccak.js": { - "types": "./keccak.d.ts", "import": "./esm/keccak.js", - "default": "./keccak.js" + "require": "./keccak.js" }, "./pbkdf2.js": { - "types": "./pbkdf2.d.ts", "import": "./esm/pbkdf2.js", - "default": "./pbkdf2.js" + "require": "./pbkdf2.js" }, "./random.js": { - "types": "./random.d.ts", "import": "./esm/random.js", - "default": "./random.js" + "require": "./random.js" }, "./ripemd160.js": { - "types": "./ripemd160.d.ts", "import": "./esm/ripemd160.js", - "default": "./ripemd160.js" + "require": "./ripemd160.js" }, "./scrypt.js": { - "types": "./scrypt.d.ts", "import": "./esm/scrypt.js", - "default": "./scrypt.js" + "require": "./scrypt.js" }, "./secp256k1-compat.js": { - "types": "./secp256k1-compat.d.ts", "import": "./esm/secp256k1-compat.js", - "default": "./secp256k1-compat.js" + "require": "./secp256k1-compat.js" }, "./secp256k1.js": { - "types": "./secp256k1.d.ts", "import": "./esm/secp256k1.js", - "default": "./secp256k1.js" + "require": "./secp256k1.js" }, "./sha256.js": { - "types": "./sha256.d.ts", "import": "./esm/sha256.js", - "default": "./sha256.js" + "require": "./sha256.js" }, "./sha512.js": { - "types": "./sha512.d.ts", "import": "./esm/sha512.js", - "default": "./sha512.js" + "require": "./sha512.js" }, "./utils.js": { - "types": "./utils.d.ts", "import": "./esm/utils.js", - "default": "./utils.js" + "require": "./utils.js" }, "./bip39/index.js": { - "types": "./bip39/index.d.ts", "import": "./esm/bip39/index.js", - "default": "./bip39/index.js" + "require": "./bip39/index.js" }, "./bip39/wordlists/czech.js": { - "types": "./bip39/wordlists/czech.d.ts", "import": "./esm/bip39/wordlists/czech.js", - "default": "./bip39/wordlists/czech.js" + "require": "./bip39/wordlists/czech.js" }, "./bip39/wordlists/english.js": { - "types": "./bip39/wordlists/english.d.ts", "import": "./esm/bip39/wordlists/english.js", - "default": "./bip39/wordlists/english.js" + "require": "./bip39/wordlists/english.js" }, "./bip39/wordlists/french.js": { - "types": "./bip39/wordlists/french.d.ts", "import": "./esm/bip39/wordlists/french.js", - "default": "./bip39/wordlists/french.js" + "require": "./bip39/wordlists/french.js" }, "./bip39/wordlists/italian.js": { - "types": "./bip39/wordlists/italian.d.ts", "import": "./esm/bip39/wordlists/italian.js", - "default": "./bip39/wordlists/italian.js" + "require": "./bip39/wordlists/italian.js" }, "./bip39/wordlists/japanese.js": { - "types": "./bip39/wordlists/japanese.d.ts", "import": "./esm/bip39/wordlists/japanese.js", - "default": "./bip39/wordlists/japanese.js" + "require": "./bip39/wordlists/japanese.js" }, "./bip39/wordlists/korean.js": { - "types": "./bip39/wordlists/korean.d.ts", "import": "./esm/bip39/wordlists/korean.js", - "default": "./bip39/wordlists/korean.js" + "require": "./bip39/wordlists/korean.js" }, "./bip39/wordlists/simplified-chinese.js": { - "types": "./bip39/wordlists/simplified-chinese.d.ts", "import": "./esm/bip39/wordlists/simplified-chinese.js", - "default": "./bip39/wordlists/simplified-chinese.js" + "require": "./bip39/wordlists/simplified-chinese.js" }, "./bip39/wordlists/spanish.js": { - "types": "./bip39/wordlists/spanish.d.ts", "import": "./esm/bip39/wordlists/spanish.js", - "default": "./bip39/wordlists/spanish.js" + "require": "./bip39/wordlists/spanish.js" }, "./bip39/wordlists/traditional-chinese.js": { - "types": "./bip39/wordlists/traditional-chinese.d.ts", "import": "./esm/bip39/wordlists/traditional-chinese.js", - "default": "./bip39/wordlists/traditional-chinese.js" + "require": "./bip39/wordlists/traditional-chinese.js" } }, "browser": { diff --git a/src/aes.ts b/src/aes.ts index dbd8e8d..294f4f3 100644 --- a/src/aes.ts +++ b/src/aes.ts @@ -1,124 +1,47 @@ -import { crypto as cr } from "@noble/hashes/crypto"; -import { concatBytes, equalsBytes } from "./utils.js"; +import { ctr, cbc } from "@noble/ciphers/aes"; +import type { CipherWithOutput } from "@noble/ciphers/utils"; -const crypto: any = { web: cr }; - -function validateOpt(key: Uint8Array, iv: Uint8Array, mode: string) { +function getCipher( + key: Uint8Array, + iv: Uint8Array, + mode: string, + pkcs7PaddingEnabled = true +): CipherWithOutput { if (!mode.startsWith("aes-")) { - throw new Error(`AES submodule doesn't support mode ${mode}`); - } - if (iv.length !== 16) { - throw new Error("AES: wrong IV length"); + throw new Error("AES: unsupported mode"); } - if ( - (mode.startsWith("aes-128") && key.length !== 16) || - (mode.startsWith("aes-256") && key.length !== 32) - ) { + const len = key.length; + if ((mode.startsWith("aes-128") && len !== 16) || (mode.startsWith("aes-256") && len !== 32)) { throw new Error("AES: wrong key length"); } -} - -async function getBrowserKey( - mode: string, - key: Uint8Array, - iv: Uint8Array -): Promise<[CryptoKey, AesCbcParams | AesCtrParams]> { - if (!crypto.web) { - throw new Error("Browser crypto not available."); + if (iv.length !== 16) { + throw new Error("AES: wrong IV length"); } - let keyMode: string | undefined; if (["aes-128-cbc", "aes-256-cbc"].includes(mode)) { - keyMode = "cbc"; + return cbc(key, iv, { disablePadding: !pkcs7PaddingEnabled }); } if (["aes-128-ctr", "aes-256-ctr"].includes(mode)) { - keyMode = "ctr"; + return ctr(key, iv); } - if (!keyMode) { - throw new Error("AES: unsupported mode"); - } - const wKey = await crypto.web.subtle.importKey( - "raw", - key, - { name: `AES-${keyMode.toUpperCase()}`, length: key.length * 8 }, - true, - ["encrypt", "decrypt"] - ); - // node.js uses whole 128 bit as a counter, without nonce, instead of 64 bit - // recommended by NIST SP800-38A - return [wKey, { name: `aes-${keyMode}`, iv, counter: iv, length: 128 }]; + throw new Error("AES: unsupported mode"); } -export async function encrypt( +export function encrypt( msg: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true -): Promise { - validateOpt(key, iv, mode); - if (crypto.web) { - const [wKey, wOpt] = await getBrowserKey(mode, key, iv); - const cipher = await crypto.web.subtle.encrypt(wOpt, wKey, msg); - // Remove PKCS7 padding on cbc mode by stripping end of message - let res = new Uint8Array(cipher); - if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc" && !(msg.length % 16)) { - res = res.slice(0, -16); - } - return res; - } else if (crypto.node) { - const cipher = crypto.node.createCipheriv(mode, key, iv); - cipher.setAutoPadding(pkcs7PaddingEnabled); - return concatBytes(cipher.update(msg), cipher.final()); - } else { - throw new Error("The environment doesn't have AES module"); - } +): Uint8Array { + return getCipher(key, iv, mode, pkcs7PaddingEnabled).encrypt(msg); } -async function getPadding( - cypherText: Uint8Array, - key: Uint8Array, - iv: Uint8Array, - mode: string -) { - const lastBlock = cypherText.slice(-16); - for (let i = 0; i < 16; i++) { - // Undo xor of iv and fill with lastBlock ^ padding (16) - lastBlock[i] ^= iv[i] ^ 16; - } - const res = await encrypt(lastBlock, key, iv, mode); - return res.slice(0, 16); -} - -export async function decrypt( - cypherText: Uint8Array, +export function decrypt( + ciphertext: Uint8Array, key: Uint8Array, iv: Uint8Array, mode = "aes-128-ctr", pkcs7PaddingEnabled = true -): Promise { - validateOpt(key, iv, mode); - if (crypto.web) { - const [wKey, wOpt] = await getBrowserKey(mode, key, iv); - // Add empty padding so Chrome will correctly decrypt message - if (!pkcs7PaddingEnabled && wOpt.name === "aes-cbc") { - const padding = await getPadding(cypherText, key, iv, mode); - cypherText = concatBytes(cypherText, padding); - } - const msg = await crypto.web.subtle.decrypt(wOpt, wKey, cypherText); - const msgBytes = new Uint8Array(msg); - // Safari always ignores padding (if no padding -> broken message) - if (wOpt.name === "aes-cbc") { - const encrypted = await encrypt(msgBytes, key, iv, mode); - if (!equalsBytes(encrypted, cypherText)) { - throw new Error("AES: wrong padding"); - } - } - return msgBytes; - } else if (crypto.node) { - const decipher = crypto.node.createDecipheriv(mode, key, iv); - decipher.setAutoPadding(pkcs7PaddingEnabled); - return concatBytes(decipher.update(cypherText), decipher.final()); - } else { - throw new Error("The environment doesn't have AES module"); - } +): Uint8Array { + return getCipher(key, iv, mode, pkcs7PaddingEnabled).decrypt(ciphertext); } diff --git a/src/bls.ts b/src/bls.ts new file mode 100644 index 0000000..21dfc9b --- /dev/null +++ b/src/bls.ts @@ -0,0 +1 @@ +export { bls12_381 } from '@noble/curves/bls12-381'; \ No newline at end of file diff --git a/src/bn.ts b/src/bn.ts new file mode 100644 index 0000000..383bd22 --- /dev/null +++ b/src/bn.ts @@ -0,0 +1 @@ +export { bn254 } from '@noble/curves/bn254'; \ No newline at end of file diff --git a/src/math.ts b/src/math.ts new file mode 100644 index 0000000..f862360 --- /dev/null +++ b/src/math.ts @@ -0,0 +1,4 @@ +import { pow, invert } from "@noble/curves/abstract/modular"; + +export const modPow = pow; +export const modInvert = invert; diff --git a/src/utils.ts b/src/utils.ts index c792592..70e967f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -51,19 +51,3 @@ export function wrapHash(hash: (msg: Uint8Array) => Uint8Array) { return hash(msg); }; } - -declare const globalThis: Record | undefined; - -// TODO(v3): switch away from node crypto, remove this unnecessary variable. -export const crypto: { node?: any; web?: any } = (() => { - const webCrypto = - typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : undefined; - const nodeRequire = - typeof module !== "undefined" && - typeof module.require === "function" && - module.require.bind(module); - return { - node: nodeRequire && !webCrypto ? nodeRequire("crypto") : undefined, - web: webCrypto - }; -})(); diff --git a/test/package-lock.json b/test/package-lock.json index 88db40d..e13afe5 100644 --- a/test/package-lock.json +++ b/test/package-lock.json @@ -27,10 +27,11 @@ "version": "2.2.1", "license": "MIT", "dependencies": { - "@noble/curves": "1.5.0", - "@noble/hashes": "1.4.0", - "@scure/bip32": "1.4.0", - "@scure/bip39": "1.3.0" + "@noble/ciphers": "0.6.0", + "@noble/curves": "1.6.0", + "@noble/hashes": "1.5.0", + "@scure/bip32": "1.5.0", + "@scure/bip39": "1.4.0" }, "devDependencies": { "@types/estree": "1.0.0", @@ -49,6 +50,9 @@ "prettier": "2.7.1", "ts-node": "10.9.1", "typescript": "5.5.4" + }, + "engines": { + "node": "^14.21.3 || >=16" } }, "node_modules/@babel/code-frame": { diff --git a/test/test-vectors/aes.ts b/test/test-vectors/aes.ts index 103c8cd..555d8a4 100644 --- a/test/test-vectors/aes.ts +++ b/test/test-vectors/aes.ts @@ -1,6 +1,6 @@ import { decrypt, encrypt } from "ethereum-cryptography/aes"; import { hexToBytes, toHex } from "ethereum-cryptography/utils"; -import { deepStrictEqual, rejects } from "./assert"; +import { deepStrictEqual, throws } from "./assert"; // Test vectors taken from https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38a.pdf const TEST_VECTORS = [ { @@ -94,8 +94,8 @@ const TEST_VECTORS = [ describe("aes", () => { for (const [i, vector] of TEST_VECTORS.entries()) { - it(`Should encrypt the test ${i} correctly`, async () => { - const encrypted = await encrypt( + it(`Should encrypt the test ${i} correctly`, () => { + const encrypted = encrypt( hexToBytes(vector.msg), hexToBytes(vector.key), hexToBytes(vector.iv), @@ -106,8 +106,8 @@ describe("aes", () => { deepStrictEqual(toHex(encrypted), vector.cypherText); }); - it(`Should decrypt the test ${i} correctly`, async () => { - const decrypted = await decrypt( + it(`Should decrypt the test ${i} correctly`, () => { + const decrypted = decrypt( hexToBytes(vector.cypherText), hexToBytes(vector.key), hexToBytes(vector.iv), @@ -119,8 +119,8 @@ describe("aes", () => { }); } - it("Should throw when not padding automatically and the message isn't the right size", async () => { - rejects(() => + it("Should throw when not padding automatically and the message isn't the right size", () => { + throws(() => encrypt( hexToBytes("abcd"), hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"), @@ -131,8 +131,8 @@ describe("aes", () => { ); }); - it("Should throw when trying to use non-aes modes", async () => { - rejects(() => + it("Should throw when trying to use non-aes modes", () => { + throws(() => encrypt( hexToBytes("abcd"), hexToBytes("2b7e151628aed2a6abf7158809cf4f3c"), @@ -143,7 +143,7 @@ describe("aes", () => { ); }); - it("aes-ctr bug (browser/node result mismatch)", async () => { + it("aes-ctr bug (browser/node result mismatch)", () => { // NOTE: full 0xff iv causes difference on counter overflow in CTR mode const iv = "ffffffffffffffffffffffffffffffff"; const vectors = [ @@ -184,9 +184,9 @@ describe("aes", () => { const msg = hexToBytes(v.msg); const key = hexToBytes(v.key); const iv = hexToBytes(v.iv); - const res = await encrypt(msg, key, iv, v.mode); + const res = encrypt(msg, key, iv, v.mode); deepStrictEqual(toHex(res), v.result); - const clearText = await decrypt(res, key, iv, v.mode); + const clearText = decrypt(res, key, iv, v.mode); deepStrictEqual(clearText, msg); } }); diff --git a/test/test-vectors/bls.ts b/test/test-vectors/bls.ts new file mode 100644 index 0000000..76083a0 --- /dev/null +++ b/test/test-vectors/bls.ts @@ -0,0 +1,51 @@ +import { bls12_381 } from "ethereum-cryptography/bls"; +import { deepStrictEqual } from "./assert"; + +describe("bls12-381", () => { + const PointG1 = bls12_381.G1.ProjectivePoint; + const PointG2 = bls12_381.G2.ProjectivePoint; + const { Fp, Fp12 } = bls12_381.fields; + + it("basic", () => { + const a = PointG1.fromAffine({ + x: Fp.create( + 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bbn + ), + y: Fp.create( + 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1n + ), + }); + a.assertValidity(); + }); + it("sign", () => { + const [priv, msg] = + "0d1bd9077705325666408124339dca98c0c842b35a90bc3cea8e0c36f2d35583:c43623:94f60dc44a4dbb2505befe346c0c143190fc877ded5e877418f0f890b8ae357a40e8fcc189139aaa509d2b6500f623a5".split( + ":" + ); + const sig = bls12_381.signShortSignature(msg, priv); + const pub = bls12_381.getPublicKeyForShortSignatures(priv); + const res = bls12_381.verifyShortSignature(sig, msg, pub); + deepStrictEqual(res, true, `${priv}-${msg}`); + }); + it("pairing", () => { + const p1 = bls12_381.pairing(PointG1.BASE, PointG2.BASE); + deepStrictEqual( + p1, + // @ts-ignore + Fp12.fromBigTwelve([ + 0x1250ebd871fc0a92a7b2d83168d0d727272d441befa15c503dd8e90ce98db3e7b6d194f60839c508a84305aaca1789b6n, + 0x089a1c5b46e5110b86750ec6a532348868a84045483c92b7af5af689452eafabf1a8943e50439f1d59882a98eaa0170fn, + 0x1368bb445c7c2d209703f239689ce34c0378a68e72a6b3b216da0e22a5031b54ddff57309396b38c881c4c849ec23e87n, + 0x193502b86edb8857c273fa075a50512937e0794e1e65a7617c90d8bd66065b1fffe51d7a579973b1315021ec3c19934fn, + 0x01b2f522473d171391125ba84dc4007cfbf2f8da752f7c74185203fcca589ac719c34dffbbaad8431dad1c1fb597aaa5n, + 0x018107154f25a764bd3c79937a45b84546da634b8f6be14a8061e55cceba478b23f7dacaa35c8ca78beae9624045b4b6n, + 0x19f26337d205fb469cd6bd15c3d5a04dc88784fbb3d0b2dbdea54d43b2b73f2cbb12d58386a8703e0f948226e47ee89dn, + 0x06fba23eb7c5af0d9f80940ca771b6ffd5857baaf222eb95a7d2809d61bfe02e1bfd1b68ff02f0b8102ae1c2d5d5ab1an, + 0x11b8b424cd48bf38fcef68083b0b0ec5c81a93b330ee1a677d0d15ff7b984e8978ef48881e32fac91b93b47333e2ba57n, + 0x03350f55a7aefcd3c31b4fcb6ce5771cc6a0e9786ab5973320c806ad360829107ba810c5a09ffdd9be2291a0c25a99a2n, + 0x04c581234d086a9902249b64728ffd21a189e87935a954051c7cdba7b3872629a4fafc05066245cb9108f0242d0fe3efn, + 0x0f41e58663bf08cf068672cbd01a7ec73baca4d72ca93544deff686bfd6df543d48eaa24afe47e1efde449383b676631n, + ]) + ); + }); +}); diff --git a/test/test-vectors/bn.ts b/test/test-vectors/bn.ts new file mode 100644 index 0000000..80a90a2 --- /dev/null +++ b/test/test-vectors/bn.ts @@ -0,0 +1,63 @@ +import { bn254 } from "ethereum-cryptography/bn"; +import { deepStrictEqual } from "./assert"; + +describe("bls12-381", () => { + const PointG1 = bn254.G1.ProjectivePoint; + const PointG2 = bn254.G2.ProjectivePoint; + const { Fp12 } = bn254.fields; + + it("basic", () => { + const g1 = + PointG1.BASE.multiply( + 18097487326282793650237947474982649264364522469319914492172746413872781676n + ); + g1.assertValidity(); + deepStrictEqual(g1.toAffine(), { + x: 0x16f7535f91f50bb2227f483b54850a63b38206f28e0a1a65c83d0c90762442a9n, + y: 0x0b46dd0c40725b6b4a298576629d77b41a545060adb4358eabec939e80691a05n, + }); + const g2 = + PointG2.BASE.multiply( + 20390255904278144451778773028944684152769293537511418234311120800877067946n + ); + g2.assertValidity(); + deepStrictEqual(g2.toAffine(), { + x: { + c0: 0x1ecfd2dff2aad18798b64bdb0c2b50c9d73e6c05619e04cbf5b448fd98726880n, + c1: 0x0e16c8d96362720af0916592be1b839a26f5e6b710f3ede0d8840d9a70eaf97fn, + }, + y: { + c0: 0x2aa778acda9e7d4925c60ad84c12fb3b4f2b9539d5699934b0e6fdd10cc2c0e1n, + c1: 0x1e8f2c1f441fed039bb46d6bfb91236cf7ba240c75080cedbe40e049c46b26ben, + }, + }); + }); + it("pairing", () => { + const g1 = + PointG1.BASE.multiply( + 18097487326282793650237947474982649264364522469319914492172746413872781676n + ); + const g2 = + PointG2.BASE.multiply( + 20390255904278144451778773028944684152769293537511418234311120800877067946n + ); + deepStrictEqual( + bn254.pairing(g1, g2, true), + // @ts-ignore + Fp12.fromBigTwelve([ + 7520311483001723614143802378045727372643587653754534704390832890681688842501n, + 20265650864814324826731498061022229653175757397078253377158157137251452249882n, + 11942254371042183455193243679791334797733902728447312943687767053513298221130n, + 759657045325139626991751731924144629256296901790485373000297868065176843620n, + 16045761475400271697821392803010234478356356448940805056528536884493606035236n, + 4715626119252431692316067698189337228571577552724976915822652894333558784086n, + 14901948363362882981706797068611719724999331551064314004234728272909570402962n, + 11093203747077241090565767003969726435272313921345853819385060670210834379103n, + 17897835398184801202802503586172351707502775171934235751219763553166796820753n, + 1344517825169318161285758374052722008806261739116142912817807653057880346554n, + 11123896897251094532909582772961906225000817992624500900708432321664085800838n, + 17453370448280081813275586256976217762629631160552329276585874071364454854650n, + ]) + ); + }); +}); diff --git a/test/test-vectors/math.ts b/test/test-vectors/math.ts new file mode 100644 index 0000000..fbc8999 --- /dev/null +++ b/test/test-vectors/math.ts @@ -0,0 +1,42 @@ +import { modPow, modInvert } from "ethereum-cryptography/math"; +import { deepStrictEqual, throws } from "./assert"; + +describe("math", () => { + it("pow", () => { + deepStrictEqual(modPow(123n, 456n, 789n), 699n); + deepStrictEqual(modPow(123n, 0n, 789n), 1n); + deepStrictEqual(modPow(2n, 5n, 789n), 32n); + deepStrictEqual(modPow(123n, 456n, 1n), 0n); + deepStrictEqual( + modPow( + 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bbn, + 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1n, + 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn + ), + 436876548127983101943682984672944697156319180922804969694242509081341800477678465744409641708610886843942671311740n + ); + throws(() => modPow(123n, 456n, 0n)); + throws(() => modPow(123n, 456n, -1n)); + throws(() => modPow(123n, -1n, 789n)); + }); + it("invert", () => { + // basic + deepStrictEqual(modInvert(3n, 11n), 4n); + deepStrictEqual(modInvert(10n, 17n), 12n); + deepStrictEqual(modInvert(22n, 5n), 3n); // bigger than modulo + deepStrictEqual( + modInvert( + 0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bbn, + 0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1n + ), + 291256306712195702191844365537370801710916620404828242975224254728724473918830780018590872057480493707327142420858n + ); // big + // zero + throws(() => modInvert(0n, 5n)); + throws(() => modInvert(5n, 0n)); + deepStrictEqual(modInvert(-1n, 5n), 4n); + throws(() => modInvert(5n, -1n)); + throws(() => modInvert(2n, 4n)); // gcd is not 1 + throws(() => modInvert(7n, 7n)); // number and modulo same + }); +}); diff --git a/tsconfig.prod.esm.json b/tsconfig.prod.esm.json index ae9efa1..57d92b9 100644 --- a/tsconfig.prod.esm.json +++ b/tsconfig.prod.esm.json @@ -5,6 +5,7 @@ "module": "es6", "moduleResolution": "node", "strict": true, + "declaration": true, "rootDir": "src", "outDir": "esm" },