Articles → Blockchain → Create Your First Blockchain Program In Javascript
Create Your First Blockchain Program In Javascript
Software Requirement
Crypto-Js Installation
npm install crypto-js --save
Click to Enlarge
Click to Enlarge
Example
- Create a block class
- Create a blockchain class
- Add block into the block chain
- Display the blockchain
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, previousHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data));
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, '02/05/2020', 'Genesis Block', "0");
}
getlatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getlatestBlock().previousHash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
}
let demoChain = new Blockchain();
demoChain.addBlock(
new Block(1, '02/05/2020', {
amount: 10
}));
demoChain.addBlock(
new Block(2, '02/05/2020', {
amount: 25
}));
console.log(JSON.stringify(demoChain));
Output
Click to Enlarge
Full Code
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, previousHash) {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
}
calculateHash() {
return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data));
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, '02/05/2020', 'Genesis Block', "0");
}
getlatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.previousHash = this.getlatestBlock().previousHash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
}
let demoChain = new Blockchain();
demoChain.addBlock(
new Block(1, '02/05/2020', {
amount: 10
}));
demoChain.addBlock(
new Block(2, '02/05/2020', {
amount: 25
}));
console.log(JSON.stringify(demoChain));