Introduction to Blockchain With Implementation in Python
Tags: Data Science, Machine Learning, Technology, Finance, Blockchain Technology

Cryptocurrency has revolutionized the way we conduct transactions and this is just scratching the surface.

Photo by André François McKenzie on Unsplash

Founded in 2009 by an unknown individual(s) named Satoshi Nakamoto, Blockchain Technology is a breakthrough and has shown immense potential as being a fast, safe, and easy to use method for transferring or receiving funds and how is that you might ask?

Well, for starters, there is no “central entity” monitoring transactions like a Bank would.

All details are kept private between the recipient and the sender and there is no “middleman” needed. Moreover, The ease of access Blockchain offers is amazing, to say the least for example There are still countries in the world where conventional payment websites(PayPal for example) are banned and this creates a lot of hurdles for people who are trying to receive or send funds to foreign nations.

Cryptocurrency, on the other hand, knows no boundaries. It can be sent from anywhere in the world to any place in the world.

But the biggest benefit of cryptocurrency in my mind is the protection it provides against inflation. Yes, Blockchain Technology is in it’s developing phases and that’s why it is volatile but unlike conventional currency which can be printed to oblivion, Cryptocurrency is REALLY HARD to mass-produce.

It takes a lot of resources to “mine” one Crypto coin and that’s where it’s value comes from. So to sum it up, Cryptocurrency is a good defense against inflation like Gold but unlike Gold, it can be very easily stored, transferred, and is virtually impossible to steal.

How does Blockchain work?

Photo by Clifford Photography on Unsplash

So how does Blockchain work? What makes it so secure? Well, In this article, I will be explaining how a Blockchain works and will write the code side by side which goes into creating a Blockchain. So without further due, Let’s get started.

As the name suggests, A Blockchain is a “chain of Blocks”. Each block contains a “hash” an “index” and information about the particular transaction that took place.

All the Blocks in the Blockchain are linked to each other with the “hash” variable. A “hash” contains information of the previous block in the chain and that’s what keeps the entire chain-linked and connected.

Basic Blockchain diagram

If any value in any of the blocks in “tampered with”, This will cause the hash to change as well and it won't match the hash in the Block after it, which will alert the network of “tampering” and will render the entire chain useless. So for any hacker to successfully “hack” into a chain, He/She will have to not only change values of one single block but all the blocks before it and after it which are virtually impossible.

Moving to the Python part, I will first define my sender as a random individual, my Blockchain as a list with a “dummy genesis block”, the transactional information as an empty list, and import a library by the name of “hashlib” (more on that later)

from hashlib import sha256

sender = 'Moeed'

blockchain = [genesis_block]

genesis_block = {'previous_hash': 'XYZ',

'index': 0,

'transactions': [], 'proof': 0} open_transactions = []

I will then define a function that will ask the sender to enter his details such as the transaction amount to send and the address of the recipient.

def get_transaction():

recipient = input('Enter your recipient')

amount = input('Enter your amount')

return (recipient,amount)

Then I will try to append the transactional informational into the “open_transaction” list defined earlier.

while True:

I = input('Enter your choice')

if I == '1':

data = get_transaction()

recipient, amount = data

transaction = {'sender': sender,

'recipient': recipient,

'amount': amount}

open_transactions.append(transaction)

print(open_transactions)

Note: The transaction information is stored in a dictionary so we can access the values using the “keys” when we feel the need.

Now I will try to create a function that will create the “Block” and append it to the Blockchain. But before I do that, I would like to go over where a Blockchain gets its security from.

SHA-256

The SHA-256 is a hashing algorithm created by the NSA back in 2001 which takes an input of any size and converts it to an output of fixed size. The beauty of the SHA-256 is that the Output is close to impossible to decode thus ensuring security.

The “hash” part of the Block in the Blockchain is nothing more than the Output of the SHA-256 algorithm whereas the input is the “hash of the previous block” the “index” and the “transaction information” all combined into the string format.

Let's look at the code here:

I have already imported the “hashlib” library.

I will try to create a function which will take the “hash”, “index” and “transaction information” of the previous block and convert it into a hash for the block after it.

def hash_block(last_block):

previous_hash = ''



for keys in last_block:

previous_hash = previous_hash + str(last_block[keys])

hash = sha256(json.dumps(previous_hash).encode('utf-8')).hexdigest()

return hash

As our Blockchain starts from the “genesis block” defined earlier, we give it a dummy “previous_hash” value of XYZ.

The “Proof of Work”

Photo by Bermix Studio on Unsplash

We know that the hash is generated using the SHA-256 algorithm by a set of inputs. But that makes adding a Block to the Blockchain a little too “easy”.

Blockchain mining is on purpose hard so that we don’t mass produce coins and the supply is kept in check as per the demand. This is accomplished using the “proof of work” algorithm.

The “proof of work” uses the same SHA-256 algorithm but instead of taking an input and giving a single output, there is a condition placed for example The output hash needs to have the first two characters as zeros.

The hash is calculated using the SHA-256 algorithm with the same inputs (previous_hash, index, transaction information) but with an addition of the iteration number also known as “proof”. So basically, the “proof” will be incremented by one until the condition we have placed ( first two zeros) is satisfied.

Once the condition is satisfied, The resulting hash from the “hash_block” will be added to the Block and then the Block will be added to the Blockchain.

Now let’s look at the code for the “proof of work” function

def proof_of_work():

previous_hash = ''

proof = 0

last_block = blockchain[-1]

for keys in last_block:

previous_hash = previous_hash + str(last_block[keys])





guess_hash = previous_hash + str(proof)

hash = sha256(hashed.encode('utf-8')).hexdigest()

while hash[0:2] != '00':

guess_hash = previous_hash + str(proof)

hash = sha256(guess_hash.encode('utf-8')).hexdigest()

proof = proof + 1

print(hash)

return proof

As already explained, the above code will perform iterations until the “zero” condition is satisfied. Let’s move forward and look at how a Block is mined.

Mining a Block

Photo by Aleksi Räisä on Unsplash

We have already gone over the proof of work algorithm. So how is a Block mined? Well, Let’s look at the code.

def hash_block(last_block):

previous_hash = ''



for keys in last_block:

previous_hash = previous_hash + str(last_block[keys])

hash = sha256(json.dumps(previous_hash).encode('utf-8')).hexdigest()

return hash def mine_block():





last_block = blockchain[-1]



hashed_block = hash_block(last_block)

proof = proof_of_work()



block = {

'previous_hash': hashed_block,

'index': len(blockchain),

'transactions': open_transactions,

'proof': proof

}

blockchain.append(block)

print(blockchain)

print(hashed_block)

print(proof)

return True

As can be seen from the above code, We first define a “hash_block” function which takes an empty string by the name of “previous_hash” and adds the other values of the block such as index and transaction information as strings and creates one big string. This string is then returned as an encrypted string using the SHA-256 algorithm.

Then we begin the “mine_block” function which uses the “hash_block” function to return a hash and the “proof of work” to calculate the hash which has two zeros at the start.

The results (proof number and the hash) are then added to the dictionary by the name of “block” which is further appended to the blockchain list.

This creates the first Block. But there’s one thing that is still missing

What if someone were to tamper with the blockchain? Let’s say what if someone were to change values in the Block. How can we stop that from happening? It’s simple, We put a check on the chain which compares “previous_hash” of one chain with a calculated hash of the Block before it. Let’s look at the code

def verify_chain():



for (index, block) in enumerate(blockchain):

if index == 0:

continue

if block['previous_hash'] != hash_block(blockchain[index - 1]):

print(block['previous_hash'])

print(hash_block(blockchain[index - 1]))

print(block)

print(blockchain[index-1])

return False



return True

and then we add a condition at last which implements the function above.

if not verify_chain():

print('Invalid block')

break

If any value inside our Blockchain is tampered with, The condition above will return “Invalid chain”

and Finally, Some code for the user to interact with the chain

while True:

I = input('Enter your choice')

print('1 to recieve transactions')

print('2 to mine block')

print('3 to alter block')

if I == '1':

data = get_transaction()

recipient, amount = data

transaction = {'sender': owner,

'recipient': recipient,

'amount': amount}



open_transactions.append(transaction)

print(open_transactions)

save_data()



if I == '2':

mine_block()

open_transactions = []





if I == '3':

alter_block()





if not verify_chain():

print('Invalid block')

break

The above code is pretty self-explanatory. Input 1 is used to receive transactions from the input. Input 2 is used to mine the block and input 3 is used to “alter the block”.

We use “alter_block” to test whether the “verify_chain” is working or not.

The code for “alter_block” function is:

def alter_block():

blockchain[0] = {'previous_hash':'ABC',

'index':0,

'transactions':[],'proof':0}

Note: In the above function, we alter the first block by changing the “previous_hash” from “XYZ” to “ABC” which will give us a wrong hash, and hence the condition “verify_hash” will come into play.

Conclusion

In this article, I went over the basics of Blockchain Technology with a simple implementation in Python. There’s definitely more to Blockchain than what I covered such as Node Networks, APIs, and OOP.

To sum it up, Blockchain Technology has immense potential and is already showing a promising future. Let’s see what the future holds