How to Create a Simple Cryptocurrency Blockchain Using JavaScript?

Estimated read time 2 min read

Here’s a simple example of how you could create a cryptocurrency blockchain in JavaScript:

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;
    this.hash = this.calculateHash();
  }

  calculateHash() {
    return SHA256(
      this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)
    ).toString();
  }
}

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];
  }

  addBlock(newBlock) {
    newBlock.previousHash = this.getLatestBlock().hash;
    newBlock.hash = newBlock.calculateHash();
    this.chain.push(newBlock);
  }

  isChainValid() {
    for (let i = 1; i < this.chain.length; i++) {
      const currentBlock = this.chain[i];
      const previousBlock = this.chain[i - 1];

      if (currentBlock.hash !== currentBlock.calculateHash()) {
        return false;
      }

      if (currentBlock.previousHash !== previousBlock.hash) {
        return false;
      }
    }
    return true;
  }
}

// Example usage:
const myCoin = new Blockchain();

myCoin.addBlock(new Block(1, Date.now(), { amount: 4 }));
myCoin.addBlock(new Block(2, Date.now(), { amount: 8 }));

console.log(JSON.stringify(myCoin, null, 4));
// Output:
// {
//     "chain": [
//         {
//             "index": 0,
//             "timestamp": 1580594535416,
//             "data": "Genesis block",
//             "previousHash": "0",
//             "hash": "c7ebdda068f0b9a9aaf5c5c5d5c8f5e62c5e00dc7766a0a8e58a9b0e3d3c3e3a"
//         },
//         {
//             "index": 1,
//             "timestamp": 1580594535416,
//             "data": {
//                 "amount": 4
//             },
//             "previousHash": "c7ebdda068f0b9a9aaf5c5c5d5c8f5e62c5e00dc7766a0a8e58a9b0e3d3c3e3a",
//             "hash": "6bfc9119feb1271b8fc13f9d6ab0714b2377c5d4680e92c04bc16

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply