Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quantra-go-algo/0c54e4d1f18df7f36814b80333f963b1 to your computer and use it in GitHub Desktop.
Save quantra-go-algo/0c54e4d1f18df7f36814b80333f963b1 to your computer and use it in GitHub Desktop.
Blockchain Explained - Example of creating a Blockchain using Python
import hashlib
import datetime as dt
# Define a block class
class block:
def __init__(self, time, data, prev_hash):
self.timestamp = time
self.data = data
self.prev_hash = prev_hash
self.hashvalue = self.generate_hash()
def generate_hash(self):
data = str(self.timestamp) + str(self.data) + str(self.prev_hash)
hashvalue = hashlib.sha256(data.encode()).hexdigest()
return hashvalue
# Create the genesis block with previous hash value as 0
def create_genesis_block():
timestamp = dt.datetime.now()
data = 'Genesis block'
prev_hash = '0'
return block(time=timestamp, data=data, prev_hash=prev_hash)
# Generate all later blocks in the blockchain
def create_block(prev_block, sender, receiver, amount):
timestamp = dt.datetime.now()
data = f'Sender: {sender}\nReceiver: {receiver}\nAmount: {amount}'
print('Data for this block is:\n',data)
prev_hash = prev_block.hashvalue
return block(time=timestamp, data=data, prev_hash=prev_hash)
# Let's create a simple blockchain with the genesis block
our_first_blockchain = [create_genesis_block()]
# The genesis block will be the previous block for the next block of the blockchain
prev_block = our_first_blockchain[0]
# Let us create a blockchain with 10 blocks
num_blocks = 10
for i in range(1, num_blocks+1):
next_block = create_block(prev_block, sender='Sender'+str(i), receiver='Receiver'+str(i), amount=i*1000)
our_first_blockchain.append(next_block)
print(f'Block number {i} is added to the blockchain. \nIts hash is {next_block.hashvalue}.\nHash of previous block is {next_block.prev_hash}.\n\n')
prev_block = next_block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment