diff --git a/scripts/test-differential.mjs b/scripts/test-differential.mjs index 83f45b2..db52bc9 100644 --- a/scripts/test-differential.mjs +++ b/scripts/test-differential.mjs @@ -40,6 +40,42 @@ for (let seed = 0; seed < 100; seed++) { equal(validateAddress(checksum, 'ethereum', { strict: true }).valid, true, 'EIP-55 strict'); } +// EVM results against a direct reading of EIP-55. `details.checksum` reports whether the input +// equals its EIP-55 form; mixed case or strict mode additionally requires it. Mutations keep +// the length so they reach the checksum path (embedded or repeated prefixes, case flips, non-hex). +function eip55(hex) { + const lower = hex.toLowerCase(); + const hash = Buffer.from(keccak_256(new TextEncoder().encode(lower))).toString('hex'); + return [...lower].map((c, i) => parseInt(hash[i], 16) >= 8 ? c.toUpperCase() : c).join(''); +} +function referenceEvm(input, strict) { + const hex = input.startsWith('0x') ? input.slice(2) : input; + if (!/^[0-9a-fA-F]{40}$/.test(hex) || /^0+$/.test(hex)) return { valid: false }; + const checksum = hex === eip55(hex); + const mixed = hex !== hex.toLowerCase() && hex !== hex.toUpperCase(); + return (strict || mixed) && !checksum ? { valid: false } : { valid: true, checksum }; +} +const evmSeeds = ['0x' + '1'.repeat(40), '0xde709f2102306220921060314715629080e2fb77', '0x52908400098527886E0F7030069857D2E4169EE7']; +for (let seed = 0; seed < 40; seed++) { + const hex = Buffer.from(bytes(20, seed)).toString('hex'); + evmSeeds.push('0x' + eip55(hex), '0x' + hex, '0x' + hex.toUpperCase(), eip55(hex)); +} +for (const seed of evmSeeds) { + const variants = new Set([seed]); + for (let i = 0; i + 2 <= seed.length; i++) { + for (const piece of ['0x', '0X', 'x0', 'zz']) variants.add(seed.slice(0, i) + piece + seed.slice(i + 2)); + const c = seed[i]; + variants.add(seed.slice(0, i) + (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()) + seed.slice(i + 1)); + } + for (const input of variants) { + for (const strict of [false, true]) { + const expected = referenceEvm(input, strict); + const actual = validateAddress(input, 'ethereum', { strict }); + equal(actual.valid ? { valid: true, checksum: actual.details?.checksum } : { valid: false }, expected, `EVM reference ${input} strict=${strict}`); + } + } +} + for (const [chain, hrp] of [['bitcoin', 'bc'], ['bitcoin', 'tb'], ['litecoin', 'ltc'], ['litecoin', 'tltc']]) { for (let version = 0; version <= 17; version++) { for (let length = 0; length <= 41; length++) { diff --git a/src/utils/keccak256.ts b/src/utils/keccak256.ts index ecf0b5c..a4a6282 100644 --- a/src/utils/keccak256.ts +++ b/src/utils/keccak256.ts @@ -1,47 +1,94 @@ // Keccak-f[1600], rate 1088, capacity 512; Ethereum uses suffix 0x01, not SHA3's 0x06. -const MASK = (1n << 64n) - 1n; +// Each 64-bit lane is stored as two 32-bit halves (lo at 2i, hi at 2i + 1) so the +// permutation runs on plain integer arithmetic instead of BigInt. +const RATE = 136; const ROTATIONS = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14]; -const ROUND_CONSTANTS = [ - 0x0000000000000001n, 0x0000000000008082n, 0x800000000000808an, 0x8000000080008000n, - 0x000000000000808bn, 0x0000000080000001n, 0x8000000080008081n, 0x8000000000008009n, - 0x000000000000008an, 0x0000000000000088n, 0x0000000080008009n, 0x000000008000000an, - 0x000000008000808bn, 0x800000000000008bn, 0x8000000000008089n, 0x8000000000008003n, - 0x8000000000008002n, 0x8000000000000080n, 0x000000000000800an, 0x800000008000000an, - 0x8000000080008081n, 0x8000000000008080n, 0x0000000080000001n, 0x8000000080008008n, -]; -function rotate(value: bigint, bits: number): bigint { - return ((value << BigInt(bits)) | (value >> BigInt(64 - bits))) & MASK; -} -function permute(state: bigint[]): void { - const c = new Array(5); - const b = new Array(25); - for (const rc of ROUND_CONSTANTS) { - for (let x = 0; x < 5; x++) c[x] = state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20]; +// Round constants as [lo, hi] pairs. +const ROUND_CONSTANTS = new Uint32Array([ + 0x00000001, 0x00000000, 0x00008082, 0x00000000, 0x0000808a, 0x80000000, 0x80008000, 0x80000000, + 0x0000808b, 0x00000000, 0x80000001, 0x00000000, 0x80008081, 0x80000000, 0x00008009, 0x80000000, + 0x0000008a, 0x00000000, 0x00000088, 0x00000000, 0x80008009, 0x00000000, 0x8000000a, 0x00000000, + 0x8000808b, 0x00000000, 0x0000008b, 0x80000000, 0x00008089, 0x80000000, 0x00008003, 0x80000000, + 0x00008002, 0x80000000, 0x00000080, 0x80000000, 0x0000800a, 0x00000000, 0x8000000a, 0x80000000, + 0x80008081, 0x80000000, 0x00008080, 0x80000000, 0x80000001, 0x00000000, 0x80008008, 0x80000000, +]); +// Destination lane for rho/pi: lane x + 5y moves to y + 5((2x + 3y) % 5). +const PI = new Uint8Array(25); +for (let x = 0; x < 5; x++) for (let y = 0; y < 5; y++) PI[x + 5 * y] = y + 5 * ((2 * x + 3 * y) % 5); + +const C = new Uint32Array(10); +const B = new Uint32Array(50); + +function permute(s: Uint32Array): void { + for (let round = 0; round < 48; round += 2) { + // Theta + for (let x = 0; x < 10; x++) C[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; for (let x = 0; x < 5; x++) { - const d = c[(x + 4) % 5] ^ rotate(c[(x + 1) % 5], 1); - for (let y = 0; y < 5; y++) state[x + 5 * y] ^= d; + const p = ((x + 4) % 5) * 2; + const n = ((x + 1) % 5) * 2; + const lo = C[p] ^ ((C[n] << 1) | (C[n + 1] >>> 31)); + const hi = C[p + 1] ^ ((C[n + 1] << 1) | (C[n] >>> 31)); + for (let y = 0; y < 50; y += 10) { + s[2 * x + y] ^= lo; + s[2 * x + y + 1] ^= hi; + } } - for (let x = 0; x < 5; x++) { - for (let y = 0; y < 5; y++) b[y + 5 * ((2 * x + 3 * y) % 5)] = rotate(state[x + 5 * y], ROTATIONS[x + 5 * y]); + // Rho and Pi + for (let i = 0; i < 25; i++) { + const lo = s[2 * i]; + const hi = s[2 * i + 1]; + const r = ROTATIONS[i]; + const d = PI[i] * 2; + if (r === 0) { + B[d] = lo; + B[d + 1] = hi; + } else if (r < 32) { + B[d] = (lo << r) | (hi >>> (32 - r)); + B[d + 1] = (hi << r) | (lo >>> (32 - r)); + } else if (r === 32) { + B[d] = hi; + B[d + 1] = lo; + } else { + const m = r - 32; + B[d] = (hi << m) | (lo >>> (32 - m)); + B[d + 1] = (lo << m) | (hi >>> (32 - m)); + } } - for (let x = 0; x < 5; x++) { - for (let y = 0; y < 5; y++) state[x + 5 * y] = b[x + 5 * y] ^ ((~b[(x + 1) % 5 + 5 * y]) & b[(x + 2) % 5 + 5 * y]); + // Chi + for (let y = 0; y < 50; y += 10) { + for (let x = 0; x < 5; x++) { + const i = y + 2 * x; + const a = y + 2 * ((x + 1) % 5); + const b = y + 2 * ((x + 2) % 5); + s[i] = B[i] ^ (~B[a] & B[b]); + s[i + 1] = B[i + 1] ^ (~B[a + 1] & B[b + 1]); + } } - state[0] ^= rc; + // Iota + s[0] ^= ROUND_CONSTANTS[round]; + s[1] ^= ROUND_CONSTANTS[round + 1]; } } + +const encoder = new TextEncoder(); +const HEX = '0123456789abcdef'; + export function keccak256(input: string): string { - const bytes = new TextEncoder().encode(input); - const padded = new Uint8Array((Math.floor(bytes.length / 136) + 1) * 136); + const bytes = encoder.encode(input); + const padded = new Uint8Array((Math.floor(bytes.length / RATE) + 1) * RATE); padded.set(bytes); padded[bytes.length] = 1; padded[padded.length - 1] |= 128; - const state = new Array(25).fill(0n); - for (let offset = 0; offset < padded.length; offset += 136) { - for (let i = 0; i < 136; i++) state[i >> 3] ^= BigInt(padded[offset + i]) << BigInt((i & 7) * 8); + const state = new Uint32Array(50); + for (let offset = 0; offset < padded.length; offset += RATE) { + // Lanes are little-endian: byte i lands in half-word i >> 2 at bit (i & 3) * 8. + for (let i = 0; i < RATE; i++) state[i >> 2] ^= padded[offset + i] << ((i & 3) * 8); permute(state); } let result = ''; - for (let i = 0; i < 32; i++) result += Number((state[i >> 3] >> BigInt((i & 7) * 8)) & 255n).toString(16).padStart(2, '0'); + for (let i = 0; i < 32; i++) { + const byte = (state[i >> 2] >>> ((i & 3) * 8)) & 255; + result += HEX[byte >> 4] + HEX[byte & 15]; + } return result; } diff --git a/src/validators/ethereum.ts b/src/validators/ethereum.ts index 008ffe3..ea8c1c1 100644 --- a/src/validators/ethereum.ts +++ b/src/validators/ethereum.ts @@ -59,6 +59,9 @@ export class EthereumValidator extends AddressValidator { const clean = stripHexPrefix(address).toLowerCase(); if (!/^[0-9a-f]{40}$/.test(clean)) throw new Error('Expected a 20-byte hexadecimal address'); const hash = keccak256(clean); - return '0x' + [...clean].map((char, i) => parseInt(hash[i], 16) >= 8 ? char.toUpperCase() : char).join(''); + let result = '0x'; + // A hash nibble of 8-f (char code >= '8') marks a letter that must be uppercase. + for (let i = 0; i < 40; i++) result += hash.charCodeAt(i) >= 56 ? clean[i].toUpperCase() : clean[i]; + return result; } } diff --git a/tests/ethereum.test.ts b/tests/ethereum.test.ts index f13e512..b06c08e 100644 --- a/tests/ethereum.test.ts +++ b/tests/ethereum.test.ts @@ -103,3 +103,22 @@ describe('Ethereum Validator', () => { }); }); }); + +describe('EIP-55 results for uniform-case vectors', () => { + // EIP-55 vectors whose checksummed form is entirely lowercase or uppercase letters. + const lowerVector = '0xde709f2102306220921060314715629080e2fb77'; + const upperVector = '0x52908400098527886E0F7030069857D2E4169EE7'; + + test.each([lowerVector, upperVector])('%s reports a valid checksum with and without strict mode', address => { + for (const options of [undefined, { strict: true }]) { + expect(validateAddress(address, 'ethereum', options)).toEqual({ valid: true, blockchain: 'ethereum', details: { checksum: true } }); + } + }); + + test('the opposite case of each vector is valid but unchecksummed, and fails strict mode', () => { + for (const address of ['0x' + lowerVector.slice(2).toUpperCase(), '0x' + upperVector.slice(2).toLowerCase()]) { + expect(validateAddress(address, 'ethereum')).toEqual({ valid: true, blockchain: 'ethereum', details: { checksum: false } }); + expect(validateAddress(address, 'ethereum', { strict: true }).details?.errorCode).toBe(ValidationError.INVALID_CHECKSUM); + } + }); +}); diff --git a/tests/utils.test.ts b/tests/utils.test.ts index e82dabd..9a087ad 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -1,3 +1,4 @@ +import { keccak_256 } from '@noble/hashes/sha3.js'; import { encodeBase58, decodeBase58 } from '../src/utils/base58'; import { isHex, stripHexPrefix, addHexPrefix } from '../src/utils/hex'; import { decodeBech32 } from '../src/utils/bech32'; @@ -67,3 +68,17 @@ describe('Utils', () => { }); }); +describe('Keccak-256', () => { + test.each([ + ['', 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'], + ['abc', '4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45'], + ])('matches the published digest of %j', (input, digest) => { + expect(keccak256(input)).toBe(digest); + }); + + // 135, 136 and 137 bytes straddle the 136-byte rate; 271-273 straddle the second block. + test.each([1, 40, 135, 136, 137, 271, 272, 273, 500])('matches @noble/hashes for %i-byte input', length => { + const input = 'x'.repeat(length); + expect(keccak256(input)).toBe(Buffer.from(keccak_256(new TextEncoder().encode(input))).toString('hex')); + }); +});