[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-10-03 10:04:15 +00:00
parent c051734d9c
commit 3d91445a57

View File

@ -11,6 +11,7 @@ difficulty is defined by the number of leading zeros required in the block hash.
import hashlib
import time
class Block:
def __init__(
self,
@ -18,7 +19,7 @@ class Block:
previous_hash: str,
transactions: str,
timestamp: float,
difficulty: int
difficulty: int,
) -> None:
"""
Initializes a Block object with the specified parameters.
@ -61,13 +62,16 @@ class Block:
Returns:
- None
"""
target = '0' * self.difficulty # Target hash should start with 'difficulty' zeros
while self.hash[:self.difficulty] != target:
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: int) -> None:
"""
@ -106,8 +110,11 @@ class Blockchain:
"""
previous_block = self.chain[-1]
new_block = Block(
len(self.chain), previous_block.hash, transactions, time.time(),
self.difficulty
len(self.chain),
previous_block.hash,
transactions,
time.time(),
self.difficulty,
)
new_block.mine_block()
self.chain.append(new_block)
@ -134,8 +141,10 @@ class Blockchain:
return True
# Test cases
def test_blockchain() -> None:
"""
Test cases for the Blockchain proof of work algorithm.
@ -154,10 +163,15 @@ def test_blockchain() -> None:
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"
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()