2019-08-27 21:46:12 +00:00
|
|
|
## Nim-LibP2P
|
|
|
|
## Copyright (c) 2018 Status Research & Development GmbH
|
|
|
|
## Licensed under either of
|
|
|
|
## * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
|
|
|
|
## * MIT license ([LICENSE-MIT](LICENSE-MIT))
|
|
|
|
## at your option.
|
|
|
|
## This file may not be copied, modified, or distributed except according to
|
|
|
|
## those terms.
|
|
|
|
|
2019-08-28 19:12:15 +00:00
|
|
|
import tables
|
2019-08-27 21:46:12 +00:00
|
|
|
import chronos
|
2019-08-28 02:30:53 +00:00
|
|
|
import connection, transport, stream,
|
2019-08-30 05:17:07 +00:00
|
|
|
multistreamselect, protocol,
|
|
|
|
peerinfo, multiaddress
|
2019-08-28 19:12:15 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
Switch* = ref object of RootObj
|
2019-08-30 05:17:07 +00:00
|
|
|
peerInfo*: PeerInfo
|
|
|
|
connections*: TableRef[string, Connection]
|
|
|
|
transports*: seq[Transport]
|
|
|
|
protocols*: seq[LPProtocol]
|
|
|
|
ms*: MultisteamSelect
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-08-28 02:30:53 +00:00
|
|
|
proc newSwitch*(peerInfo: PeerInfo, transports: seq[Transport]): Switch =
|
|
|
|
new result
|
|
|
|
result.peerInfo = peerInfo
|
|
|
|
result.ms = newMultistream()
|
|
|
|
result.transports = transports
|
2019-08-30 05:17:07 +00:00
|
|
|
result.protocols = newSeq[LPProtocol]()
|
2019-08-28 19:12:15 +00:00
|
|
|
result.connections = newTable[string, Connection]()
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-08-28 02:30:53 +00:00
|
|
|
proc dial*(s: Switch, peer: PeerInfo, proto: string = ""): Future[Connection] {.async.} = discard
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-08-30 05:17:07 +00:00
|
|
|
proc mount*(s: Switch, protocol: LPProtocol) = discard
|
2019-08-28 02:30:53 +00:00
|
|
|
|
|
|
|
proc start*(s: Switch) {.async.} =
|
2019-08-28 19:12:15 +00:00
|
|
|
# TODO: how bad is it that this is a closure?
|
|
|
|
proc handle(conn: Connection): Future[void] {.closure, gcsafe.} =
|
2019-08-30 05:17:07 +00:00
|
|
|
s.ms.handle(conn)
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-08-28 02:30:53 +00:00
|
|
|
for t in s.transports: # for each transport
|
|
|
|
for a in s.peerInfo.addrs:
|
|
|
|
if t.handles(a): # check if it handles the multiaddr
|
|
|
|
await t.listen(a, handle) # listen for incoming connections
|
|
|
|
break
|
2019-08-27 21:46:12 +00:00
|
|
|
|
2019-08-28 02:30:53 +00:00
|
|
|
proc stop*(s: Switch) {.async.} =
|
2019-08-28 19:12:15 +00:00
|
|
|
for c in s.connections.values:
|
|
|
|
await c.close()
|