1. Introduction

Blockchain Programming Code Example

From the above picture of Blockchain, it is clear that we can code it in pretty much any programming language. For instance, the above concept can be implemented in C++, Python, Java and even JavaScript. Let us take a look at a sample Python code:

	# A block is stored as a tuple of
	# (parent_hash, transactions, hash_itself)
	def get_parent_hash(block):
	return block[0]
	def get_transactions(block):
	return block[1]
	def get_hash_itself(block):
	return block[2]
	# function to create a block in a blockchain
	def create_block(transactions, parent_hash):
	hash_itself = hash((transactions, parent_hash))
	return (parent_hash, transactions, hash_itself)
	# function to create the genesis block
	def create_genesis_block(transactions):
	return create_block(transactions, 0)
	# we create our genesis block
	genesis_block = create_genesis_block("X paid $100 to Y")
	# print the hash of the genesis_block
	genesis_block_hash = get_hash_itself(genesis_block)
	print "genesis_block_hash:", genesis_block_hash
	# create another block
	block1 = create_block("Y paid $20 to Z, X paid $10 to P", genesis_block_hash)
	# print the hash of block1
	block1_hash = get_hash_itself(block1)
	print "block1_hash:", block1_hash

Now suppose, if we were to mutilate the genesis_block

	genesis_block[1] = "Y paid $100 to X"
	genesis_block_hash = get_hash_itself(genesis_block)
	print "genesis_block_hash:", genesis_block_hash
	print "block1_parent_hash:", get_parent_hash(block1)

The output will be as follows:

	genesis_block_hash: 3495953456182427352
	block1_hash: -554281952046316805
	genesis_block_hash: 3220110016770526666
	block1_parent_hash: 3495953456182427352

Here, the value of genesis_block_hash and block1_parent_hash are clearly different while they should actually be the same in the correct Blockchain. As a result, the Blockchain is now corrupted.


Think of Blockchain as a distributed and secured data structure that can be used in places where no middlemen are involved. The decentralized nature of Blockchain is what helps in removing the middlemen and it comes from the above immutability of Blockchain. It is an interesting data structure and as we all have seen cryptocurrency is a real-life implementation of it.

Leave a Reply

Your email address will not be published. Required fields are marked *