Skip to content

Instantly share code, notes, and snippets.

@felipemfp
Created March 10, 2018 12:50
Show Gist options
  • Save felipemfp/90e6f5db4df7ca551693d9c6431ab36c to your computer and use it in GitHub Desktop.
Save felipemfp/90e6f5db4df7ca551693d9c6431ab36c to your computer and use it in GitHub Desktop.
from hashlib import sha256
from datetime import datetime
class Blockchain:
def __init__(self):
self.blocks = []
self.set_genesis_block()
def set_genesis_block(self):
data = 'Hello, World!'
timestamp = datetime.utcnow().timestamp()
prev_hash = 0
index = 0
self.hash_block(
data, timestamp, prev_hash, index
)
def hash_block(self, data, timestamp, prev_hash, index):
hash = ''
nonce = 1
while not self.is_hash_valid(hash):
block = '{}:{}:{}:{}:{}'.format(
data, timestamp, prev_hash, index, nonce
)
hash = sha256(block.encode()).hexdigest()
nonce += 1
print('[nonce]', nonce)
self.blocks.append(hash)
def get_last_hash(self):
return self.blocks[-1]
def is_hash_valid(self, hash):
return hash.startswith('0000')
def add_new_block(self, data):
index = len(self.blocks)
prev_hash = self.get_last_hash()
timestamp = datetime.utcnow().timestamp()
self.hash_block(
data, timestamp, prev_hash, index
)
def get_all(self):
return self.blocks[:]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment