-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathpeer.py
140 lines (112 loc) · 3.98 KB
/
peer.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
import json
import socket
import socketserver
# CLP
import multiprocessing
class _PeerRequestHandler(socketserver.BaseRequestHandler):
# Message Handling function.
def handle(self):
msg_str = self.request.recv(655350).strip().decode('utf-8')
msg_obj = json.loads(msg_str)
msg_type = msg_obj['type']
response = 'OK'
peer = self.server.peer
if msg_type == 'MINE':
# Call mine func
peer.mine(msg_obj['data'])
elif msg_type == 'CONNECT':
host = msg_obj['host']
port = msg_obj['port']
peer.connect_to_peer(host, port)
elif msg_type == 'PEERS':
response = json.dumps(peer.peers)
elif msg_type == 'SHOW':
response = json.dumps(peer.chain.to_dict())
elif msg_type == 'CHAIN':
chain = msg_obj['chain']
peer.replace_chain(chain)
self.request.sendall(response.encode('utf-8'))
class Peer(object):
def __init__(self, host='127.0.0.1', port=5000):
self.host = host
self.port = port
self._peers = set()
# self._chain = Chain()
def start(self):
server = socketserver.ThreadingTCPServer(
(self.host, self.port), _PeerRequestHandler)
server.peer = self
try:
server.serve_forever()
except KeyboardInterrupt as _:
server.server_close()
# connect new peer.
def connect_to_peer(self, host, port):
if (host, port) in self._peers:
return
'''
When new peer is added.
1. You will add peer.
2. send connection request.
3. broadcast your chain.
'''
self._peers.add((host, port))
peers = self._request_peers(host, port)
self._add_peers(json.loads(peers))
self._request_connection()
# self._broadcast_chain()
# it will be useless maybe...
def mine(self, data):
self._chain.mine(data)
self._broadcast_chain()
# replace chain function need to be coded.
def replace_chain(self, chain):
self._chain.replace_chain(chain)
@property
def chain(self):
return self._chain
@property
def peers(self):
return [{'host': host, 'port': port} for (host, port) in self._peers]
def _add_peers(self, peers):
for peer in peers:
host = peer['host']
port = peer['port']
if host == self.host and port == self.port:
continue
if (host, port) in self._peers:
continue
self._peers.add((host, port))
# Communication part.
def _request_connection(self):
message = {'type': 'CONNECT', 'host': self.host, 'port': self.port}
return self._broadcast(message)
def _request_peers(self, host, port):
message = {'type': 'PEERS', 'host': self.host, 'port': self.port}
return self._unicast(host, port, message)
def _broadcast_chain(self):
message = {'type': 'CHAIN', 'chain': self._chain.to_dict()}
return self._broadcast(message)
# Base communication
def _unicast(self, host, port, message):
pool = multiprocessing.Pool(1)
result = pool.apply_async(
self._send_message, args=(host, port, message))
pool.close()
pool.join()
return result.get()
def _broadcast(self, message):
results = []
pool = multiprocessing.Pool(5)
for (host, port) in self._peers:
results.append(pool.apply_async(
self._send_message, args=(host, port, message)))
pool.close()
pool.join()
return [result.get() for result in results]
def _send_message(self, host, port, message):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((host, port))
s.sendall(json.dumps(message).encode('utf-8'))
response = s.recv(655350, 0)
return response.decode('utf-8')