loading...

Let's Build the Tiniest Blockchain

aunyks profile image Gerald Nash ⚡️ ・4 min read

Note: This article was originally published to Crypto Currently.

Bitcoin Logo

Although some think blockchain is a solution waiting for problems, there’s no doubt that this novel technology is a marvel of computing. But, what exactly is a blockchain?

Blockchain

a digital ledger in which transactions made in bitcoin or another cryptocurrency are recorded chronologically and publicly. >

In more general terms, it’s a public database where new data are stored in a container called a block and are added to an immutable chain (hence blockchain) with data added in the past. In the case of Bitcoin and other cryptocurrencies, these data are groups of transactions. But, the data can be of any type, of course.

Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that aren’t issued or managed by a central authority. This brings new freedom to individuals who believe that today’s banking systems are a scam or subject to failure. Blockchain has also revolutionized distributed computing in the form of technologies like Ethereum, which has introduced interesting concepts like smart contracts.

In this article, I’ll make a simple blockchain in less than 50 lines of Python 2 code. It’ll be called SnakeCoin.

We’ll start by first defining what our blocks will look like. In blockchain, each block is stored with a timestamp and, optionally, an index. In SnakeCoin, we’re going to store both. And to help ensure integrity throughout the blockchain, each block will have a self-identifying hash. Like Bitcoin, each block’s hash will be a cryptographic hash of the block’s index, timestamp, data, and the hash of the previous block’s hash. Oh, and the data can be anything you want.

import hashlib as hasher

class Block:
  def __init__(self, index, timestamp, data, previous_hash):
    self.index = index
    self.timestamp = timestamp
    self.data = data
    self.previous_hash = previous_hash
    self.hash = self.hash_block()

  def hash_block(self):
    sha = hasher.sha256()
    sha.update(str(self.index) + 
               str(self.timestamp) + 
               str(self.data) + 
               str(self.previous_hash))
    return sha.hexdigest()

Awesome! We have our block structure, but we’re creating a block chain. We need to start adding blocks to the actual chain. As I mentioned earlier, each block requires information from the previous block. But with that being said, a question arises: how does the first block in the blockchain get there? Well, the first block, or genesis block, is a special block. In many cases, it’s added manually or has unique logic allowing it to be added.

We’ll create a function that simply returns a genesis block to make things easy. This block is of index 0, and it has an arbitrary data value and an arbitrary value in the “previous hash” parameter.

import datetime as date

def create_genesis_block():
  # Manually construct a block with
  # index zero and arbitrary previous hash
  return Block(0, date.datetime.now(), "Genesis Block", "0")

Now that we’re able to create a genesis block, we need a function that will generate succeeding blocks in the blockchain. This function will take the previous block in the chain as a parameter, create the data for the block to be generated, and return the new block with its appropriate data. When new blocks hash information from previous blocks, the integrity of the blockchain increases with each new block. If we didn’t do this, it would be easier for an outside party to “change the past” and replace our chain with an entirely new one of their own. This chain of hashes acts as cryptographic proof and helps ensure that once a block is added to the blockchain it cannot be replaced or removed.

def next_block(last_block):
  this_index = last_block.index + 1
  this_timestamp = date.datetime.now()
  this_data = "Hey! I'm block " + str(this_index)
  this_hash = last_block.hash
  return Block(this_index, this_timestamp, this_data, this_hash)

That’s the majority of the hard work. Now, we can create our blockchain! In our case, the blockchain itself is a simple Python list. The first element of the list is the genesis block. And of course, we need to add the succeeding blocks. Because SnakeCoin is the tiniest blockchain, we’ll only add 20 new blocks. We can do this with a for loop.

# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# How many blocks should we add to the chain
# after the genesis block
num_of_blocks_to_add = 20

# Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
  block_to_add = next_block(previous_block)
  blockchain.append(block_to_add)
  previous_block = block_to_add
  # Tell everyone about it!
  print "Block #{} has been added to the blockchain!".format(block_to_add.index)
  print "Hash: {}\n".format(block_to_add.hash)

Let’s test what we’ve made so far.

Terminal Output
There we go! Our blockchain works. If you want to see more information in the console, you could edit the complete source file and print each block’s timestamp or data.

That’s about all that SnakeCoin has to offer. To make SnakeCoin scale to the size of today’s production blockchains, we’d have to add more features like a server layer to track changes to the chain on multiple machines and a proof-of-work algorithm to limit the amount of blocks added in a given time period.

If you’d like to get more technical, you can view the original Bitcoin whitepaper here. Best of luck and happy hacking!

Thank You

Thank you very much for reading!
Twitter, Github, Snapchat, Medium, Instagram

Posted on by:

Discussion

markdown guide
 

Really cool article. Looks a little similar to creating functions and classes in an MVC app. I'm curious about building in the hashing functions. Would creating a blockchain for any other purpose also require you to build in the hashing for it to be self contained or does the lib come with something?

 

Not exactly sure what library you're referring to. But yes, for nearly all blockchain papers and implementations I've seen the hashing is a very important part of technology. That's because the continuous hashing sort of "sets the data in stone" in that more hashes means more trustability in the chain.

 

As a data structure it seems to me that blockchaining is essentially creating chunks of data and arranging them in linked lists. Only difference (that I can see) is the hashing. Great post, really educational.

 
 
 
 
 

Brilliant post. It feels like Blockchain is the "Breaking Bad" of the programming world at the moment - everyone keeps telling me to get into it. I have resisted up until now as I haven't been able to find a good jumping in resource. This post has explained what I need to know to get started with Blockchain in a really accessible way. Thank you for writing this!

 
 

Great article... Thanks for simplifying it in 50lines of Python code :)

 

Blockchains make SO much more sense now! Thanks so much, dude!

 

Very nice article !
for those interested, I wrote an implementation of the code above in NodeJs for fun and profit

github.com/henryleparisien/SnakeCo...

 

I'm the happiest man on earth, this is awesome!

 
 

cool port and supper clean! i also tried in php ,copied your read me file for saving time xD
github.com/ponickkhan/snakecoin/bl...

 

Glad you like it! Would be nice, if you mentioned the source in your README as well ;)

 
 

Can you tell me how did you do this? This part of series thing?

 

Just came across this article, very nice introduction to what a blockchain is! I've been involved in all things blockchain for a few months now and this is really cool! Great work, onto part 2 now!

 

Nice Article!

here's the Ruby version for people interested:

gist.github.com/shaunakpp/704d2052...