Member-only story

Simple Blockchain Demo With Python

Eray ALTILI
4 min readJan 3, 2019

--

Blockchain, is a growing list of records, called blocks, which are linked using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data (generally represented as a merkle tree root hash). In this post we will no discuss about fundamentals of Blockchain as it was discussed in previous blog. Also there is a nice Visualization of Blockchain by Anders Brownworth at Github.

Basically we will just implement Block, Basic Blockchain Architecture, and very simple Blockchain Network.

import hashlib


class Block:
# Defining Block Structure
def __init__ (self, no, nonce, data, hashcode, prev):
self.no = no
self.nonce = nonce
self.data = data
self.hashcode = hashcode
self.prev = prev

def getStringVal (self):
return self.no, self.nonce, self.data, self.hashcode, self.prev


class BlockChain:
# Defining simple Blockchain structure, adding blocks and chaining them together
def __init__(self):
self.chain = []
self.prefix = "0000"

def addNewBlock (self, data):
no, nonce, prev = len(self.chain), 0 , "0" if len(self.chain)==0 else self.chain[-1].hashcode
myHash = hashlib.sha256(str(data).encode('utf-8')).hexdigest()
block = Block (no,nonce,data,myHash,prev)
self.chain.append (block)

def printBlockChain(self) :
chaintDict = {}
for no in range (len(self.chain)) :
chaintDict[no] = self.chain[no].getStringVal()
print…

--

--

Eray ALTILI
Eray ALTILI

Written by Eray ALTILI

I am passionate about Technology, Cloud Computing, Machine Learning, Blockchain and Finance. All opinions are my own and do not express opinions of my employer.

No responses yet