Implement new stream function

This commit is contained in:
Stuckinaboot 2018-11-11 16:42:10 -05:00
parent 6ba5793c1d
commit 4851137ece

View File

@ -1,6 +1,6 @@
import uuid
from .network_interface import INetwork
from muxer.mplex.muxed_connection import MuxedConn
from transport.connection.raw_connection import RawConnection
from .stream.net_stream import NetStream
class Swarm(INetwork):
@ -8,6 +8,7 @@ class Swarm(INetwork):
self.my_peer_id = my_peer_id
self.peerstore = peerstore
self.connections = {}
self.upgrader = upgrader
def set_stream_handler(self, stream_handler):
"""
@ -20,26 +21,41 @@ class Swarm(INetwork):
"""
:param peer_id: peer_id of destination
:param protocol_id: protocol id
:return: stream instance
:return: net stream instance
"""
muxed_connection = None
muxed_conn = None
if peer_id in self.connections:
"""
If muxed connection already exists for peer_id,
set muxed connection equal to
existing muxed connection
"""
muxed_connection = self.connections[peer_id]
muxed_conn = self.connections[peer_id]
else:
# Get peer info from peer store
addrs = self.peerstore.addrs(peer_id)
stream_ip = addrs.get_protocol_value("ip")
stream_port = addrs.get_protocol_value("port")
if len(addrs) > 0:
conn = RawConnection(stream_ip, stream_port)
muxed_connection = MuxedConnection(conn, True)
else:
raise Exception("No IP and port in addr")
return muxed_connection.open_stream(protocol_id, "", peer_id, addrs)
# Transport dials peer (gets back a raw conn)
if not addrs:
raise SwarmException("No known addresses to peer")
first_addr = addrs[0]
raw_conn = self.transport.dial(first_addr)
# Use upgrader to upgrade raw conn to muxed conn
muxed_conn = self.upgrader.upgrade_connection(raw_conn)
# Store muxed connection in connections
self.connections[peer_id] = muxed_conn
# Use muxed conn to open stream, which returns
# a muxed stream
stream_id = str(uuid.uuid4())
muxed_stream = muxed_conn.open_stream(protocol_id, stream_id, peer_id, first_addr)
# Create a net stream
net_stream = NetStream(muxed_stream)
return net_stream
def listen(self, *args):
"""
@ -47,3 +63,10 @@ class Swarm(INetwork):
:return: true if at least one success
"""
pass
def add_transport(self, transport):
# TODO: Support more than one transport
self.transport = transport
class SwarmException(Exception):
pass