Skip to content

Instantly share code, notes, and snippets.



Last active May 18, 2018
What would you like to do?
Simple implementation of blockchain by example
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib as hasher
import datetime as date
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp = data
self.previous_hash = previous_hash
self.hash = self.hash_block()
def hash_block(self):
sha = hasher.sha256()
sha.update("%s%s%s%s" % (self.index, self.timestamp,, self.previous_hash))
return sha.hexdigest()
def __str__(self):
return "Block <%s>: %s" % (self.hash,
class SampleCoin(object):
blockchain = [Block(0,, "Genesis Block", "0")]
def add_block(self, data):
new_block = Block(
self.blockchain[-1].index + 1,
return new_block
def main():
snake_coin = SampleCoin()
# Add 20 blocks to the chain
for i in range(20):
block = snake_coin.add_block("Hey! I'm block #%s" % i)
# Tell everyone about it!
print("Block #{} has been added to the blockchain!".format(block.index))
print("Hash: {}\n".format(block.hash))
print(snake_coin.blockchain[-1]) # show last block
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.