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()