# Blockchain implementation

Posted on Mon 26 March 2018   •   12 min read

### Create data structure for block:¶

• 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)

# Add blocks to the chain

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: 5c1e3c83d68a582dd43868b0d3fca148611d338ba18ee7dc835a99b77c1e055f


In [6]:
from IPython.core.display import HTML
def css_styling():