DEV Community

Cover image for Create a Blockchain in 50 lines of code with NodeJS
Florian
Florian

Posted on

Create a Blockchain in 50 lines of code with NodeJS

Blockchain with NodeJS

I already talked about the nonce in my previous article. It's know time to create our first Blockchain application in 50 lines of codes with NodeJS!

We'll create an oversimplified version of what can be a Blockchain, and I will focus on the mining process, not on how to design the networking system between multiple nodes.

Also, because NodeJS is a single-thread language, I can't recommend to use it for the mining side. This article is exclusively here to demystify how the Blockchain works.

We need two main files :

  • blockchain.JSON will store the Blockchain data

  • app.js for the app

I won't describe each line of code since I've already added comments to my source code.

blockchain.JSON will store the Blockchain data architecture :

[
  {
    "id": "0",
    "timestamp": 0,
    "nonce": 0
  }
]

Enter fullscreen mode Exit fullscreen mode

app.js :

// Sha3 is a module to hash documents
const { SHA3 } = require("sha3");
const hash = new SHA3(256);
const fs = require("fs");

const fileName = "./blochain.json";

// We start our nonce at 0
let nonce = 0;
// Difficulty of the Blockchain. The more you add 0, the more it will be difficut to mine a Block
const difficulty = "000";
// Switch to end the while loop
let notFounded = true;

// Function used to update our Blockhcain
const updateBlockchain = (id, timestamp, nonce) => {
  let blockchain = require(fileName);
  // We create the new Block
  const addBlock = {
    id: id,
    timestamp: timestamp,
    nonce: nonce
  };
  // We add it into the Blockchain
  blockchain.push(addBlock);
  fs.writeFile(
    fileName,
    JSON.stringify(blockchain, null, 2),
    function writeJSON(err) {
      if (err) return console.log(err);
    }
  );
};

// Function to mine a Block
const mining = () => {
  var start = new Date().getTime();
  // We import the Blockchain
  const blockchain = require(fileName);

  while (notFounded) {
    // We need to reset our hash every loop
    hash.reset();
    // We hash the new data (block + nonce)
    hash.update(JSON.stringify(blockchain) + nonce);
    let hashed = hash.digest("hex");
    // IF the new hashed data starts with '000'
    if (hashed.startsWith(difficulty)) {
      var diff = (new Date().getTime() - start) / 1000;
      // We turn the switch off to end the while loop
      notFounded = false;
      console.log("\x1b[46m%s\x1b[0m", "//// FOUNDED ! ////");
      console.log(`Hash : ${hashed}`);
      console.log(`Nonce : ${nonce}`);
      console.log(`Total time : ${diff}s`);
      console.log("\x1b[46m%s\x1b[0m", "////           ////");
      // We execute the updateBlockchain
      updateBlockchain(hashed, Date.now(), nonce);
    } else {
      // PLEASE NOTE: If you want your mining process to be faster, delete or comment the next console.log()
      console.log(hashed);
      // We increment the nonce and start again the loop
      nonce++;
    }
  }
};

// When we launch the app, start mining
mining();

Enter fullscreen mode Exit fullscreen mode

To run the app :
First, install yarn npm -g yarn
Then, install sha3 yarn add sha3
And that's it! You are ready to start the miner with node app.js . If you want, you can improve the difficulty by adding more 0 into const difficulty.

Repo under MIT Licence: https://github.com/Icesofty/blockchain-demo

Top comments (4)

Collapse
 
thorstenhirsch profile image
Thorsten Hirsch

Any reason why you use npm to install yarn to install sha3? Why not installing sha3 with npm directly?

Collapse
 
icesofty profile image
Florian

Hello Thorsten,

Thanks for your feedback. That's a really good question. There is no specific reason, to be honest, I just want to be consistent with my GH repo where I use yarn.

You can, of course, only use "npm i sha3" :)

P.S. : I love your profile pic, one of my favorite Disney!

Collapse
 
javaarchive profile image
Raymond

this is going to sound a bit dumb but what about bcrypt but with the rounds number being the diffculty

Collapse
 
akroutihamza profile image
Hamza Akrouti

It easy to hack hahah