Skip to content

Commit

Permalink
fix serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
dskvr committed Sep 14, 2024
1 parent 421d03a commit bffde9a
Show file tree
Hide file tree
Showing 3 changed files with 284 additions and 128 deletions.
9 changes: 6 additions & 3 deletions demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,19 @@ <h1><code>⛏️ notemine</code></h1>
<input type="number" id="difficulty" value="21" min="1">
<br><br>

<button id="mineButton" disabled>Mine & Publish</button>
<button id="mineButton" disabled>Mine & Publish</button>
<button id="cancelButton" disabled>Cancel Mining</button>

<h2>Hash Rate:</h2>
<pre id="hashrate">0 H/s</pre>
<h2>Result:</h2>
<pre id="result">Waiting for worker to initialize...</pre>

<code id="relayStatus"></code>
<pre id="relayStatus"></pre>

<button id="cancelButton" disabled>Cancel Mining</button>
<pre id="neventOutput"></pre>



<!-- Include main.js as a module -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
Expand Down
110 changes: 109 additions & 1 deletion demo/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ let pubs = []
//worker
const worker = new Worker('./worker.js', { type: 'module' });

const pointer = {}

//dom
const mineButton = document.getElementById('mineButton');
const eventInput = document.getElementById('eventInput');
Expand All @@ -26,6 +28,7 @@ const resultOutput = document.getElementById('result');
const hashrateOutput = document.getElementById('hashrate');
const cancelButton = document.getElementById('cancelButton');
const relayStatus = document.getElementById('relayStatus');
const neventOutput = document.getElementById('neventOutput');

let isWorkerReady = false;

Expand All @@ -49,7 +52,10 @@ worker.onmessage = function (e) {
resultOutput.textContent = 'Worker is ready. You can start mining.';
} else if (type === 'result') {
if (data.error) {
resultOutput.textContent = `Error: ${data.error}`;
resultOutput.textContent = ```
Error: ${data.error}
JSON.stringify(data, null, 2)
```;
} else {
try {
resultOutput.textContent = JSON.stringify(data, null, 2);
Expand All @@ -73,6 +79,9 @@ mineButton.addEventListener('click', () => {
const nostrEvent = generateEvent(content);
const difficulty = parseInt(difficultyInput.value, 10);

relayStatus.textContent = ''
neventOutput.textContent = ''

if (!content) {
alert('Please enter content for the Nostr event.');
return;
Expand Down Expand Up @@ -110,6 +119,85 @@ cancelButton.addEventListener('click', () => {
}
});

// const getPow = (hex) => {
// let count = 0;
// for (let i = 0; i < hex.length; i++) {
// const nibble = parseInt(hex[i], 16);
// if (nibble === 0) {
// count += 4;
// } else {
// let leadingZeros;
// switch (nibble) {
// case 0:
// leadingZeros = 4;
// break;
// case 1:
// case 2:
// case 4:
// case 8:
// leadingZeros = Math.clz32(nibble << 28) - 28;
// break;
// default:
// leadingZeros = Math.clz32(nibble << 28) - 28;
// break;
// }
// count += leadingZeros;
// break;
// }
// }
// return count;
// }

// const verifyPow = (event) => {
// const eventCopy = { ...event };
// delete eventCopy.id;
// const hash = window.NostrTools.getEventHash(eventCopy);
// let hashHex;
// if (typeof hash === 'string') {
// hashHex = hash;
// } else {
// hashHex = Array.from(new Uint8Array(hash))
// .map(b => b.toString(16).padStart(2, '0'))
// .join('');
// }
// const count = getPow(hashHex);
// const nonceTag = event.tags.find(tag => tag[0] === 'nonce');
// if (!nonceTag || nonceTag.length < 3) {
// return 0;
// }
// const targetDifficulty = parseInt(nonceTag[2], 10);
// return Math.min(count, targetDifficulty);
// }


const getPow = (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
}

const verifyPow = (event) => {
const hash = window.NostrTools.getEventHash(event)
console.log(`event hash ${hash}, event id: ${event.id}`)
const count = getPow(hash)
const nonceTag = event.tags.find(tag => tag[0] === 'nonce');
if (!nonceTag || nonceTag.length < 3) {
return 0
}
const targetDifficulty = parseInt(nonceTag[2], 10);
return Math.min(count, targetDifficulty)
}


const generateEvent = (content) => {
return {
Expand All @@ -120,7 +208,24 @@ const generateEvent = (content) => {
}
}

const generateNEvent = ( event ) => {
const { id, pubkey: author } = event;
const pointer = { id, pubkey, relays: RELAYS };
return window.NostrTools.nip19.neventEncode(pointer);
}

const publishEvent = async (ev) => {
const hash = window.NostrTools.getEventHash(ev)
// const diff = parseInt(difficultyInput.value, 10);
// const pow = getPow(ev);
const pow = verifyPow(ev)

if(!pow || getPow(ev.id) < pow) {
console.log(pow, diff)
console.log('verifyPow', verifyPow(ev), 'getPow', getPow(ev.id))
resultOutput.textContent = `Error: Invalid POW ${pow}<${diff}`;
return
}
console.log('Publishing event:', ev);
try {
ev = window.NostrTools.finalizeEvent(ev, secret);
Expand All @@ -130,12 +235,15 @@ const publishEvent = async (ev) => {
await Promise.allSettled(pubs);
showRelayStatus()
console.log('Event published successfully.');
neventOutput.textContent = generateNEvent(ev)
} catch (error) {
console.error('Error publishing event:', error);
resultOutput.textContent = `Error publishing event: ${error.message}`;
}
};

let settledCount = 0

const showRelayStatus = () => {
const settled = Array(pubs.length).fill(false);
const intervalId = setInterval(() => {
Expand Down
Loading

0 comments on commit bffde9a

Please sign in to comment.