-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathNetwork0.1
More file actions
67 lines (51 loc) · 2.24 KB
/
Network0.1
File metadata and controls
67 lines (51 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import hashlib
import time
from typing import List
class Block:
def __init__(self, index: int, timestamp: str, data: str, previous_hash: str):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash
self.nonce = 0
self.hash = self.calculate_hash()
def calculate_hash(self) -> str:
return hashlib.sha256(f"{self.index}{self.timestamp}{self.data}{self.previous_hash}{self.nonce}".encode()).hexdigest()
def mine_block(self, difficulty: int):
while self.hash[:difficulty] != "0" * difficulty:
self.nonce += 1
self.hash = self.calculate_hash()
print(f"Block mined: {self.hash}")
class Blockchain:
def __init__(self):
self.chain: List[Block] = [self.create_genesis_block()]
self.difficulty = 4
def create_genesis_block(self) -> Block:
return Block(0, time.time(), "Genesis Block", "0")
def get_latest_block(self) -> Block:
return self.chain[-1]
def add_block(self, new_block: Block):
new_block.previous_hash = self.get_latest_block().hash
new_block.mine_block(self.difficulty)
self.chain.append(new_block)
def is_chain_valid(self) -> bool:
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.calculate_hash():
print("Current block hash is invalid")
return False
if current_block.previous_hash != previous_block.hash:
print("Previous block hash is invalid")
return False
return True
# Example Usage
if __name__ == "__main__":
my_blockchain = Blockchain()
print("Mining block 1...")
my_blockchain.add_block(Block(1, time.time(), "Block 1 Data", my_blockchain.get_latest_block().hash))
print("Mining block 2...")
my_blockchain.add_block(Block(2, time.time(), "Block 2 Data", my_blockchain.get_latest_block().hash))
print("Is blockchain valid?", my_blockchain.is_chain_valid())
for block in my_blockchain.chain:
print(f"Index: {block.index}, Timestamp: {block.timestamp}, Data: {block.data}, Hash: {block.hash}")