Skip to content

Commit ef12e2b

Browse files
authored
Create proof_of_work.py
1 parent 65a08c3 commit ef12e2b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

blockchain/proof_of_work.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import hashlib
2+
import time
3+
from datetime import datetime
4+
5+
class Block:
6+
def __init__(self, index: int, previous_hash: str, data: str, timestamp: str):
7+
self.index = index
8+
self.previous_hash = previous_hash
9+
self.data = data
10+
self.timestamp = timestamp
11+
self.nonce = 0
12+
self.hash = self.calculate_hash()
13+
14+
def calculate_hash(self) -> str:
15+
value = (str(self.index) + str(self.previous_hash) +
16+
str(self.data) + str(self.timestamp) + str(self.nonce))
17+
return hashlib.sha256(value.encode('utf-8')).hexdigest()
18+
19+
def mine_block(self, difficulty: int) -> None:
20+
target = '0' * difficulty
21+
while self.hash[:difficulty] != target:
22+
self.nonce += 1
23+
self.hash = self.calculate_hash()
24+
print(f"Block mined: {self.hash}")
25+
26+
class Blockchain:
27+
def __init__(self):
28+
self.chain = [self.create_genesis_block()]
29+
self.difficulty = 4
30+
31+
def create_genesis_block(self) -> Block:
32+
return Block(0, "0", "Genesis Block", datetime.now().isoformat())
33+
34+
def get_latest_block(self) -> Block:
35+
return self.chain[-1]
36+
37+
def add_block(self, new_block: Block) -> None:
38+
new_block.previous_hash = self.get_latest_block().hash
39+
new_block.mine_block(self.difficulty)
40+
self.chain.append(new_block)
41+
42+
# Example usage
43+
blockchain = Blockchain()
44+
blockchain.add_block(Block(1, "", "Block 1 Data", datetime.now().isoformat()))
45+
blockchain.add_block(Block(2, "", "Block 2 Data", datetime.now().isoformat()))
46+
47+
# Display the blockchain
48+
for block in blockchain.chain:
49+
print(f"Block {block.index} - Hash: {block.hash} - Data: {block.data}")

0 commit comments

Comments
 (0)