Last active
September 11, 2019 12:14
-
-
Save lucasomigli/f60e5b912edf705912aff89f6b29ef66 to your computer and use it in GitHub Desktop.
Blockchain Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import hashlib | |
import random | |
class Block: | |
blockNo = 0 | |
data = None | |
next = None | |
hash = None | |
nonce = 0 | |
previous_hash = 0x0 # Formally a pointer to the previous block hash. | |
timestamp = datetime.datetime.now() # Class records the time when the block object gets created. | |
# Initiate Blockchain with a data | |
def __init__(self, data): | |
self.data = data | |
# Using hashlib.SHA256() for hashing block data. | |
def hash(self): | |
h = hashlib.sha256() | |
h.update((str(self.blockNo) + | |
str(self.data) + | |
str(self.hash) + | |
str(self.nonce) + | |
str(self.previous_hash) + | |
str(self.timestamp) | |
).encode('utf-8')) | |
return h.hexdigest() | |
def __str__(self): | |
return "BlockNo: " + str(self.blockNo) + | |
"\ndata: " + str(self.data) + | |
"\nhash: " + str(self.hash()) + | |
"\nnonce: " + str(self.nonce) + | |
"\npreviousHash: " + str(self.previous_hash) | |
class Blockchain: | |
# Level of difficulty can be set higher if needed. The higher the value, the more time the algorithm will need | |
# in order to mine the underlying block as target = 2 ** (256 - difficulty) | |
# maxNonce is the maximum amount of trials per block. | |
difficulty = 20 | |
maxNonce = 2**32 | |
target = 2 ** (256 - difficulty) | |
block = Block("Genesis") | |
dummy = head = block | |
def add(self, block): | |
block.previous_hash = self.block.hash() | |
block.blockNo = self.block.blockNo + 1 | |
self.block.next = block | |
self.block = self.block.next | |
# Mine selected Block with hashlib.sha256() | |
def mineBlock(self, block): | |
for n in range(maxNonce): | |
if target >= int(block.hash(), 16): | |
self.add(block) | |
print(block) | |
break | |
else: | |
block.nonce += 1 | |
def printBlocks(self): | |
while self.head is not None: | |
print(self.head) | |
self.head = self.head.next | |
self.head = self.dummy | |
def printBlock(self, blockNumber): | |
while self.head.blockNo <= blockNumber-1: | |
self.head = self.head.next | |
print(self.head) | |
self.head = self.dummy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment