<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chenjiejie on Medium]]></title>
        <description><![CDATA[Stories by Chenjiejie on Medium]]></description>
        <link>https://medium.com/@chenjiejie334?source=rss-106b5e523d2c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3jU5Iuq_3lPqa0jLfXkTNg.jpeg</url>
            <title>Stories by Chenjiejie on Medium</title>
            <link>https://medium.com/@chenjiejie334?source=rss-106b5e523d2c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:30:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chenjiejie334/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Create ethereum mnemonic and wallet address .]]></title>
            <link>https://medium.com/@chenjiejie334/create-ethereum-mnemonic-and-wallet-address-b21f54e9af7e?source=rss-106b5e523d2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b21f54e9af7e</guid>
            <category><![CDATA[wallet]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethersjs]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Chenjiejie]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 06:36:36 GMT</pubDate>
            <atom:updated>2023-02-18T09:15:22.330Z</atom:updated>
            <content:encoded><![CDATA[<h3>Create ethereum mnemonic and wallet address .</h3><p>Dear everyone</p><p>Let me introduce the way to generate ethereum wallet mnemonic and create addresses using bip39 and hdkey</p><pre>import bip39 from &#39;bip39&#39;<br>import hdkey from &#39;hdkey&#39;<br>const HARDEND= &quot;m/44&#39;/60&#39;/0&#39;/0/&quot;<br><br>/**<br>* 12 words 128bit<br>* 15 words 160bits<br>* 18 words 192bits<br>* 21 words 224bits<br>* 24 words 256bits<br>*/<br>const mnemonic = bip39.generateMnemonic(128)</pre><p>You can get 12 | 15 | 18 | 21 | 24 words by parameter.<br>ex: subway fee primary wrap often ethics movie panic delay enlist mandate left<br>Here is wallet address generate function.</p><pre><br>const getAddressFromMnemonic = (mnemonic: string, index: number) =&gt; {<br>  const seed=bip39.mnemonicToSeedSync(mnemonic);<br>  const lastRoot = hdkey.fromMasterSeed(seed);<br>  const addrNode = lastRoot.derive(HARDEND + index);<br>  const privatekey = addrNode.privateKey;<br>  const pubKey = ethUtil.privateToPublic(privatekey);<br>  const address = ethUtil.publicToAddress(pubKey).toString(&#39;hex&#39;);<br>  return address<br>}</pre><p>So you can get public address from mnemonic and index.<br>Thank you for reading. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b21f54e9af7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain is not only crappy technology but a bad vision for the future]]></title>
            <link>https://medium.com/@chenjiejie334/blockchain-is-not-only-crappy-technology-but-a-bad-vision-for-the-future-b8cd64d548e3?source=rss-106b5e523d2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8cd64d548e3</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Chenjiejie]]></dc:creator>
            <pubDate>Mon, 09 Apr 2018 16:34:15 GMT</pubDate>
            <atom:updated>2023-02-18T09:21:02.478Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Blockchain is not only crappy technology but a bad vision for the future. Its failure to achieve adoption to date is because systems built on trust, norms, and institutions inherently function better than the type of no-need-for-trusted-parties systems blockchain envisions. That’s permanent: no matter how much blockchain improves it is still headed in the wrong direction.</em></p><p>This December I wrote a <a href="http://www.sohu.com/a/213276912_114778">w</a>i <a href="https://www.calcalist.co.il/markets/articles/0,7340,L-3728835,00.html">d</a>e <a href="https://www.bright.nl/bright-business/blockchain-heeft-geen-toegevoegde-waarde">l</a>y- <a href="http://news.joins.com/article/22236321">c</a>i <a href="https://www.e15.cz/kryptomeny/analytik-revoluce-se-nekona-blockchain-stale-ceka-na-vetsi-vyuziti-mimo-bitcoin-1341547">r</a>c <a href="https://chibicode.com/jp/blockchain/">u</a>l <a href="https://www.americanbanker.com/opinion/dont-believe-the-hype-there-are-no-good-uses-for-blockchain">a</a>t <a href="https://www.cnbc.com/2017/12/26/ten-years-in-nobody-has-come-up-with-a-use-for-blockchain.html?__source=facebook%7Cmain">e</a>d <a href="https://hackernoon.com/ten-years-in-nobody-has-come-up-with-a-use-case-for-blockchain-ee98c180100">article</a> on the inapplicability of blockchain to any actual problem. People objected mostly not to the technology argument, but rather <a href="https://medium.com/@DisRconsult/ok-im-only-a-cpa-with-some-legal-experience-background-74467b057b9d">hoped</a> <a href="https://medium.com/@matthewpirkowski/my-comment-has-little-to-do-with-the-number-of-possible-comparisons-and-everything-to-do-with-the-32b8e460e085">that</a> <a href="https://medium.com/@nickramos/great-points-but-you-are-missing-the-most-important-use-case-and-the-need-for-it-is-happening-666aa5de8708">decentralization</a> <a href="https://medium.com/@conches/the-reason-why-i-am-hopeful-for-the-blockchain-is-not-to-do-what-we-are-already-doing-better-but-to-87d80ed293b6">could</a> <a href="https://venturebeat.com/2017/12/23/why-you-want-blockchain-based-ai-even-if-you-dont-know-it-yet/">produce</a> <a href="https://medium.com/@brianhanley/the-real-meaning-of-cryptocurrency-is-the-same-one-that-drove-ben-franklin-to-print-money-for-the-7dd2aae9cd28">integrity</a>.</p><p>Let’s start with this: Venmo is a free service to transfer dollars, and bitcoin transfers are not free. Yet after I wrote<a href="https://medium.com/@kaistinchcombe/ten-years-in-nobody-has-come-up-with-a-use-case-for-blockchain-ee98c180100"> an article last December</a> saying bitcoin had no use, someone<a href="https://medium.com/@aaronjmendelsohn/there-is-so-much-wrong-with-this-i-couldnt-get-through-it-all-2dd24a109e0c"> responded</a> that Venmo and Paypal are raking in consumers’ money and people should switch to bitcoin.</p><p>What a surreal contrast between blockchain’s non-usefulness/non-adoption and the conviction of its believers! It’s so entirely evident that this person didn’t become a bitcoin enthusiast because they were looking for a convenient, free way to transfer money from one person to another and discovered bitcoin. In fact, I would assert that there is <em>no single person in existence</em> who had a problem they wanted to solve, discovered that an available blockchain solution was the best way to solve it, and therefore became a blockchain enthusiast.</p><blockquote><em>There is </em>no single person in existence<em> who had a problem they wanted to solve, discovered that an available blockchain solution was the best way to solve it, and therefore became a blockchain enthusiast.</em></blockquote><p>The number of retailers accepting cryptocurrency as a form of payment is<a href="http://www.businessinsider.com/bitcoin-price-rises-but-retailers-wont-accept-it-7-2017"> declining</a>, and its biggest corporate boosters like <a href="https://www.google.com/search?q=ibm+supply+chain+solutions">IBM</a>, <a href="http://ir.nasdaq.com/releasedetail.cfm?releaseid=948326">NASDAQ</a>, <a href="https://www.coindesk.com/fidelity-ceo-talks-love-bitcoin-blockchain-will-change-markets/">Fidelity</a>, <a href="https://www.linkedin.com/pulse/swift-official-blockchain-dead-end-patrick-mcconnell/">Swift</a> and Walmart have gone long on press but short on actual rollout. Even the most prominent blockchain company, Ripple, <a href="https://www.bloomberg.com/news/articles/2018-01-25/ripple-wants-xrp-to-be-bitcoin-for-banks-if-only-the-banks-wanted-it">doesn’t use blockchain in its product</a>. You read that right: the company <em>Ripple</em> decided the best way to move money across international borders was to <em>not use Ripples</em>.</p><h3>A blockchain is a literal technology, not a metaphor</h3><p>Why all the enthusiasm for something so useless in practice?</p><p>People have made a number of implausible claims about the future of blockchain-like that you <a href="https://venturebeat.com/2017/12/23/why-you-want-blockchain-based-ai-even-if-you-dont-know-it-yet/">should use it for AI</a> in place of the type of behavior-tracking that google and facebook do, for example. This is based on a misunderstanding of what a blockchain is. A blockchain isn’t an ethereal thing out there in the universe that you can “put” things into, it’s a specific data structure: a linear transaction log, typically replicated by computers whose owners (called miners) are rewarded for logging new transactions.</p><p>There are two things that are cool about this particular data structure. One is that a change in any block invalidates every block after it, which means that you can’t tamper with historical transactions. The second is that you only get rewarded if you’re working on the same chain as everyone else, so each participant has an incentive to go with the consensus.</p><p>The end result is a shared definitive historical record. And, what’s more, because consensus is formed by each person acting in their own interest, adding a false transaction or working from a different history just means you’re not getting paid and everyone else is. Following the rules is mathematically enforced-no government or police force need come in and tell you the transaction you’ve logged is false (or extort bribes or bully the participants). It’s a powerful idea.</p><p>So in summary, here’s what blockchain-the-technology is: <em>“Let’s create a very long sequence of small files — each one containing a hash of the previous file, some new data, and the answer to a difficult math problem — and divide up some money every hour among anyone willing to certify and store those files for us on their computers.”</em></p><p>Now, here’s what blockchain-the-metaphor is: <em>“What if everyone keeps their records in a tamper-proof repository not owned by anyone?”</em></p><p>An illustration of the difference: In 2006, Walmart launched a system to track its bananas and mangoes from field to store. In 2009 they abandoned it because of logistical problems getting everyone to enter the data, and in 2017 they re-launched it (to <a href="https://www.google.com/search?q=%22six%20days,%2018%20hours,%20and%2026%20minutes%22">much fanfare</a>) on blockchain. If someone comes to you with “the mango-pickers don’t like doing data entry,” “I know: let’s create a very long sequence of small files, each one containing a hash of the previous file” is a nonsense answer, but “What if everyone keeps their records in a tamper-proof repository not owned by anyone?” at least addresses the right question!</p><h3>Blockchain-based trustworthiness falls apart in practice</h3><p>People treat blockchain as a “futuristic integrity wand”-wave a blockchain at the problem, and suddenly your data will be valid. For almost anything people want to be <em>valid</em>, blockchain has been proposed as a solution.</p><p>It’s true that tampering with data stored on a blockchain is hard, but it’s false that blockchain is a good way to create data that has integrity.</p><blockquote><em>It’s true that tampering with data stored on a blockchain is hard, but it’s false that blockchain is a good way to create data that has integrity.</em></blockquote><p>To understand why this is the case, let’s work from the practical to the theoretical. For example, let’s consider a widely-proposed use case for blockchain: buying an e-book with a “smart” contract. The goal of the blockchain is, you don’t trust an e-book vendor and they don’t trust you (because you’re just two individuals on the internet), but, because it’s on blockchain, you’ll be able to trust the transaction.</p><p>In the traditional system, once you pay you’re <em>hoping</em> you’ll receive the book, but once the vendor has your money they don’t have any incentive to deliver. You’re relying on Visa or Amazon or the government to make things fair-what a recipe for being a chump! In contrast, on a blockchain system, by executing the transaction as a record in a tamper-proof repository not owned by anyone, the transfer of money and digital product is automatic, atomic, and direct, with no middleman needed to arbitrate the transaction, dictate terms, and take a fat cut on the way. Isn’t that better for everybody?</p><p>Hm. Perhaps you are very skilled at writing software. When the novelist proposes the smart contract, you take an hour or two to make sure that the contract will withdraw only an amount of money equal to the agreed-upon price, and that the book — rather than some other file, or nothing at all — will actually arrive.</p><p>Auditing software is hard! The most-heavily scrutinized smart contract in history had a small bug that nobody noticed — that is, until someone did notice it, and used it to steal fifty million dollars. If cryptocurrency enthusiasts putting together a $150m investment fund can’t properly audit the software, how confident are you in your e-book audit? Perhaps you would rather write your own counteroffer software contract, in case this e-book author has hidden a recursion bug in their version to drain your ethereum wallet of all your life savings?</p><p>It’s a complicated way to buy a book! It’s not <em>trustless</em>, you’re trusting in the software (and your ability to defend yourself in a software-driven world), instead of trusting other people.</p><p>Another example: the <a href="http://web.archive.org/web/20180313084043/https://qz.com/1227050/sierra-leone-elections-powered-by-blockchain/">purported advantages</a> for a voting system in a weakly-governed country. “Keep your voting records in a tamper-proof repository not owned by anyone” <em>sounds</em> right — yet is your Afghan villager going to download the blockchain from a broadcast node and decrypt the Merkle root from his Linux command line to independently verify that his vote has been counted? Or will he rely on the mobile app of a trusted third party — like the nonprofit or open-source consortium <a href="https://qz.com/1234268/sierra-leone-blockchain-election-election-commission-denies-use-of-blockchain/">administering the election</a> or providing the software?</p><p>These sound like stupid examples — novelists and villagers hiring e-bodyguard hackers to protect them from malicious customers and nonprofits whose clever smart-contracts might steal their money and votes?? — until you realize that’s actually <em>the point</em>. Instead of relying on trust or regulation, in the blockchain world, individuals are <em>on-purpose</em> responsible for their own security precautions. And if the software they use is malicious or buggy, they should have read the software more carefully.</p><h3>The entire worldview underlying blockchain is wrong</h3><p>You actually see it over and over again. Blockchain systems are supposed to be <em>more</em> trustworthy, but in fact they are <em>the least trustworthy systems in the world</em>. Today, in less than a decade, <a href="https://hackernoon.com/ten-years-in-nobody-has-come-up-with-a-use-case-for-blockchain-ee98c180100#75b9">three successive top bitcoin exchanges</a> have been hacked, another is <a href="https://motherboard.vice.com/en_us/article/pam4xn/coinbase-insider-trading-lawsuit-gdax-bitcoin-cash">accused</a> of insider trading, <a href="https://hackernoon.com/ten-years-in-nobody-has-come-up-with-a-use-case-for-blockchain-ee98c180100#6aa2">the demonstration-project DAO smart contract got drained</a>, crypto price swings are ten times those of the world’s most mismanaged currencies, and bitcoin, the “killer app” of crypto transparency, is almost certainly<a href="http://www.tetherreport.com/"> artificially</a> <a href="https://www.cnbc.com/2018/02/02/tether-what-you-need-to-know-about-the-cryptocurrency-worrying-markets.html">propped up</a> by<a href="https://hackernoon.com/the-curious-tale-of-tethers-6b0031eead87"> fake</a> <a href="https://arstechnica.com/tech-policy/2018/02/tether-says-its-cryptocurrency-is-worth-2-billion-but-its-audit-failed/">transactions</a> <a href="https://www.reddit.com/r/btc/comments/7e54vo/how_is_tether_even_receiving_usd_since_the/">involving</a> <a href="https://cointelegraph.com/news/tether-really-isnt-a-scam-company-promises">billions</a> <a href="https://medium.com/@bitfinexed/the-mystery-of-the-bitfinex-tether-bank-and-why-this-is-suspicious-a8a6407a1241">of</a> <em>literally imaginary</em><a href="https://medium.com/@bitfinexed/"> dollars</a>.</p><p>Blockchain systems do not magically make the data in them accurate or the people entering the data trustworthy, they merely enable you to audit whether it has been tampered with. A person who sprayed pesticides on a mango can still enter onto a blockchain system that the mangoes were organic. A corrupt government can create a blockchain system to count the votes and just allocate an extra million addresses to their cronies. An investment fund whose charter is written in software can still misallocate funds.</p><p>How then, is trust created?</p><p>In the case of buying an e-book, <em>even if you’re buying it with a smart contract,</em> instead of auditing the software you’ll rely on one of four things, each of them characteristics of the “old way”: either the author of the smart contract is someone you know of and trust, the seller of the e-book has a <a href="https://en.wikipedia.org/wiki/The_Evolution_of_Cooperation">reputation to uphold</a>, you or friends of yours have bought e-books from this seller in the past successfully, or you’re just willing to hope that this person will deal fairly. In each case, <em>even</em> if the transaction is effectuated via a smart contract, in practice you’re relying on trust of a counterparty or middleman, not your self-protective right to audit the software, each man an island unto himself. The contract still works, but the fact that the promise is written in auditable software rather than government-enforced English makes it <em>less</em> transparent, not <em>more</em> transparent.</p><p>The same for the vote counting. Before blockchain can even get involved, you need to trust that voter registration is done fairly, that ballots are given only to eligible voters, that the votes are made anonymously rather than bought or intimidated, that the vote displayed by the balloting system is the same as the vote recorded, and that no extra votes are given to the political cronies to cast. Blockchain makes none of these problems easier and many of them harder-but more importantly, solving them in a blockchain context requires a set of awkward workarounds that undermine the core premise. So we know the entries are valid, let’s allow only trusted nonprofits to make entries-and you’re back at the good old “classic” ledger. In fact, if you look at <em>any</em> blockchain solution, inevitably you’ll find an awkward workaround to re-create trusted parties in a trustless world.</p><h3>A crypto-medieval system</h3><p>Yet absent these “old way” factors-supposing you actually attempted to rely on blockchain’s self-interest/self-protection to build a real system-you’d be in a real mess.</p><p>The Knights Templar <a href="https://en.wikipedia.org/wiki/Knights_Templar">was sort of a banking system, actually</a>.</p><p>Eight hundred years ago in Europe — with weak governments unable to enforce laws and trusted counterparties few, fragile and far between — theft was rampant, safe banking was a fantasy, and personal security was at the point of the sword. This is what Somalia looks like now, and also, what it looks like to transact on the blockchain <em>in the ideal scenario</em>.</p><p>Somalia on purpose. That’s the vision. Nobody wants it!</p><p><em>Even the most die-hard crypto enthusiasts</em> prefer in practice to rely on trust rather than their own crypto-medieval systems. 93% of bitcoins are mined by managed consortiums, yet none of the consortiums use smart contracts to manage payouts. Instead, they<a href="https://slushpool.com/home/"> promise</a> things like a “long history of stable and accurate payouts.” Sounds like a trustworthy middleman!</p><p>Same with Silk Road, a cryptocurrency-driven online drug bazaar. The key to Silk Road wasn’t the bitcoins (that was just to evade government detection), it was the <em>reputation scores</em> that allowed people to trust criminals. And the reputation scores weren’t tracked on a tamper-proof blockchain, they were tracked by a trusted middleman!</p><p>If Ripple, Silk Road, Slush Pool, and the DAO all prefer “old way” systems of creating and enforcing trust, it’s no wonder that the outside world had not adopted trustless systems either!</p><h3>In the name of all blockchain stands for, it’s time to abandon blockchain</h3><p>A decentralized, tamper-proof repository sounds like a great way to audit where your mango comes from, how fresh it is, and whether it has been sprayed with pesticides or not. But actually, laws on food labeling, nonprofit or government inspectors, an independent, trusted free press, empowered workers who trust whistleblower protections, credible grocery stores, your local nonprofit farmer’s market, and so on, do a way better job. People who actually care about food safety do not adopt blockchain because <em>trusted is better than trustless. </em>Blockchain’s technology mess exposes its metaphor mess — a software engineer pointing out that storing the data a sequence of small hashed files won’t get the mango-pickers to accurately report whether they sprayed pesticides is <em>also</em> pointing out why peer-to-peer interaction with no regulations, norms, middlemen, or trusted parties is actually a bad way to empower people.</p><p>Like the farmer’s market or the organic labeling standard, so many <em>real</em> ideas are hiding in plain sight. Do you wish there was a type of financial institution that was secure and well-regulated in all the traditional ways, but also has the integrity of being people-powered? A credit union’s members elect its directors, and the transaction-processing revenue is divided up among the members. Move your money! Prefer a deflationary monetary policy? Central bankers are appointed by elected leaders. Want to make elections more secure and democratic? Help write open source voting software, go out and register voters, or volunteer as an election observer here or abroad! Wish there was a trusted e-book delivery service that charged lower transaction fees and distributed more of the earnings to the authors? You can <em>already</em> consider stated payout rates when you buy music or books, buy directly from the authors, or start your own e-book site that’s even better than what’s out there!</p><p>Projects based on the elimination of trust have failed to capture customers’ interest <em>because trust is actually so damn valuable</em>. A lawless and mistrustful world where self-interest is the only principle and paranoia is the only source of safety is a not a paradise but a crypto-medieval hellhole.</p><p>As a society, and as technologists and entrepreneurs in particular, we’re going to have to get good at cooperating — at building trust, and, at being trustworthy. Instead of directing resources to the <em>elimination</em> of trust, we should direct our resources to the <em>creation</em> of trust-whether we use a long series of sequentially hashed files as our storage medium or not.</p><p><em>Kai Stinchcombe coined the terms “crypto-medieval” “futuristic integrity wand” and “smart mango.” Please use freely: coining terms makes you a futurist.</em></p><p><em>Originally published at </em><a href="https://medium.com/@kaistinchcombe/decentralized-and-trustless-crypto-paradise-is-actually-a-medieval-hellhole-c1ca122efdec"><em>https://medium.com</em></a><em> on April 9, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8cd64d548e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Blockchains by Building One]]></title>
            <link>https://medium.com/@chenjiejie334/learn-blockchains-by-building-one-6de99d43bf57?source=rss-106b5e523d2c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6de99d43bf57</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[news]]></category>
            <dc:creator><![CDATA[Chenjiejie]]></dc:creator>
            <pubDate>Mon, 25 Sep 2017 06:05:49 GMT</pubDate>
            <atom:updated>2023-02-18T09:21:23.333Z</atom:updated>
            <content:encoded><![CDATA[<p>You’re here because, like me, you’re psyched about the rise of Cryptocurrencies. And you want to know how Blockchains work-the fundamental technology behind them.</p><p>But understanding Blockchains isn’t easy-or at least wasn’t for me. I trudged through dense videos, followed porous tutorials, and dealt with the amplified frustration of too few examples.</p><p>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’ll have a functioning Blockchain with a solid grasp of how they work.</p><p>Remember that a blockchain is an <em>immutable, sequential </em>chain of records called Blocks. They can contain transactions, files or any data you like, really. But the important thing is that they’re <em>chained</em> together using <em>hashes</em>.</p><p>If you aren’t sure what a hash is, <a href="https://learncryptography.com/hash-functions/what-are-hash-functions">here’s an explanation</a>.</p><p><strong><em>Who is this guide aimed at?</em></strong> You should be comfy reading and writing some basic Python, as well as have some understanding of how HTTP requests work, since we’ll be talking to our Blockchain over HTTP.</p><p><strong><em>What do I need?</em> </strong>Make sure that <a href="https://www.python.org/downloads/">Python 3.6</a>+ (along with pip) is installed. You&#39;ll also need to install Flask and the wonderful Requests library:</p><pre>pip install Flask==0.12.2 requests==2.18.4</pre><p>Oh, you’ll also need an HTTP Client, like <a href="https://www.getpostman.com/">Postman</a> or cURL. But anything will do.</p><p><strong><em>Where’s the final code? </em></strong>The source code is <a href="https://github.com/dvf/blockchain">available here</a>.</p><p>Open up your favourite text editor or IDE, personally I ❤️ <a href="https://www.jetbrains.com/pycharm/">PyCharm</a>. Create a new file, called blockchain.py. We&#39;ll only use a single file, but if you get lost, you can always refer to the <a href="https://github.com/dvf/blockchain">source code</a>.</p><h3>Representing a Blockchain</h3><p>We’ll create a Blockchain class whose constructor creates an initial empty list (to store our blockchain), and another to store transactions. Here&#39;s the blueprint for our class:</p><p>Blueprint of our Blockchain Class</p><p>Our Blockchain class is responsible for managing the chain. It will store transactions and have some helper methods for adding new blocks to the chain. Let&#39;s start fleshing out some methods.</p><h3>What does a Block look like?</h3><p>Each Block has an <em>index</em>, a <em>timestamp</em> (in Unix time), a <em>list of transactions</em>, a <em>proof</em> (more on that later), and the <em>hash of the previous Block</em>.</p><p>Here’s an example of what a single Block looks like:</p><p>Example of a Block in our Blockchain</p><p>At this point, the idea of a <em>chain</em> should be apparent-each new block contains within itself, the hash of the previous Block. <strong>This is crucial because it’s what gives blockchains immutability:</strong> If an attacker corrupted an earlier Block in the chain then subsequent blocks will contain incorrect hashes.</p><p><em>Does this make sense? If it doesn’t, take some time to let it sink in-it’s the core idea behind blockchains.</em></p><h3>Adding Transactions to a Block</h3><p>We’ll need a way of adding transactions to a Block. Our new_transaction() method is responsible for this, and it&#39;s pretty straight-forward:</p><p>After new_transaction() adds a transaction to the list, it returns the <em>index</em> of the block which the transaction will be added to- <em>the next one to be mined.</em> This will be useful later on, to the user submitting the transaction.</p><h3>Creating new Blocks</h3><p>When our Blockchain is instantiated we&#39;ll need to seed it with a <em>genesis</em> block-a block with no predecessors. We&#39;ll also need to add a <em>&quot;proof&quot;</em> to our genesis block which is the result of mining (or proof of work). We&#39;ll talk more about mining later.</p><p>In addition to creating the <em>genesis</em> block in our constructor, we’ll also flesh out the methods for new_block(), new_transaction() and hash():</p><p>The above should be straight-forward-I’ve added some comments and <em>docstrings</em> to help keep it clear. We’re almost done with representing our blockchain. But at this point, you must be wondering how new blocks are created, forged or mined.</p><h3>Understanding Proof of Work</h3><p>A Proof of Work algorithm (PoW) is how new Blocks are created or <em>mined </em>on the blockchain<em>. </em>The goal of PoW is to discover a number which solves a problem. The number must be <strong>difficult to find</strong> <strong>but easy to verify</strong> -computationally speaking-by anyone on the network. This is the core idea behind Proof of Work.</p><p>We’ll look at a very simple example to help this sink in.</p><p>Let’s decide that the <em>hash</em> of some integer x multiplied by another y must end in 0. So, hash(x * y) = ac23dc...0. And for this simplified example, let&#39;s fix x = 5. Implementing this in Python:</p><pre>from hashlib import sha256 x = 5while sha256(f&#39;{x*y}&#39;.encode()).hexdigest()[-1] != &quot;0&quot;:<br>y = 0 # We don&#39;t know what y should be yet... <br> y += 1 print(f&#39;The solution is y = {y}&#39;)</pre><p>The solution here is y = 21. Since, the produced hash ends in 0:</p><pre>hash(5 * 21) = 1253e9373e...5e3600155e860</pre><p>In Bitcoin, the Proof of Work algorithm is called . And it’s not too different from our basic example above. It’s 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-in a transaction.</p><p>The network is able to <em>easily </em>verify their solution.</p><h3>Implementing basic Proof of Work</h3><p>Let’s implement a similar algorithm for our blockchain. Our rule will be similar to the example above:</p><blockquote>Find a number <em>p</em> that when hashed with the previous block’s solution a hash with 4 leading s is produced.</blockquote><p>To adjust the difficulty of the algorithm, we could modify the number of leading zeroes. But 4 is sufficient. You’ll find out that the addition of a single leading zero makes a mammoth difference to the time required to find a solution.</p><p>Our class is almost complete and we’re ready to begin interacting with it using HTTP requests.</p><p>We’re going to use the Python Flask Framework. It’s 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><p>We’ll create three methods:</p><ul><li>/transactions/new to create a new transaction to a block</li><li>/mine to tell our server to mine a new block.</li><li>/chain to return the full Blockchain.</li></ul><h3>Setting up Flask</h3><p>Our “server” will form a single node in our blockchain network. Let’s create some boilerplate code:</p><p>A brief explanation of what we’ve added above:</p><ul><li><strong>Line 15:</strong> Instantiates our Node. Read more about Flask <a href="http://flask.pocoo.org/docs/0.12/quickstart/#a-minimal-application">here</a>.</li><li><strong>Line 18:</strong> Create a random name for our node.</li><li><strong>Line 21:</strong> Instantiate our Blockchain class.</li><li><strong>Line 24–26:</strong> Create the /mine endpoint, which is a GET request.</li><li><strong>Line 28–30:</strong> Create the /transactions/new endpoint, which is a POST request, since we&#39;ll be sending data to it.</li><li><strong>Line 32–38:</strong> Create the /chain endpoint, which returns the full Blockchain.</li><li><strong>Line 40–41:</strong> Runs the server on port 5000.</li></ul><h3>The Transactions Endpoint</h3><p>This is what the request for a transaction will look like. It’s what the user sends to the server:</p><pre>{<br> &quot;sender&quot;: &quot;my address&quot;,<br> &quot;recipient&quot;: &quot;someone else&#39;s address&quot;,<br> &quot;amount&quot;: 5<br>}</pre><p>Since we already have our class method for adding transactions to a block, the rest is easy. Let’s write the function for adding transactions:</p><p>A method for creating Transactions</p><h3>The Mining Endpoint</h3><p>Our mining endpoint is where the magic happens, and it’s easy. It has to do three things:</p><ol><li>Calculate the Proof of Work</li><li>Reward the miner (us) by adding a transaction granting us 1 coin</li><li>Forge the new Block by adding it to the chain</li></ol><p>Note that the recipient of the mined block is the address of our node. And most of what we’ve done here is just interact with the methods on our Blockchain class. At this point, we’re done, and can start interacting with our blockchain.</p><p>You can use plain old cURL or Postman to interact with our API over a network.</p><p>Fire up the server:</p><pre>$ python blockchain.py * Running onhttp://127.0.0.1:5000/ (Press CTRL+C to quit)</pre><p>Let’s try mining a block by making a GET request to <a href="http://localhost:5000/mine:">http://localhost:5000/mine:</a></p><p>Let’s create a new transaction by making a POST request to http://localhost:5000/transactions/new with a body containing our transaction structure:</p><p>If you aren’t using Postman, then you can make the equivalent request using cURL:</p><pre>$ curl -X POST -H &quot;Content-Type: application/json&quot; -d &#39;{<br> &quot;sender&quot;: &quot;d4ee26eee15148ee92c6cd394edd974e&quot;,<br> &quot;recipient&quot;: &quot;someone-other-address&quot;,<br> &quot;amount&quot;: 5<br>}&#39; &quot;http://localhost:5000/transactions/new&quot;</pre><p>I restarted my server, and mined two blocks, to give 3 in total. Let’s inspect the full chain by requesting <a href="http://localhost:5000/chain:">http://localhost:5000/chain:</a></p><p>This is very cool. We’ve 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 <em>decentralized</em>. And if they’re decentralized, how on earth do we ensure that they all reflect the same chain? This is called the problem of <em>Consensus</em>, and we’ll have to implement a Consensus Algorithm if we want more than one node in our network.</p><h3>Registering new Nodes</h3><p>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’ll need some more endpoints:</p><ol><li>/nodes/register to accept a list of new nodes in the form of URLs.</li><li>/nodes/resolve to implement our Consensus Algorithm, which resolves any conflicts-to ensure a node has the correct chain.</li></ol><p>We’ll need to modify our Blockchain’s constructor and provide a method for registering nodes:</p><p>A method for adding neighbouring nodes to our Network</p><p>Note that we’ve used a set() to hold the list of nodes. This is a cheap way of ensuring that the addition of new nodes is idempotent-meaning that no matter how many times we add a specific node, it appears exactly once.</p><h3>Implementing the Consensus Algorithm</h3><p>As mentioned, a conflict is when one node has a different chain to another node. To resolve this, we’ll make the rule that <em>the longest valid chain is authoritative.</em> In other words, the longest chain on the network is the <em>de-facto</em> one. Using this algorithm, we reach <em>Consensus</em> amongst the nodes in our network.</p><p>The first method valid_chain() is responsible for checking if a chain is valid by looping through each block and verifying both the hash and the proof.</p><p>resolve_conflicts() is a method which loops through all our neighbouring nodes, <em>downloads</em> their chains and verifies them using the above method. <strong>If a valid chain is found, whose length is greater than ours, we replace ours.</strong></p><p>Let’s register the two endpoints to our API, one for adding neighbouring nodes and the another for resolving conflicts:</p><p>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: <a href="http://localhost:5000/">http://localhost:5000</a> and <a href="http://localhost:5001.">http://localhost:5001.</a></p><p>I then mined some new Blocks on node 2, to ensure the chain was longer. Afterward, I called GET /nodes/resolve on node 1, where the chain was replaced by the Consensus Algorithm:</p><p>And that’s a wrap… Go get some friends together to help test out your Blockchain.</p><p>I hope that this has inspired you to create something new. I’m ecstatic about Cryptocurrencies because I believe that Blockchains will rapidly change the way we think about economies, governments and record-keeping.</p><p><strong>Update:</strong> I’m planning on following up with a Part 2, where we’ll extend our Blockchain to have a Transaction Validation Mechanism as well as discuss some ways in which you can productionize your Blockchain.</p><blockquote>If you enjoyed this guide, or have any suggestions or questions, let me know in the comments. And if you’ve spotted any errors, feel free to contribute to the code !</blockquote><p><em>Originally published at </em><a href="https://medium.com/@vanflymen/learn-blockchains-by-building-one-117428612f46"><em>https://medium.com</em></a><em> on September 25, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6de99d43bf57" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>