Let's think about this for a second
In this project we'll take the block, hashing, and immutability concepts you learned in the Basic chapter and actually wire them together in real code. In real blockchains like Bitcoin and Ethereum, each block's hash gets stored in the next block's previousHash field, linking them into a chain. To really understand this mechanism, we'll compute a SHA256 hash directly with Node.js's built-in crypto module and write our own Block class. This part covers building the Block class and getting the Blockchain class's genesis block started — transactions and mining come in the next part.
Let's build it
Open a new project folder and create a blockchain.js file. Require the crypto module as a built-in (no npm install needed). Give the Block class an index, timestamp, data, previousHash, and hash field, and inside the calculateHash() method, hash index+previousHash+timestamp+JSON.stringify(data) with SHA256. In the Blockchain class, initialize the chain array with createGenesisBlock() and add a getLatestBlock() method. Finally, print the genesis block with console.log(JSON.stringify(myChain, null, 2)).
Code Example
const crypto = require('crypto');
class Block {
constructor(index, timestamp, data, previousHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash();
}
calculateHash() {
return crypto
.createHash('sha256')
.update(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data))
.digest('hex');
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, Date.now(), 'Genesis Block', '0');
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
}
const myChain = new Blockchain();
console.log(JSON.stringify(myChain, null, 2));
Running node blockchain.js will print the chain array to the terminal, showing one genesis block with its hash value in hex string format, formatted as JSON.5-Minute Try-It
Change the genesis block's data field from 'Genesis Block' to 'genesis block' (just switching one letter to lowercase) and run it again — spend 5 minutes noticing how the entire hash value comes out completely different.
A Quick Word of Caution
This is purely a learning simulation — a real blockchain only confirms a block after consensus is reached across many distributed nodes, so this single-file version should never be used in production.