add PoW option

This commit is contained in:
En 2025-01-18 14:18:31 +01:00
parent e144db938b
commit 1b9b51f063

View File

@ -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;
}