-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.py
190 lines (163 loc) · 6.76 KB
/
node.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import json
import sys
import threading
import uuid
import requests
from bottle import Bottle, request, response
from blockchain import Chain, Block
class Node(Bottle):
def __init__(self, host, port, entry_node=None):
super(Node, self).__init__()
self.node_id = uuid.uuid4()
self.nodes = set()
self.host = host
self.port = port
self.name = "Node"
self.blockchain = Chain()
# API Paths
self.get('/test', callback=self.test)
self.get('/list_nodes', callback=self.list_nodes)
self.get('/get_blockchain', callback=self.get_blockchain)
self.get('/get_tail_block', callback=self.get_tail_block)
self.post('/update_blockchain', callback=self.update_blockchain)
self.post('/register_node', callback=self.register_node)
self.post('/add_block', callback=self.add_block)
if entry_node is not None:
print("Registering node to: {}".format(entry_node))
register_node_response = requests.post("http://{}/register_node".format(entry_node),
data=self.node_connection_string()
)
self.nodes.add(json.dumps(register_node_response.json()))
target_blockchain = requests.get("http://{}:{}/get_blockchain".format(
entry_node.split(':')[0], entry_node.split(':')[1]
)).json()
self.build_from_target(target_blockchain)
self.nodes.add(self.node_connection_string())
print("Nodes: ")
for _node in self.nodes:
print(_node)
self.run()
def build_from_target(self, target_json):
self.blockchain.blockchain = []
chain = target_json['blockchain']
for _block in chain:
block = Block.from_json(_block)
self.blockchain.blockchain.append(block)
def node_connection_string(self):
connection_dict = {
'node_id': str(self.node_id),
'host': self.host,
'port': self.port}
return json.dumps(connection_dict)
def run(self, **kwargs):
super().run(host=self.host, port=self.port, debug=True)
def list_nodes(self):
node_list = []
for node_item in self.nodes:
node_item_json = json.loads(node_item)
node_list.append({
'node_id': str(node_item_json['node_id']),
'host': node_item_json['host'],
'port': node_item_json['port']
})
return json.dumps(node_list)
def register_node(self):
new_node_string = request.body.read().decode('utf-8')
new_node_object = json.loads(new_node_string)
for _node in self.nodes:
_node_object = json.loads(_node)
if (_node_object['host'] == new_node_object['host']
and _node_object['port'] == new_node_object['port']):
self.nodes.discard(_node)
break
self.nodes.add(new_node_string)
print("New node registered: {} \nCurrent node list: ".format(new_node_string))
for _node in self.nodes:
if _node == self.node_connection_string():
print("(SELF)" + _node)
continue
print(_node)
return self.node_connection_string()
def get_blockchain(self):
response.content_type = 'application/json'
json_chain = self.blockchain.get_json()
object_chain = {
"blockchain_length": len(self.blockchain.blockchain),
"blockchain": json.loads(json_chain)
}
return json.dumps(object_chain)
def get_tail_block(self):
response.content_type = 'application/json'
return self.blockchain.read_tail_block().get_json()
def add_block(self):
response.content_type = 'application/json'
add_block_string = request.body.read()
add_block_json = json.loads(add_block_string)
insert_block = Block.from_json(add_block_json)
# Make sure our chain is up to date
for _node in self.nodes:
if _node == self.node_connection_string():
continue
node_dict = json.loads(_node)
tail_block = requests.get("http://{}:{}/get_tail_block"
.format(node_dict['host'], node_dict['port'])).json()
if tail_block['hash'] == self.blockchain.read_tail_block().hash:
print("Current chain up to date. Proceed to add block")
else:
target_blockchain = requests.get("http://{}:{}/get_blockchain".format(
node_dict['host'], node_dict['port']
)).json()
self.build_from_target(target_blockchain)
return json.dumps({
'status': 'operation failed',
'reason': 'blockchain outdated'
})
self.blockchain.add_block(insert_block)
threading.Thread(target=self.prompt_blockchain_update).start()
return json.dumps(insert_block.get_dict())
def prompt_blockchain_update(self):
for _node in self.nodes:
if _node == self.node_connection_string():
continue
node_dict = json.loads(_node)
request_response = requests.post("http://{}:{}/update_blockchain".format(
node_dict['host'], node_dict['port']),
data=self.node_connection_string())
return request_response
def update_blockchain(self):
response.content_type = 'application/json'
update_blockchain_string = request.body.read()
update_blockchain_json = json.loads(update_blockchain_string)
current_chain = requests.get(
"http://{}:{}/get_blockchain"
.format(update_blockchain_json['host'], update_blockchain_json['port'])).json()
self.build_from_target(current_chain)
def test(self):
return_message = request.headers.get('message')
return "{} - {}\n{}:{}".format(self.node_id,
return_message,
self.host,
self.port)
if __name__ == '__main__':
_host = "localhost"
_port = "8080"
_target = None
try:
_host = str(sys.argv[1])
_port = str(sys.argv[2])
_target = str(sys.argv[3])
except IndexError as ex:
print("No target supplied: {}".format(ex))
if _target is not None:
print("Running on {}:{} targeting {}".format(
_host,
_port,
_target
))
node = Node(_host, _port, _target)
else:
print("Running on {}:{}".format(
_host,
_port
))
node = Node(_host, _port)