diff --git a/libp2p/mplex.nim b/libp2p/mplex.nim new file mode 100644 index 000000000..1ecb9cd21 --- /dev/null +++ b/libp2p/mplex.nim @@ -0,0 +1,145 @@ +## 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. + +import chronos +import ../varint, ../connection, + ../vbuffer, ../protocol + +const DefaultReadSize: uint = 1024 + +const MaxMsgSize* = 1 shl 20 # 1mb +const MaxChannels* = 1000 + +type + MplexUnknownMsgError* = object of CatchableError + + MessageType* {.pure.} = enum + New, + MsgIn, + MsgOut, + CloseIn, + CloseOut, + ResetIn, + ResetOut + + ChannelHandler* = proc(conn: Connection) {.gcsafe.} + + Mplex* = ref object of LPProtocol + remote*: seq[Connection] + local*: seq[Connection] + channelHandler*: ChannelHandler + currentId*: uint + + Channel* = ref object of BufferStream + id*: int + initiator*: bool + reset*: bool + closedLocal*: bool + closedRemote*: bool + mplex*: Mplex + +proc newMplexUnknownMsgError*(): ref MplexUnknownMsgError = + result = newException(MplexUnknownMsgError, "Unknown mplex message type") + +proc readLp*(conn: Connection): Future[tuple[id: uint, msgType: MessageType]] {.gcsafe.} = + var + header: uint + length: int + res: VarintStatus + var buffer = newSeq[byte](10) + try: + for i in 0..