Python Blockchain Creating a Blockchain

Python Blockchain: Creating a Blockchain

A blockchain consists of a list of blocks linked to each other. To store the entire list, we’ll create a list variable called TPCoins –

TPCoins = []

We’ll also write a utility method called dump_blockchain to dump the contents of the entire blockchain. We first print the length of the blockchain so we can tell how many blocks are currently in the blockchain.

def dump_blockchain (self):
print ("Number of blocks in the chain: " + str(len (self))))

Note that over time, the number of blocks in a blockchain can become prohibitively large to print. Therefore, when you print the contents of the blockchain, you may need to decide which range you want to examine. In the code below, we print the entire blockchain, as we won’t be adding many blocks in this demonstration.

To iterate over the blockchain, we set up a for loop as shown below.

for x in range (len(TPCoins)):
block_temp = TPCoins[x]

Each referenced block is copied to a temporary variable called block_temp.

We print the block number as the title of each block. Note that these numbers will start at 0; the first block is the genesis block, which is numbered 0.

print ("block # " + str(x))

In each block (except the genesis block), we store a list of three transactions in a variable called verified_transactions . We iterate over this list in a for loop, and for each retrieved item, we call the display_transaction function to display the transaction details.

for transaction in block_temp.verified_transactions:
   display_transaction (transaction)

The entire function definition is as follows

def dump_blockchain (self):
   print ("Number of blocks in the chain: " + str(len (self)))
   for x in range (len(TPCoins)):
      block_temp = TPCoins[x]
      print ("block # " + str(x))
      for transaction in block_temp.verified_transactions:
         display_transaction (transaction)
         print ('-------------')
      print ('=====================================')

Note that we’ve inserted delimiters at appropriate locations in the code to separate blocks and transactions.

Now that we’ve created a blockchain to store blocks, our next task is to create blocks and begin adding them to the blockchain. To do this, we’ll add the genesis block you created in the previous step.

Leave a Reply

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