We earn commission when you buy through affiliate links.
This does not influence our reviews or recommendations.Learn more.
Did you know that Bitcoin is built on top of Blockchain?
Today, were going to build a Blockchain with Python from scratch.
What is Blockchain?
In 2008, theBitcoin paperwas published by an unknown individual or group named Satoshi Nakamoto.
Each block is built on top of another block, creating an irreversible chain of blocks.
In other words, every block depends on another.
This turns out into a robust and immutable system in which anyone with the correct permissions can review integrity.
At its core, it would be a list of transactions linked to one another.
ensure to check it out.
Without further delay, lets build a simple Blockchain with Python.
This will let us simplify the process and focus on applying the key concepts of a Blockchain.
This will be the file well work with.
Now, importhashlib, a module that lets us create one-way encrypted messages.
Cryptography techniques like hashing make Blockchain create secure transactions.
Well see this in action later on.
Just keep in mind well be using thehashlib.sha256()function.
Now, lets get into the GeekCoinBlock, our totally original blockchain name.
I know this may result in a clunky piece of code.
Lets break down each part in the next section.
Finally, we create theblock_hash, which other blocks will use to continue the chain.
This function receives encoded strings (or bytes) as parameters.
Thats why were using theblock_data.encode()method.
After that, we callhexdigest()to return the encoded data into hexadecimal format.
I know all of this can be overwhelming, so lets play with hashlib on a Python shell.
This has all to do with Blockchain integrity.
If you introduce some little change into a blockchain, its hash will dramatically change.
This is the reason why the saying You cant corrupt a Blockchain is true.
Then, we do the same with the second block, but passing the first block hash as theprevious_hashargument.
Lets run and analyze the output we get from this piece of code.
You start with a genesis block, the base of all other blocks.
Anyone can validate the chains integrity, and thats why a Blockchain is such a secure system.
you’re free to see the current project on thisGitHub repo.
We have the blocks.
Its time to build a class that joins them into a Blockchain.
Lets start by deleting our previous transactions and block objects, then using the code below.
This is again a huge piece of code.
Lets break down each part:
Lets test this Blockchain up.
Now, run themain.pyfile.
You just created a simple Python Blockchain from scratch.
Conclusion
Blockchain is the technology behind Bitcoin, Ethereum, and every other cryptocurrency out there.
Many people are making fortunes from cryptocurrencies.
Just imagine what you could do if you created one by yourself.