Python Blockchain

Saumitra Kapoor, pythonblockchain
Back

In this project, a basic blockchain was implemented using Python. The blockchain features include the storage of transactions in blocks, secure hash function to protect the integrity of the data, and a consensus algorithm to ensure network agreement on the state of the blockchain. The result is a functional, yet basic, demonstration of how a blockchain works and can be used to store and secure digital information.

Link

Code

from hashlib import sha256
import json
import time

class Chain:

    def __init__(self):

        self.blockchain = []

        self.pending = []

        self.add_block(prevhash="Genesis", proof=123)

    
def add_transaction(self, sender, recipient, amount):

    transaction = {

        "sender": sender,

        "recipient": recipient,

        "amount": amount

    }

def add_block(self, proof, prevhash=None):

    block = {

        "index": len(self.blockchain),

        "timestamp": time.time(),

        "transactions": self.pending,

        "proof": proof,

        "prevhash": prevhash or self.compute_hash(self.blockchain[-1])

    }

    self.pending = []

    self.blockchain.append(block)

    self.pending.append(transaction)

def compute_hash(self, block):

        json_block = json.dumps(block, sort_keys=True).encode()

        curhash = sha256(json_block).hexdigest()

        return curhash

chain = Chain()

t1 = chain.add_transaction("Vitalik", "Satoshi", 100)

t2 = chain.add_transaction("Satoshi", "Alice", 10)

t3 = chain.add_transaction("Alice", "Charlie", 34)

chain.add_block(12345)

t4 = chain.add_transaction("Bob", "Eve", 23)

t5 = chain.add_transaction("Dennis", "Brian", 3)

t6 = chain.add_transaction("Ken", "Doug", 88)

chain.add_block(6789)

print(chain.blockchain)
© Saumitra Kapoor.