From 8b1917c49f9eff591e10a146787dbdbfd2fc2cc7 Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Sun, 29 Dec 2024 02:03:54 -0800 Subject: [PATCH] Write test to validate generated PoW. --- test/calculate-pow.test.mjs | 46 +++++++++++++++++++++++++++++++++++++ test/main.mjs | 1 + 2 files changed, 47 insertions(+) create mode 100644 test/calculate-pow.test.mjs diff --git a/test/calculate-pow.test.mjs b/test/calculate-pow.test.mjs new file mode 100644 index 0000000..41a89c2 --- /dev/null +++ b/test/calculate-pow.test.mjs @@ -0,0 +1,46 @@ +// SPDX-FileCopyrightText: 2024 Chris Duncan +// SPDX-License-Identifier: GPL-3.0-or-later + +'use strict' + +import { assert, suite, test } from '#GLOBALS.mjs' +import { NANO_TEST_VECTORS } from '#test/TEST_VECTORS.js' +import { SendBlock, Blake2b } from '#dist/main.js' + +await suite('Calculate proof-of-work', async () => { + + await test('SendBlock PoW', async () => { + const block = new SendBlock( + NANO_TEST_VECTORS.SEND_BLOCK.account, + NANO_TEST_VECTORS.SEND_BLOCK.balance, + NANO_TEST_VECTORS.SEND_BLOCK.link, + '0', + NANO_TEST_VECTORS.SEND_BLOCK.representative, + NANO_TEST_VECTORS.SEND_BLOCK.previous + ) + await block.pow() + console.log(block.work) + assert.equals(block.previous.length, 64) + assert.equals(block.work?.length, 16) + + const work = block.work + ?.match(/.{2}/g) + ?.map(hex => parseInt(hex, 16)) + .reverse() + if (work == null) throw new Error('Work invalid') + const previous = block.previous + ?.match(/.{2}/g) + ?.map(hex => parseInt(hex, 16)) + if (previous == null) throw new Error('Previous block hash invalid') + + const bytes = new Uint8Array([...work, ...previous]) + assert.equals(bytes.byteLength, 40) + + const hash = new Blake2b(8) + .update(bytes) + .digest('hex') + .slice(8, 16) + assert.ok(parseInt(hash.slice(0, 2), 16) > 0xf0) + assert.equals(parseInt(hash.slice(2, 8), 16), 0xffffff) + }) +}) diff --git a/test/main.mjs b/test/main.mjs index 4a78267..1737521 100644 --- a/test/main.mjs +++ b/test/main.mjs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2024 Chris Duncan // SPDX-License-Identifier: GPL-3.0-or-later +import './calculate-pow.test.mjs' import './create-wallet.test.mjs' import './derive-accounts.test.mjs' import './import-wallet.test.mjs' -- 2.34.1