2018-10-15 13:52:25 +08:00
|
|
|
from .network_interface import INetwork
|
2018-11-12 00:58:48 +08:00
|
|
|
from muxer.mplex.muxed_connection import MuxedConn
|
|
|
|
from transport.connection.raw_connection import RawConnection
|
2018-10-15 01:47:06 +08:00
|
|
|
|
2018-10-15 13:52:25 +08:00
|
|
|
class Swarm(INetwork):
|
|
|
|
|
2018-11-12 05:09:37 +08:00
|
|
|
def __init__(self, my_peer_id, peerstore, upgrader):
|
2018-10-15 13:52:25 +08:00
|
|
|
self.my_peer_id = my_peer_id
|
2018-11-12 01:36:15 +08:00
|
|
|
self.peerstore = peerstore
|
2018-11-01 05:40:01 +08:00
|
|
|
self.connections = {}
|
2018-10-15 13:52:25 +08:00
|
|
|
|
|
|
|
def set_stream_handler(self, stream_handler):
|
|
|
|
"""
|
|
|
|
:param stream_handler: a stream handler instance
|
|
|
|
:return: true if successful
|
|
|
|
"""
|
|
|
|
pass
|
|
|
|
|
2018-11-01 05:40:01 +08:00
|
|
|
def new_stream(self, peer_id, protocol_id):
|
|
|
|
"""
|
2018-11-01 06:31:52 +08:00
|
|
|
:param peer_id: peer_id of destination
|
|
|
|
:param protocol_id: protocol id
|
|
|
|
:return: stream instance
|
2018-11-01 05:40:01 +08:00
|
|
|
"""
|
|
|
|
muxed_connection = None
|
|
|
|
if peer_id in self.connections:
|
2018-11-12 05:09:37 +08:00
|
|
|
"""
|
|
|
|
If muxed connection already exists for peer_id,
|
|
|
|
set muxed connection equal to
|
|
|
|
existing muxed connection
|
|
|
|
"""
|
2018-11-01 05:40:01 +08:00
|
|
|
muxed_connection = self.connections[peer_id]
|
|
|
|
else:
|
2018-11-12 01:36:15 +08:00
|
|
|
addrs = self.peerstore.addrs(peer_id)
|
2018-11-01 06:31:52 +08:00
|
|
|
stream_ip = addrs.get_protocol_value("ip")
|
|
|
|
stream_port = addrs.get_protocol_value("port")
|
2018-11-01 05:40:01 +08:00
|
|
|
if len(addrs) > 0:
|
2018-11-01 06:31:52 +08:00
|
|
|
conn = RawConnection(stream_ip, stream_port)
|
2018-11-01 05:40:01 +08:00
|
|
|
muxed_connection = MuxedConnection(conn, True)
|
|
|
|
else:
|
|
|
|
raise Exception("No IP and port in addr")
|
2018-11-12 00:52:26 +08:00
|
|
|
return muxed_connection.open_stream(protocol_id, "", peer_id, addrs)
|
2018-10-22 01:51:55 +08:00
|
|
|
|
|
|
|
def listen(self, *args):
|
|
|
|
"""
|
|
|
|
:param *args: one or many multiaddrs to start listening on
|
|
|
|
:return: true if at least one success
|
|
|
|
"""
|
|
|
|
pass
|