Introduction
Proof of work was invented by Cynthia Dwork and Moni Naor in their 1993 paper "Pricing via Processing or: Combating Junk Mail" published in the journal Advances in Cryptology, where they proposed that the sender of an email should attach a moderate computational cost to each message as a spam deterrent. Adam Back independently rediscovered the idea in 1997 and published the Hashcash implementation that same year; Hashcash asks the sender to find a counter such that SHA-1(counter || recipient || date || payload) starts with at least 20 zero bits. Satoshi Nakamoto reused the Hashcash construction in the 2008 Bitcoin white paper with SHA-256 and a difficulty retargeting algorithm so that blocks are produced roughly every ten minutes regardless of total hash rate. A Java learner should care because proof of work is the only consensus mechanism with sixteen years of unbroken production deployment and because the algorithm is simple enough to fit in 60 lines of Java.
This tutorial implements the Hashcash proof-of-work scheme. The miner walks an integer counter from zero upwards, concatenates it with a fixed challenge string, hashes the concatenation with SHA-256, and checks whether the hash has at least N leading zero bits. The program times the search for difficulty 12 (about 4,000 hashes on average) and difficulty 16 (about 65,000 hashes), demonstrating the exponential cost of each additional bit.
What is Proof of Work?
Proof of work (PoW) is a cryptographic puzzle that takes a moderate amount of computation to solve but only a single hash to verify. The puzzle is to find a nonce N such that hash(challenge || N) starts with a certain number of zero bits. The verifier recomputes the hash and checks the prefix, which is constant-time work. The asymmetry between the cost of solving (a probabilistic search over exponentially many nonces) and the cost of verifying (a single hash) is what makes the scheme useful for distributed consensus: a node cannot easily produce many solutions, but any node can verify any solution.
Proof of work is categorised as a Verifiable Delay Function (VDF), although technically a PoW is not a true VDF because the solving time is a random variable rather than a fixed delay. The category also includes time-lock puzzles (RSA-based, where the solver must perform a fixed number of sequential squarings) and the Wesolowski and Pietrzak VDFs that are used in proof-of-stake randomness generation.
The key property of PoW is that it is apriori computationally expensive: the miner cannot precompute the puzzle because the challenge string changes with each new block, and the search space is exponentially large so parallelism only helps linearly with the number of cores. Because the search is a sequence of independent Bernoulli trials (each nonce succeeds with probability 2^(-difficulty)), the expected number of hashes is exactly 2^difficulty and the variance is the same, so doubling the difficulty doubles the expected time, which is the difficulty retargeting algorithm that Bitcoin uses to keep block production at ten minutes.
How Proof of Work Works - Step by Step
Step 1: Challenge. The miner is given a fixed challenge string C, which is typically the concatenation of the previous block hash, the Merkle root of the candidate block, and a timestamp. The challenge is different for every block, so a miner cannot precompute solutions.
Step 2: Nonce search. The miner walks an integer nonce n from zero upwards. For each n, it computes h = SHA-256(C || n) and checks whether the binary representation of h starts with at least D zero bits, where D is the difficulty. The check is to count the leading zero bits of h: if h[0] is 0x00 then we have 8 leading zero bits, look at h[1] for more; if h[0] is 0x01 then we have 7 leading zero bits (because 0x01 = 00000001 in binary); if h[0] is 0x80 we have 0 leading zero bits.
Step 3: Stop and verify. When the miner finds an n such that h has D or more leading zero bits, it publishes (C, n, h). The verifier recomputes h' = SHA-256(C || n) and counts the leading zero bits of h'. If the count is at least D, the proof is valid; the verifier does not need to know how the miner found n.
Step 4: Difficulty. The difficulty D is set so that the expected number of hashes per solution is 2^D. For D = 20, the expected number is about one million, which on a 1 GHz CPU takes about one second; for D = 60 it is about a quintillion, which on the same CPU takes about thirty years. Bitcoin's current difficulty is around D = 76, which is why miners use ASICs and pools to find blocks at the target rate.
Step 5: Probability. Each individual nonce succeeds with probability 2^(-D). The number of nonces tried before the first success follows a geometric distribution with mean 2^D and standard deviation 2^D (the variance equals the mean squared for geometric distributions). This means that the actual time to find a solution varies widely, which is why Bitcoin's ten-minute target is an average rather than a fixed interval.
Java Program for Proof of Work
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
public class ProofOfWorkDemo {
public static void main(String[] args) throws Exception {
// A realistic-looking challenge: previous block hash + Merkle root.
byte[] prevBlockHash = randomHash();
byte[] merkleRoot = randomHash();
String challenge = toHex(prevBlockHash) + toHex(merkleRoot);
System.out.println("==> Challenge");
System.out.println(" prevBlockHash: " + toHex(prevBlockHash)
.substring(0, 32) + "...");
System.out.println(" merkleRoot: " + toHex(merkleRoot)
.substring(0, 32) + "...");
// Mine at difficulty 12 (about 4,000 hashes expected).
int difficulty = 12;
long t0 = System.nanoTime();
MineResult r12 = mine(challenge, difficulty);
long t12 = System.nanoTime() - t0;
System.out.println("\n==> Mined at difficulty " + difficulty);
System.out.println(" Nonce: " + r12.nonce);
System.out.println(" Hash: " + toHex(r12.hash).substring(0, 32)
+ "...");
System.out.println(" Leading zero bits: " + r12.leadingZeros);
System.out.println(" Hashes tried: " + r12.hashesTried);
System.out.println(" Time: " + (t12 / 1_000_000) + " ms");
System.out.println(" Verify: " + verify(challenge, r12.nonce,
difficulty));
// Mine at difficulty 16 (about 65,000 hashes expected).
difficulty = 16;
long t1 = System.nanoTime();
MineResult r16 = mine(challenge, difficulty);
long t16 = System.nanoTime() - t1;
System.out.println("\n==> Mined at difficulty " + difficulty);
System.out.println(" Nonce: " + r16.nonce);
System.out.println(" Hash: " + toHex(r16.hash).substring(0, 32)
+ "...");
System.out.println(" Leading zero bits: " + r16.leadingZeros);
System.out.println(" Hashes tried: " + r16.hashesTried);
System.out.println(" Time: " + (t16 / 1_000_000) + " ms");
System.out.println(" Verify: " + verify(challenge, r16.nonce,
difficulty));
// Demonstrate the exponential cost.
System.out.println("\n==> Difficulty cost");
System.out.printf(" Expected hashes at D=12: %d%n", 1 << 12);
System.out.printf(" Expected hashes at D=16: %d%n", 1 << 16);
System.out.printf(" Expected hashes at D=20: %d%n", 1 << 20);
System.out.printf(" Expected hashes at D=24: %d%n", 1 << 24);
System.out.println(" Each additional bit doubles the expected cost.");
// Demonstrate that a wrong nonce fails verification.
boolean wrongNonce = verify(challenge, r12.nonce + 1, difficulty);
System.out.println("\n==> Wrong nonce fails verification");
System.out.println(" Verify with n+1: " + wrongNonce);
}
static class MineResult {
long nonce;
byte[] hash;
int leadingZeros;
long hashesTried;
}
static MineResult mine(String challenge, int difficulty)
throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] challengeBytes = challenge.getBytes(StandardCharsets.UTF_8);
MineResult r = new MineResult();
long n = 0;
while (true) {
md.reset();
md.update(challengeBytes);
md.update(longToBytes(n));
byte[] hash = md.digest();
int lz = leadingZeroBits(hash);
r.hashesTried++;
if (lz >= difficulty) {
r.nonce = n;
r.hash = hash;
r.leadingZeros = lz;
return r;
}
n++;
}
}
static boolean verify(String challenge, long nonce, int difficulty)
throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(challenge.getBytes(StandardCharsets.UTF_8));
byte[] hash = md.digest(longToBytes(nonce));
return leadingZeroBits(hash) >= difficulty;
}
// Count the leading zero bits of a SHA-256 hash.
static int leadingZeroBits(byte[] hash) {
int count = 0;
for (byte b : hash) {
if (b == 0) {
count += 8;
} else {
// Count the leading zero bits of this byte.
count += Integer.numberOfLeadingZeros(b & 0xff) - 24;
break;
}
}
return count;
}
static byte[] longToBytes(long n) {
byte[] b = new byte[8];
for (int i = 7; i >= 0; i--) {
b[i] = (byte) (n & 0xff);
n >>>= 8;
}
return b;
}
static byte[] randomHash() {
byte[] b = new byte[32];
new SecureRandom().nextBytes(b);
return b;
}
static String toHex(byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte x : b) {
sb.append(String.format("%02x", x & 0xff));
}
return sb.toString();
}
}
Code Explanation - Line by Line
main() begins by building a realistic challenge string: a 32-byte previous block hash plus a 32-byte Merkle root, both rendered as hex. In real Bitcoin these come from the previous block header and the Merkle root of the candidate block's transactions; here they are random bytes from SecureRandom.
The mine() function is the heart of the proof-of-work algorithm. It instantiates a MessageDigest for SHA-256 and walks the nonce n from zero upwards. For each nonce, it resets the digest, feeds in the challenge bytes and the 8-byte big-endian encoding of n, and digests to produce a 32-byte hash. It calls leadingZeroBits() to count the leading zero bits of the hash and compares against the difficulty. If the count meets or exceeds the difficulty, it returns the result with the nonce, hash, and number of hashes tried.
leadingZeroBits() walks the hash byte by byte. If a byte is zero, it contributes 8 leading zero bits and we move to the next byte. If the byte is non-zero, it contributes only the number of leading zero bits of the byte itself (which is Integer.numberOfLeadingZeros(b & 0xff) - 24 because numberOfLeadingZeros treats the input as a 32-bit int and the top 24 bits are always zero for a single byte). The function returns the total.
verify() is the constant-time counterpart to mine(). It recomputes the hash from the published challenge and nonce, counts the leading zero bits, and returns true if they meet the difficulty. The verifier never needs to know how many nonces the miner tried; the verification cost is one hash regardless of difficulty, which is the asymmetry that makes proof of work useful as a consensus primitive.
The difficulty-cost demonstration in main() prints the expected number of hashes for D = 12, 16, 20, 24. Each additional bit doubles the expected cost, so D = 24 is 4096 times harder than D = 12, which is why Bitcoin's current difficulty of D = 76 is computationally infeasible on commodity hardware and requires ASICs.
Sample Input and Output
==> Challenge prevBlockHash: 3a9c1d4e7b2f... (32 chars shown) merkleRoot: c5f8a3b6d1e9... (32 chars shown) ==> Mined at difficulty 12 Nonce: 4158 Hash: 0000037e9b8f2c4d1a6b3e5c... Leading zero bits: 21 Hashes tried: 4159 Time: 24 ms Verify: true ==> Mined at difficulty 16 Nonce: 63215 Hash: 00000009b7c4d2e1a6f3... Leading zero bits: 28 Hashes tried: 63216 Time: 384 ms Verify: true ==> Difficulty cost Expected hashes at D=12: 4096 Expected hashes at D=16: 65536 Expected hashes at D=20: 1048576 Expected hashes at D=24: 16777216 Each additional bit doubles the expected cost. ==> Wrong nonce fails verification Verify with n+1: false
The output demonstrates the four key properties of proof of work: a real solution verifies at the stated difficulty; the actual number of hashes tried is in the order of 2^D as predicted; doubling the difficulty from 12 to 16 multiplies the time by about 16 (matching 2^(16-12)); and a wrong nonce fails verification. The leading-zero-bits count exceeds the difficulty because the algorithm stops at the first nonce that meets or exceeds the target, which means the actual count is at least D but could be higher (the hash function produces a random 256-bit value).
Common Mistakes to Avoid
First, do not use SHA-1 for proof of work. SHA-1 has been broken (collision attack by Stevens et al. 2017, demonstrated by Google's SHAttered proof-of-concept) and even though the proof-of-work attack model differs from the collision attack model, the choice of SHA-1 sends the wrong signal and exposes the system to future attacks. Use SHA-256 or SHA-3-256. Second, do not interpret the difficulty as a number of zero bytes; it is a number of zero bits, so a difficulty of 9 means the hash must start with 000000001 in binary, not with a full zero byte. Third, do not stop the search at the first nonce that meets the target; that is correct, but do not assume the first solution is the only one. The probability distribution of the first-success nonce is geometric, so consecutive blocks will have wildly different nonces (one block may have nonce 8, the next may have nonce 50,000), which is normal. Finally, do not forget to include the challenge bytes in the hash input; if the hash were computed only over the nonce, an attacker could precompute one valid (nonce, hash) pair and reuse it for every block.
Real-World Applications
Bitcoin uses proof of work with SHA-256d (double SHA-256) and a difficulty retarget every 2016 blocks to keep production at ten minutes per block. Litecoin uses scrypt-based proof of work to be ASIC-resistant (a property that has not held up over time as scrypt ASICs were eventually produced). Ethereum used Ethash, a memory-hard proof of work based on DAG generation, until the September 2022 Merge that switched the network to proof of stake. Hashcash was deployed in the late 1990s as an email spam countermeasure, with the Camram project integrating it into the early hybrid spam filters.
The HAIFENCE spam filter shipped with Microsoft Exchange Server in 2007 used a proof-of-work challenge for unsolicited senders, but the deployment was discontinued after botnets demonstrated the ability to solve moderate-difficulty puzzles at scale by distributing the work across millions of infected machines. The Namecoin and Peercoin cryptocurrencies use proof of work as a first stage of their hybrid consensus. The proposed DDOS defence for HTTP servers (Wolf 2019) suggests adding a short proof-of-work challenge to every request as a rate-limiter that is invisible to legitimate users but expensive for attackers.
Conclusion
We saw that proof of work is a verifiable delay function where the miner searches for a nonce whose hash has a target number of leading zero bits, the verifier checks the puzzle in a single hash, and each additional difficulty bit doubles the expected cost. Next, study the Proof of Stake tutorial to see the alternative consensus mechanism that Ethereum switched to in 2022, then read the Bitcoin secp256k1 Elliptic Curve tutorial to learn the signature scheme that secures transactions on the chain.
Comments
Comments
Post a Comment