import { createHash } from 'node:crypto'; import { describe, expect, it } from 'vitest'; import { sha256, solveProof, verifyProof } from './proof.ts'; const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex'); describe('sha256', () => { it.each(['', 'abc', 'challenge:12345', 'x'.repeat(55), 'x'.repeat(56), 'y'.repeat(64), 'z'.repeat(200)])( 'matches node for a message of %#', (message) => { expect(hex(sha256(Buffer.from(message)))).toBe(createHash('sha256').update(message).digest('hex')); }, ); }); describe('proof of work', () => { it('finds a nonce the verifier accepts', () => { const nonce = solveProof('AAAAAAAAAAAAAAAAAAAAAA', 12)!; expect(verifyProof('AAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(true); expect(verifyProof('BAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(false); }); it('agrees with node about the leading zero bits', () => { const nonce = solveProof('challenge', 10)!; const digest = createHash('sha256').update(`challenge:${nonce}`).digest(); expect(digest[0]).toBe(0); expect(digest[1]! >> 6).toBe(0); }); it('stops after the given number of attempts', () => { expect(solveProof('challenge', 32, 0, 100)).toBeUndefined(); }); });