Create a Blockchain using Python
Currently we have been talking about blockchain and cryptocurrencies in our daily lifes. But what is blockchain? A blockchain is a distributed database that is shared among the nodes of a computer network. As a database, a blockchain stores information electronically in digital format. Blockchains are best known for their crucial role in cryptocurrency systems, such as Bitcoin, for maintaining a secure and decentralized record of transactions.
So, after this little text on what is blockchain, let's create our own blockchain using python. This will be a very simple project just to make you understand how the blockchain works and how to create it.
To create a blockchain we need to create the blocks that will cointain all the neccessary information such as timestamp, previous block hash, data and block hash.
Before start creating our block class we need to import the libraries that we are going to use. The most important library that we are going to use is hashlib, hashlib is a library that will convert our information into an hash. The other library will be datetime to use in our timestamp.
import hashlib
import datetime
Now it is time to create our class and define our variables:
class Block:
def __init__(self, timestamp, data, previoushash):
self.previoushash = previoushash
self.timestamp = timestamp
self.data = data
self.hash = self.getHash()
Has you can see in the code above we are declaring our class variables to receive information that we are going to pass. In the hash we are going to call a function getHash, this function will generate an hash for the current block.
Now we need to create our first block or Genesis Block. The function that we are about to create will be a static method.
Recommended by LinkedIn
@staticmethod
def createGenesisBlock():
return Block("0", "0", datetime.datetime.now())
After creating our static method to create our Genesis Block, we have to create our method that will generate our hash.
def generateHash(self):
header_bin = (
str(self.previousHash) +
str(self.data) +
str(self.timestamp)
).encode()
inner_hash = hashlib.sha256(header_bin).hexadigest().encode
outer_hash = hashlib.sha256(inner_hash).hexadigest()
return outer_hash
So, we are adding our previoushash, data and timestamp in one string and returning an encoded string to our variable, after that we are going to convert our string into an hash object, that way we need to use hexadigest to convert it into to a string and then encoded.
Last we are going to convert that inner_hash into an outer_hash and return it to be store in our block hash variable.
And our Block class is completed, now let's create a small blockchain.
blockChain = [Block.createGenesisBlock()]
print("Genesis block created!")
nblocksToAdd = 10
for i in range(1, nblocksToAdd+1):
blockChain.append(
Block(blockChain[-1].hash, "Data!", datetime.datetime.now()))
print("Block #%d has been created. " % i)
print("Block #%d hash: %s" % (i, blockChain[i].hash))
Result will be something like this:
Genesis block created!
Block #1 has been created.
Block #1 hash: 9fdcbd93a89d54b619f0b6e36bff33c4b5248ad3138047d332776325a9a4bd97
Block #2 has been created.
Block #2 hash: f7bf5a2e114f404e8ac479d9ce5e1c0315d347853ae8ac9ae08a95dd677cffbb
Block #3 has been created.
Block #3 hash: 5247ada9e1aeada256e6c06fb32dbf8b8274deef0c1dd9869dc65fb8ec5885f5
Block #4 has been created.
Block #4 hash: cb4f773756a1bf20b22fb2b6e3986bcc841a1dbfca2d674071735f86450902cf
Block #5 has been created.
Block #5 hash: 10f426febbf201eb3560665ae608d7f29b220118946f4e1d37d81c4a1d959f83
Block #6 has been created.
Block #6 hash: 65e53b86ad421773398af29e21faa6f1a1c9dfa34d93424d6d9d8228ec6861fe
Block #7 has been created.
Block #7 hash: 94ae451a372567752bef18c987601206583394d870e9a239e10d307e033c51af
Block #8 has been created.
Block #8 hash: 15aa9bd32a07754110df11eb0ade954795295fd22d72bee20870a3cd2ba96245
Block #9 has been created.
Block #9 hash: 59c1f502007c51734d8d126100f3ce4d0204618066ee7b6445ecca4b6d09b230
Block #10 has been created.
Block #10 hash: d4df6f6d2e4897aef59b6aeccce26d6f305c24a47e3813455ad19aee56adee72
Conclusion
Now you have a basic understanding how to create your own blockchain and how it works. If you are interested in blockchain you can explore more complex ways to create a really secure blockchain.