From 6a091e095e58a44e980eed22d7507c30ad50acdc Mon Sep 17 00:00:00 2001 From: Vaishali Singh <140580678+vaishaliisingh@users.noreply.github.com> Date: Sat, 14 Sep 2024 21:36:49 +0530 Subject: [PATCH 1/3] Add files via upload This file contains the code for basic implementation of blockchain with the help of poof of work algorithm. --- blockchain/blockchain_main.py | 112 ++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 blockchain/blockchain_main.py diff --git a/blockchain/blockchain_main.py b/blockchain/blockchain_main.py new file mode 100644 index 000000000000..fb52d123afd8 --- /dev/null +++ b/blockchain/blockchain_main.py @@ -0,0 +1,112 @@ +import hashlib +import json +from time import time +from uuid import uuid4 + +class Blockchain: + def __init__(self): + # Initialize blockchain as an empty list and pending transactions + self.chain = [] + self.current_transactions = [] + + # Create the genesis block + self.new_block(previous_hash='1', proof=100) + + def new_block(self, proof, previous_hash=None): + """ + Creates a new block and adds it to the chain. + :param proof: The proof given by the Proof of Work algorithm + :param previous_hash: (Optional) Hash of previous block + :return: New Block + """ + block = { + 'index': len(self.chain) + 1, + 'timestamp': time(), + 'transactions': self.current_transactions, + 'proof': proof, + 'previous_hash': previous_hash or self.hash(self.chain[-1]) + } + + # Reset the current list of transactions + self.current_transactions = [] + + self.chain.append(block) + return block + + def new_transaction(self, sender, recipient, amount): + """ + Creates a new transaction to go into the next mined block. + :param sender: Address of the sender + :param recipient: Address of the recipient + :param amount: Amount of the transaction + :return: The index of the block that will hold this transaction + """ + self.current_transactions.append({ + 'sender': sender, + 'recipient': recipient, + 'amount': amount + }) + + return self.last_block['index'] + 1 + + @staticmethod + def hash(block): + """ + Creates a SHA-256 hash of a block. + :param block: Block + :return: Hash as a hex string + """ + # Ensure the dictionary is ordered to avoid inconsistent hashes + block_string = json.dumps(block, sort_keys=True).encode() + return hashlib.sha256(block_string).hexdigest() + + @property + def last_block(self): + """ + Returns the last block in the chain. + :return: Last Block + """ + return self.chain[-1] + + def proof_of_work(self, last_proof): + """ + Simple Proof of Work algorithm: + - Find a number p' such that hash(pp') contains leading 4 zeroes + - p is the previous proof, and p' is the new proof + :param last_proof: Previous proof + :return: New proof + """ + proof = 0 + while self.valid_proof(last_proof, proof) is False: + proof += 1 + + # Add the mining reward here + self.new_transaction( + sender="0", # System or network + recipient="Miner1", # Replace with the miner's address + amount=1 # Reward amount + ) + return proof + + @staticmethod + def valid_proof(last_proof, proof): + """ + Validates the proof: Does hash(last_proof, proof) contain 4 leading zeroes? + :param last_proof: Previous proof + :param proof: Current proof + :return: True if correct, False if not. + """ + guess = f'{last_proof}{proof}'.encode() + guess_hash = hashlib.sha256(guess).hexdigest() + return guess_hash[:4] == "0000" + +# Create a new blockchain instance +blockchain = Blockchain() + +# Example usage: Add a new transaction and mine a new block +blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) +last_proof = blockchain.last_block['proof'] +proof = blockchain.proof_of_work(last_proof) +block = blockchain.new_block(proof) + +print(f"New block created: {block}") From 33474e44d8bc2e74ddebd60a62f5e914c364fb99 Mon Sep 17 00:00:00 2001 From: Vaishali Singh <140580678+vaishaliisingh@users.noreply.github.com> Date: Sat, 14 Sep 2024 21:39:23 +0530 Subject: [PATCH 2/3] Update README.md --- blockchain/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/blockchain/README.md b/blockchain/README.md index b5fab7b36eaa..3d224165177b 100644 --- a/blockchain/README.md +++ b/blockchain/README.md @@ -43,3 +43,6 @@ So this is all about introduction to blockchain technology. To learn more about * * * + +## about blockchain_main file: +This python file contains the code for basic implementaion of blockchain in python with proof of work algorithm. From 2cf71e3d8c1e9c620f9b4a5216d3670fd881f117 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sat, 14 Sep 2024 16:12:31 +0000 Subject: [PATCH 3/3] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- blockchain/README.md | 2 +- blockchain/blockchain_main.py | 32 ++++++++++++++++---------------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/blockchain/README.md b/blockchain/README.md index 3d224165177b..e7e4873a0acd 100644 --- a/blockchain/README.md +++ b/blockchain/README.md @@ -45,4 +45,4 @@ So this is all about introduction to blockchain technology. To learn more about * ## about blockchain_main file: -This python file contains the code for basic implementaion of blockchain in python with proof of work algorithm. +This python file contains the code for basic implementaion of blockchain in python with proof of work algorithm. diff --git a/blockchain/blockchain_main.py b/blockchain/blockchain_main.py index fb52d123afd8..c91a0710ea48 100644 --- a/blockchain/blockchain_main.py +++ b/blockchain/blockchain_main.py @@ -3,6 +3,7 @@ from time import time from uuid import uuid4 + class Blockchain: def __init__(self): # Initialize blockchain as an empty list and pending transactions @@ -10,7 +11,7 @@ def __init__(self): self.current_transactions = [] # Create the genesis block - self.new_block(previous_hash='1', proof=100) + self.new_block(previous_hash="1", proof=100) def new_block(self, proof, previous_hash=None): """ @@ -20,11 +21,11 @@ def new_block(self, proof, previous_hash=None): :return: New Block """ block = { - 'index': len(self.chain) + 1, - 'timestamp': time(), - 'transactions': self.current_transactions, - 'proof': proof, - 'previous_hash': previous_hash or self.hash(self.chain[-1]) + "index": len(self.chain) + 1, + "timestamp": time(), + "transactions": self.current_transactions, + "proof": proof, + "previous_hash": previous_hash or self.hash(self.chain[-1]), } # Reset the current list of transactions @@ -41,13 +42,11 @@ def new_transaction(self, sender, recipient, amount): :param amount: Amount of the transaction :return: The index of the block that will hold this transaction """ - self.current_transactions.append({ - 'sender': sender, - 'recipient': recipient, - 'amount': amount - }) + self.current_transactions.append( + {"sender": sender, "recipient": recipient, "amount": amount} + ) - return self.last_block['index'] + 1 + return self.last_block["index"] + 1 @staticmethod def hash(block): @@ -79,12 +78,12 @@ def proof_of_work(self, last_proof): proof = 0 while self.valid_proof(last_proof, proof) is False: proof += 1 - + # Add the mining reward here self.new_transaction( sender="0", # System or network recipient="Miner1", # Replace with the miner's address - amount=1 # Reward amount + amount=1, # Reward amount ) return proof @@ -96,16 +95,17 @@ def valid_proof(last_proof, proof): :param proof: Current proof :return: True if correct, False if not. """ - guess = f'{last_proof}{proof}'.encode() + guess = f"{last_proof}{proof}".encode() guess_hash = hashlib.sha256(guess).hexdigest() return guess_hash[:4] == "0000" + # Create a new blockchain instance blockchain = Blockchain() # Example usage: Add a new transaction and mine a new block blockchain.new_transaction(sender="Alice", recipient="Bob", amount=50) -last_proof = blockchain.last_block['proof'] +last_proof = blockchain.last_block["proof"] proof = blockchain.proof_of_work(last_proof) block = blockchain.new_block(proof)