Skip to content

Commit 9a6fcd5

Browse files
authored
Update pow_algorithm.py
1 parent 3d91445 commit 9a6fcd5

File tree

1 file changed

+40
-42
lines changed

1 file changed

+40
-42
lines changed

blockchain/pow_algorithm.py

+40-42
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
1-
"""
21
# Title: Proof of Work Algorithm for Blockchain
32

43
## Algorithm Statement:
5-
The algorithm implements the Proof of Work (PoW) consensus mechanism used in
6-
blockchain to validate blocks. PoW ensures participants (miners) perform a
7-
computational task to create a valid block and add it to the blockchain. The
8-
difficulty is defined by the number of leading zeros required in the block hash.
9-
"""
4+
# The algorithm implements the Proof of Work (PoW) consensus mechanism used in
5+
# blockchain to validate blocks. PoW ensures participants (miners) perform a
6+
# computational task to create a valid block and add it to the blockchain. The
7+
# difficulty is defined by the number of leading zeros required in the block hash.
108

119
import hashlib
1210
import time
1311

14-
1512
class Block:
1613
def __init__(
1714
self,
1815
index: int,
1916
previous_hash: str,
2017
transactions: str,
2118
timestamp: float,
22-
difficulty: int,
19+
difficulty: int
2320
) -> None:
2421
"""
2522
Initializes a Block object with the specified parameters.
@@ -28,7 +25,8 @@ def __init__(
2825
- index (int): The index of the block in the blockchain.
2926
- previous_hash (str): The hash of the previous block.
3027
- transactions (str): The list of transactions in the block.
31-
- timestamp (float): The time when the block was created (in Unix timestamp format).
28+
- timestamp (float): The time when the block was created
29+
(in Unix timestamp format).
3230
- difficulty (int): The difficulty level for mining this block.
3331
"""
3432
self.index = index
@@ -42,9 +40,9 @@ def __init__(
4240
def compute_hash(self) -> str:
4341
"""
4442
Generates the hash of the block content.
45-
Combines index, previous hash, transactions, timestamp, and nonce into a string,
46-
which is then hashed using SHA-256.
47-
43+
Combines index, previous hash, transactions, timestamp, and nonce into
44+
a string, which is then hashed using SHA-256.
45+
4846
Returns:
4947
- str: The hash of the block.
5048
"""
@@ -57,40 +55,38 @@ def compute_hash(self) -> str:
5755
def mine_block(self) -> None:
5856
"""
5957
Performs Proof of Work by adjusting the nonce until a valid hash is found.
60-
A valid hash has the required number of leading zeros based on the difficulty level.
61-
58+
A valid hash has the required number of leading zeros based on the
59+
difficulty level.
60+
6261
Returns:
6362
- None
6463
"""
65-
target = (
66-
"0" * self.difficulty
67-
) # Target hash should start with 'difficulty' zeros
68-
while self.hash[: self.difficulty] != target:
64+
target = '0' * self.difficulty # Target hash should start with 'difficulty' zeros
65+
while self.hash[:self.difficulty] != target:
6966
self.nonce += 1
7067
self.hash = self.compute_hash()
7168

7269
print(f"Block mined with nonce {self.nonce}, hash: {self.hash}")
7370

74-
7571
class Blockchain:
7672
def __init__(self, difficulty: int) -> None:
7773
"""
7874
Initializes the blockchain with a given difficulty level.
7975
8076
Parameters:
8177
- difficulty (int): The difficulty level for mining blocks in this blockchain.
82-
78+
8379
Returns:
8480
- None
8581
"""
86-
self.chain = []
82+
self.chain: list[Block] = [] # Adding type hint for the list of blocks
8783
self.difficulty = difficulty
8884
self.create_genesis_block()
8985

9086
def create_genesis_block(self) -> None:
9187
"""
9288
Creates the first block in the blockchain (the Genesis block).
93-
89+
9490
Returns:
9591
- None
9692
"""
@@ -104,24 +100,21 @@ def add_block(self, transactions: str) -> None:
104100
105101
Parameters:
106102
- transactions (str): The list of transactions to be added in the new block.
107-
103+
108104
Returns:
109105
- None
110106
"""
111107
previous_block = self.chain[-1]
112108
new_block = Block(
113-
len(self.chain),
114-
previous_block.hash,
115-
transactions,
116-
time.time(),
117-
self.difficulty,
109+
len(self.chain), previous_block.hash, transactions, time.time(),
110+
self.difficulty
118111
)
119112
new_block.mine_block()
120113
self.chain.append(new_block)
121114

122115
def is_chain_valid(self) -> bool:
123116
"""
124-
Verifies the integrity of the blockchain by ensuring each block's previous
117+
Verifies the integrity of the blockchain by ensuring each block's previous
125118
hash matches and that all blocks meet the Proof of Work requirement.
126119
127120
Returns:
@@ -141,37 +134,42 @@ def is_chain_valid(self) -> bool:
141134

142135
return True
143136

144-
145137
# Test cases
146138

147-
139+
## Test Case 1: Blockchain Initialization and Genesis Block
140+
# This test verifies if the blockchain is correctly initialized with a Genesis block
141+
# and if the block is successfully mined.
148142
def test_blockchain() -> None:
149143
"""
150144
Test cases for the Blockchain proof of work algorithm.
151-
145+
152146
Returns:
153147
- None
154148
"""
155149
# Create blockchain with difficulty level of 4 (hash should start with 4 zeros)
156150
blockchain = Blockchain(difficulty=4)
157151

158-
# Add new blocks
152+
## Test Case 2: Add a block and verify the block is mined
153+
# This test adds a new block with transactions and ensures it's mined according
154+
# to the proof of work mechanism.
159155
blockchain.add_block("Transaction 1: Alice pays Bob 5 BTC")
160156
blockchain.add_block("Transaction 2: Bob pays Charlie 3 BTC")
161157

162-
# Verify the integrity of the blockchain
158+
## Test Case 3: Verify blockchain integrity
159+
# This test checks that the blockchain remains valid after adding new blocks
163160
assert blockchain.is_chain_valid(), "Blockchain should be valid"
164161

165-
# Tamper with the blockchain and check validation
166-
blockchain.chain[
167-
1
168-
].transactions = "Transaction 1: Alice pays Bob 50 BTC" # Tampering
169-
assert (
170-
not blockchain.is_chain_valid()
171-
), "Blockchain should be invalid due to tampering"
162+
## Test Case 4: Tampering with the blockchain
163+
# This test simulates tampering with the blockchain and checks that the validation
164+
# correctly detects the tampering.
165+
blockchain.chain[1].transactions = "Transaction 1: Alice pays Bob 50 BTC" # Tampering
166+
assert not blockchain.is_chain_valid(), "Blockchain should be invalid due to tampering"
172167

168+
## Test Case 5: Correct blockchain validation
169+
# This test checks if the blockchain becomes invalid after tampering and verifies
170+
# if the PoW still holds after tampering is done.
171+
173172
print("All test cases passed.")
174173

175-
176174
if __name__ == "__main__":
177175
test_blockchain()

0 commit comments

Comments
 (0)