Skip to content

Commit

Permalink
cancel kinda sorta works now, when a note is mined the miners stop. t…
Browse files Browse the repository at this point in the history
…hat's good I guess :D
  • Loading branch information
dskvr committed Sep 14, 2024
1 parent 39350da commit 33178ea
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 10 deletions.
4 changes: 2 additions & 2 deletions demo/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
<script src="https://unpkg.com/nostr-tools/lib/nostr.bundle.js"></script>
</head>
<body>
<h1><code>️ notemine</code></h1>
<h1><code>️notemine</code></h1>

<p>this is a demo of notemine, a wasm nostr note miner written in rust. </p>

Expand Down Expand Up @@ -73,7 +73,7 @@ <h1><code>⛏️ notemine</code></h1>
<br><br>

<label for="difficulty"># of workers:</label>
<input type="number" id="numberOfWorkers" value="21" min="1">
<input type="number" id="numberOfWorkers" min="1" max="">
<br><br>

<button id="mineButton" disabled>Mine & Publish</button>
Expand Down
7 changes: 7 additions & 0 deletions demo/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,14 @@ ${JSON.stringify(data, null, 2)}
}
hashrateOutput.textContent = '0 H/s';
mineButton.disabled = false;
cancelButton.disabled = true; // Disable the cancel button
isMining = false;
workerHashRates = {}; // Reset hash rates after mining
} else if (type === 'error') {
resultOutput.textContent = `Error: ${error}`;
hashrateOutput.textContent = '0 H/s';
mineButton.disabled = false;
cancelButton.disabled = true; // Disable the cancel button
isMining = false;
workerHashRates = {}; // Reset hash rates on error
}
Expand All @@ -89,6 +91,8 @@ function cancelOtherWorkers(excludeWorkerId) {
});
}



mineButton.addEventListener('click', () => {
if (isMining) return;

Expand Down Expand Up @@ -120,6 +124,7 @@ mineButton.addEventListener('click', () => {
const event = JSON.stringify(nostrEvent);

mineButton.disabled = true;
cancelButton.disabled = false; // Enable the cancel button
resultOutput.textContent = 'Mining in progress...';
hashrateOutput.textContent = '0 H/s';
isMining = true;
Expand All @@ -142,11 +147,13 @@ cancelButton.addEventListener('click', () => {
resultOutput.textContent = 'Mining cancellation requested.';
hashrateOutput.textContent = '0 H/s';
mineButton.disabled = false;
cancelButton.disabled = true; // Disable the cancel button
isMining = false;
workerHashRates = {}; // Reset hash rates after cancellation
}
});


const getPow = (hex) => {
let count = 0;

Expand Down
18 changes: 14 additions & 4 deletions demo/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import init, { mine_event } from './pkg/notemine.js';
let wasm;
let mining = false;
let workerId;
let miningCancelled = false;

async function initWasm() {
try {
Expand All @@ -17,27 +18,36 @@ function reportProgress(hashRate) {
postMessage({ type: 'progress', hashRate, workerId });
}

function shouldCancel() {
return miningCancelled;
}

self.onmessage = async function (e) {
const { type, event, difficulty, id } = e.data;
if (type === 'init') {
workerId = id;
initWasm();
} else if (type === 'mine' && !mining) {
miningCancelled = false; // Reset cancellation flag
mining = true;
try {
if (typeof event !== 'string') {
throw new Error('Event must be a stringified JSON.');
}
const minedResult = mine_event(event, difficulty, reportProgress);
const minedResult = mine_event(event, difficulty, reportProgress, shouldCancel);
postMessage({ type: 'result', data: minedResult, workerId });
} catch (error) {
postMessage({ type: 'error', error: error.message, workerId });
if (error.message !== 'Mining cancelled.') {
postMessage({ type: 'error', error: error.message, workerId });
} else {
console.log('Mining was cancelled.');
postMessage({ type: 'cancelled', workerId });
}
} finally {
mining = false;
}
} else if (type === 'cancel' && mining) {
console.log('Mining cancellation requested.');
// Implement cancellation logic if possible
mining = false;
miningCancelled = true;
}
};
24 changes: 20 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,9 @@ pub fn mine_event(
event_json: &str,
difficulty: u32,
report_progress: JsValue,
should_cancel: JsValue,
) -> JsValue {

let mut event: NostrEvent = match serde_json::from_str(event_json) {
Ok(e) => e,
Err(err) => {
Expand Down Expand Up @@ -130,8 +132,9 @@ pub fn mine_event(
let mut nonce: u64 = 0;
let mut total_hashes: u64 = 0;

let report_interval = 100_000;
let report_interval = 200_000;
let mut last_report_time = start_time;
let should_cancel = should_cancel.dyn_into::<Function>().ok();

loop {
if let Some(index) = nonce_index {
Expand Down Expand Up @@ -175,6 +178,19 @@ pub fn mine_event(

nonce += 1;

if let Some(ref should_cancel) = should_cancel {
if nonce % 10_000 == 0 {
let cancel = should_cancel.call0(&JsValue::NULL).unwrap_or(JsValue::FALSE);
if cancel.is_truthy() {
console::log_1(&"Mining cancelled.".into());
return serde_wasm_bindgen::to_value(&serde_json::json!({
"error": "Mining cancelled."
}))
.unwrap_or(JsValue::NULL);
}
}
}

if nonce % report_interval == 0 {
let current_time = js_sys::Date::now();
let elapsed_time = (current_time - last_report_time) / 1000.0;
Expand All @@ -192,9 +208,9 @@ pub fn mine_event(
}
}

if nonce % 100_000 == 0 {
console::log_1(&format!("Checked nonce up to: {}", nonce).into());
}
// if nonce % report_interval == 0 {
// console::log_1(&format!("Checked nonce up to: {}", nonce).into());
// }
}
}

Expand Down

0 comments on commit 33178ea

Please sign in to comment.