From 11fcb03dfa44ad5a98b1da453bfb40978d28ec0f Mon Sep 17 00:00:00 2001 From: OrcaWin Date: Sat, 12 Sep 2026 18:12:29 -0700 Subject: [PATCH] perf: avoid typed-array iteration in shared SHA-256 blocks (#20346) Co-authored-by: Orca Worker --- src/shared/sha256.test.ts | 16 ++++++++++++++++ src/shared/sha256.ts | 9 ++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 src/shared/sha256.test.ts diff --git a/src/shared/sha256.test.ts b/src/shared/sha256.test.ts new file mode 100644 index 00000000000..7e06e32b777 --- /dev/null +++ b/src/shared/sha256.test.ts @@ -0,0 +1,16 @@ +import { createHash } from 'node:crypto' +import { describe, expect, it } from 'vitest' +import { sha256 } from './sha256' + +describe('shared sha256', () => { + it.each([0, 1, 55, 56, 63, 64, 65, 119, 120, 127, 128, 1024, 65_536])( + 'matches Node crypto for a %i-byte offset view', + (length) => { + const backing = Uint8Array.from({ length: length + 7 }, (_, index) => index % 251) + const bytes = backing.subarray(7) + expect(Buffer.from(sha256(bytes)).toString('hex')).toBe( + createHash('sha256').update(bytes).digest('hex') + ) + } + ) +}) diff --git a/src/shared/sha256.ts b/src/shared/sha256.ts index 10350ddf7c8..aa628091e69 100644 --- a/src/shared/sha256.ts +++ b/src/shared/sha256.ts @@ -43,7 +43,14 @@ export function sha256(message: Uint8Array): Uint8Array { words[index] = (words[index - 16] + s0 + words[index - 7] + s1) | 0 } - let [a, b, c, d, e, f, g, h] = hash + let a = hash[0] + let b = hash[1] + let c = hash[2] + let d = hash[3] + let e = hash[4] + let f = hash[5] + let g = hash[6] + let h = hash[7] for (let index = 0; index < 64; index += 1) { const sigma1 = rotateRight(e, 6) ^ rotateRight(e, 11) ^ rotateRight(e, 25) const choice = (e & f) ^ (~e & g)