Running Proof-of-Work Safely In The Browser

How bounded mining batches, cancellation, progress reporting, deterministic validation, and JavaScript/WebAssembly fallback keep a browser mining simulation responsive.

Engineering Lab

Running Proof-of-Work Safely In The Browser

Proof-of-Work mining is deliberately repetitive. A miner changes a nonce, hashes the block, checks the difficulty target, and repeats. Running that loop without boundaries will freeze a browser interface.

An educational simulation therefore needs two kinds of correctness: correct mining behavior and correct interaction behavior.

Use Bounded Mining Batches

Instead of running until a valid nonce is found, process a fixed number of attempts and yield control back to the browser.

typescriptasync function mineInBatches(block: Block, batchSize = 5000) {
  while (!matchesDifficulty(block.hash, block.difficulty)) {
    for (let attempt = 0; attempt < batchSize; attempt += 1) {
      block.nonce += 1;
      block.hash = calculateHash(block);

      if (matchesDifficulty(block.hash, block.difficulty)) return block;
    }

    await new Promise((resolve) => setTimeout(resolve, 0));
  }
}

Yielding allows React to paint progress, process cancellation, and keep navigation usable.

Cancellation Must Be Part Of The Engine

A cancel button is not enough if the mining loop never checks cancellation state. The engine should inspect an abort signal between batches and return a clear cancelled result.

This keeps UI state separate from mining logic while preserving user control.

Validate From Chain Data

Wallet balances should be derived from confirmed transactions, not trusted as mutable fields. Chain validation should recompute:

  • block hashes
  • previous-hash links
  • difficulty targets
  • transaction effects
  • mining rewards

This makes tamper detection visible and deterministic.

Treat WebAssembly As An Optional Engine

A C++ WebAssembly miner can improve throughput, but the simulation should not depend on it. A JavaScript fallback keeps the system portable and makes engine behavior comparable through benchmarks.

The application should report which engine is active instead of hiding that implementation detail.

Engineering Outcome

The browser is not only a visualization surface. It is a constrained compute environment. Bounded work, explicit cancellation, deterministic validation, and fallback execution make compute-heavy simulations understandable without sacrificing responsiveness.