<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/building-your-own-blockchain-in-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://bigdata-doctor.com/building-your-own-blockchain-in-r/"> R – Big Data Doctor</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div><img src="https://i1.wp.com/bigdata-doctor.com/wp-content/uploads/2017/12/pexels-photo-220783.jpeg?w=90%25" data-recalc-dims="1"></div>
<div>
<div><a rel="nofollow" href="http://bigdata-doctor.com/building-your-own-blockchain-in-r/?format=pdf" title="Download PDF" target="_blank"><img alt="Download PDF" src="https://i0.wp.com/bigdata-doctor.com/wp-content/plugins/wp-post-to-pdf-enhanced/asset/images/pdf.png?w=456" data-recalc-dims="1"></a></div>
<p>Everybody is freaking out about the rise of the Bitcoin and the potential of the <strong>Blockchain</strong> technologies. The advent of cryptocurrencies, game changing use cases, disruption of established business models by disintermediation, etc..<br>
By the time I’m writing this article, there are more than 1300 crypto-currencies listed in <a rel="nofollow" href="https://coinmarketcap.com/all/views/all/" target="_blank">coinmarketcap</a>.. And a lot more coming with the next ICOs (Internet Coin Offering).</p>
<p>Most certainly, the main enabler of Bitcoin and of many other currencies (although not all of them) is the Blockchain technology.</p>
<p>Although the <a rel="nofollow" href="https://bitcoin.org/bitcoin.pdf" target="_blank">original paper from Satoshi</a> explains very well the ground idea behind this technology, nothing like <strong>creating your own blockchain</strong> to fully understand how it works, its limitations and potential improvements (aka <strong><em>“If you can code it, you certainly understand it”</em></strong>).</p>
<p>In this post I’d like to share a gentle coding exercise in R (#rstats). Why R? Just because it’s my favorite language… I wouldn’t choose R for a productive, full-fledge block chain implementation, but again, this is not the purpose of this post. This is just a learning exercise hacked quite quickly without any aspiration of ever running this code in a productive environment, and should be understood as such.</p>
<p>For convenience, I stored the code in a <a rel="nofollow" href="https://github.com/jbernabe/rblockchain" target="_blank">git repository</a>, for others to improve, re-use, try, etc.</p>
<h3>First things first: what is what in a Blockchain</h3>
<p> A <strong>blockchain</strong> is an immutable chain of sequential records or blocks that are “chained” together using hashes. <strong>Blocks</strong> can be understood as containers, typically of transactions, but it can be extended to documents, etc. We can think of a blockchain as a database where new data is stored in blocks, that are added to an <em>immutable</em> chain based on all other existing blocks.<br>
Blockchain is often referred as a <em>digital ledger</em> of transactions performed in a cryptocurrency of choice (Bitcoin or whatever). A <strong>transaction</strong> requires a sender address, a recipient address and a given amount and needs to be assigned to a block.<br>
The json below shows a typical block with a particular index, an integer representing the proof, a hashed representation of the previous block, which allows for consistency check (more about proof and hashing later) and a timestamp.</p>
<pre>
{
	&quot;index&quot;: 2,
	&quot;timestamp&quot;: 1514108190.2831,
	&quot;transactions&quot;: [{
		&quot;sender&quot;: &quot;d4ee26eee15148ee92c6cd394edd964&quot;,
		&quot;recipient&quot;: &quot;23448ee92cd4ee26eee6cd394edd964&quot;,
		&quot;amount&quot;: 15
	}, {
		&quot;sender&quot;: &quot;6eee15148ee92c6cd394edd974d4ee2&quot;,
		&quot;recipient&quot;: &quot;15148ee92cd4ee26eee6cd394edd964&quot;,
		&quot;amount&quot;: 225
	}],
	&quot;proof&quot;: 211,
	&quot;previousHash&quot;: &quot;afb49032c6c086445a1d420dbaf88e4925681dec0a5b660d528fe399e557bf68&quot;
}
</pre>
<p>Once we have understood the concept behind the blockchain, let’s build one and make it work <img alt="🙂" src="https://i0.wp.com/s.w.org/images/core/emoji/2.2.1/72x72/1f642.png?w=456&ssl=1" class="wp-smiley" data-recalc-dims="1"><br>
We are going to need three different files:</p>
<ul>
<li>The <strong>class definition file</strong>, where we create the Blockchain class with its components and methods.</li>
<li>The <strong>API definition file</strong>, where we instantiate the class, register a node and expose the blockchain methods as GET and POST calls for the peers to interact with.</li>
<li>The <strong>plumber launch file</strong>, to start the server and expose the API methods</li>
</ul>
<h3>Building a Blockchain</h3>
<p>To represent the Blockchain, we need a list of blocks (the <strong>chain</strong>), a list of <strong>currentTransactions</strong> (waiting to be mined) and a list of mining <strong>nodes</strong>.</p>
<p>Our Blockchain class implements a method to register a new transaction <strong>addTransaction</strong>. Transactions are appended to the list of currentTransactions until a new block is created, which takes care of the newly added transactions that have not been added to any block yet.<br>
The creation of a new block takes place after calling <strong>nextBlock</strong>. To maintain the consistency, a new block can only be added knowing the hashed value of the previous one as part of a <a rel="nofollow" href="https://en.bitcoin.it/wiki/Proof_of_work" target="_blank">Proof of Work</a> procedure (PoW). Basically, it is just finding a number that satisfies a condition. This number should be easy enough to be verified by anyone in the chain, but difficult enough so that a brute force attack to find it wouldn’t be feasible (too long, too expensive).<br>
In our example, <strong>proofOfWork</strong> relies on finding a number called <em>proof</em> such that if we append this proof to the previous proof and we hash it, the last 2 characters of the resulting string are exactly two zeroes. The way it works in the real Bitcoin chain is quite different, but based on the same concept.</p>
<p>In Bitcoin, the <strong>Proof of Work</strong> algorithm is called <a rel="nofollow" href="https://en.bitcoin.it/wiki/Hashcash" target="_blank">Hashcash</a>. Solving this problem requires computational resources (the longer the strings and the more characters to be found within it, the higher the complexity), and miners are rewarded by receiving a coin—in a transaction.</p>
<p>The Blockchain class provides a method to check the consistency over all blocks <strong>validChain</strong>, which iterates over the chain checking if both each block is <em>properly linked</em> to the previous one and whether the PoW is preserved.<br>
The method <strong>registerNode</strong> adds the URL of a mining node to the central nodes register.</p>
<p>Finally, as we need to think of a Blockchain as a distributed system, there is a chance that one node has a different chain to another node. The handleConflicts resolves this conflict by declaring the longest chain the proper one… the one that all nodes take.</p>
<pre>
list.of.packages &lt;- c(&quot;digest&quot;, &quot;httr&quot;,&quot;jsonlite&quot;)
new.packages &lt;- list.of.packages[!(list.of.packages %in% installed.packages()[,&quot;Package&quot;])]
if(length(new.packages)) install.packages(new.packages)
require(digest)
require(jsonlite)
require(httr)
Blockchain &lt;- function ()
{
  bc = list (
    chain = list(),
    currentTransactions  = list(),
    nodes = list()
  )
  #' Create a new Block in the Blockchain
  #'
  #' @param proof </pre></div>