{"id":2240,"date":"2022-01-25T17:59:16","date_gmt":"2022-01-25T17:59:16","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2240"},"modified":"2022-01-25T17:59:16","modified_gmt":"2022-01-25T17:59:16","slug":"how-to-build-a-simple-cryptocurrency-blockchain-in-node-js","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2240","title":{"rendered":"How To Build A Simple Cryptocurrency Blockchain In Node.js"},"content":{"rendered":"\n<p>The unprecedented rise of cryptocurrencies, and their underpinning blockchain technology, have taken the world by storm \u2014 from the humble beginnings of being an academic concept over a decade ago to current increased adoption in various industries.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>The blockchain technology is receiving a lot of attention because of its ability to enhance&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/category\/security\">security<\/a>&nbsp;in trustless environments, enforce decentralization, and make processes efficient.<\/p>\n\n\n\n<p>Traditionally, Python has been the de facto programming language for blockchain development. However, with the proliferation of this amazing technology, the development options have also increased \u2014 and Node.js has not been left behind.<\/p>\n\n\n\n<p>In this tutorial, I\u2019m going to talk about how to build a simple cryptocurrency blockchain in Node.js. It\u2019s not going to be too fancy, but just sufficient to assist you to understand how a blockchain works.<\/p>\n\n\n\n<p>I\u2019ll call this simple cryptocurrency&nbsp;<code>smashingCoin<\/code>.<\/p>\n\n\n\n<p>If you are a JavaScript developer who wants to take a leap into the burgeoning field of cryptocurrency, this article will equip you with the necessary skills to get started. Or, if you\u2019re curious about how things work in the world of cryptocurrencies, then this tutorial may help in answering some of your questions.<\/p>\n\n\n\n<p><strong>Recommended reading<\/strong>:&nbsp;<em><a href=\"https:\/\/www.smashingmagazine.com\/2019\/04\/understanding-subresource-integrity\/\">Understanding Subresource Integrity<\/a>&nbsp;by Drew McLellan<\/em><\/p>\n\n\n\n<h3 id=\"prerequisites\">PREREQUISITES&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#prerequisites\">#<\/a><\/h3>\n\n\n\n<p>To follow this tutorial successfully, you\u2019ll need to have the following:<\/p>\n\n\n\n<ul><li>Node.js installed on your machine. You can download it from&nbsp;<a href=\"https:\/\/nodejs.org\/en\/\">here<\/a>;<\/li><li>A code editor, such as Visual Studio Code, Sublime Text, or any other.<\/li><\/ul>\n\n\n\n<p>Let\u2019s get started\u2026More after jump! Continue reading below&nbsp;\u2193<\/p>\n\n\n\n<p>Meet&nbsp;<strong><a href=\"https:\/\/www.smashingconf.com\/online-workshops\/\">Smashing Online Workshops<\/a><\/strong>&nbsp;on&nbsp;<strong>front-end &amp; UX<\/strong>, with practical takeaways, live sessions,&nbsp;<strong>video recordings<\/strong>&nbsp;and a friendly Q&amp;A. On design systems, CSS\/JS and UX. With Carie Fisher, Stefan Baumgartner and&nbsp;<a href=\"https:\/\/smashingconf.com\/online-workshops\/workshops\">so many others<\/a>.<a href=\"https:\/\/smashed.by\/smashing-workshops\">Jump to online workshops&nbsp;\u21ac<\/a><a href=\"https:\/\/smashed.by\/smashing-workshops\"><\/a><\/p>\n\n\n\n<h2 id=\"what-is-a-blockchain\">What Is A Blockchain?&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#what-is-a-blockchain\">#<\/a><\/h2>\n\n\n\n<p>Blockchain is the technology that powers digital currencies, such as Bitcoin and Ethereum. It is an innovative distributed public ledger technology that maintains a continuously growing list of records, referred to as blocks, which are connected securely using cryptography.<\/p>\n\n\n\n<p>The term&nbsp;<em>blockchain<\/em>&nbsp;has earned its name because of the manner it keeps transaction data, i.e. in&nbsp;<em>blocks<\/em>&nbsp;that are connected to each other to create a&nbsp;<em>chain<\/em>. The size of the blockchain grows with an increase in the number of transactions undertaken.<\/p>\n\n\n\n<p>Any valid transaction data is logged into the blockchain network, which is governed by peer-to-peer rules that the participants stipulate. For example, this data could contain the \u201cvalue\u201d of the block such as in digital currencies, a record of transactions (such as when parties exchange goods and services), or entitlement privileges such as when the chain records ownership information.<\/p>\n\n\n\n<p>Besides the transaction data, every block may contain its own cryptographic hash (a unique identifier or digital footprint), its own nonce value (an arbitrary random number used once in cryptographic computations), the hash of the previous block, and a timestamp of recent authenticated transactions.<\/p>\n\n\n\n<p>Since every new block should point to the previous block, if a block is incorporated into the chain without containing the right hash of the last block, it could render the entire blockchain invalid. This immutability property is key to the security of blockchains.<\/p>\n\n\n\n<p>Furthermore, various types of consensus protocols are often applied to maintain the authenticity of the blockchain. Consensus ensures that all participants agree to the network-validated transactions.<\/p>\n\n\n\n<p>For example, a commonly used consensus protocol is proof of work, which aims to identify a number that finds a solution to a complicated mathematical problem after completing a certain amount of computing work.<\/p>\n\n\n\n<p>The main idea of proof work is that any participant in the blockchain network should find this number difficult to identify but easily verifiable. Consequently, it discourages spamming and tampering with the structure of the blockchain.<\/p>\n\n\n\n<p>In the case of most cryptocurrencies, adding a new block to the blockchain requires solving a complex mathematical equation, which increases in difficulty over time as the blockchain grows. Consequently, any person who proves that they\u2019ve done work by solving this problem is compensated with a digital currency, in a process referred to as \u201cmining\u201d.<\/p>\n\n\n\n<h2 id=\"how-to-create-a-block\">How To Create A Block&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#how-to-create-a-block\">#<\/a><\/h2>\n\n\n\n<p>Now, after introducing the blockchain technology and how it works, let\u2019s see how we can apply the concepts in creating a block. As earlier mentioned, blocks are what interlink to each other to form a blockchain.<\/p>\n\n\n\n<p>To create the&nbsp;<code>smashingCoin<\/code>&nbsp;currency, I\u2019ll use&nbsp;<a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\/Reference\/Classes\">JavaScript classes<\/a>, which were introduced in ES6.<\/p>\n\n\n\n<p>Ready?<\/p>\n\n\n\n<p>Let\u2019s get our hands dirty\u2026<\/p>\n\n\n\n<p>Here is the code for the&nbsp;<code>CryptoBlock<\/code>&nbsp;class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const SHA256 = require('crypto-js\/sha256');\nclass CryptoBlock{\n    constructor(index, timestamp, data, precedingHash=\" \"){\n     this.index = index;\n     this.timestamp = timestamp;\n     this.data = data;\n     this.precedingHash = precedingHash;\n     this.hash = this.computeHash();     \n    }\n    computeHash(){\n        return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)).toString();\n    }   \n}\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>As you can see in the code above, I created the&nbsp;<code>CryptoBlock<\/code>&nbsp;class and added the&nbsp;<code>constructor()<\/code>&nbsp;method to it \u2014 just like it\u2019s done in any other JavaScript class. Then, to initialize its properties, I assigned the following parameters to the&nbsp;<code>constructor<\/code>&nbsp;method:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><code>index<\/code><\/td><td>It\u2019s a unique number that tracks the position of every block in the entire blockchain.<\/td><\/tr><tr><td><code>timestamp<\/code><\/td><td>It keeps a record of the time of occurrence of each completed transaction.<\/td><\/tr><tr><td><code>data<\/code><\/td><td>It provides data about the completed transactions, such as the sender details, recipient\u2019s details, and quantity transacted.<\/td><\/tr><tr><td><code>precedingHash<\/code><\/td><td>It points to the hash of the preceding block in the blockchain, something important in maintaining the blockchain\u2019s integrity.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Furthermore, I used the&nbsp;<code>computeHash<\/code>&nbsp;method to calculate the hash of the block based on its properties, as given in the data above.<\/p>\n\n\n\n<p>As you can see, I imported the&nbsp;<a href=\"https:\/\/www.npmjs.com\/package\/crypto-js\">crypto-js JavaScript library<\/a>&nbsp;and used its&nbsp;<code>crypto-js\/sha256<\/code>&nbsp;module to calculate the hash of each block. Since the module returns a number object, I used the&nbsp;<code>toString()<\/code>&nbsp;method to convert it into a string.<\/p>\n\n\n\n<p>To add the crypto-js library to your project, go the terminal and run the following command to install it using&nbsp;<code>npm<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install --save crypto-js\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>After running the above command, the node modules directory, which contains the library and other essential files, will be added to your project\u2019s folder.<\/p>\n\n\n\n<h2 id=\"how-to-create-a-blockchain\">How To Create A Blockchain&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#how-to-create-a-blockchain\">#<\/a><\/h2>\n\n\n\n<p>As earlier explained, the blockchain technology is based on the concept that all the blocks are chained to one another. So, let\u2019s create a&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class that will be responsible for handling the operations of the entire chain. This is where the rubber is going to meet the road.<\/p>\n\n\n\n<p>The&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class will maintain the operations of the blockchain using helper methods that accomplish different tasks, such as creating new blocks and adding them to the chain.<\/p>\n\n\n\n<p>Here is the code for the&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class CryptoBlockchain{\n    constructor(){\n        this.blockchain = &#91;this.startGenesisBlock()];     \n    }\n    startGenesisBlock(){\n        return new CryptoBlock(0, \"01\/01\/2020\", \"Initial Block in the Chain\", \"0\");\n    }\n    obtainLatestBlock(){\n        return this.blockchain&#91;this.blockchain.length - 1];\n    }\n    addNewBlock(newBlock){\n        newBlock.precedingHash = this.obtainLatestBlock().hash;\n        newBlock.hash = newBlock.computeHash();        \n        this.blockchain.push(newBlock);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>Let me talk about the roles of each of the helper methods that constitute the&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class.<\/p>\n\n\n\n<h3 id=\"1-constructor-method\">1. CONSTRUCTOR METHOD&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#1-constructor-method\">#<\/a><\/h3>\n\n\n\n<p>This method instantiates the blockchain. Inside the constructor, I created the&nbsp;<code>blockchain<\/code>&nbsp;property, which refers to an array of blocks. Notice that I passed to it the&nbsp;<code>startGenesisBlock()<\/code>&nbsp;method, which creates the initial block in the chain.<\/p>\n\n\n\n<h3 id=\"2-creating-the-genesis-block\">2. CREATING THE GENESIS BLOCK&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#2-creating-the-genesis-block\">#<\/a><\/h3>\n\n\n\n<p>In a blockchain, the genesis block refers to the first-ever block created on the network. Whenever a block is integrated with the rest of the chain, it should reference the preceding block.<\/p>\n\n\n\n<p>Conversely, in the case of this initial block, it does not have any preceding block to point to. Therefore, a genesis block is usually hardcoded into the blockchain. This way, subsequent blocks can be created on it. It usually has an index of 0.<\/p>\n\n\n\n<p>I used the&nbsp;<code>startGenesisBlock()<\/code>&nbsp;method to create the genesis block. Notice that I created it using the afore-created&nbsp;<code>CryptoBlock<\/code>&nbsp;class and passed the&nbsp;<code>index<\/code>,&nbsp;<code>timestamp<\/code>,&nbsp;<code>data<\/code>, and&nbsp;<code>precedingHash<\/code>&nbsp;parameters.<\/p>\n\n\n\n<h3 id=\"3-obtaining-the-latest-block\">3. OBTAINING THE LATEST BLOCK&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#3-obtaining-the-latest-block\">#<\/a><\/h3>\n\n\n\n<p>Getting the latest block in the blockchain assists in ensuring the hash of the current block points to the hash of the previous block \u2014 thus maintaining the chain\u2019s integrity.<\/p>\n\n\n\n<p>I used the&nbsp;<code>obtainLatestBlock()<\/code>&nbsp;method to retrieve it.<\/p>\n\n\n\n<h3 id=\"4-adding-new-blocks\">4. ADDING NEW BLOCKS&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#4-adding-new-blocks\">#<\/a><\/h3>\n\n\n\n<p>I used the&nbsp;<code>addNewBlock()<\/code>&nbsp;method to add a new block to the chain. To accomplish this, I set the previous hash of the new block to be equal to the hash of the last block in the chain \u2014 thus ensuring the chain is tamper-proof.<\/p>\n\n\n\n<p>Since the properties of the new block get changed with every new calculation, it\u2019s important to calculate its cryptographic hash again. After updating its hash, the new block is pushed into the blockchain array.<\/p>\n\n\n\n<p>In reality, adding a new block to a blockchain is not that easy because of the several checks that have been placed. Nonetheless, for this simple cryptocurrency, it\u2019s enough to demonstrate how a blockchain actually works.<\/p>\n\n\n\n<h2 id=\"testing-the-blockchain\">Testing The Blockchain&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#testing-the-blockchain\">#<\/a><\/h2>\n\n\n\n<p>Now, let\u2019s test our simple blockchain and see if it works.<\/p>\n\n\n\n<p>Here is the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let smashingCoin = new CryptoBlockchain();\nsmashingCoin.addNewBlock(new CryptoBlock(1, \"01\/06\/2020\", {sender: \"Iris Ljesnjanin\", recipient: \"Cosima Mielke\", quantity: 50}));\nsmashingCoin.addNewBlock(new CryptoBlock(2, \"01\/07\/2020\", {sender: \"Vitaly Friedman\", recipient: \"Ricardo Gimenes\", quantity: 100}) );\nconsole.log(JSON.stringify(smashingCoin, null, 4));\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>As you can see in the code above, I created a new instance of the&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class and named it as&nbsp;<code>smashingCoin<\/code>. Then, I added two blocks into the blockchain using some arbitrary values. In the&nbsp;<code>data<\/code>&nbsp;parameter, I used an object and added sender details, recipient\u2019s details, and quantity transacted.<\/p>\n\n\n\n<p>If I run the code on the terminal, here is the output I get:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/0dabfd37-e21e-4083-a99d-5e3cc495ccab\/cryptocurrency-blockchain-terminal-image-one.jpg\"><img src=\"https:\/\/res.cloudinary.com\/indysigner\/image\/fetch\/f_auto,q_80\/w_400\/https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/0dabfd37-e21e-4083-a99d-5e3cc495ccab\/cryptocurrency-blockchain-terminal-image-one.jpg\" alt=\"How a blockchain looks like under the hood\"\/><\/a><figcaption>Testing to see if our blockchain works. (<a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/0dabfd37-e21e-4083-a99d-5e3cc495ccab\/cryptocurrency-blockchain-terminal-image-one.jpg\">Large preview<\/a>)<\/figcaption><\/figure>\n\n\n\n<p>That\u2019s what the&nbsp;<code>smashingCoin<\/code>&nbsp;looks like! It\u2019s an object that contains the&nbsp;<code>blockchain<\/code>&nbsp;property, which is an array containing all the blocks in the chain. As you can see in the image above, each block references the hash of the previous block. For example, the second block references the hash of the first block. After testing and seeing that our blockchain works, let\u2019s add some more functionalities to enhance the features of the&nbsp;<code>smashingCoin<\/code>.<\/p>\n\n\n\n<h2 id=\"how-to-verify-the-blockchain-s-integrity\">How To Verify The Blockchain\u2019s Integrity&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#how-to-verify-the-blockchain-s-integrity\">#<\/a><\/h2>\n\n\n\n<p>As earlier mentioned, a key characteristic of a blockchain is that once a block has been added to the chain, it cannot be changed without invalidating the integrity of the rest of the chain.<\/p>\n\n\n\n<p>Therefore, to verify the integrity of the blockchain, I\u2019ll add a&nbsp;<code>checkChainValidity()<\/code>&nbsp;method to the&nbsp;<code>CryptoBlockchain<\/code>&nbsp;class.<\/p>\n\n\n\n<p>Hashes are critical for ensuring the validity and security of a blockchain because any change in the contents of a block will result in the production of an entirely new hash, and invalidating the blockchain.<\/p>\n\n\n\n<p>As such, the&nbsp;<code>checkChainValidity()<\/code>&nbsp;method will make use of&nbsp;<code>if<\/code>&nbsp;statements to verify whether the hash of every block has been tampered with. Starting from the first created block, it\u2019ll loop over the entire blockchain and check for its validity. Note that since the genesis block was hardcoded, it\u2019ll not be checked.<\/p>\n\n\n\n<p>Also, the method will verify whether the hashes of each two consecutive blocks are pointing to one another. If the integrity of the blockchain has not been compromised, it returns true; otherwise, in case of any anomalies, it returns false.<\/p>\n\n\n\n<p>Here is the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>checkChainValidity(){\n        for(let i = 1; i &lt; this.blockchain.length; i++){\n            const currentBlock = this.blockchain&#91;i];\n            const precedingBlock= this.blockchain&#91;i-1];\n\n          if(currentBlock.hash !== currentBlock.computeHash()){\n              return false;\n          }\n          if(currentBlock.precedingHash !== precedingBlock.hash)\n            return false;\n        }\n        return true;\n    }\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<h2 id=\"how-to-add-proof-of-work\">How To Add Proof Of Work&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#how-to-add-proof-of-work\">#<\/a><\/h2>\n\n\n\n<p>As earlier mentioned, proof of work is the concept applied to increase the difficulty entailed in mining or adding new blocks to the blockchain.<\/p>\n\n\n\n<p>In the case of&nbsp;<code>smashingCoin<\/code>, I\u2019ll employ a simple algorithm that deters people from generating new blocks easily or spamming the blockchain.<\/p>\n\n\n\n<p>So, in the&nbsp;<code>CryptoBlock<\/code>&nbsp;class, I\u2019ll add another method called&nbsp;<code>proofOfWork().<\/code>Essentially, this simple algorithm identifies a number, passed as a&nbsp;<code>difficulty<\/code>&nbsp;property, such that the hash of every block contains leading zeros that correspond to this&nbsp;<code>difficulty<\/code>&nbsp;level.<\/p>\n\n\n\n<p>Ensuring the hash of every block begins with the number of zeros as set in the&nbsp;<code>difficulty<\/code>&nbsp;level requires a lot of computing power. The higher the difficulty level, the more time it takes to mine new blocks.<\/p>\n\n\n\n<p>Furthermore, I\u2019ll add a random&nbsp;<code>nonce<\/code>&nbsp;value to every hashed block such that, when rehashing takes place, the difficulty level restrictions can still be met.<\/p>\n\n\n\n<p>Here is the code:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>proofOfWork(difficulty){\n      while(this.hash.substring(0, difficulty) !==Array(difficulty + 1).join(\"0\")){\n          this.nonce++;\n          this.hash = this.computeHash();\n      }        \n  }\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>And, here is the updated&nbsp;<code>computeHash()<\/code>&nbsp;method with the&nbsp;<code>nonce<\/code>&nbsp;variable included:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>computeHash(){\n        return SHA256(this.index + this.precedingHash + this.timestamp + JSON.stringify(this.data)+this.nonce).toString();\n    }\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>Additionally, to implement the proof of work mechanism in the generation of new blocks, I\u2019ll include it in the&nbsp;<code>addNewBlock()<\/code>&nbsp;method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>addNewBlock(newBlock){\n      newBlock.precedingHash = this.obtainLatestBlock().hash;\n      \/\/newBlock.hash = newBlock.computeHash(); \n      newBlock.proofOfWork(this.difficulty);       \n      this.blockchain.push(newBlock);\n  }\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<h2 id=\"wrapping-up\">Wrapping Up&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#wrapping-up\">#<\/a><\/h2>\n\n\n\n<p>Here is the entire code for building the&nbsp;<code>smashingCoin<\/code>&nbsp;cryptocurrency using Node.js:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const SHA256 = require(\"crypto-js\/sha256\");\nclass CryptoBlock {\n  constructor(index, timestamp, data, precedingHash = \" \") {\n    this.index = index;\n    this.timestamp = timestamp;\n    this.data = data;\n    this.precedingHash = precedingHash;\n    this.hash = this.computeHash();\n    this.nonce = 0;\n  }\n\n  computeHash() {\n    return SHA256(\n      this.index +\n        this.precedingHash +\n        this.timestamp +\n        JSON.stringify(this.data) +\n        this.nonce\n    ).toString();\n  }\n\n  proofOfWork(difficulty) {\n    while (\n      this.hash.substring(0, difficulty) !== Array(difficulty + 1).join(\"0\")\n    ) {\n      this.nonce++;\n      this.hash = this.computeHash();\n    }\n  }\n}\n\nclass CryptoBlockchain {\n  constructor() {\n    this.blockchain = &#91;this.startGenesisBlock()];\n    this.difficulty = 4;\n  }\n  startGenesisBlock() {\n    return new CryptoBlock(0, \"01\/01\/2020\", \"Initial Block in the Chain\", \"0\");\n  }\n\n  obtainLatestBlock() {\n    return this.blockchain&#91;this.blockchain.length - 1];\n  }\n  addNewBlock(newBlock) {\n    newBlock.precedingHash = this.obtainLatestBlock().hash;\n    \/\/newBlock.hash = newBlock.computeHash();\n    newBlock.proofOfWork(this.difficulty);\n    this.blockchain.push(newBlock);\n  }\n\n  checkChainValidity() {\n    for (let i = 1; i &lt; this.blockchain.length; i++) {\n      const currentBlock = this.blockchain&#91;i];\n      const precedingBlock = this.blockchain&#91;i - 1];\n\n      if (currentBlock.hash !== currentBlock.computeHash()) {\n        return false;\n      }\n      if (currentBlock.precedingHash !== precedingBlock.hash) return false;\n    }\n    return true;\n  }\n}\n\nlet smashingCoin = new CryptoBlockchain();\n\nconsole.log(\"smashingCoin mining in progress....\");\nsmashingCoin.addNewBlock(\n  new CryptoBlock(1, \"01\/06\/2020\", {\n    sender: \"Iris Ljesnjanin\",\n    recipient: \"Cosima Mielke\",\n    quantity: 50\n  })\n);\n\nsmashingCoin.addNewBlock(\n  new CryptoBlock(2, \"01\/07\/2020\", {\n    sender: \"Vitaly Friedman\",\n    recipient: \"Ricardo Gimenes\",\n    quantity: 100\n  })\n);\n\nconsole.log(JSON.stringify(smashingCoin, null, 4));\n<\/code><\/pre>\n\n\n\n<p>Copy<\/p>\n\n\n\n<p>If I run the code on the terminal, here is the output I get:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/e99946ab-3c1d-4bf2-aac2-e93640aad3fc\/cryptocurrency-blockchain-terminal-image-two.jpg\"><img src=\"https:\/\/res.cloudinary.com\/indysigner\/image\/fetch\/f_auto,q_80\/w_400\/https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/e99946ab-3c1d-4bf2-aac2-e93640aad3fc\/cryptocurrency-blockchain-terminal-image-two.jpg\" alt=\"Output of creating a simple cryptocurrency in Node.js\"\/><\/a><figcaption>At last, our&nbsp;<code>smashingCoin<\/code>&nbsp;cryptocurrency! (<a href=\"https:\/\/cloud.netlifyusercontent.com\/assets\/344dbf88-fdf9-42bb-adb4-46f01eedd629\/e99946ab-3c1d-4bf2-aac2-e93640aad3fc\/cryptocurrency-blockchain-terminal-image-two.jpg\">Large preview<\/a>)<\/figcaption><\/figure>\n\n\n\n<p>As you can see on the image above, the hashes now start with four zeros, which correspond with the difficulty level set in the proof of work mechanism.<\/p>\n\n\n\n<h2 id=\"conclusion\">Conclusion&nbsp;<a href=\"https:\/\/www.smashingmagazine.com\/2020\/02\/cryptocurrency-blockchain-node-js\/#conclusion\">#<\/a><\/h2>\n\n\n\n<p>That\u2019s it! That\u2019s how you can build a simple cryptocurrency blockchain using Node.js.<\/p>\n\n\n\n<p>Of course, the&nbsp;<code>smashingCoin<\/code>&nbsp;cryptocurrency is far from complete. In fact, if you release it without making more improvements, it is unlikely to meet the current market demands for a secure, reliable, and intuitive digital currency \u2014 making you the only one using it!<\/p>\n\n\n\n<p>Nonetheless, I hope that this tutorial has equipped you with some basic skills to get your feet wet in the thrilling world of cryptos.<\/p>\n\n\n\n<p>If you have any comments or questions, please post them below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The unprecedented rise of cryptocurrencies, and their underpinning blockchain technology, have taken the world by storm \u2014 from the humble beginnings of being an academic concept over a decade ago to current increased adoption in various industries.<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[178],"tags":[154,94],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2240"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2240"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2240\/revisions"}],"predecessor-version":[{"id":2241,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2240\/revisions\/2241"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2240"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2240"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2240"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}