Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion docs/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 1 addition & 2 deletions src/blockchains/monero.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
5 changes: 1 addition & 4 deletions src/utils/address.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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`
Expand Down
3 changes: 1 addition & 2 deletions src/utils/bip32/parent.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
3 changes: 1 addition & 2 deletions src/utils/bip322/taproot.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down
2 changes: 1 addition & 1 deletion src/utils/bip322/verify.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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";
Expand Down
3 changes: 1 addition & 2 deletions src/utils/bip38/index.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down
55 changes: 55 additions & 0 deletions src/utils/bytes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,58 @@ export function concatBytes(...parts: readonly Uint8Array[]): Uint8Array<ArrayBu
}
return result;
}

/**
* Compares bytes without an early exit, once the lengths match.
* @param a - One array
* @param b - The other
* @returns {boolean} Whether both hold the same bytes
*/
export function equalBytes(a: Uint8Array, b: Uint8Array): boolean {
if (a.length !== b.length) return false;
let diff = 0;
for (const [index, byte] of a.entries()) diff |= byte ^ (b[index] ?? 0);
return diff === 0;
}

/**
* Reads big endian bytes as a number.
* @param bytes - The bytes, empty for 0
* @returns {bigint} The number
*/
export function bytesToNumberBE(bytes: Uint8Array): bigint {
return bytes.length === 0 ? 0n : BigInt(`0x${bytes.toHex()}`);
}

/**
* Reads little endian bytes as a number.
* @param bytes - The bytes, empty for 0
* @returns {bigint} The number
*/
export function bytesToNumberLE(bytes: Uint8Array): bigint {
return bytesToNumberBE(bytes.toReversed());
}

/**
* Writes a number as big endian bytes of a fixed length.
* @param value - The number, zero or more
* @param length - How many bytes to fill
* @returns {Uint8Array} Zero padded bytes
* @throws {RangeError} When the number is negative or needs more bytes
*/
export function numberToBytesBE(value: bigint, length: number): Uint8Array<ArrayBuffer> {
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<ArrayBuffer> {
return globalThis.crypto.getRandomValues(new Uint8Array(length));
}
50 changes: 50 additions & 0 deletions src/utils/modular.ts
Original file line number Diff line number Diff line change
@@ -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);
}
5 changes: 2 additions & 3 deletions src/utils/openpgp/algorithms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
3 changes: 1 addition & 2 deletions src/utils/openpgp/certificate.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down
3 changes: 1 addition & 2 deletions src/utils/secp256k1/compact-signature.ts
Original file line number Diff line number Diff line change
@@ -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`. */
Expand Down
3 changes: 1 addition & 2 deletions src/utils/signing.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down
3 changes: 1 addition & 2 deletions src/utils/store/index.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down
17 changes: 4 additions & 13 deletions src/utils/transaction/evm.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand Down Expand Up @@ -91,15 +91,6 @@ const UNSUPPORTED_TYPES: Readonly<Record<string, string>> = {
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
Expand Down Expand Up @@ -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);
}

/**
Expand Down Expand Up @@ -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) };
}
Expand Down
3 changes: 1 addition & 2 deletions src/utils/wif/index.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down
64 changes: 64 additions & 0 deletions test/utils/bytes.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
Loading
Loading