-
Notifications
You must be signed in to change notification settings - Fork 2
/
spvclient.py
80 lines (65 loc) · 2.34 KB
/
spvclient.py
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
from shortuuid import uuid
import time
import json
import argparse
from src.nodes import SPVNode
from src.blockchain import Blockchain
"""
===========
MAIN CODE
===========
"""
parser = argparse.ArgumentParser()
parser.add_argument('-n', type=str, help='node name')
parser.add_argument('-p', type=int, help='port number (default: 5000)')
parser.add_argument('--file', type=str, help='specified file storing the blockchain (default: \'blockchain.json\')')
parser.add_argument('-o', type=str, help='output file without requiring an initial blockchain file to read from (default: \'blockchain.json\')')
args = parser.parse_args()
node_id = uuid()
if __name__ == '__main__':
# Load Blockchain File
filename = args.file
if filename:
data = json.load(open(filename))
blockchain = Blockchain(list(map(lambda block: block['header'], data['chain'])))
else:
filename = args.o
blockchain = Blockchain()
node = SPVNode(
name=args.n or f'node-{node_id}',
port=args.p or 5000,
blockchain=blockchain
)
try:
print(f'Starting node-{node_id}')
# Establish Connection
while not node.ready:
node.send('version', message=json.dumps({
'height': len(node.blockchain.chain)
}))
time.sleep(1)
# Sync up with the other nodes
while not node.synced:
node.resolve_conflicts()
time.sleep(5)
# Listen for new blocks being added
while True:
user_input = input('\nDo you want to add a transaction? (y/n) ')
if user_input.lower == 'yes' or user_input.lower == 'y':
recipient = input('Recipient: ')
amount = input('Amount: ')
previous_hash = input('Previous Hash: ')
tx = node.blockchain.verify_and_add_transaction(
sender=node.identifier,
recipient=recipient,
amount=int(amount),
previous_hash=previous_hash
)
if tx:
node.send('addtx', message=json.dumps({
'tx': json.dumps(tx)
}))
time.sleep(1)
except (EOFError, KeyboardInterrupt):
node.stop()
node.blockchain.save(filename or 'blockchain.json')