From e922a68b39e402470fdd1dc7e9ecd30927813f41 Mon Sep 17 00:00:00 2001 From: Aei <256851514+aeitwoen@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:49:11 +0100 Subject: [PATCH 1/2] refactor: drop noble helpers --- docs/nuxt.config.ts | 1 - src/blockchains/monero.ts | 3 +- src/utils/address.ts | 5 +- src/utils/bip32/parent.ts | 3 +- src/utils/bip322/taproot.ts | 3 +- src/utils/bip322/verify.ts | 2 +- src/utils/bip38/index.ts | 3 +- src/utils/bytes.ts | 55 ++++++++++++++++++++ src/utils/modular.ts | 50 ++++++++++++++++++ src/utils/openpgp/algorithms.ts | 5 +- src/utils/openpgp/certificate.ts | 3 +- src/utils/secp256k1/compact-signature.ts | 3 +- src/utils/signing.ts | 3 +- src/utils/store/index.ts | 3 +- src/utils/transaction/evm.ts | 17 ++----- src/utils/wif/index.ts | 3 +- test/utils/bytes.test.ts | 64 ++++++++++++++++++++++++ test/utils/modular.test.ts | 55 ++++++++++++++++++++ 18 files changed, 241 insertions(+), 40 deletions(-) create mode 100644 src/utils/modular.ts create mode 100644 test/utils/bytes.test.ts create mode 100644 test/utils/modular.test.ts diff --git a/docs/nuxt.config.ts b/docs/nuxt.config.ts index 83776a2d..a116df5a 100644 --- a/docs/nuxt.config.ts +++ b/docs/nuxt.config.ts @@ -39,7 +39,6 @@ const libraryEntries = [ "@agntn/hashes", "@noble/curves/ed25519.js", "@noble/curves/secp256k1.js", - "@noble/curves/utils.js", "@scure/bip32", "@scure/bip39", "@scure/bip39/wordlists/czech.js", diff --git a/src/blockchains/monero.ts b/src/blockchains/monero.ts index e39f5d7d..c3b21918 100644 --- a/src/blockchains/monero.ts +++ b/src/blockchains/monero.ts @@ -11,10 +11,9 @@ import { import { base58 } from "@agntn/encodings/base58"; import { keccak256 } from "@agntn/hashes"; import { ed25519 } from "@noble/curves/ed25519.js"; -import { bytesToNumberLE, equalBytes } from "@noble/curves/utils.js"; import { AbstractBlockchain } from "../blockchain.ts"; import { BIP44 } from "../utils/bip44/index.ts"; -import { concatBytes } from "../utils/bytes.ts"; +import { bytesToNumberLE, concatBytes, equalBytes } from "../utils/bytes.ts"; import { decodeMoneroSeed } from "../utils/monero-seed.ts"; import { assertSignOptions, assertVerifyOptions } from "../utils/options.ts"; import { assertNoRecoveryByte } from "../utils/signing.ts"; diff --git a/src/utils/address.ts b/src/utils/address.ts index 1091d699..f20105fa 100644 --- a/src/utils/address.ts +++ b/src/utils/address.ts @@ -1,5 +1,6 @@ import { ripemd160, sha256 } from "@agntn/hashes"; import { secp256k1 } from "@noble/curves/secp256k1.js"; +import { bytesToNumberBE } from "./bytes.ts"; import { encodeBase58Check, validateBase58Check } from "./encoding.ts"; import { decodePublicPoint } from "./secp256k1/decode.ts"; import { segwit } from "@agntn/encodings/bech32"; @@ -13,10 +14,6 @@ export function hash160(data: Uint8Array): Uint8Array { return ripemd160(sha256(data)); } -function bytesToNumberBE(bytes: Uint8Array): bigint { - return BigInt(`0x${bytes.toHex()}`); -} - /** * BIP340 tagged hash: SHA-256 over the tag's SHA-256 twice, then the data. * @param tag - Tag text, such as `TapTweak` diff --git a/src/utils/bip32/parent.ts b/src/utils/bip32/parent.ts index 3f49aa6c..d8b489de 100644 --- a/src/utils/bip32/parent.ts +++ b/src/utils/bip32/parent.ts @@ -1,8 +1,7 @@ import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { equalBytes } from "@noble/curves/utils.js"; import { HDKey } from "@scure/bip32"; import { Sha512Hasher, hmac } from "@agntn/hashes"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { KEY_OFFSET, decodeExtendedKey, extendedKeyVersion } from "../extended-key.ts"; import { HARDENED_OFFSET } from "../hd-index.ts"; import { assertOptions } from "../options.ts"; diff --git a/src/utils/bip322/taproot.ts b/src/utils/bip322/taproot.ts index 18e49a4c..e18363c9 100644 --- a/src/utils/bip322/taproot.ts +++ b/src/utils/bip322/taproot.ts @@ -1,7 +1,6 @@ import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { equalBytes } from "@noble/curves/utils.js"; import { taggedHash } from "../address.ts"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { varBytes } from "../transaction/transaction.ts"; /** First byte BIP341 reserves for an annex, the last of two or more witness items. */ diff --git a/src/utils/bip322/verify.ts b/src/utils/bip322/verify.ts index a778431e..9966c21a 100644 --- a/src/utils/bip322/verify.ts +++ b/src/utils/bip322/verify.ts @@ -1,6 +1,5 @@ import { sha256 } from "@agntn/hashes"; import { schnorr } from "@noble/curves/secp256k1.js"; -import { equalBytes } from "@noble/curves/utils.js"; import { Bitcoin } from "../../blockchains/bitcoin.ts"; import { hash160 } from "../address.ts"; import { assertOptions } from "../options.ts"; @@ -32,6 +31,7 @@ import { type TransactionInput, type TransactionOutput, } from "../transaction/transaction.ts"; +import { equalBytes } from "../bytes.ts"; /** What a verifier concludes: BIP322's valid, invalid and inconclusive. */ export type BIP322State = "valid" | "invalid" | "inconclusive"; diff --git a/src/utils/bip38/index.ts b/src/utils/bip38/index.ts index 876c4145..9e3ad08f 100644 --- a/src/utils/bip38/index.ts +++ b/src/utils/bip38/index.ts @@ -1,9 +1,8 @@ import { ecb } from "@agntn/ciphers/aes"; import { scrypt, sha256 } from "@agntn/hashes"; import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { equalBytes } from "@noble/curves/utils.js"; import { generateAddressLegacy } from "../address.ts"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { decodeBase58Check } from "../encoding.ts"; import { encode as encodeWIF } from "../wif/index.ts"; diff --git a/src/utils/bytes.ts b/src/utils/bytes.ts index 7d9057b5..8f1e4389 100644 --- a/src/utils/bytes.ts +++ b/src/utils/bytes.ts @@ -12,3 +12,58 @@ export function concatBytes(...parts: readonly Uint8Array[]): Uint8Array { + const digits = value.toString(16); + if (value < 0n || digits.length > length * 2) { + throw new RangeError(`Number does not fit ${length} bytes`); + } + return Uint8Array.fromHex(digits.padStart(length * 2, "0")); +} + +/** + * Draws random bytes from `globalThis.crypto`. + * @param length - How many bytes + * @returns {Uint8Array} Fresh random bytes + */ +export function randomBytes(length: number): Uint8Array { + return globalThis.crypto.getRandomValues(new Uint8Array(length)); +} diff --git a/src/utils/modular.ts b/src/utils/modular.ts new file mode 100644 index 00000000..fffd499a --- /dev/null +++ b/src/utils/modular.ts @@ -0,0 +1,50 @@ +/** + * Reduces a number into `0..modulus - 1`, negatives included. + * @param value - Any integer + * @param modulus - The modulus + * @returns {bigint} The residue + */ +function mod(value: bigint, modulus: bigint): bigint { + const residue = value % modulus; + return residue < 0n ? residue + modulus : residue; +} + +/** + * Modular power. Variable time, so public input only. + * @param base - The base + * @param exponent - The power, zero or more + * @param modulus - The modulus, above 1 + * @returns {bigint} `base ** exponent mod modulus` + * @throws {RangeError} When the modulus is 1 or less, or the exponent is negative + */ +export function pow(base: bigint, exponent: bigint, modulus: bigint): bigint { + if (modulus <= 1n) throw new RangeError("Modulus must be above 1"); + if (exponent < 0n) throw new RangeError("Exponent must not be negative"); + let result = 1n; + let square = mod(base, modulus); + for (let rest = exponent; rest > 0n; rest >>= 1n) { + if ((rest & 1n) === 1n) result = (result * square) % modulus; + square = (square * square) % modulus; + } + return result; +} + +/** + * Modular inverse. Variable time, so public input only. + * @param value - The number to invert + * @param modulus - The modulus, above 1 + * @returns {bigint} The inverse in `1..modulus - 1` + * @throws {RangeError} When the modulus is 1 or less, or no inverse exists + */ +export function invert(value: bigint, modulus: bigint): bigint { + if (modulus <= 1n) throw new RangeError("Modulus must be above 1"); + let [a, b] = [mod(value, modulus), modulus]; + let [x, u] = [0n, 1n]; + while (a !== 0n) { + const quotient = b / a; + [a, b] = [b - a * quotient, a]; + [x, u] = [u, x - u * quotient]; + } + if (b !== 1n) throw new RangeError("Number has no inverse under this modulus"); + return mod(x, modulus); +} diff --git a/src/utils/openpgp/algorithms.ts b/src/utils/openpgp/algorithms.ts index 5b31a1a1..06ffe9c2 100644 --- a/src/utils/openpgp/algorithms.ts +++ b/src/utils/openpgp/algorithms.ts @@ -17,11 +17,10 @@ import { sha384, sha512, } from "@agntn/hashes"; -import { invert, pow } from "@noble/curves/abstract/modular.js"; import { ed25519 } from "@noble/curves/ed25519.js"; import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { bytesToNumberBE, equalBytes, numberToBytesBE } from "@noble/curves/utils.js"; -import { concatBytes } from "../bytes.ts"; +import { bytesToNumberBE, concatBytes, equalBytes, numberToBytesBE } from "../bytes.ts"; +import { invert, pow } from "../modular.ts"; import { type Reader, createReader } from "./packets.ts"; /** One hash from RFC 9580 Table 23 that this module can compute. */ diff --git a/src/utils/openpgp/certificate.ts b/src/utils/openpgp/certificate.ts index 78e5c004..12f69e0c 100644 --- a/src/utils/openpgp/certificate.ts +++ b/src/utils/openpgp/certificate.ts @@ -1,5 +1,4 @@ -import { equalBytes } from "@noble/curves/utils.js"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { checkMath, hashAlgorithm, minimumDigestBits } from "./algorithms.ts"; import { type Certificate, diff --git a/src/utils/secp256k1/compact-signature.ts b/src/utils/secp256k1/compact-signature.ts index 1cb32285..8f91ed47 100644 --- a/src/utils/secp256k1/compact-signature.ts +++ b/src/utils/secp256k1/compact-signature.ts @@ -1,7 +1,6 @@ import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { equalBytes } from "@noble/curves/utils.js"; import type { MessageSigner } from "../../types.ts"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { decodeKeyPrivate, decodePublicPoint } from "./decode.ts"; /** Header byte plus 32 bytes each of `r` and `s`. */ diff --git a/src/utils/signing.ts b/src/utils/signing.ts index b75079d8..e642acf0 100644 --- a/src/utils/signing.ts +++ b/src/utils/signing.ts @@ -1,8 +1,7 @@ import { secp256k1 } from "@noble/curves/secp256k1.js"; import { ed25519 } from "@noble/curves/ed25519.js"; -import { equalBytes } from "@noble/curves/utils.js"; import { sha256 } from "@agntn/hashes"; -import { concatBytes } from "./bytes.ts"; +import { concatBytes, equalBytes } from "./bytes.ts"; import { assertSignOptions, assertVerifyOptions } from "./options.ts"; import { decodeKeyPrivate } from "./secp256k1/decode.ts"; import { signBytes, verifyBytes as verifySr25519 } from "./sr25519.ts"; diff --git a/src/utils/store/index.ts b/src/utils/store/index.ts index d85ef370..0a928f94 100644 --- a/src/utils/store/index.ts +++ b/src/utils/store/index.ts @@ -1,8 +1,7 @@ import { ecb } from "@agntn/ciphers/aes"; import { Sha256Hasher, keccak256, pbkdf2, scrypt } from "@agntn/hashes"; import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { equalBytes, randomBytes } from "@noble/curves/utils.js"; -import { concatBytes } from "../bytes.ts"; +import { concatBytes, equalBytes, randomBytes } from "../bytes.ts"; import { generateAddress, toChecksumAddress } from "../evm-address.ts"; import { assertEncryptOptions } from "../options.ts"; diff --git a/src/utils/transaction/evm.ts b/src/utils/transaction/evm.ts index 516d5217..8dd687e3 100644 --- a/src/utils/transaction/evm.ts +++ b/src/utils/transaction/evm.ts @@ -1,7 +1,7 @@ import { rlp, type RlpInput, type RlpItem } from "@agntn/encodings/rlp"; import { keccak256 } from "@agntn/hashes"; import { secp256k1 } from "@noble/curves/secp256k1.js"; -import { concatBytes } from "../bytes.ts"; +import { bytesToNumberBE, concatBytes } from "../bytes.ts"; import { generateAddress } from "../evm-address.ts"; /** A signed transaction as `eth_getTransactionByHash` returns it, quantities and data as 0x hex. */ @@ -91,15 +91,6 @@ const UNSUPPORTED_TYPES: Readonly> = { 4: "Type 4 set code transactions are not supported yet", }; -/** - * Reads an RLP integer. - * @param bytes - Big endian bytes, empty for 0 - * @returns {bigint} The integer - */ -function toBigInt(bytes: Uint8Array): bigint { - return bytes.length === 0 ? 0n : BigInt(`0x${bytes.toHex()}`); -} - /** * Writes an integer as 64 hex digits. * @param value - The integer @@ -165,7 +156,7 @@ function bytesField(item: ReadItem | undefined, position: number): Uint8Array { function scalarField(item: ReadItem | undefined, position: number): bigint { const bytes = bytesField(item, position); if (bytes.length > 32) throw new RangeError(`Transaction field ${position} exceeds 32 bytes`); - return toBigInt(bytes); + return bytesToNumberBE(bytes); } /** @@ -218,11 +209,11 @@ function rlpPayload(type: 0 | 1 | 2, body: Uint8Array): SignedPayload { const items = decodeList(body); const fields = payloadFields(items, type); const at = fields.length; - const v = toBigInt(bytesField(items[at], at)); + const v = bytesToNumberBE(bytesField(items[at], at)); const { chainId, recovery } = type === 0 ? splitLegacyV(v) - : { chainId: toBigInt(bytesField(items[0], 0)), recovery: parity(v) }; + : { chainId: bytesToNumberBE(bytesField(items[0], 0)), recovery: parity(v) }; const r = scalarField(items[at + 1], at + 1); return { type, fields, chainId, recovery, r, s: scalarField(items[at + 2], at + 2) }; } diff --git a/src/utils/wif/index.ts b/src/utils/wif/index.ts index e5f9276c..b764d350 100644 --- a/src/utils/wif/index.ts +++ b/src/utils/wif/index.ts @@ -1,7 +1,6 @@ import { secp256k1 } from "@noble/curves/secp256k1.js"; import { blake256 } from "@agntn/hashes"; -import { concatBytes } from "../bytes.ts"; -import { equalBytes } from "@noble/curves/utils.js"; +import { concatBytes, equalBytes } from "../bytes.ts"; import { base58 } from "@agntn/encodings/base58"; import { decodeBase58Check, encodeBase58Check } from "../encoding.ts"; diff --git a/test/utils/bytes.test.ts b/test/utils/bytes.test.ts new file mode 100644 index 00000000..a1781297 --- /dev/null +++ b/test/utils/bytes.test.ts @@ -0,0 +1,64 @@ +import { describe, expect, it } from "vite-plus/test"; +import { hex } from "@agntn/encodings/hex"; +import { + bytesToNumberBE, + bytesToNumberLE, + equalBytes, + numberToBytesBE, + randomBytes, +} from "../../src/utils/bytes.ts"; + +describe("equalBytes", () => { + it("accepts the same bytes, empty arrays included", () => { + expect(equalBytes(hex.decode("00ff10"), hex.decode("00ff10"))).toBe(true); + expect(equalBytes(new Uint8Array(), new Uint8Array())).toBe(true); + }); + + it.each([ + ["the first byte", "01ff10"], + ["the last byte", "00ff11"], + ["a prefix", "00ff"], + ["a longer array", "00ff1000"], + ])("refuses a difference in %s", (_, other) => { + expect(equalBytes(hex.decode("00ff10"), hex.decode(other))).toBe(false); + }); +}); + +describe("byte and number conversion", () => { + it("reads both byte orders", () => { + expect(bytesToNumberBE(hex.decode("0102ff"))).toBe(0x0102ffn); + expect(bytesToNumberLE(hex.decode("0102ff"))).toBe(0xff0201n); + }); + + it("reads no bytes as zero and keeps leading zeros harmless", () => { + expect(bytesToNumberBE(new Uint8Array())).toBe(0n); + expect(bytesToNumberLE(new Uint8Array())).toBe(0n); + expect(bytesToNumberBE(hex.decode("000001"))).toBe(1n); + }); + + it("leaves the input of a little endian read alone", () => { + const bytes = hex.decode("0102"); + bytesToNumberLE(bytes); + expect(hex.encode(bytes)).toBe("0102"); + }); + + it("pads a number to the asked length", () => { + expect(hex.encode(numberToBytesBE(0x1ffn, 4))).toBe("000001ff"); + expect(hex.encode(numberToBytesBE(0n, 2))).toBe("0000"); + expect(hex.encode(numberToBytesBE(0xffffn, 2))).toBe("ffff"); + }); + + it("refuses a number that does not fit, and a negative one", () => { + expect(() => numberToBytesBE(0x10000n, 2)).toThrow(RangeError); + expect(() => numberToBytesBE(-1n, 2)).toThrow(RangeError); + }); +}); + +describe("randomBytes", () => { + it("draws the asked length, fresh each time", () => { + const first = randomBytes(32); + expect(first).toHaveLength(32); + expect(hex.encode(randomBytes(32))).not.toBe(hex.encode(first)); + expect(randomBytes(0)).toHaveLength(0); + }); +}); diff --git a/test/utils/modular.test.ts b/test/utils/modular.test.ts new file mode 100644 index 00000000..cd54b717 --- /dev/null +++ b/test/utils/modular.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vite-plus/test"; +import { invert, pow } from "../../src/utils/modular.ts"; + +/* The secp256k1 field prime, big enough to leave the native `**` behind. */ +const P = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2fn; + +describe("pow", () => { + it("agrees with native exponentiation on small numbers", () => { + for (const [base, exponent, modulus] of [ + [2n, 10n, 1000n], + [7n, 0n, 13n], + [7n, 1n, 13n], + [0n, 5n, 13n], + [12345n, 67n, 89n], + ] as const) { + expect(pow(base, exponent, modulus)).toBe(base ** exponent % modulus); + } + }); + + it("holds Fermat's little theorem on a 256-bit prime", () => { + expect(pow(2n, P - 1n, P)).toBe(1n); + expect(pow(P - 1n, 2n, P)).toBe(1n); + }); + + it("reduces a negative base into the ring", () => { + expect(pow(-2n, 3n, 13n)).toBe(5n); + }); + + it("refuses a modulus of 1 or less and a negative exponent", () => { + expect(() => pow(2n, 2n, 1n)).toThrow(RangeError); + expect(() => pow(2n, 2n, 0n)).toThrow(RangeError); + expect(() => pow(2n, -1n, 13n)).toThrow(RangeError); + }); +}); + +describe("invert", () => { + it("finds the inverse", () => { + expect(invert(3n, 7n)).toBe(5n); + expect(invert(-3n, 7n)).toBe(2n); + expect(invert(10n, 7n)).toBe(5n); + }); + + it("agrees with Fermat on a 256-bit prime", () => { + const value = 0x1234567890abcdef1234567890abcdefn; + const inverse = invert(value, P); + expect(inverse).toBe(pow(value, P - 2n, P)); + expect((value * inverse) % P).toBe(1n); + }); + + it("refuses zero, a shared factor and a modulus of 1 or less", () => { + expect(() => invert(0n, 7n)).toThrow(RangeError); + expect(() => invert(4n, 8n)).toThrow(RangeError); + expect(() => invert(3n, 1n)).toThrow(RangeError); + }); +}); From febc976e017ec37ab5c8cd712ecf4f1cdb98e638 Mon Sep 17 00:00:00 2001 From: Aei <256851514+aeitwoen@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:04:39 +0100 Subject: [PATCH 2/2] docs: name the length check --- src/utils/bytes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/utils/bytes.ts b/src/utils/bytes.ts index 8f1e4389..48257788 100644 --- a/src/utils/bytes.ts +++ b/src/utils/bytes.ts @@ -14,7 +14,7 @@ export function concatBytes(...parts: readonly Uint8Array[]): Uint8Array