Blockchain implementation

Posted on Mon 26 March 2018   •   12 min read

Create data structure for block:

block 'metadata':

  • index - each block is numbered (has it's index)
  • timestamp - block creation time needed for conflict resolution
  • previous hash - signature of previous block in chain
  • hash - signature of this block

data stored in block:

  • data - actual 'payload' of the block

The hasher aggregate all elements of block (except this block hash) and calculates hash.

In [2]:
import hashlib as hasher

class Block:
    def __init__(self, index, timestamp, data, previous_hash):
        self.index = index
        self.timestamp = timestamp
        self.data = data
        self.previous_hash = previous_hash
        self.hash = self.hash_block()

    def hash_block(self):
        sha = hasher.sha256()
        sha.update((str(self.index) + 
                   str(self.timestamp) + 
                   str(self.data) + 
                   str(self.previous_hash)).encode('utf-8'))
        return sha.hexdigest()

First block in chain is different from the rest in that sense that it has no predecessor - there is no previous block.

In [3]:
import datetime as date

def create_genesis_block():
    # Manually construct a block with
    # index zero and arbitrary previous hash
    return Block(0, date.datetime.now(), "Genesis Block", "0")

Create next block based on last block

In [4]:
def next_block(last_block):
    this_index = last_block.index + 1
    this_timestamp = date.datetime.now()
    this_data = "Hey! I'm block " + str(this_index)
    this_hash = last_block.hash
    return Block(this_index, this_timestamp, this_data, this_hash)
In [5]:
# Create the blockchain and add the genesis block
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

# lenght of the blockchain (excluding genesis block)
num_of_blocks_to_add = 20

# Add blocks to the chain
for i in range(0, num_of_blocks_to_add):
    block_to_add = next_block(previous_block)
    blockchain.append(block_to_add)
    previous_block = block_to_add
    print("Block #{} has been added to the blockchain!".format(block_to_add.index))
print ("Hash: {}\n".format(block_to_add.hash))
Block #1 has been added to the blockchain!
Block #2 has been added to the blockchain!
Block #3 has been added to the blockchain!
Block #4 has been added to the blockchain!
Block #5 has been added to the blockchain!
Block #6 has been added to the blockchain!
Block #7 has been added to the blockchain!
Block #8 has been added to the blockchain!
Block #9 has been added to the blockchain!
Block #10 has been added to the blockchain!
Block #11 has been added to the blockchain!
Block #12 has been added to the blockchain!
Block #13 has been added to the blockchain!
Block #14 has been added to the blockchain!
Block #15 has been added to the blockchain!
Block #16 has been added to the blockchain!
Block #17 has been added to the blockchain!
Block #18 has been added to the blockchain!
Block #19 has been added to the blockchain!
Block #20 has been added to the blockchain!
Hash: 4f610cd0aef5197b4cf4cee262d25094d47ae65a1d943dce9bc220fa8a98dbc7

In [17]:
from IPython.core.display import HTML
HTML("<style>.prompt{display: None;</style>")
Out[17]: