-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
163 lines (132 loc) · 5.25 KB
/
server.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
import datetime
import json
import socket
import sys
from json.decoder import JSONDecodeError
from blockchain import Blockchain
from util import LockedOpen
HEADER_SIZE = 10
MAX_CONNECTIONS = 5
class P2PServer(object):
P2P_SERVERS_LIST = 'nodes.json'
def __init__(self, port):
self.blockchain = Blockchain()
self.port = port
def listen(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind(('localhost', self.port))
self.socket.listen(MAX_CONNECTIONS)
self.subscribe() # attach self to P2P network
# cycle = (1) connect, (2) get msg, (3) process msg, (4) respond
while True:
# accept connections
client, addr = self.socket.accept()
self.log(f"Connected to '{addr}'")
# get message
size = int(str(client.recv(HEADER_SIZE), 'utf-8'))
data = str(client.recv(size), 'utf-8')
self.log(f"Receiving message ({size} chars) -> {data[:100]}")
# process request
resp = self.process_request(data)
self.log(f"Server response -> {resp[:100]}")
# respond
client.send(bytes(f'{len(resp):<{HEADER_SIZE}}{resp}', 'utf-8'))
client.close()
self.log(f"Client '{addr}' disconnected")
if resp == 'EXITING':
self.log("Terminating server")
self.unsubscribe() # detach self from the P2P network
exit(0)
def log(self, msg):
print(f"{datetime.datetime.today()} :: ({self.port}) :: {msg}")
def notify_nodes(self, blockchain):
"""
notify each node in the network of a change in the blockchain
:param blockchain: Blockchain
:return: NoReturn
"""
servers = self._open_servers_list()
for port, address in servers.items():
response = self.send(int(port), blockchain.JSONify())
def process_request(self, data):
"""
Process the incoming request. Valid requests are:
GET CHAIN -> Returns this nodes blockchain as a JSON parsable string
SHUTDOWN -> Unsubscribe this node from the P2P network and exit process
[{block}, ...] -> A JSON parsable string implies that a blockchain
candidate is sent our way
:param data: str
:return: str
"""
if data.upper() == 'GET CHAIN':
return self.blockchain.JSONify()
if data.upper() == 'SHUTDOWN':
return 'EXITING'
try:
blockchain = Blockchain(json.loads(data))
except JSONDecodeError:
return 'INVALID JSON'
size = blockchain.is_valid(return_size=True)
if size <= self.blockchain.size:
return 'BLOCKCHAIN REJECTED'
else:
self.blockchain = blockchain
return 'BLOCKCHAIN ACCEPTED'
def send(self, port: int, msg: str):
"""
Send a message to another peer on the given port.
:param msg: str
:param port: int
:return:
"""
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('localhost', port))
msg = f'{len(msg):<{HEADER_SIZE}}{msg}'
self.log(f"Sending msg to '{port}' -> {msg[:100]}")
client.send(bytes(msg, 'utf-8'))
# get response
size = int(str(client.recv(HEADER_SIZE), 'utf-8'))
response = str(client.recv(size), 'utf-8')
self.log(f"Receiving response ({size} chars) -> {response[:100]}")
return response
def sync_nodes(self):
"""
Get longest valid chain on the network
"""
servers = self._open_servers_list()
for port, address in servers.items():
response = self.send(int(port), 'GET CHAIN')
peer_blockchain = Blockchain(response)
size = peer_blockchain.is_valid(return_size=True)
if size > self.blockchain.size:
self.blockchain.set_blockchain(peer_blockchain)
def subscribe(self):
# subscribe self as a listening P2P node / connect to network
with LockedOpen(self.P2P_SERVERS_LIST, 'w') as fd:
servers = json.load(fd)
servers[port] = 'localhost' # everything is on localhost
fd.write(json.dumps(servers, indent=2))
def unsubscribe(self):
# unsubscribe self as a listening P2P node / disconnect from network
with LockedOpen(self.P2P_SERVERS_LIST, 'w') as fd:
servers = json.load(fd)
del servers[port]
fd.write(json.dumps(servers, indent=2))
def _open_servers_list(self):
try:
with LockedOpen(self.P2P_SERVERS_LIST, 'r') as fd:
return json.load(fd)
except FileNotFoundError:
return []
if __name__ == '__main__':
# python server.py 1> localhost_port.log 2>&1
try:
port = int(sys.argv[1])
except IndexError:
print(f"{datetime.datetime.today()} :: Port number argument missing. "
f"Try 'python server.py 6001'.")
exit(1)
except ValueError:
print(f"{datetime.datetime.today()} :: 'Port' argument is not a valid "
f"integer. Try 'python server.py 6001'.")
exit(1)