44 lines
1.8 KiB
JavaScript
44 lines
1.8 KiB
JavaScript
import { argon2id } from "https://esm.sh/hash-wasm@4.12.0";
|
|
|
|
function hasLeadingZeroBits(bytes, requiredBits) {
|
|
const whole = Math.floor(requiredBits / 8);
|
|
const remaining = requiredBits % 8;
|
|
for (let i = 0; i < whole; i++) {
|
|
if (bytes[i] !== 0) return false;
|
|
}
|
|
return remaining === 0 || bytes[whole] >>> (8 - remaining) === 0;
|
|
}
|
|
|
|
self.onmessage = async ({ data }) => {
|
|
const { challenge, difficulty, startNonce = 0 } = data;
|
|
if (difficulty < 0 || difficulty > 256 || !Number.isInteger(difficulty)) {
|
|
throw new Error("Invalid difficulty");
|
|
}
|
|
console.log(`[PoW] Difficulty: ${difficulty}, Starting Nonce: ${startNonce}, Challenge: ${challenge}`)
|
|
const startTime = performance.now();
|
|
const encoder = new TextEncoder();
|
|
const input = encoder.encode(challenge);
|
|
for (let nonce = startNonce; ; nonce++) {
|
|
const salt = new Uint8Array(8);
|
|
new DataView(salt.buffer).setBigUint64(0, BigInt(nonce), true);
|
|
const digest = await argon2id({
|
|
password: input,
|
|
salt,
|
|
parallelism: 1,
|
|
iterations: 2,
|
|
memorySize: 4096,
|
|
hashLength: 32,
|
|
outputType: "binary"
|
|
});
|
|
if (hasLeadingZeroBits(digest, difficulty)) {
|
|
const hashHex = Array.from(digest).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
const elapsed = performance.now() - startTime;
|
|
const attempts = nonce - startNonce + 1;
|
|
console.log(`[PoW] took ${elapsed} ms to solve challenge`)
|
|
console.log(`[PoW] ${(attempts / (elapsed / 1000)).toFixed(0)} hashes/s`)
|
|
console.log(`[PoW] Result: ${hashHex}, Nonce: ${nonce}`)
|
|
self.postMessage({ nonce: nonce, hash: hashHex, });
|
|
return;
|
|
}
|
|
}
|
|
}; |