-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
Proof of Work Algorithm for Blockchain #11699
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anurags10
wants to merge
11
commits into
TheAlgorithms:master
Choose a base branch
from
anurags10:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
18e367f
updating DIRECTORY.md
anurags10 37549d5
Create PoWAlgorithm.py
anurags10 f5459b8
updating DIRECTORY.md
anurags10 9573205
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 5ebea50
Update and rename PoWAlgorithm.py to pow_algorithm.py
anurags10 91a4325
updating DIRECTORY.md
anurags10 66cd40e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] c051734
Update pow_algorithm.py with return type
anurags10 3d91445
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9a6fcd5
Update pow_algorithm.py
anurags10 6a7b49d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,123 @@ | ||
""" | ||
# Title: Proof of Work Algorithm for Blockchain | ||
|
||
## Algorithm Statement: | ||
The algorithm implements the Proof of Work (PoW) consensus mechanism used in | ||
blockchain to validate blocks. PoW ensures participants (miners) perform a | ||
computational task to create a valid block and add it to the blockchain. The | ||
difficulty is defined by the number of leading zeros required in the block hash. | ||
""" | ||
|
||
import hashlib | ||
import time | ||
|
||
class Block: | ||
def __init__(self, index, previous_hash, transactions, timestamp, difficulty): | ||
self.index = index | ||
self.previous_hash = previous_hash | ||
self.transactions = transactions | ||
self.timestamp = timestamp | ||
self.nonce = 0 # Start with nonce 0 | ||
self.difficulty = difficulty | ||
self.hash = self.compute_hash() | ||
|
||
def compute_hash(self): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Generates the hash of the block content. | ||
Combines index, previous hash, transactions, timestamp, and nonce into a string, | ||
which is then hashed using SHA-256. | ||
""" | ||
block_string = ( | ||
f"{self.index}{self.previous_hash}{self.transactions}{self.timestamp}" | ||
f"{self.nonce}" | ||
) | ||
return hashlib.sha256(block_string.encode()).hexdigest() | ||
|
||
def mine_block(self): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Performs Proof of Work by adjusting the nonce until a valid hash is found. | ||
A valid hash has the required number of leading zeros based on the difficulty | ||
level. | ||
""" | ||
target = '0' * self.difficulty # Target hash should start with 'difficulty' zeros | ||
while self.hash[:self.difficulty] != target: | ||
self.nonce += 1 | ||
self.hash = self.compute_hash() | ||
|
||
print(f"Block mined with nonce {self.nonce}, hash: {self.hash}") | ||
|
||
class Blockchain: | ||
def __init__(self, difficulty): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.chain = [] | ||
self.difficulty = difficulty | ||
self.create_genesis_block() | ||
|
||
def create_genesis_block(self): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Creates the first block in the blockchain (the Genesis block). | ||
""" | ||
genesis_block = Block(0, "0", "Genesis Block", time.time(), self.difficulty) | ||
genesis_block.mine_block() | ||
self.chain.append(genesis_block) | ||
|
||
def add_block(self, transactions): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Adds a new block to the blockchain after performing Proof of Work. | ||
""" | ||
previous_block = self.chain[-1] | ||
new_block = Block(len(self.chain), previous_block.hash, transactions, time.time(), | ||
Check failure on line 68 in blockchain/pow_algorithm.py
|
||
self.difficulty) | ||
new_block.mine_block() | ||
self.chain.append(new_block) | ||
|
||
def is_chain_valid(self): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Verifies the integrity of the blockchain by ensuring each block's previous | ||
hash matches and that all blocks meet the Proof of Work requirement. | ||
""" | ||
for i in range(1, len(self.chain)): | ||
current_block = self.chain[i] | ||
previous_block = self.chain[i - 1] | ||
|
||
if current_block.hash != current_block.compute_hash(): | ||
print(f"Invalid block at index {i}. Hash mismatch.") | ||
return False | ||
|
||
if current_block.previous_hash != previous_block.hash: | ||
print(f"Invalid chain at index {i}. Previous hash mismatch.") | ||
return False | ||
|
||
return True | ||
|
||
# Test cases | ||
|
||
def test_blockchain(): | ||
anurags10 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Test cases for the Blockchain proof of work algorithm. | ||
""" | ||
# Create blockchain with difficulty level of 4 (hash should start with 4 zeros) | ||
blockchain = Blockchain(difficulty=4) | ||
|
||
# Add new blocks | ||
blockchain.add_block("Transaction 1: Alice pays Bob 5 BTC") | ||
blockchain.add_block("Transaction 2: Bob pays Charlie 3 BTC") | ||
|
||
# Verify the integrity of the blockchain | ||
assert blockchain.is_chain_valid(), "Blockchain should be valid" | ||
|
||
# Tamper with the blockchain and check validation | ||
blockchain.chain[1].transactions = "Transaction 1: Alice pays Bob 50 BTC" # Tampering | ||
assert not blockchain.is_chain_valid(), "Blockchain should be invalid due to tampering" | ||
|
||
print("All test cases passed.") | ||
|
||
if __name__ == "__main__": | ||
test_blockchain() | ||
|
||
""" | ||
# Output: | ||
- Block mined with nonce X, hash: 0000abcd... | ||
- Block mined with nonce Y, hash: 0000xyz... | ||
- Block mined with nonce Z, hash: 0000pqrs... | ||
- All test cases passed. | ||
""" |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.