Build the smallest blockchain with less than 50 lines of Python code

reference

As Bitcoin continues to grow, so does its underlying technology, blockchain. This article uses less than 50 lines of Python code to build a minimal data blockchain, giving a brief introduction to the decentralized structure of blockchain and how it works.

Although some see blockchain as a solution to a problem in waiting, there is no doubt that this new technology is a marvel of computing. But what exactly is a blockchain?

Block chain

It is a digital ledger of transactions in Bitcoin or other cryptocurrencies, recorded chronologically and publicly available.

In more general terms, it’s a public database where new data is stored in a container called a block and added to an immutable chain (later blockchains) to add data from the past. In the case of Bitcoin and other cryptocurrencies, that data is a set of records of transactions. Of course, data can be of any type.

Blockchain technology has given rise to new, fully digital currencies like Bitcoin and Litecoin that are not issued or managed by a central government. Thus a new freedom for those who believe that today’s banking system is a sham or doomed to failure. The ethereum technology included in blockchain revolutionizes distributed computing and introduces some interesting concepts, such as smart contracts.

In this article, I’ll do a simple blockchain with less than 50 lines of Python2 code. I call it SnakeCoin.

The first step is to define what the block will look like. In a blockchain, each block stores a timestamp and an index. In SnakeCoin, you need to store both. To ensure the integrity of the entire blockchain, each block has an auto-recognition hash. As with Bitcoin, the hash of each block will be a cryptographic hash of the block index, timestamp, data, and hash of the previous block. 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()
Copy the code

After this step there is a block structure, but now you are creating the blockchain, so you need to add blocks to the actual chain. As mentioned earlier, each block requires information about the previous block. But there’s a problem with that statement. How did the first block of the blockchain get there? I have to say, the first block, or the origin block, is a special block. In many cases, it is added manually or has unique logic that allows it to be added.

The next step is to create a function that simply returns an origin block to generate the first block. This block is index 0, which has any data value and any 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")
Copy the code

Now that you have created the origin block, you need a function to generate subsequent blocks in the blockchain. This function takes the previous block in the chain as an argument, creates data for the block to be generated, and returns the new block with the appropriate data. When new block hash information comes from previous blocks, the integrity of the blockchain increases with each new block. If this is not done, it is easier for outside organisations to “change the past” and replace existing chains in entirely new ways. This series of hashes serves as evidence of encryption 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)
Copy the code

Most of the work is done and you can now create the blockchain. In this example, the blockchain itself is a simple Python list. The first element in the list is the origin block. Of course, subsequent blocks need to be added, since SnakeCoin is the smallest blockchain, only 20 new blocks will be added here. You can use a for loop to generate new blocks.

# 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)Copy the code

Let’s test the blockchain that has been created so far.

See, this is blockchain. If you want to see more information in the console, you can edit the complete source file and print the timestamp or data for each block.

That’s all SnakeCoin has to offer. In order for SnakeCoin to scale up to today’s production blockchains, more features must be added, such as a server layer to track chain changes across multiple machines, as well as working algorithms that limit the number of blocks added over a given period of time.

For more technical information, check out the original Bitcoin white paper here.

— — — — — — — — — — —

End of translation!

Of course, this blockchain example is actually a very simple example, and it’s unlikely to be as popular as bitcoin, but it’s ok to give a general demonstration.