From 1b9b51f0638800af674051dc19896b4ee4005c59 Mon Sep 17 00:00:00 2001 From: En Date: Sat, 18 Jan 2025 14:18:31 +0100 Subject: [PATCH] add PoW option --- index.js | 43 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 21c9748..13d71ad 100644 --- a/index.js +++ b/index.js @@ -36,7 +36,7 @@ try { } const pk = getPublicKey(sk); - const profileEvent = finalizeEvent( + const profileEvent = finalizeEventWithPoW( { kind: 0, content: BOT, @@ -60,7 +60,7 @@ try { const dayOfWeek = today.getUTCDay(); const message = `${dayOfWeek % 6 === 0 ? "gfy" : "GM"} fiatjaf`; - const event = finalizeEvent( + const event = finalizeEventWithPoW( { kind: 1, content: message, @@ -90,3 +90,42 @@ try { clearInterval(intervalId); process.exit(1); } + +function finalizeEventWithPoW(event, sk, difficulty = 0) { + if (difficulty === 0) return finalizeEvent(event, sk); + + const pk = getPublicKey(sk); + let nonce = 0; + let leadingZeroes = 0; + let event = { ...event, pubkey: pk }; + while (true) { + event.tags = [["nonce", nonce.toString(), difficulty.toString()]]; + event.created_at = Math.floor(Date.now() / 1000); + + const hash = getEventHash(event); + leadingZeroes = countLeadingZeroes(hash); + + if (leadingZeroes >= difficulty) { + return finalizeEvent(event, sk); + } + + nonce++; + } +} + +// hex should be a hexadecimal string (with no 0x prefix) +function countLeadingZeroes(hex) { + let count = 0; + + for (let i = 0; i < hex.length; i++) { + const nibble = parseInt(hex[i], 16); + if (nibble === 0) { + count += 4; + } else { + count += Math.clz32(nibble) - 28; + break; + } + } + + return count; +}