refactor(protocol): reuse tested Sha1Stream in video block-sha1 (drop dup)

video-upload.ts 有一份 ~110 行手写、**无测试**的流式 SHA1(Sha1StreamState),与
sha1-stream.ts 里已充分测试的 Sha1Stream 逐字节相同(transform 数学等价、中间 state
小端)。删掉该重复,computeVideoSha1Blocks 改用 Sha1Stream 做 1MB 块的中间 state、
Node crypto 做整文件 final(与受测的 computeSha1StateV 同一套路;已实测旧 final() ===
Node crypto 整文件 sha1)。

- 新增 video-sha1-blocks.test.ts(4 例):golden 值从**旧实现**抓取,锁定重写 byte-
  identical(两个 1MB 中间 state + overall),并给这个原本无测试的函数永久覆盖。
- 删掉的 tail-update 只影响旧自实现 final,不动任何中间块(tail<64B 不触发 1MB 边界)。

protocol 565 全绿、typecheck 干净;对抗性 Agent 独立复现旧实现确认 golden 逐字节
相同、transform 数学等价无精度问题、无残留引用。
This commit is contained in:
DrSmoothl committed 2026-07-01 20:14:55 +08:00
1 parent c822c5dab6
commit ade76d3d2f
2 files changed
+62 -131

No files matched your search

@@ -0,0 +1,46 @@
import { describe, it, expect } from 'vitest';
import { createHash } from 'node:crypto';
import { computeVideoSha1Blocks } from '../../src/highway/video-upload';
// Deterministic input generator (matches the golden-capture script).
function det(len: number): Uint8Array {
const b = new Uint8Array(len);
for (let i = 0; i < len; i++) b[i] = (i * 31 + 7) & 0xFF;
return b;
}
const hex = (u: Uint8Array): string => Buffer.from(u).toString('hex');
const nodeSha1 = (b: Uint8Array): string => createHash('sha1').update(Buffer.from(b)).digest('hex');
describe('computeVideoSha1Blocks', () => {
// GOLDEN: captured from the previous hand-rolled Sha1StreamState implementation
// before the F3 rewrite (Sha1Stream + Node crypto), so this locks the rewrite
// byte-identical for the block states AND the overall digest.
it('reproduces the pre-refactor golden 1MB-block states + overall sha1', () => {
const input = det(2 * 1024 * 1024 + 12345); // 2 full 1MB blocks + a partial tail
expect(computeVideoSha1Blocks(input).map(hex)).toEqual([
'ab9a20fd6c98fc1f8f0c985cd552ff14c6feacfd', // intermediate un-finalized state @1MB (little-endian)
'2ccc5923b75f46ebd8ccb78e8c413c18025178b9', // intermediate un-finalized state @2MB
'dd9cfd4648ab460260afa820c98bfec1b17655d4', // overall (finalized)
]);
});
it('the final block equals the standard full-file SHA1', () => {
const input = det(2 * 1024 * 1024 + 12345);
const blocks = computeVideoSha1Blocks(input);
expect(hex(blocks[blocks.length - 1]!)).toBe(nodeSha1(input));
});
it('a file shorter than 1MB yields just the overall sha1', () => {
const input = det(1000);
const blocks = computeVideoSha1Blocks(input);
expect(blocks).toHaveLength(1);
expect(hex(blocks[0]!)).toBe(nodeSha1(input));
});
it('a file that is an exact 1MB multiple emits the boundary state then the overall', () => {
const input = det(1024 * 1024);
const blocks = computeVideoSha1Blocks(input);
expect(blocks).toHaveLength(2);
expect(hex(blocks[1]!)).toBe(nodeSha1(input)); // last is the finalized overall
});
});