py-libp2p/network/swarm.py

52 lines
1.7 KiB
Python
Raw Normal View History

2018-10-15 13:52:25 +08:00
from .network_interface import INetwork
2018-11-01 05:40:01 +08:00
from ..connection.muxed_connection import MuxedConnection
from ..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-11 23:43:03 +08:00
def __init__(self, my_peer_id, peerstore):
2018-10-15 13:52:25 +08:00
self.my_peer_id = my_peer_id
self.peer_store = peer_store
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):
"""
Determine if a connection to peer_id already exists
If a connection to peer_id exists, then
2018-11-01 06:31:52 +08:00
c = existing connection,
2018-11-01 05:40:01 +08:00
otherwise c = new muxed connection to peer_id
s = c.open_stream(protocol_id)
return s
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:
muxed_connection = self.connections[peer_id]
else:
addrs = self.peer_store.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")
return muxed_connection.open_stream(protocol_id, "")
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