49 lines
1.8 KiB
TypeScript
49 lines
1.8 KiB
TypeScript
import { expect, test } from 'vitest';
|
|
import { isHex } from '@bitauth/libauth';
|
|
import { scriptToScriptHash } from '../source/index.ts';
|
|
|
|
/**
|
|
* Tests that scriptToScriptHash produces the correct reversed SHA256 for a standard P2PKH locking script
|
|
* and returns a 64 character hex string.
|
|
*/
|
|
const testScriptHashForP2pkhScript = (): void => {
|
|
// Standard P2PKH locking script: OP_DUP OP_HASH160 <20 zero bytes> OP_EQUALVERIFY OP_CHECKSIG
|
|
const p2pkhScript = new Uint8Array([ 0x76, 0xa9, 0x14, ...new Uint8Array(20).fill(0), 0x88, 0xac ]);
|
|
|
|
// Precomputed reversed SHA256 of the above script bytes
|
|
const expectedHash = 'acb87996319dca2c2e2afd6c0f7514b18e72e204069718976e1abdc8fcf5de75';
|
|
|
|
// Generate the script hash
|
|
const scriptHash = scriptToScriptHash(p2pkhScript);
|
|
|
|
// The script hash must match the known-good precomputed value exactly
|
|
expect(scriptHash).toBe(expectedHash);
|
|
|
|
// The script hash is 64 characters long
|
|
expect(scriptHash).toHaveLength(64);
|
|
|
|
// The script hash is a valid hex string
|
|
expect(isHex(scriptHash)).toBe(true);
|
|
};
|
|
|
|
/**
|
|
* Tests that two different scripts produce different script hashes.
|
|
*/
|
|
const testScriptHashIsDifferentForDifferentScripts = (): void => {
|
|
// Generate the first script hash
|
|
const hashA = scriptToScriptHash(new Uint8Array([ 0x01 ]));
|
|
|
|
// Generate the second script hash
|
|
const hashB = scriptToScriptHash(new Uint8Array([ 0x02 ]));
|
|
|
|
// The different scripts produce different script hashes
|
|
expect(hashA).not.toBe(hashB);
|
|
};
|
|
|
|
const runTests = async (): Promise<void> => {
|
|
test('scriptToScriptHash: produces reversed SHA256 for a P2PKH locking script', testScriptHashForP2pkhScript);
|
|
test('scriptToScriptHash: produces different hashes for different scripts', testScriptHashIsDifferentForDifferentScripts);
|
|
};
|
|
|
|
await runTests();
|