How to Create Your Own Cryptocurrency Blockchain in Python

Initial Structure of the Block Class

Here is the code for our initial block class:

import hashlib

import time

class Block(object):

    def __init__(self, index, proof_number, previous_hash, data, timestamp=None):

        self.index = index

        self.proof_number = proof_number

        self.previous_hash = previous_hash = data

        self.timestamp = timestamp or time.time()


    def compute_hash(self):

        string_block = "{}{}{}{}{}".format(self.index, self.proof_number, self.previous_hash,, self.timestamp)

        return hashlib.sha256(string_block.encode()).hexdigest()

As you can see above, the class constructor or initiation method ( __init__()) above takes the following parameters:

  • self — just like any other Python class, this parameter is used to refer to the class itself. Any variable associated with the class can be accessed using it.
  • index — it’s used to track the position of a block within the blockchain.
  • previous_hash — it used to reference the hash of the previous block within the blockchain.
  • data—it gives details of the transactions done, for example, the amount bought.
  • timestamp—it inserts a timestamp for all the transactions performed.

The second method in the class,  compute_hash , is used to produce the cryptographic hash of each block based on the above values.

As you can see, we imported the SHA-256 algorithm into the cryptocurrency blockchain project to help in getting the hashes of the blocks.

Once the values have been placed inside the hashing module, the algorithm will return a 256-bit string denoting the contents of the block.

So, this is what gives the blockchain immutability. Since each block will be represented by a hash, which will be computed from the hash of the previous block, corrupting any block in the chain will make the other blocks have invalid hashes, resulting in breakage of the whole blockchain network.

Prev2 of 6Next

Leave a Reply

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