self.onmessage = async (e) => {
    const { nonce, difficulty } = e.data
    const ENCODER = new TextEncoder()
    const BATCH = 1000
    let counter = 0

    while (true) {
        const batch = await Promise.all(
            Array.from({ length: BATCH }, (_, i) => {
                const data = ENCODER.encode(nonce + (counter + i))
                return crypto.subtle.digest('SHA-256', data)
            }),
        )
        for (let i = 0; i < BATCH; i++) {
            const hash = new Uint8Array(batch[i])
            let zeroBits = 0
            for (const byte of hash) {
                if (byte === 0) {
                    zeroBits += 8
                } else {
                    zeroBits += Math.clz32(byte) - 24
                    break
                }
            }
            if (zeroBits >= difficulty) {
                self.postMessage({ counter: counter + i })
                return
            }
        }
        counter += BATCH
    }
}
