{"id":1425,"date":"2019-02-15T10:32:09","date_gmt":"2019-02-15T10:32:09","guid":{"rendered":"http:\/\/kusuaks7\/?p=1030"},"modified":"2023-07-19T13:54:08","modified_gmt":"2023-07-19T13:54:08","slug":"learn-blockchains-by-building-one","status":"publish","type":"post","link":"https:\/\/www.experfy.com\/blog\/fintech\/learn-blockchains-by-building-one\/","title":{"rendered":"Learn Blockchains by Building One"},"content":{"rendered":"<p><strong><em>Ready to learn Blockchain?\u00a0<a href=\"https:\/\/www.experfy.com\/training\/courses\">Browse courses<\/a>\u00a0like\u00a0<a href=\"https:\/\/www.experfy.com\/training\/courses\/blockchain-technology-fundamentals\">Blockchain Technology Fundamentals<\/a> developed by industry thought leaders and Experfy in Harvard Innovation Lab.<\/em><\/strong><\/p>\n<p>The fastest way to learn how Blockchains work is to build\u00a0one<\/p>\n<section>\n<p id=\"e816\">You\u2019re here because, like me, you\u2019re psyched about the rise of Cryptocurrencies. And you want to know how Blockchains work\u2014the fundamental technology behind them.<\/p>\n<p id=\"bd65\">But understanding Blockchains isn\u2019t easy\u2014or at least wasn\u2019t for me. I trudged through dense videos, followed porous tutorials, and dealt with the amplified frustration of too few examples.<\/p>\n<p id=\"4741\">I like learning by doing. It forces me to deal with the subject matter at a code level, which gets it sticking. If you do the same, at the end of this guide you\u2019ll have a functioning Blockchain with a solid grasp of how they work.<\/p>\n<h3 id=\"6db5\">Before you get\u00a0started\u2026<\/h3>\n<p id=\"2c71\">Remember that a blockchain is an\u00a0<em>immutable, sequential\u00a0<\/em>chain of records called Blocks. They can contain transactions, files or any data you like, really. But the important thing is that they\u2019re\u00a0<em>chained<\/em>\u00a0together using\u00a0<em>hashes<\/em>.<\/p>\n<p id=\"d788\">If you aren\u2019t sure what a hash is,\u00a0<a href=\"https:\/\/learncryptography.com\/hash-functions\/what-are-hash-functions\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/learncryptography.com\/hash-functions\/what-are-hash-functions\" data->here\u2019s an explanation<\/a>.<\/p>\n<p id=\"3369\"><strong><em>Who is this guide aimed at?<\/em><\/strong>\u00a0You should be comfy reading and writing some basic Python, as well as have some understanding of how HTTP requests work, since we\u2019ll be talking to our Blockchain over HTTP.<\/p>\n<p id=\"5da1\"><strong><em>What do I need?<\/em>\u00a0<\/strong>Make sure that\u00a0<a href=\"https:\/\/www.python.org\/downloads\/\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/www.python.org\/downloads\/\" data->Python 3.6<\/a>+ (along with\u00a0<code>pip<\/code>) is installed. You\u2019ll also need to install Flask and the wonderful Requests library:<\/p>\n<pre id=\"209c\"><code>pip install Flask==0.12.2 requests==2.18.4<\/code><\/pre>\n<p id=\"b587\">Oh, you\u2019ll also need an HTTP Client, like\u00a0<a href=\"https:\/\/www.getpostman.com\/\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/www.getpostman.com\">Postman<\/a>\u00a0or cURL. But anything will do.<\/p>\n<p id=\"8308\"><strong><em>Where\u2019s the final code?\u00a0<\/em><\/strong>The source code is\u00a0<a href=\"https:\/\/github.com\/dvf\/blockchain\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/github.com\/dvf\/blockchain\" data->available here<\/a>.<\/p>\n<\/section>\n<section>\n<hr \/>\n<h3 id=\"6994\">Step 1: Building a Blockchain<\/h3>\n<p id=\"0863\">Open up your favourite text editor or IDE, personally I \u2764\ufe0f\u00a0<a href=\"https:\/\/www.jetbrains.com\/pycharm\/\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/www.jetbrains.com\/pycharm\/\" data->PyCharm<\/a>. Create a new file, called\u00a0<code>blockchain.py<\/code>. We\u2019ll only use a single file, but if you get lost, you can always refer to the\u00a0<a href=\"https:\/\/github.com\/dvf\/blockchain\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/github.com\/dvf\/blockchain\" data->source code<\/a>.<\/p>\n<h4 id=\"6c47\">Representing a Blockchain<\/h4>\n<p id=\"48c8\">We\u2019ll create a\u00a0<code>Blockchain<\/code>\u00a0class whose constructor creates an initial empty list (to store our blockchain), and another to store transactions. Here\u2019s the blueprint for our class:<\/p>\n<figure id=\"bb54\"><figcaption>Blueprint of our Blockchain Class<\/figcaption><\/figure>\n<p id=\"eb0a\">Our\u00a0<code>Blockchain<\/code>\u00a0class is responsible for managing the chain. It will store transactions and have some helper methods for adding new blocks to the chain. Let\u2019s start fleshing out some methods.<\/p>\n<h4 id=\"1a89\">What does a Block look\u00a0like?<\/h4>\n<p id=\"e489\">Each Block has an\u00a0<em>index<\/em>, a\u00a0<em>timestamp<\/em>\u00a0(in Unix time), a\u00a0<em>list of transactions<\/em>, a\u00a0<em>proof<\/em>\u00a0(more on that later), and the\u00a0<em>hash of the previous Block<\/em>.<\/p>\n<p id=\"73a8\">Here\u2019s an example of what a single Block looks like:<\/p>\n<figure id=\"f122\"><figcaption>Example of a Block in our Blockchain<\/figcaption><\/figure>\n<p id=\"414f\">At this point, the idea of a\u00a0<em>chain<\/em>\u00a0should be apparent\u2014each new block contains within itself, the hash of the previous Block.\u00a0<strong>This is crucial because it\u2019s what gives blockchains immutability:<\/strong>\u00a0If an attacker corrupted an earlier Block in the chain then\u00a0<strong><em>all<\/em><\/strong>\u00a0subsequent blocks will contain incorrect hashes.<\/p>\n<p id=\"809e\"><em>Does this make sense? If it doesn\u2019t, take some time to let it sink in\u2014it\u2019s the core idea behind blockchains.<\/em><\/p>\n<h4 id=\"04e0\">Adding Transactions to a\u00a0Block<\/h4>\n<p id=\"a276\">We\u2019ll need a way of adding transactions to a Block. Our\u00a0<code>new_transaction()<\/code>method is responsible for this, and it\u2019s pretty straight-forward:<\/p>\n<p id=\"5a22\">After\u00a0<code>new_transaction()<\/code>\u00a0adds a transaction to the list, it returns the\u00a0<em>index<\/em>\u00a0of the block which the transaction will be added to\u2014<em>the next one to be mined.<\/em>This will be useful later on, to the user submitting the transaction.<\/p>\n<h4 id=\"0db8\">Creating new\u00a0Blocks<\/h4>\n<p id=\"de4b\">When our\u00a0<code>Blockchain<\/code>\u00a0is instantiated we\u2019ll need to seed it with a\u00a0<em>genesis<\/em>\u00a0block\u2014a block with no predecessors. We\u2019ll also need to add a\u00a0<em>\u201cproof\u201d<\/em>\u00a0to our genesis block which is the result of mining (or proof of work). We\u2019ll talk more about mining later.<\/p>\n<p id=\"8d25\">In addition to creating the\u00a0<em>genesis<\/em>\u00a0block in our constructor, we\u2019ll also flesh out the methods for\u00a0<code>new_block()<\/code>,\u00a0<code>new_transaction()<\/code>\u00a0and\u00a0<code>hash()<\/code>:<\/p>\n<p id=\"61d8\">The above should be straight-forward\u2014I\u2019ve added some comments and\u00a0<em>docstrings<\/em>\u00a0to help keep it clear. We\u2019re almost done with representing our blockchain. But at this point, you must be wondering how new blocks are created, forged or mined.<\/p>\n<h4 id=\"4133\">Understanding Proof of\u00a0Work<\/h4>\n<p id=\"657e\">A Proof of Work algorithm (PoW) is how new Blocks are created or\u00a0<em>mined\u00a0<\/em>on the blockchain<em>.\u00a0<\/em>The goal of PoW is to discover a number which solves a problem. The number must be\u00a0<strong>difficult to find<\/strong>\u00a0<strong>but easy to verify<\/strong>\u2014computationally speaking\u2014by anyone on the network. This is the core idea behind Proof of Work.<\/p>\n<p id=\"633b\">We\u2019ll look at a very simple example to help this sink in.<\/p>\n<p id=\"835c\">Let\u2019s decide that the\u00a0<em>hash<\/em>\u00a0of some integer\u00a0<code>x<\/code>\u00a0multiplied by another\u00a0<code>y<\/code>\u00a0must end in\u00a0<code>0<\/code>. So,\u00a0<code>hash(x * y) = ac23dc...0<\/code>. And for this simplified example, let\u2019s fix\u00a0<code>x = 5<\/code>. Implementing this in Python:<\/p>\n<pre id=\"026a\">from hashlib import sha256<\/pre>\n<pre id=\"faa1\">x = 5\r\ny = 0  # We don't know what y should be yet...<\/pre>\n<pre id=\"55e4\">while sha256(f'{x*y}'.encode()).hexdigest()[-1] != \"0\":\r\ny += 1<\/pre>\n<pre id=\"7453\">print(f'The solution is y = {y}')<\/pre>\n<p id=\"bb3f\">The solution here is\u00a0<code>y = 21<\/code>. Since, the produced hash ends in\u00a0<code>0<\/code>:<\/p>\n<pre id=\"02f8\">hash(5 * 21) = 1253e9373e...5e3600155e860<\/pre>\n<p id=\"45f6\">In Bitcoin, the Proof of Work algorithm is called\u00a0<a href=\"https:\/\/en.wikipedia.org\/wiki\/Hashcash\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"https:\/\/en.wikipedia.org\/wiki\/Hashcash\" data-><em>Hashcash<\/em><\/a>. And it\u2019s not too different from our basic example above. It\u2019s the algorithm that miners race to solve in order to create a new block. In general, the difficulty is determined by the number of characters searched for in a string. The miners are then rewarded for their solution by receiving a coin\u2014in a transaction.<\/p>\n<p id=\"4ac4\">The network is able to\u00a0<em>easily\u00a0<\/em>verify their solution.<\/p>\n<h4 id=\"0cd0\">Implementing basic Proof of\u00a0Work<\/h4>\n<p id=\"5e95\">Let\u2019s implement a similar algorithm for our blockchain. Our rule will be similar to the example above:<\/p>\n<blockquote id=\"5dfc\"><p><em>Find a number\u00a0<\/em>p<em>\u00a0that when hashed with the previous block\u2019s solution a hash with 4 leading\u00a0<\/em><code><em>0<\/em><\/code><em>s is produced.<\/em><\/p><\/blockquote>\n<p id=\"33a6\">To adjust the difficulty of the algorithm, we could modify the number of leading zeroes. But 4 is sufficient. You\u2019ll find out that the addition of a single leading zero makes a mammoth difference to the time required to find a solution.<\/p>\n<p id=\"fa1c\">Our class is almost complete and we\u2019re ready to begin interacting with it using HTTP requests.<\/p>\n<\/section>\n<section>\n<hr \/>\n<h3 id=\"40c2\">Step 2: Our Blockchain as an\u00a0API<\/h3>\n<p id=\"b021\">We\u2019re going to use the Python Flask Framework. It\u2019s a micro-framework and it makes it easy to map endpoints to Python functions. This allows us talk to our blockchain over the web using HTTP requests.<\/p>\n<p id=\"55fc\">We\u2019ll create three methods:<\/p>\n<ul>\n<li id=\"a678\"><code>\/transactions\/new<\/code>\u00a0to create a new transaction to a block<\/li>\n<li id=\"39e2\"><code>\/mine<\/code>\u00a0to tell our server to mine a new block.<\/li>\n<li id=\"748e\"><code>\/chain<\/code>\u00a0to return the full Blockchain.<\/li>\n<\/ul>\n<h4 id=\"fe8e\">Setting up\u00a0Flask<\/h4>\n<p id=\"6068\">Our \u201cserver\u201d will form a single node in our blockchain network. Let\u2019s create some boilerplate code:<\/p>\n<p id=\"4b5f\">A brief explanation of what we\u2019ve added above:<\/p>\n<ul>\n<li id=\"196c\"><strong>Line 15:<\/strong>\u00a0Instantiates our Node. Read more about Flask\u00a0<a href=\"http:\/\/flask.pocoo.org\/docs\/0.12\/quickstart\/#a-minimal-application\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"http:\/\/flask.pocoo.org\/docs\/0.12\/quickstart\/#a-minimal-application\" data->here<\/a>.<\/li>\n<li id=\"d40b\"><strong>Line 18:<\/strong>\u00a0Create a random name for our node.<\/li>\n<li id=\"91a0\"><strong>Line 21:<\/strong>\u00a0Instantiate our\u00a0<code>Blockchain<\/code>\u00a0class.<\/li>\n<li id=\"d357\"><strong>Line 24\u201326:<\/strong>\u00a0Create the\u00a0<code>\/mine<\/code>\u00a0endpoint, which is a\u00a0<code>GET<\/code>\u00a0request.<\/li>\n<li id=\"83c2\"><strong>Line 28\u201330:<\/strong>\u00a0Create the\u00a0<code>\/transactions\/new<\/code>\u00a0endpoint, which is a\u00a0<code>POST<\/code>request, since we\u2019ll be sending data to it.<\/li>\n<li id=\"3244\"><strong>Line 32\u201338:<\/strong>\u00a0Create the\u00a0<code>\/chain<\/code>\u00a0endpoint, which returns the full Blockchain.<\/li>\n<li id=\"0276\"><strong>Line 40\u201341:<\/strong>\u00a0Runs the server on port 5000.<\/li>\n<\/ul>\n<h4 id=\"feb2\">The Transactions Endpoint<\/h4>\n<p id=\"a52a\">This is what the request for a transaction will look like. It\u2019s what the user sends to the server:<\/p>\n<pre id=\"0707\">{\r\n\"sender\": \"my address\",\r\n\"recipient\": \"someone else's address\",\r\n\"amount\": 5\r\n}<\/pre>\n<p id=\"2909\">Since we already have our class method for adding transactions to a block, the rest is easy. Let\u2019s write the function for adding transactions:<\/p>\n<p style=\"text-align: center;\">A method for creating Transactions<\/p>\n<h4 id=\"570a\">The Mining\u00a0Endpoint<\/h4>\n<p id=\"3c93\">Our mining endpoint is where the magic happens, and it\u2019s easy. It has to do three things:<\/p>\n<ol>\n<li id=\"bf40\">Calculate the Proof of Work<\/li>\n<li id=\"aa86\">Reward the miner (us) by adding a transaction granting us 1 coin<\/li>\n<li id=\"aed5\">Forge the new Block by adding it to the chain<\/li>\n<\/ol>\n<p id=\"6082\">Note that the recipient of the mined block is the address of our node. And most of what we\u2019ve done here is just interact with the methods on our Blockchain class. At this point, we\u2019re done, and can start interacting with our blockchain.<\/p>\n<h3 id=\"7101\">Step 3: Interacting with our Blockchain<\/h3>\n<p id=\"7139\">You can use plain old cURL or Postman to interact with our API over a network.<\/p>\n<p id=\"81ca\">Fire up the server:<\/p>\n<pre id=\"3085\">$ python blockchain.py<\/pre>\n<pre id=\"bbc3\">* Running on <a href=\"http:\/\/127.0.0.1:5000\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" data-href=\"http:\/\/127.0.0.1:5000\/\" data->http:\/\/127.0.0.1:5000\/<\/a> (Press CTRL+C to quit)<\/pre>\n<p id=\"e87a\">Let\u2019s try mining a block by making a\u00a0<code>GET<\/code>\u00a0request to\u00a0<code>http:\/\/www.experfy.com:5000\/mine<\/code>:<\/p>\n<figure id=\"ebf1\"><canvas width=\"75\" height=\"52\"><\/canvas><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*ufYwRmWgQeA-Jxg0zgYLOA.png\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*ufYwRmWgQeA-Jxg0zgYLOA.png\" \/><\/figure>\n<p style=\"text-align: center;\">Using Postman to make a GET\u00a0request<\/p>\n<p id=\"9ed9\">Let\u2019s create a new transaction by making a\u00a0<code>POST<\/code>\u00a0request to<code>http:\/\/www.experfy.com:5000\/transactions\/new<\/code>\u00a0with a body containing our transaction structure:<\/p>\n<figure id=\"05da\"><canvas width=\"75\" height=\"50\"><\/canvas><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*O89KNbEWj1vigMZ6VelHAg.png\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*O89KNbEWj1vigMZ6VelHAg.png\" \/><\/figure>\n<p style=\"text-align: center;\">Using Postman to make a POST\u00a0request<\/p>\n<p id=\"85eb\">If you aren\u2019t using Postman, then you can make the equivalent request using cURL:<\/p>\n<div id=\"fbfb\"><span style=\"font-family: courier new,courier,monospace;\"><span style=\"background-color: #d3d3d3;\">$ curl -X POST -H &#8220;Content-Type: application\/<\/span><\/span><span style=\"font-family: courier new,courier,monospace;\"><span style=\"background-color: #d3d3d3;\">json<\/span><\/span><span style=\"font-family: courier new,courier,monospace;\"><span style=\"background-color: #d3d3d3;\">&#8221; -d &#8216;{<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">&#8220;sender&#8221;: &#8220;d4ee26eee15148ee92c6cd394edd974e&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">&#8220;recipient&#8221;: &#8220;someone-other-address&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">&#8220;amount&#8221;: 5<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">}&#8217; &#8220;<\/span><a href=\"http:\/\/www.experfy.com:5000\/transactions\/new\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" data-href=\"http:\/\/www.experfy.com:5000\/transactions\/new\" data-><span style=\"background-color: #d3d3d3;\">http:\/\/www.experfy.com:5000\/transactions\/new<\/span><\/a><span style=\"background-color: #d3d3d3;\">&#8220;<\/span><\/span><\/div>\n<p id=\"311a\">I restarted my server, and mined two blocks, to give 3 in total. Let\u2019s inspect the full chain by requesting\u00a0<code><a href=\"http:\/\/www.experfy.com:5000\/chain:\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"http:\/\/www.experfy.com:5000\/chain:\" data->http:\/\/www.experfy.com:5000\/chain<\/a><\/code><a href=\"http:\/\/www.experfy.com:5000\/chain:\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"http:\/\/www.experfy.com:5000\/chain:\" data->:<\/a><\/p>\n<div id=\"e8d9\"><span style=\"font-family: courier new,courier,monospace;\"><span style=\"background-color: #d3d3d3;\">{<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0 &#8220;chain&#8221;: [<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 {<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;index&#8221;: 1,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;previous_hash&#8221;: 1,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;proof&#8221;: 100,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;timestamp&#8221;: 1506280650.770839,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;transactions&#8221;: []<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 },<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 {<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;index&#8221;: 2,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;previous_hash&#8221;: &#8220;c099bc&#8230;bfb7&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;proof&#8221;: 35293,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;timestamp&#8221;: 1506280664.717925,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;transactions&#8221;: [<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;amount&#8221;: 1,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;recipient&#8221;: &#8220;8bbcb347e0634905b0cac7955bae152b&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;sender&#8221;: &#8220;0&#8221;<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 ]<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 },<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 {<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;index&#8221;: 3,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;previous_hash&#8221;: &#8220;eff91a&#8230;10f2&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;proof&#8221;: 35089,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;timestamp&#8221;: 1506280666.1086972,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;transactions&#8221;: [<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 {<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;amount&#8221;: 1,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;recipient&#8221;: &#8220;8bbcb347e0634905b0cac7955bae152b&#8221;,<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 &#8220;sender&#8221;: &#8220;0&#8221;<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0 }<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0\u00a0\u00a0 ]<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0\u00a0\u00a0 }<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0 ],<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">\u00a0 &#8220;length&#8221;: 3<\/span><br \/>\n<span style=\"background-color: #d3d3d3;\">}<\/span><\/span><\/div>\n<h3 id=\"849f\">Step 4: Consensus<\/h3>\n<p id=\"c7d9\">This is very cool. We\u2019ve got a basic Blockchain that accepts transactions and allows us to mine new Blocks. But the whole point of Blockchains is that they should be\u00a0<em>decentralized<\/em>. And if they\u2019re decentralized, how on earth do we ensure that they all reflect the same chain? This is called the problem of\u00a0<em>Consensus<\/em>, and we\u2019ll have to implement a Consensus Algorithm if we want more than one node in our network.<\/p>\n<h4 id=\"8e32\">Registering new\u00a0Nodes<\/h4>\n<p id=\"461d\">Before we can implement a Consensus Algorithm, we need a way to let a node know about neighbouring nodes on the network. Each node on our network should keep a registry of other nodes on the network. Thus, we\u2019ll need some more endpoints:<\/p>\n<ol>\n<li id=\"5b1c\"><code>\/nodes\/register<\/code>\u00a0to accept a list of new nodes in the form of URLs.<\/li>\n<li id=\"7e9f\"><code>\/nodes\/resolve<\/code>\u00a0to implement our Consensus Algorithm, which resolves any conflicts\u2014to ensure a node has the correct chain.<\/li>\n<\/ol>\n<p id=\"d653\">We\u2019ll need to modify our Blockchain\u2019s constructor and provide a method for registering nodes:<\/p>\n<figure id=\"08fb\"><figcaption>A method for adding neighbouring nodes to our Network<\/figcaption><\/figure>\n<p id=\"e01e\">Note that we\u2019ve used a\u00a0<code>set()<\/code>\u00a0to hold the list of nodes. This is a cheap way of ensuring that the addition of new nodes is idempotent\u2014meaning that no matter how many times we add a specific node, it appears exactly once.<\/p>\n<h4 id=\"2491\">Implementing the Consensus Algorithm<\/h4>\n<p id=\"1921\">As mentioned, a conflict is when one node has a different chain to another node. To resolve this, we\u2019ll make the rule that\u00a0<em>the longest valid chain is authoritative.<\/em>\u00a0In other words, the longest chain on the network is the\u00a0<em>de-facto<\/em>one. Using this algorithm, we reach\u00a0<em>Consensus<\/em>\u00a0amongst the nodes in our network.<\/p>\n<p id=\"4779\">The first method\u00a0<code>valid_chain()<\/code>\u00a0is responsible for checking if a chain is valid by looping through each block and verifying both the hash and the proof.<\/p>\n<p id=\"a99b\"><code>resolve_conflicts()<\/code>\u00a0is a method which loops through all our neighbouring nodes,\u00a0<em>downloads<\/em>\u00a0their chains and verifies them using the above method.\u00a0<strong>If a valid chain is found, whose length is greater than ours, we replace ours.<\/strong><\/p>\n<p id=\"cd9a\">Let\u2019s register the two endpoints to our API, one for adding neighbouring nodes and the another for resolving conflicts:<\/p>\n<p id=\"f01b\">At this point you can grab a different machine if you like, and spin up different nodes on your network. Or spin up processes using different ports on the same machine. I spun up another node on my machine, on a different port, and registered it with my current node. Thus, I have two nodes:\u00a0<code><a href=\"http:\/\/www.experfy.com:5000\/\" target=\"_blank\" rel=\"noopener noreferrer\" data-href=\"http:\/\/www.experfy.com:5000\">http:\/\/www.experfy.com:5000<\/a><\/code>\u00a0and\u00a0<code>http:\/\/www.experfy.com:5001<\/code>.<\/p>\n<figure id=\"6b41\"><canvas width=\"75\" height=\"42\"><\/canvas><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*Dd78u-gmtwhQWHhPG3qMTQ.png\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*Dd78u-gmtwhQWHhPG3qMTQ.png\" \/><\/figure>\n<p style=\"text-align: center;\">Registering a new\u00a0Node<\/p>\n<p id=\"75a7\">I then mined some new Blocks on node 2, to ensure the chain was longer. Afterward, I called\u00a0<code>GET \/nodes\/resolve<\/code>\u00a0on node 1, where the chain was replaced by the Consensus Algorithm:<\/p>\n<figure id=\"fe84\"><canvas width=\"75\" height=\"47\"><\/canvas><img decoding=\"async\" src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*SGO5MWVf7GguIxfz6S8NVw.png\" data-src=\"https:\/\/cdn-images-1.medium.com\/max\/800\/1*SGO5MWVf7GguIxfz6S8NVw.png\" \/><\/figure>\n<p style=\"text-align: center;\">Consensus Algorithm at\u00a0Work<\/p>\n<p id=\"88ac\">And that\u2019s a wrap&#8230; Go get some friends together to help test out your Blockchain.<\/p>\n<\/section>\n<section>\n<hr \/>\n<p id=\"5262\">I hope that this has inspired you to create something new. I\u2019m ecstatic about Cryptocurrencies because I believe that Blockchains will rapidly change the way we think about economies, governments and record-keeping.<\/p>\n<p id=\"6163\"><strong>Update:<\/strong>\u00a0I\u2019m planning on following up with a Part 2, where we\u2019ll extend our Blockchain to have a Transaction Validation Mechanism as well as discuss some ways in which you can productionize your Blockchain.<\/p>\n<p>First appeared in <a href=\"https:\/\/hackernoon.com\/learn-blockchains-by-building-one-117428612f46\" rel=\"noopener\">Hackernoon<\/a><\/p>\n<\/section>\n","protected":false},"excerpt":{"rendered":"<p>You want to know how Blockchains work&mdash;the fundamental technology behind them. Remember that a blockchain is an&nbsp;immutable, sequential&nbsp;chain of records called Blocks. They can contain transactions, files or any data you like, really. But understanding Blockchains isn&rsquo;t easy. Learn by doing. It forces you to deal with the subject matter at a code level, which gets it sticking at the end of this guide, you&rsquo;ll have a functioning Blockchain with a solid grasp of how they work.<\/p>\n","protected":false},"author":409,"featured_media":3411,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"content-type":"","footnotes":""},"categories":[192],"tags":[98],"ppma_author":[2958],"class_list":["post-1425","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-fintech","tag-blockchain"],"authors":[{"term_id":2958,"user_id":409,"is_guest":0,"slug":"daniel-van-flymen","display_name":"Daniel Flymen","avatar_url":"https:\/\/secure.gravatar.com\/avatar\/?s=96&d=mm&r=g","user_url":"","last_name":"Flymen","first_name":"Daniel","job_title":"","description":"<a href=\"https:\/\/twitter.com\/van_flymen?lang=en\">Daniel van Flymen<\/a>, Engineering Manager at <a href=\"http:\/\/www.blinkhealth.com\/\">Blink Health<\/a>, is an entrepreneur with a background in Mathematics and Art, and interested in Blockchains."}],"_links":{"self":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1425","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/users\/409"}],"replies":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/comments?post=1425"}],"version-history":[{"count":4,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1425\/revisions"}],"predecessor-version":[{"id":29390,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/posts\/1425\/revisions\/29390"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/media\/3411"}],"wp:attachment":[{"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/media?parent=1425"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/categories?post=1425"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/tags?post=1425"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.experfy.com\/blog\/wp-json\/wp\/v2\/ppma_author?post=1425"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}