Introduction
The blockchain hash chain was invented by Stuart Haber and Scott Stornetta in their 1991 paper "How to Time-Stamp a Digital Document" published in the Journal of Cryptology, where they proposed linking documents together by including the hash of the previous document in the hash input of the next document, so that any modification to a past document would cascade into a different hash for every subsequent document. Satoshi Nakamoto reused this exact construction in the 2008 Bitcoin white paper to link blocks of transactions together, and the same idea backs every chain-of-custody log, every certificate transparency log, and every git commit graph. A Java learner should care because the hash chain is the smallest possible introduction to tamper-evident logs and because it exercises the MessageDigest API in a non-trivial loop.
This tutorial builds a tiny blockchain in Java. Each block contains an index, a timestamp, a payload, a previous-hash reference, and a self-hash computed over all four of those fields. The chain is a List of blocks; tampering with any past block invalidates every block that follows it. The program demonstrates both the honest chain and the broken chain after a tamper attempt.
What is a Blockchain Hash Chain?
A blockchain hash chain is a sequence of blocks where each block stores the cryptographic hash of the previous block as one of its fields. The first block is called the genesis block and stores an all-zero previous-hash. The chain is tamper-evident because changing any block's data changes its self-hash, which changes the previous-hash stored in the next block, which changes that block's self-hash, and so on cascading to the end of the chain. To verify a chain, a validator walks from genesis to the latest block, recomputes each block's self-hash from its fields, and checks both that the recomputed hash matches the stored self-hash and that the previous-hash field matches the previous block's self-hash.
The hash chain is the simplest form of tamper-evident log; it provides integrity over the entire history of the log without requiring the validator to recompute every historical operation. It is also the fundamental data structure that backs Bitcoin, Ethereum, Hyperledger Fabric, and every other distributed ledger. In Bitcoin the blocks also include a proof-of-work nonce (see the Proof of Work tutorial), and the chain is replicated across thousands of nodes that agree on the longest chain by majority vote.
The hash chain provides tamper-evidence but not Byzantine fault tolerance. A single node can rewrite the chain at will; the chain only becomes trustworthy when it is either widely replicated (Bitcoin) or anchored in an external trust anchor (the Bitcoin blockchain's periodic embedding of the latest hash into the Bitcoin blockchain is how the certificate transparency log anchors itself).
How the Blockchain Hash Chain Works - Step by Step
Step 1: Genesis block. Block 0 has index 0, an empty or hardcoded payload such as "Genesis Block", a timestamp, a previous-hash of 64 zero characters (representing SHA-256 of nothing), and a self-hash computed as SHA-256(index || timestamp || payload || previousHash).
Step 2: Append a block. Block 1 has index 1, a payload such as "Alice pays Bob 5 BTC", a timestamp, a previousHash equal to the self-hash of block 0, and a self-hash computed as SHA-256(1 || timestamp || payload || previousHash). Block 2 follows the same recipe with previousHash equal to the self-hash of block 1.
Step 3: Verify the chain. Walk the list from index 0 to the latest. For each block, recompute the self-hash from (index, timestamp, payload, previousHash). Compare the recomputed self-hash to the stored selfHash field. Compare the previousHash field to the previous block's selfHash field. If any comparison fails, the chain is broken at that block.
Step 4: Tamper. Suppose an attacker modifies the payload of block 1 from "Alice pays Bob 5 BTC" to "Alice pays Bob 5000 BTC" to enrich themselves. The recomputed self-hash of block 1 changes because the payload field changed. Block 2's previousHash field, which still holds the old selfHash of block 1, no longer matches the recomputed selfHash of block 1, so block 2 fails the comparison. Block 3 fails because block 2's selfHash changed too, and the cascade continues to the end of the chain.
Step 5: Re-mine. To make the tamper undetectable, the attacker would have to recompute the selfHash of block 1, then update block 2's previousHash to the new value and recompute block 2's selfHash, and so on for every block to the end of the chain. In Bitcoin this is made computationally expensive by the proof-of-work requirement that the selfHash start with a certain number of zero bits, which means the attacker must redo the proof-of-work for every block they want to rewrite. That is the Nakamoto consensus mechanism.
Java Program for Blockchain Hash Chain
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
public class BlockchainHashChainDemo {
static class Block {
int index;
long timestamp;
String payload;
String previousHash;
String selfHash;
Block(int index, long timestamp, String payload, String previousHash) {
this.index = index;
this.timestamp = timestamp;
this.payload = payload;
this.previousHash = previousHash;
this.selfHash = computeHash();
}
String computeHash() {
String input = index + ":" + timestamp + ":"
+ payload + ":" + previousHash;
return sha256Hex(input);
}
}
static List<Block> chain = new ArrayList<>();
public static void main(String[] args) throws Exception {
// Step 1: create genesis block.
chain.add(new Block(0, Instant.now().getEpochSecond(),
"Genesis Block", "0".repeat(64)));
System.out.println("==> Genesis block");
printBlock(chain.get(0));
// Step 2: append three blocks.
chain.add(makeBlock("Alice pays Bob 5 IMC"));
chain.add(makeBlock("Bob pays Carol 3 IMC"));
chain.add(makeBlock("Carol pays Dave 1 IMC"));
System.out.println("\n==> Full chain");
for (Block b : chain) {
printBlock(b);
}
// Step 3: verify the honest chain.
System.out.println("\n==> Verifying honest chain");
boolean ok = verifyChain(chain);
System.out.println(" Valid: " + ok);
// Step 4: tamper with block 1's payload.
System.out.println("\n==> Tampering with block 1 payload");
chain.get(1).payload = "Alice pays Bob 5000 IMC";
System.out.println(" Old selfHash of block 1 unchanged in memory; "
+ "recompute needed.");
boolean okAfterTamper = verifyChain(chain);
System.out.println(" Valid after tamper: " + okAfterTamper);
// Step 5: re-mine the tampered block and cascade.
System.out.println("\n==> Attacker re-mines the chain");
for (int i = 1; i < chain.size(); i++) {
Block prev = chain.get(i - 1);
Block curr = chain.get(i);
curr.previousHash = prev.selfHash;
curr.selfHash = curr.computeHash();
}
System.out.println(" After re-mining, the chain is internally "
+ "consistent again.");
boolean okAfterRemine = verifyChain(chain);
System.out.println(" Valid after re-mine: " + okAfterRemine);
System.out.println(" But in Bitcoin this would require redoing the "
+ "proof-of-work for every block, which is the security "
+ "guarantee of the Nakamoto consensus.");
}
static Block makeBlock(String payload) {
Block prev = chain.get(chain.size() - 1);
return new Block(prev.index + 1,
Instant.now().getEpochSecond(), payload, prev.selfHash);
}
static void printBlock(Block b) {
System.out.printf(" #%d prev=%s...%n", b.index,
b.previousHash.substring(0, 12));
System.out.printf(" self=%s...%n", b.selfHash.substring(0, 12));
System.out.printf(" payload: %s%n", b.payload);
}
static boolean verifyChain(List<Block> chain) {
for (int i = 0; i < chain.size(); i++) {
Block b = chain.get(i);
String recomputed = b.computeHash();
if (!recomputed.equals(b.selfHash)) {
System.out.printf(" Block %d selfHash mismatch: "
+ "stored=%s..., recomputed=%s...%n",
b.index,
b.selfHash.substring(0, 12),
recomputed.substring(0, 12));
return false;
}
if (i > 0) {
Block prev = chain.get(i - 1);
if (!b.previousHash.equals(prev.selfHash)) {
System.out.printf(" Block %d previousHash does not match "
+ "block %d selfHash%n", b.index, prev.index);
return false;
}
} else {
if (!b.previousHash.equals("0".repeat(64))) {
System.out.println(" Genesis previousHash not zero");
return false;
}
}
}
return true;
}
static String sha256Hex(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
StringBuilder sb = new StringBuilder();
for (byte b : hash) {
sb.append(String.format("%02x", b & 0xff));
}
return sb.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Code Explanation - Line by Line
The Block class is a plain Java POJO with the five fields that every blockchain block carries: index (block height), timestamp (epoch seconds), payload (the data the block records), previousHash (link to the parent), and selfHash (the cryptographic seal over the other four fields). The constructor calls computeHash() so the selfHash is computed exactly once at block creation; later recomputations compare against this stored value.
computeHash() concatenates the four input fields with a colon separator and feeds the resulting string to sha256Hex(). The colon prevents the concatenation ambiguity where (12, 3) and (1, 23) would both produce "123"; with separators they become "12:3" and "1:23", which hash differently.
The main() method creates the genesis block with a hardcoded all-zero previousHash (because there is no previous block to reference), then appends three blocks through makeBlock(). The makeBlock() helper reads the last block in the chain, increments its index, and uses its selfHash as the new block's previousHash. This is the canonical chain-extension algorithm used by every blockchain client.
verifyChain() is the heart of the tamper-evidence demo. It walks every block in order, recomputes the selfHash from the four input fields, and compares the recomputed value to the stored selfHash. If they match, the block's contents have not been modified since the selfHash was computed. The second check verifies that the previousHash field of the current block equals the selfHash field of the previous block, which is the chain integrity check. If either check fails, the chain is broken at that block and verifyChain() returns false.
The tamper step modifies block 1's payload in memory without re-computing its selfHash. On the next verifyChain() call, the recomputed selfHash of block 1 will differ from the stored selfHash, and the chain breaks. The re-mine step simulates what an attacker would do to repair the chain: walk from the tampered block to the end, update each block's previousHash to the previous block's selfHash, and recompute the selfHash. After re-mining, the chain is internally consistent again, which is exactly why Bitcoin requires proof-of-work: re-mining is cheap without the puzzle, so the security guarantee must come from the proof-of-work difficulty.
Sample Input and Output
==> Genesis block
#0 prev=000000000000...
self=4d2a...8c3b...
payload: Genesis Block
==> Full chain
#0 prev=000000000000...
self=4d2a...8c3b...
payload: Genesis Block
#1 prev=4d2a...8c3b...
self=7f1c...2e9d...
payload: Alice pays Bob 5 IMC
#2 prev=7f1c...2e9d...
self=a83b...1f0c...
payload: Bob pays Carol 3 IMC
#3 prev=a83b...1f0c...
self=b62f...45a8...
payload: Carol pays Dave 1 IMC
==> Verifying honest chain
Valid: true
==> Tampering with block 1 payload
Old selfHash of block 1 unchanged in memory; recompute needed.
Block 1 selfHash mismatch: stored=7f1c..., recomputed=9e5a...
Valid after tamper: false
==> Attacker re-mines the chain
After re-mining, the chain is internally consistent again.
Valid after re-mine: true
But in Bitcoin this would require redoing the proof-of-work for every block,
which is the security guarantee of the Nakamoto consensus.
The output demonstrates that any single-byte modification of a past block cascades through the entire chain and is detected by the verifyChain() walk. The re-mine step proves that the hash chain alone provides tamper-evidence but not tamper-resistance; tamper-resistance requires the proof-of-work difficulty on top of the hash chain.
Common Mistakes to Avoid
First, do not use a fast hash like MurmurHash or xxHash for a blockchain; those are non-cryptographic and are designed to be invertible. The whole point of the chain is that an attacker cannot easily find a payload that produces a target selfHash, which requires SHA-256, SHA-3, or BLAKE2 with a 256-bit output. Second, do not forget to include the index in the hash input; without the index, two blocks with the same payload and timestamp would have the same selfHash, which would let an attacker swap blocks in a chain. Third, do not trust the stored selfHash; always recompute it from the other four fields and compare. The stored selfHash is the data the attacker can modify; the recomputed selfHash is the truth. Finally, do not concatenate fields without a separator; the "12" + "3" and "1" + "23" ambiguity is a real bug that has been observed in production audit-log code.
Real-World Applications
Bitcoin blocks link to each other through the previous-block-hash field of the 80-byte block header, and the entire 600-GiB chain is verified by every full node on the network every time it syncs. Ethereum blocks link through the parent-hash field of the block header and add a state-root Merkle root that lets light clients verify account balances without downloading the entire chain. Hyperledger Fabric uses the same hash-chain construction for its blocks and adds Raft-based consensus for the orderer nodes. Git commits link to their parents through the parent field of the commit object; the commit hash is a SHA-1 hash over the entire commit content including the parent reference, which is why rewriting history in a public git repo is detectable unless the attacker can force-push the rewrite.
Certificate Transparency logs (RFC 6962) maintain an append-only hash chain of every TLS certificate issued by participating CAs, and the log periodically anchors its latest hash into the Bitcoin blockchain so that the entire CT log is tamper-evident even against the log operator. The hash chain is also the basic building block of academic timestamping services such as Surety's AbsoluteProof which has been anchoring documents to Bitcoin weekly since 1995 (originally to newspaper classified ads).
Conclusion
We saw that a blockchain hash chain links blocks together by including the previous block's hash in the next block's hash input, which makes the chain tamper-evident because a single-byte change to any block invalidates every block after it. Next, study the Merkle Tree tutorial to learn how to compactly commit to a large number of leaf transactions inside a single block, then read the Proof of Work tutorial to see how the chain becomes tamper-resistant.
Comments
Comments
Post a Comment