Create a Blockchain in 50 lines of code with NodeJS
Tags: node, blockchain, javascript, tutorial
Published: 2020-08-08 13:30:41

![Blockchain with NodeJS](https://media.giphy.com/media/Pm4IClgubRGiDyKkcS/giphy.gif)

[I already talked about the nonce in my previous article.](https://dev.to/icesofty/understanding-the-concept-of-the-nonce-sha3-256-in-a-blockchain-with-nodejs-205h) 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 : 

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

```



app.js :

```javascript
// 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();

```



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