export async function powWorkJs(challenge) {
if (challenge.length < 5) {
console.error('Invalid PoW challenge input length');
return undefined;
}
const version = challenge[0];
if (version !== '1') {
console.error('Unknown PoW challenge version');
return undefined;
}
const difficulty = parseInt(challenge.slice(2, 4));
const sliceLength = (difficulty / 8) + 1;
const bits = [128, 64, 32, 16, 8, 4, 2, 1];
let counter = 0;
while (true) {
const value = challenge + counter;
const data = new TextEncoder().encode(value);
const hash = await crypto.subtle.digest("SHA-256", data);
const view = new Int8Array(hash.slice(0, sliceLength));
let bit = 0;
while (bit < difficulty) {
let value = view[bit >> 3] & bits[bit % 8] ? 1 : 0;
if (value === 1) {
break;
}
bit += 1;
}
if (bit === difficulty) {
return value;
}
counter += 1;
}
}