]> zoso.dev Git - libnemo.git/commitdiff
Write test to validate generated PoW.
authorChris Duncan <chris@zoso.dev>
Sun, 29 Dec 2024 10:03:54 +0000 (02:03 -0800)
committerChris Duncan <chris@zoso.dev>
Sun, 29 Dec 2024 10:03:54 +0000 (02:03 -0800)
test/calculate-pow.test.mjs [new file with mode: 0644]
test/main.mjs

diff --git a/test/calculate-pow.test.mjs b/test/calculate-pow.test.mjs
new file mode 100644 (file)
index 0000000..41a89c2
--- /dev/null
@@ -0,0 +1,46 @@
+// SPDX-FileCopyrightText: 2024 Chris Duncan <chris@zoso.dev>\r
+// SPDX-License-Identifier: GPL-3.0-or-later\r
+\r
+'use strict'\r
+\r
+import { assert, suite, test } from '#GLOBALS.mjs'\r
+import { NANO_TEST_VECTORS } from '#test/TEST_VECTORS.js'\r
+import { SendBlock, Blake2b } from '#dist/main.js'\r
+\r
+await suite('Calculate proof-of-work', async () => {\r
+\r
+       await test('SendBlock PoW', async () => {\r
+               const block = new SendBlock(\r
+                       NANO_TEST_VECTORS.SEND_BLOCK.account,\r
+                       NANO_TEST_VECTORS.SEND_BLOCK.balance,\r
+                       NANO_TEST_VECTORS.SEND_BLOCK.link,\r
+                       '0',\r
+                       NANO_TEST_VECTORS.SEND_BLOCK.representative,\r
+                       NANO_TEST_VECTORS.SEND_BLOCK.previous\r
+               )\r
+               await block.pow()\r
+               console.log(block.work)\r
+               assert.equals(block.previous.length, 64)\r
+               assert.equals(block.work?.length, 16)\r
+\r
+               const work = block.work\r
+                       ?.match(/.{2}/g)\r
+                       ?.map(hex => parseInt(hex, 16))\r
+                       .reverse()\r
+               if (work == null) throw new Error('Work invalid')\r
+               const previous = block.previous\r
+                       ?.match(/.{2}/g)\r
+                       ?.map(hex => parseInt(hex, 16))\r
+               if (previous == null) throw new Error('Previous block hash invalid')\r
+\r
+               const bytes = new Uint8Array([...work, ...previous])\r
+               assert.equals(bytes.byteLength, 40)\r
+\r
+               const hash = new Blake2b(8)\r
+                       .update(bytes)\r
+                       .digest('hex')\r
+                       .slice(8, 16)\r
+               assert.ok(parseInt(hash.slice(0, 2), 16) > 0xf0)\r
+               assert.equals(parseInt(hash.slice(2, 8), 16), 0xffffff)\r
+       })\r
+})\r
index 4a78267c0d6dc5f0fef1e4701870b7bc0964e2fc..173752155251d3a950e653305233c17456a4d10f 100644 (file)
@@ -1,6 +1,7 @@
 // SPDX-FileCopyrightText: 2024 Chris Duncan <chris@zoso.dev>
 // 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'