{"id":2242,"date":"2022-01-25T18:01:12","date_gmt":"2022-01-25T18:01:12","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2242"},"modified":"2022-01-25T18:01:12","modified_gmt":"2022-01-25T18:01:12","slug":"building-a-simple-cryptocurrency-blockchain-using-node-js","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2242","title":{"rendered":"Building a Simple Cryptocurrency Blockchain using Node.js"},"content":{"rendered":"\n<p>A blockchain is an open, digital, and duplicated ledger of transactions. Each new transaction history is recorded and stored in an encrypted way that is very difficult to change or modify. A copy of this recorded information is sent a cross the blockchain network. Thus, making it highly secure.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>A cryptocurrency is a digitally secured currency used in most current trade. The use of&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Cryptographic_hash_function\">cryptographic hash<\/a>&nbsp;has played a major role is securing cryptocurrencies.<\/p>\n\n\n\n<p>This ensures only genuine transactions are recorded and commited. Most cryptocurrencies apply a&nbsp;<a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/en.wikipedia.org\/wiki\/Decentralization\">decentralized<\/a>&nbsp;principle using&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Blockchain\">blockchain<\/a>&nbsp;technology.<\/p>\n\n\n\n<p>In this tutorial, we will learn a little about blockchain and decentralization in detail. We will also build a simple cryptocurrency system, called&nbsp;<code>thecoin<\/code>.<\/p>\n\n\n\n<p><code>Thecoin<\/code>&nbsp;is one such implementation of a cryptocurrency that we are going to build in a this article.<\/p>\n\n\n\n<h3 id=\"prerequisite\">Prerequisite<\/h3>\n\n\n\n<p>To keep this tutorial flowing smoothly, you\u2019ll need to have a good understanding about:<\/p>\n\n\n\n<ul><li><a href=\"https:\/\/developer.mozilla.org\/en-US\/docs\/Web\/JavaScript\">JavaScript<\/a><\/li><li><a href=\"https:\/\/nodejs.org\/en\/docs\/\">Node.js<\/a><\/li><\/ul>\n\n\n\n<p>To start with, you must have:<\/p>\n\n\n\n<ul><li>Node.js installed in your machine.<\/li><li>A code editor.<\/li><\/ul>\n\n\n\n<h3 id=\"table-of-contents\">Table of contents<\/h3>\n\n\n\n<ul><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#what-is-blockchain\">What is Blockchain?<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#decentralization\">Decentralization<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#the-blockchain-theorem\">The blockchain theorem<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#verifying-blockchain-integrity\">Verifying blockchain integrity<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#running-our-blockchain\">Running our blockchain<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#conclusion\">Conclusion<\/a><\/li><li><a href=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/#references\">References<\/a><\/li><\/ul>\n\n\n\n<h3 id=\"what-is-blockchain\">What is Blockchain?<\/h3>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/bitcoin.jpg\" alt=\"Bitcoin Image\"\/><\/figure>\n\n\n\n<p><em>Bitcoin image<\/em><\/p>\n\n\n\n<p>Bitcoin and Ethereum are digital cryptocurrencies powered and adopted with a powerful technology called&nbsp;<strong>the blockchain<\/strong>. It uses cryptography to securely connect and maintain a list of records growing continuously known as&nbsp;<strong>blocks<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/ethereum.jpg\" alt=\"ethereum\"\/><\/figure>\n\n\n\n<p><em>Ethereum image<\/em><\/p>\n\n\n\n<p><strong>Blockchain<\/strong>&nbsp;as the name states, are blocks of transaction data growing increasingly to create a chain of transaction occurrences. Valid transaction data is logged into the blockchain network following the peer-to-peer rule laid down by participants.<\/p>\n\n\n\n<h3 id=\"decentralization\">Decentralization<\/h3>\n\n\n\n<p>Usually, the data in the databases are centralized. By centralizing, we operate based on only one server. Chances of risk are paramount due to failures of the system. Alternatively, decentralization allows data to be stored everywhere, thus making it faster, more secure and a better way of storing data.<\/p>\n\n\n\n<p>Blockchain stores its information in several locations. Whenever a new block is added to the blockchain, a copy is sent to all computers. This makes it very difficult to tamper with the blockchain, as all computers in the network must agree with the change(s) yet to be made in order for it to take place.<\/p>\n\n\n\n<p>We\u2019ll have a better understanding of blockchain and cryptocurrencies and their operation by the end of this article.<\/p>\n\n\n\n<p>Let\u2019s get into the code. I\u2019ll name my app&nbsp;<code>thecoin<\/code>.<\/p>\n\n\n\n<p>Create the app named&nbsp;<code>thecoin.js<\/code>&nbsp;and open it in your code editor.<\/p>\n\n\n\n<p>In the development folder, let\u2019s install the&nbsp;<code>crypto<\/code>&nbsp;library that we\u2019re going to use, using the command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install --save crypto-js\n<\/code><\/pre>\n\n\n\n<p>We\u2019ll use this library to import modules in our project.<\/p>\n\n\n\n<p>I\u2019ll begin by creating a class&nbsp;<code>BlockCypto<\/code>&nbsp;as shown below:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const SHA256 = require('crypto-js\/sha256');\nclass BlockCypto{\n    constructor(index, current_time, info, nextHash=\" \"){\n    this.index = index;\n    this.current_time = current_time;\n    this.info = info;\n    this.nextHash = nextHash;\n    this.hash = this.computeHash();     \n    }\n    computeHash(){\n        return SHA256(this.info + this.nextHash + this.current_time + JSON.stringify(this.info)).toString();\n    }   \n}\n<\/code><\/pre>\n\n\n\n<p>I\u2019ll explain each part of the code here:<\/p>\n\n\n\n<p>I\u2019ve created the class&nbsp;<code>BlockCrytpo<\/code>&nbsp;for my&nbsp;<em><strong>block<\/strong><\/em>&nbsp;and added a constructor just like any other JavaScript class.<\/p>\n\n\n\n<p>In the constructor, we initialize its properties and assign parameters to it, as follows:<\/p>\n\n\n\n<ul><li><code>crypto-js\/sha256<\/code>: This is the module we\u2019ve imported to calculate the hash of each block. We converted it to string using&nbsp;<code>toString()<\/code>&nbsp;method as the module will return the object.<\/li><li><code>index<\/code>: This is a distinctive number tracking the index of every block in the blockchain.<\/li><li><code>current_time<\/code>: As the name states, it keeps a record of the time when each transaction is completed.<\/li><li><code>info<\/code>: All completed transactions data are recorded and stored by this method.<\/li><li><code>nexthash<\/code>: It is pointing to the hash_key of the next block in the network chain. It\u2019s mainly used to keep and maintain the integrity of the blockchain.<\/li><li><code>computeHash<\/code>: Based on properties passed to this method, it is used to calculate the hashkey of the next block in the chain.<\/li><\/ul>\n\n\n\n<h3 id=\"the-blockchain-theorem\">The blockchain theorem<\/h3>\n\n\n\n<p>It is a type of database that stores a collection of data together in groups, with certain capacity of storage. The blocks are connected to the already created blocks, this forms a chain of a data tree.<\/p>\n\n\n\n<p>The chain is irreversible as the system is decentralized. Here, each block is assigned a timestamp when added to the chain.<\/p>\n\n\n\n<p>Now, let\u2019s create a class&nbsp;<code>Blockchain<\/code>&nbsp;that will maintain this operation:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class Blockchain{\n    constructor(){\n        this.block1chain = &#91;this.startGenesisBlock()];     \n    }\n    initGenesisBlock(){\n        return new BlockCrypto(0, \"06\/04\/2021\", \"Initial Block in the Chain\", \"0\");\n    }\n    latestBlock(){\n        return this.block1chain&#91;this.block1chain.length - 1];\n    }\n    addNewBlock(newBlock){\n        newBlock.nextHash = this.latestBlock().hash;\n        newBlock.hash = newBlock.computeHash();        \n        this.block1chain.push(newBlock);\n    }\n}\n<\/code><\/pre>\n\n\n\n<p>Let\u2019s understand the code snippet above.<\/p>\n\n\n\n<p>As usual, we have our constructor which instantiates the blockchain.<\/p>\n\n\n\n<p>But this time, we passed it to the&nbsp;<code>initGenesisBlock()<\/code>&nbsp;method, which initializes the block in the chain. This property refers to an array of blocks in our case.<\/p>\n\n\n\n<ul><li><code>initGenesisBlock()<\/code>: This is the first block created in the peer-to-peer network and has not been linked to any other. To our knowledge of indexing it\u2019s at index&nbsp;<code>0<\/code>.<\/li><\/ul>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Notice that, we created it using the previously created&nbsp;<code>BlockCrypto<\/code>&nbsp;class and passed all the parameters as arguments.<\/p><\/blockquote>\n\n\n\n<ul><li><code>latestBlock<\/code>: As named, we use it for finding the last block added in the chain. As explained earlier, it helps to ensure the hash of the current block and map it to the hash of the previous block to ensure the chain integrity.<\/li><li><code>addNewBlock<\/code>: A new block is added to the chain using this method. The previous hash block is matched to the current hash block to ensure minimal or no tampering with the chain.<\/li><\/ul>\n\n\n\n<p>Now that our blockchain is ready to work. We are missing something that is a core blockchain principle, the blockchain&nbsp;<em>integrity<\/em>.<\/p>\n\n\n\n<p>Let\u2019s see how to verify it and test our app.<\/p>\n\n\n\n<h3 id=\"verifying-blockchain-integrity\">Verifying blockchain integrity<\/h3>\n\n\n\n<p>The main characteristic of a blockchain is that once a block has been added to the network, it can\u2019t be changed without invalidating the entire blockchain integrity.<\/p>\n\n\n\n<p>To perform this, we use digital security or cryptographic hash, which ensures the securing and validation of the blockchain by producing a new hash every time a change is made in the block.<\/p>\n\n\n\n<p>We\u2019ll loop over the entire blockchain to check whether any hash has been tampered with, taking into account the exception of the first block, which is hardcoded.<\/p>\n\n\n\n<p>Besides, this method verifies if the cryptographic-key of each two blocks in series are pointing to one another. If the integrity of the blockchain has been compromised, it returns&nbsp;<code>false<\/code>; otherwise, in case no anomalies are encountered, it returns&nbsp;<code>true<\/code>.<\/p>\n\n\n\n<p>We\u2019ll create this method inside the&nbsp;<code>Blockchain<\/code>&nbsp;class:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>checkValidity(){\n    \/\/ Checking validity\n    for(let i = 1; i &lt; this.block1chain.length; i++) {\n        const currentBlock = this.block1chain&#91;i];\n        const nextBlock= this.blockchain&#91;i-1];\n    \/\/ Checking current blcok hash\n    \n    if(currentBlock.hash !== currentBlock.computeHash()) {\n        return false;\n    }\n    \/\/ Comparing current block hash with the next block\n\n    if(currentBlock.nextHash !== nextBlock.hash) {\n        return false;\n    }\n    return true;\n}\n<\/code><\/pre>\n\n\n\n<p>Now, we can test our app and see the results:<\/p>\n\n\n\n<p>But, before we dive into running the code, let\u2019s create a new instance of the&nbsp;<code>Blockchain<\/code>&nbsp;class and name it&nbsp;<code>thecoin<\/code>, and add some blocks in the blockchain using random values.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>let thecoin = new Blockchain();\n\nthecoin.addNewBlock(new BlockCrypto(1, \"06\/04\/2021\", {sender: \"Rabin Yitzack\", recipient: \"Loyd Eve\", quantity: 20}));\n\nthecoin.addNewBlock(new BlockCrypto(2, \"07\/04\/2021\", {sender: \"Anita Vyona\", recipient: \"Felix Mush\", quantity: 349}));\n\nconsole.log(JSON.stringify(thecoin, null, 4));\n<\/code><\/pre>\n\n\n\n<h3 id=\"running-our-blockchain\">Running our blockchain<\/h3>\n\n\n\n<p>Typing this command in our terminal&nbsp;<code>node thecoin.js<\/code>&nbsp;will result in:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.section.io\/engineering-education\/building-a-simple-cryptocurrency-blockchain\/output.jpg\" alt=\"output\"\/><\/figure>\n\n\n\n<blockquote class=\"wp-block-quote\"><p><strong>NOTE:<\/strong>&nbsp;Before running the command, make sure to navigate to the right path on your terminal.<\/p><\/blockquote>\n\n\n\n<p><em>Hint:<\/em>&nbsp;Using the command&nbsp;<code>pwd<\/code>&nbsp;to check the path.<\/p>\n\n\n\n<p>You can find our full source code&nbsp;<a href=\"https:\/\/github.com\/yitzackRabin\/crypto\">here<\/a>.<\/p>\n\n\n\n<h3 id=\"conclusion\">Conclusion<\/h3>\n\n\n\n<p>Kudos!<\/p>\n\n\n\n<p>You have built your own cryptocurrency using Node.js. This step has brought you closer to getting you started on building pro-apps using Node.js, or rather you can just add more features to our simple blockchain and share it with the market.<\/p>\n\n\n\n<p>Nevertheless, I hope that this tutorial has provided you with basic skill proficiency to get you going with the stimulating Node.js development.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>A blockchain is an open, digital, and duplicated ledger of transactions. Each new transaction history is recorded and stored in an encrypted way that is very difficult to change or modify. A copy of this recorded information is sent a cross the blockchain network. Thus, making it highly secure.<\/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\/2242"}],"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=2242"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2242\/revisions"}],"predecessor-version":[{"id":2243,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2242\/revisions\/2243"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2242"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2242"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2242"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}