From: Chris Duncan Date: Mon, 2 Dec 2024 16:43:15 +0000 (-0800) Subject: Tabs. X-Git-Url: https://zoso.dev/?a=commitdiff_plain;h=3c2422fc91e017b68a7310655e63e6b983acb984;p=libnemo.git Tabs. --- diff --git a/src/lib/pow.ts b/src/lib/pow.ts index 2be8a41..7a9fea1 100644 --- a/src/lib/pow.ts +++ b/src/lib/pow.ts @@ -4,49 +4,49 @@ import { Blake2b } from './blake2b.js' const p = () => { - const NONCE_BYTES = 8 - const RECEIVE_THRESHOLD = 'fffffe0000000000' - const SEND_THRESHOLD = 'fffffff800000000' - - /** - * Listens for messages from a calling function. - */ - addEventListener('message', (message) => { - const data = JSON.parse(new TextDecoder().decode(message.data ?? message)) - for (const d of data) { - d.nonce = find(d.hash, d.threshold) - } - const buf = new TextEncoder().encode(JSON.stringify(data)).buffer - //@ts-expect-error - postMessage(buf, [buf]) - }) - - async function find (hash: string, threshold: string = SEND_THRESHOLD) { - let count = 0 - let result = null - do { - count++ - const nonce: Uint8Array = new Uint8Array(NONCE_BYTES) - crypto.getRandomValues(nonce) - const test: string = new Blake2b(NONCE_BYTES) - .update(nonce) - .update(parseHex(hash)) - .digest('hex') as string - if (count % 1000 === 0) console.log(`${count} hashes...`) - if (BigInt(`0x${test}`) >= BigInt(`0x${threshold}`)) { - result = nonce - } - } while (result == null) - return result - } - - function parseHex (hex: string) { - if (hex.length % 2 === 1) hex = `0${hex}` - const arr = hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) - return Uint8Array.from(arr ?? []) - } - - return { find } + const NONCE_BYTES = 8 + const RECEIVE_THRESHOLD = 'fffffe0000000000' + const SEND_THRESHOLD = 'fffffff800000000' + + /** + * Listens for messages from a calling function. + */ + addEventListener('message', (message) => { + const data = JSON.parse(new TextDecoder().decode(message.data ?? message)) + for (const d of data) { + d.nonce = find(d.hash, d.threshold) + } + const buf = new TextEncoder().encode(JSON.stringify(data)).buffer + //@ts-expect-error + postMessage(buf, [buf]) + }) + + async function find (hash: string, threshold: string = SEND_THRESHOLD) { + let count = 0 + let result = null + do { + count++ + const nonce: Uint8Array = new Uint8Array(NONCE_BYTES) + crypto.getRandomValues(nonce) + const test: string = new Blake2b(NONCE_BYTES) + .update(nonce) + .update(parseHex(hash)) + .digest('hex') as string + if (count % 1000 === 0) console.log(`${count} hashes...`) + if (BigInt(`0x${test}`) >= BigInt(`0x${threshold}`)) { + result = nonce + } + } while (result == null) + return result + } + + function parseHex (hex: string) { + if (hex.length % 2 === 1) hex = `0${hex}` + const arr = hex.match(/.{1,2}/g)?.map(byte => parseInt(byte, 16)) + return Uint8Array.from(arr ?? []) + } + + return { find } } export const Pow = p()