-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_chain_sync.py
More file actions
84 lines (65 loc) · 2.59 KB
/
test_chain_sync.py
File metadata and controls
84 lines (65 loc) · 2.59 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import asyncio
import os
import time
import shutil
from src.core.chain import Blockchain
from src.network.node import Node
# Clean up previous tests
if os.path.exists("local_chain_8000.json"): os.remove("local_chain_8000.json")
if os.path.exists("local_chain_8001.json"): os.remove("local_chain_8001.json")
async def test_persistence():
print("\n--- TEST 1: PERSISTENCE ---")
chain = Blockchain()
# We manually set the 'chain_file' conceptually by saving it manually or mocking Node
# Let's use Node to drive it
node = Node("127.0.0.1", 8000, chain)
# Mine a block
print("Mining block 1 on Node A...")
chain.mine_pending_transactions("MinerA")
node.blockchain.save_chain("local_chain_8000.json")
# Verify file exists
if os.path.exists("local_chain_8000.json"):
print("Success: Chain file created.")
else:
print("Failure: Chain file not found.")
return
# Create new node/chain instance and load
print("Restarting Node A (Loading chain)...")
chain2 = Blockchain()
chain2.load_chain("local_chain_8000.json")
if len(chain2.chain) == 2: # Genesis + 1
print("Success: Chain loaded with correct height.")
else:
print(f"Failure: Expected height 2, got {len(chain2.chain)}")
async def test_sync():
print("\n--- TEST 2: SYNC ---")
# Setup Node A (The Authority) - Already has 2 blocks from Test 1
chainA = Blockchain()
nodeA = Node("127.0.0.1", 8000, chainA) # Will load local_chain_8000.json automatically
# Setup Node B (The Newcomer) - Empty (only Genesis)
chainB = Blockchain()
nodeB = Node("127.0.0.1", 8001, chainB)
# Start Servers
serverA = asyncio.create_task(nodeA.start_server())
serverB = asyncio.create_task(nodeB.start_server())
await asyncio.sleep(1)
print(f"Node A Height: {len(nodeA.blockchain.chain)}") # Should be 2
print(f"Node B Height: {len(nodeB.blockchain.chain)}") # Should be 1
# Connect B to A
print("Connecting Node B to Node A...")
await nodeB.connect_to_peer("127.0.0.1", 8000)
# Wait for sync (handshake -> query -> response -> process)
await asyncio.sleep(2)
print(f"Node B Height after sync: {len(nodeB.blockchain.chain)}")
if len(nodeB.blockchain.chain) == len(nodeA.blockchain.chain):
print("Success: Node B synced with Node A.")
else:
print("Failure: Node B did not sync.")
# Cleanup
serverA.cancel()
serverB.cancel()
async def main():
await test_persistence()
await test_sync()
if __name__ == "__main__":
asyncio.run(main())