-
Notifications
You must be signed in to change notification settings - Fork 0
/
PeerDiscoveryHandler.py
65 lines (55 loc) · 2.38 KB
/
PeerDiscoveryHandler.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
import threading
import time
from Message import Message
from BlockchainUtils import BlockchainUtils
class PeerDiscoveryHandler():
def __init__(self, node):
self.socketCommunication = node
def start(self):
statusThread = threading.Thread(target=self.status, args=())
statusThread.start()
discoveryThread = threading.Thread(target=self.discovery, args=())
discoveryThread.start()
# print information about the current connections (peers) every 20 seconds
def status(self):
while True:
print('Current Connections:')
for peer in self.socketCommunication.peers:
print(str(peer.ip) + ':' + str(peer.port))
time.sleep(20)
# broadcast a handshake message every 15 seconds to discover new peers
def discovery(self):
while True:
handshakeMessage = self.handshakeMessage()
self.socketCommunication.broadcast(handshakeMessage)
time.sleep(15)
# send message to connnected nodes
def handshake(self, connected_node):
handshakeMessage = self.handshakeMessage()
self.socketCommunication.send(connected_node, handshakeMessage)
# create a handshake message containing information about the current node's peers
def handshakeMessage(self):
ownConnector = self.socketCommunication.socketConnector
ownPeers = self.socketCommunication.peers
data = ownPeers
messageType = 'DISCOVERY'
message = Message(ownConnector, messageType, data)
encodedMessage = BlockchainUtils.encode(message)
return encodedMessage
def handleMessage(self, message):
peersSocketConnector = message.senderConnector
peersPeerList = message.data
newPeer = True
for peer in self.socketCommunication.peers:
if peer.equals(peersSocketConnector):
newPeer = False
if newPeer:
self.socketCommunication.peers.append(peersSocketConnector)
for peersPeer in peersPeerList:
peerKnown = False
for peer in self.socketCommunication.peers:
if peer.equals(peersPeer):
peerKnown = True
if not peerKnown and not peersPeer.equals(self.socketCommunication.socketConnector):
self.socketCommunication.connect_with_node(
peersPeer.ip, peersPeer.port)