2019-05-29 08:21:03 +00:00
|
|
|
import
|
2019-05-31 18:36:32 +00:00
|
|
|
tables, deques, options, algorithm, std_shims/[macros_shim, tables_shims],
|
|
|
|
ranges/ptr_arith, chronos, chronicles, serialization, faststreams/input_stream,
|
2019-06-17 11:08:05 +00:00
|
|
|
eth/async_utils, eth/p2p/p2p_protocol_dsl, libp2p/daemon/daemonapi,
|
2019-06-24 15:13:48 +00:00
|
|
|
libp2p_json_serialization, ssz
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
export
|
2019-06-24 15:13:48 +00:00
|
|
|
daemonapi, p2pProtocol, serialization, ssz, libp2p_json_serialization
|
2019-05-31 18:36:32 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
const
|
|
|
|
# Compression nibble
|
2019-06-17 11:08:05 +00:00
|
|
|
NoCompression* = byte 0
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
# Encoding nibble
|
2019-06-17 11:08:05 +00:00
|
|
|
SszEncoding* = byte 1
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
beaconChainProtocol = "/eth/serenity/beacon/rpc/1"
|
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
type
|
|
|
|
Eth2Node* = ref object of RootObj
|
|
|
|
daemon*: DaemonAPI
|
|
|
|
peers*: Table[PeerID, Peer]
|
|
|
|
protocolStates*: seq[RootRef]
|
|
|
|
|
|
|
|
EthereumNode = Eth2Node # needed for the definitions in p2p_backends_helpers
|
|
|
|
|
2019-06-05 02:00:07 +00:00
|
|
|
Peer* = ref object
|
|
|
|
network*: Eth2Node
|
|
|
|
id*: PeerID
|
2019-06-17 11:08:05 +00:00
|
|
|
lastReqId*: uint64
|
2019-06-05 02:00:07 +00:00
|
|
|
rpcStream*: P2PStream
|
|
|
|
connectionState*: ConnectionState
|
|
|
|
awaitedMessages: Table[CompressedMsgId, FutureBase]
|
2019-06-17 11:08:05 +00:00
|
|
|
outstandingRequests*: Table[uint64, OutstandingRequest]
|
2019-06-05 02:00:07 +00:00
|
|
|
protocolStates*: seq[RootRef]
|
2019-06-17 11:08:05 +00:00
|
|
|
maxInactivityAllowed*: Duration
|
2019-06-05 02:00:07 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
ConnectionState* = enum
|
|
|
|
None,
|
|
|
|
Connecting,
|
|
|
|
Connected,
|
|
|
|
Disconnecting,
|
|
|
|
Disconnected
|
|
|
|
|
|
|
|
DisconnectionReason* = enum
|
|
|
|
ClientShutdown = 1
|
|
|
|
IrrelevantNetwork
|
|
|
|
FaultOrError
|
|
|
|
|
|
|
|
CompressedMsgId = tuple
|
2019-06-03 17:07:50 +00:00
|
|
|
protocolIdx, methodId: int
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-30 18:57:12 +00:00
|
|
|
ResponderWithId*[MsgType] = object
|
2019-05-29 08:21:03 +00:00
|
|
|
peer*: Peer
|
2019-06-03 17:07:50 +00:00
|
|
|
reqId*: uint64
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
Response*[MsgType] = distinct Peer
|
|
|
|
|
|
|
|
# -----------------------------------------
|
|
|
|
|
|
|
|
ResponseCode* = enum
|
|
|
|
NoError
|
|
|
|
ParseError = 10
|
|
|
|
InvalidRequest = 20
|
|
|
|
MethodNotFound = 30
|
|
|
|
ServerError = 40
|
|
|
|
|
|
|
|
OutstandingRequest* = object
|
2019-05-31 18:36:32 +00:00
|
|
|
id*: uint64
|
2019-05-29 08:21:03 +00:00
|
|
|
future*: FutureBase
|
|
|
|
timeoutAt*: Moment
|
2019-06-17 11:08:05 +00:00
|
|
|
responseThunk*: ThunkProc
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
ProtocolConnection* = object
|
|
|
|
stream*: P2PStream
|
|
|
|
protocolInfo*: ProtocolInfo
|
|
|
|
|
|
|
|
MessageInfo* = object
|
|
|
|
id*: int
|
|
|
|
name*: string
|
|
|
|
|
|
|
|
# Private fields:
|
|
|
|
thunk*: ThunkProc
|
|
|
|
printer*: MessageContentPrinter
|
|
|
|
nextMsgResolver*: NextMsgResolver
|
|
|
|
requestResolver*: RequestResolver
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
ProtocolInfoObj* = object
|
|
|
|
name*: string
|
|
|
|
version*: int
|
|
|
|
messages*: seq[MessageInfo]
|
|
|
|
index*: int # the position of the protocol in the
|
|
|
|
# ordered list of supported protocols
|
|
|
|
|
|
|
|
# Private fields:
|
|
|
|
peerStateInitializer*: PeerStateInitializer
|
|
|
|
networkStateInitializer*: NetworkStateInitializer
|
|
|
|
handshake*: HandshakeStep
|
|
|
|
disconnectHandler*: DisconnectionHandler
|
|
|
|
|
|
|
|
ProtocolInfo* = ptr ProtocolInfoObj
|
|
|
|
|
|
|
|
SpecOuterMsgHeader {.packed.} = object
|
|
|
|
compression {.bitsize: 4.}: uint
|
|
|
|
encoding {.bitsize: 4.}: uint
|
|
|
|
msgLen: uint64
|
|
|
|
|
|
|
|
SpecInnerMsgHeader {.packed.} = object
|
|
|
|
reqId: uint64
|
|
|
|
methodId: uint16
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
ErrorResponse {.packed.} = object
|
|
|
|
outerHeader: SpecOuterMsgHeader
|
|
|
|
innerHeader: SpecInnerMsgHeader
|
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
PeerStateInitializer* = proc(peer: Peer): RootRef {.gcsafe.}
|
|
|
|
NetworkStateInitializer* = proc(network: Eth2Node): RootRef {.gcsafe.}
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
HandshakeStep* = proc(peer: Peer, handshakeStream: P2PStream): Future[void] {.gcsafe.}
|
|
|
|
DisconnectionHandler* = proc(peer: Peer): Future[void] {.gcsafe.}
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
ThunkProc* = proc(peer: Peer,
|
|
|
|
stream: P2PStream,
|
|
|
|
reqId: uint64,
|
2019-06-17 11:08:05 +00:00
|
|
|
reqFuture: FutureBase,
|
2019-05-29 08:21:03 +00:00
|
|
|
msgData: ByteStreamVar): Future[void] {.gcsafe.}
|
|
|
|
|
|
|
|
MessageContentPrinter* = proc(msg: pointer): string {.gcsafe.}
|
2019-06-03 17:07:50 +00:00
|
|
|
NextMsgResolver* = proc(msg: pointer, future: FutureBase) {.gcsafe.}
|
2019-05-29 08:21:03 +00:00
|
|
|
RequestResolver* = proc(msg: pointer, future: FutureBase) {.gcsafe.}
|
|
|
|
|
|
|
|
Bytes = seq[byte]
|
|
|
|
|
|
|
|
InvalidMsgIdError = object of InvalidMsgError
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
PeerDisconnected* = object of P2PBackendError
|
|
|
|
reason*: DisconnectionReason
|
|
|
|
|
2019-06-05 02:00:07 +00:00
|
|
|
PeerLoopExitReason = enum
|
|
|
|
Success
|
|
|
|
UnsupportedCompression
|
|
|
|
UnsupportedEncoding
|
|
|
|
ProtocolViolation
|
|
|
|
InactivePeer
|
|
|
|
InternalError
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
const
|
|
|
|
HandshakeTimeout = FaultOrError
|
2019-06-05 02:00:07 +00:00
|
|
|
BreachOfProtocol* = FaultOrError
|
|
|
|
# TODO: We should lobby for more disconnection reasons.
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
template isOdd(val: SomeInteger): bool =
|
|
|
|
type T = type(val)
|
|
|
|
(val and T(1)) != 0
|
|
|
|
|
|
|
|
proc init(T: type SpecOuterMsgHeader,
|
|
|
|
compression, encoding: byte, msgLen: uint64): T =
|
|
|
|
T(compression: compression, encoding: encoding, msgLen: msgLen)
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
proc readPackedObject(stream: P2PStream, T: type): Future[T] {.async.} =
|
2019-05-29 08:21:03 +00:00
|
|
|
await stream.transp.readExactly(addr result, sizeof result)
|
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
proc appendPackedObject(stream: OutputStreamVar, value: auto) =
|
2019-05-31 18:36:32 +00:00
|
|
|
let valueAsBytes = cast[ptr byte](unsafeAddr(value))
|
|
|
|
stream.append makeOpenArray(valueAsBytes, sizeof(value))
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc getThunk(protocol: ProtocolInfo, methodId: uint16): ThunkProc =
|
|
|
|
if methodId.int >= protocol.messages.len: return nil
|
|
|
|
protocol.messages[methodId.int].thunk
|
|
|
|
|
2019-06-05 02:00:07 +00:00
|
|
|
include eth/p2p/p2p_backends_helpers
|
|
|
|
include eth/p2p/p2p_tracing
|
2019-06-24 02:34:01 +00:00
|
|
|
include libp2p_backends_common
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
proc handleConnectingBeaconChainPeer(daemon: DaemonAPI, stream: P2PStream) {.async, gcsafe.}
|
|
|
|
|
2019-06-12 12:23:05 +00:00
|
|
|
proc init*(T: type Eth2Node, daemon: DaemonAPI): Future[Eth2Node] {.async.} =
|
|
|
|
new result
|
|
|
|
result.daemon = daemon
|
|
|
|
result.daemon.userData = result
|
|
|
|
result.peers = initTable[PeerID, Peer]()
|
2019-05-31 18:36:32 +00:00
|
|
|
|
2019-06-12 12:23:05 +00:00
|
|
|
newSeq result.protocolStates, allProtocols.len
|
2019-05-31 18:36:32 +00:00
|
|
|
for proto in allProtocols:
|
|
|
|
if proto.networkStateInitializer != nil:
|
2019-06-12 12:23:05 +00:00
|
|
|
result.protocolStates[proto.index] = proto.networkStateInitializer(result)
|
2019-05-31 18:36:32 +00:00
|
|
|
|
2019-06-12 12:23:05 +00:00
|
|
|
await daemon.addHandler(@[beaconChainProtocol], handleConnectingBeaconChainPeer)
|
2019-05-31 18:36:32 +00:00
|
|
|
|
|
|
|
proc init*(T: type Peer, network: Eth2Node, id: PeerID): Peer =
|
|
|
|
new result
|
|
|
|
result.id = id
|
|
|
|
result.network = network
|
|
|
|
result.awaitedMessages = initTable[CompressedMsgId, FutureBase]()
|
2019-06-17 11:08:05 +00:00
|
|
|
result.maxInactivityAllowed = 15.minutes # TODO: read this from the config
|
|
|
|
result.connectionState = None
|
2019-05-31 18:36:32 +00:00
|
|
|
newSeq result.protocolStates, allProtocols.len
|
|
|
|
for i in 0 ..< allProtocols.len:
|
|
|
|
let proto = allProtocols[i]
|
|
|
|
if proto.peerStateInitializer != nil:
|
|
|
|
result.protocolStates[i] = proto.peerStateInitializer(result)
|
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
proc init*[MsgName](T: type ResponderWithId[MsgName],
|
|
|
|
peer: Peer, reqId: uint64): T =
|
|
|
|
T(peer: peer, reqId: reqId)
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc sendMsg*(peer: Peer, data: Bytes) {.gcsafe, async.} =
|
2019-06-10 23:20:18 +00:00
|
|
|
try:
|
2019-06-17 11:08:05 +00:00
|
|
|
var unsentBytes = data.len
|
|
|
|
while true:
|
|
|
|
# TODO: this looks wrong.
|
|
|
|
# We are always trying to write the same data.
|
|
|
|
# Find all other places where such code is used.
|
|
|
|
unsentBytes -= await peer.rpcStream.transp.write(data)
|
|
|
|
if unsentBytes <= 0: return
|
2019-06-10 23:20:18 +00:00
|
|
|
except CatchableError:
|
2019-06-17 11:08:05 +00:00
|
|
|
await peer.disconnect(FaultOrError)
|
|
|
|
# this is usually a "(32) Broken pipe":
|
|
|
|
# FIXME: this exception should be caught somewhere in addMsgHandler() and
|
|
|
|
# sending should be retried a few times
|
|
|
|
raise
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc sendMsg*[T](responder: ResponderWithId[T], data: Bytes): Future[void] =
|
|
|
|
return sendMsg(responder.peer, data)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc sendErrorResponse(peer: Peer, reqId: uint64,
|
|
|
|
responseCode: ResponseCode): Future[void] =
|
|
|
|
var resp = ErrorResponse(
|
|
|
|
outerHeader: SpecOuterMsgHeader.init(
|
|
|
|
compression = NoCompression,
|
|
|
|
encoding = SszEncoding,
|
|
|
|
msgLen = uint64 sizeof(SpecInnerMsgHeader)),
|
|
|
|
innerHeader: SpecInnerMsgHeader(
|
|
|
|
reqId: reqId,
|
|
|
|
methodId: uint16(responseCode)))
|
|
|
|
|
|
|
|
# TODO: don't allocate the Bytes sequence here
|
|
|
|
return peer.sendMsg @(makeOpenArray(cast[ptr byte](addr resp), sizeof resp))
|
|
|
|
|
|
|
|
proc recvAndDispatchMsg*(peer: Peer): Future[PeerLoopExitReason] {.async.} =
|
2019-05-29 08:21:03 +00:00
|
|
|
template fail(reason) =
|
|
|
|
return reason
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
# For now, we won't try to handle the presence of multiple sub-protocols
|
|
|
|
# since the spec is not defining how they will be mapped to P2P streams.
|
|
|
|
doAssert allProtocols.len == 1
|
|
|
|
|
|
|
|
var
|
|
|
|
stream = peer.rpcStream
|
|
|
|
protocol = allProtocols[0]
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
var outerHeader = await stream.readPackedObject(SpecOuterMsgHeader)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
if outerHeader.compression != NoCompression:
|
|
|
|
fail UnsupportedCompression
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
if outerHeader.encoding != SszEncoding:
|
|
|
|
fail UnsupportedEncoding
|
|
|
|
|
|
|
|
if outerHeader.msgLen <= SpecInnerMsgHeader.sizeof.uint64:
|
|
|
|
fail ProtocolViolation
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
let
|
|
|
|
innerHeader = await stream.readPackedObject(SpecInnerMsgHeader)
|
|
|
|
reqId = innerHeader.reqId
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
var msgContent = newSeq[byte](outerHeader.msgLen - SpecInnerMsgHeader.sizeof.uint64)
|
|
|
|
await stream.transp.readExactly(addr msgContent[0], msgContent.len)
|
|
|
|
|
|
|
|
var msgContentStream = memoryStream(msgContent)
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
if reqId.isOdd:
|
|
|
|
peer.outstandingRequests.withValue(reqId, req):
|
|
|
|
let thunk = req.responseThunk
|
|
|
|
let reqFuture = req.future
|
|
|
|
peer.outstandingRequests.del(reqId)
|
|
|
|
|
|
|
|
try:
|
|
|
|
await thunk(peer, stream, reqId, reqFuture, msgContentStream)
|
|
|
|
except SerializationError:
|
|
|
|
debug "Error during deserialization", err = getCurrentExceptionMsg()
|
|
|
|
fail ProtocolViolation
|
|
|
|
except CatchableError:
|
|
|
|
# TODO
|
|
|
|
warn ""
|
|
|
|
do:
|
|
|
|
debug "Ignoring late or invalid response ID", peer, id = reqId
|
|
|
|
# TODO: skip the message
|
|
|
|
else:
|
|
|
|
let thunk = protocol.getThunk(innerHeader.methodId)
|
|
|
|
if thunk != nil:
|
|
|
|
try:
|
|
|
|
await thunk(peer, stream, reqId, nil, msgContentStream)
|
|
|
|
except SerializationError:
|
|
|
|
debug "Error during deserialization", err = getCurrentExceptionMsg()
|
|
|
|
fail ProtocolViolation
|
|
|
|
except CatchableError:
|
|
|
|
# TODO
|
|
|
|
warn ""
|
|
|
|
else:
|
|
|
|
debug "P2P request method not found", methodId = innerHeader.methodId
|
|
|
|
await peer.sendErrorResponse(reqId, MethodNotFound)
|
2019-05-31 18:36:32 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc dispatchMessages*(peer: Peer): Future[PeerLoopExitReason] {.async.} =
|
2019-05-29 08:21:03 +00:00
|
|
|
while true:
|
2019-06-17 11:08:05 +00:00
|
|
|
let dispatchedMsgFut = recvAndDispatchMsg(peer)
|
|
|
|
doAssert peer.maxInactivityAllowed.milliseconds > 0
|
2019-05-29 08:21:03 +00:00
|
|
|
yield dispatchedMsgFut or sleepAsync(peer.maxInactivityAllowed)
|
|
|
|
if not dispatchedMsgFut.finished:
|
|
|
|
return InactivePeer
|
|
|
|
elif dispatchedMsgFut.failed:
|
|
|
|
error "Error in peer loop"
|
|
|
|
return InternalError
|
|
|
|
else:
|
|
|
|
let status = dispatchedMsgFut.read
|
|
|
|
if status == Success: continue
|
|
|
|
return status
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc performProtocolHandshakes*(peer: Peer) {.async.} =
|
|
|
|
peer.initProtocolStates allProtocols
|
|
|
|
|
|
|
|
# Please note that the ordering of operations here is important!
|
|
|
|
#
|
|
|
|
# We must first start all handshake procedures and give them a
|
|
|
|
# chance to send any initial packages they might require over
|
|
|
|
# the network and to yield on their `nextMsg` waits.
|
|
|
|
#
|
|
|
|
var subProtocolsHandshakes = newSeqOfCap[Future[void]](allProtocols.len)
|
|
|
|
for protocol in allProtocols:
|
|
|
|
if protocol.handshake != nil:
|
|
|
|
subProtocolsHandshakes.add((protocol.handshake)(peer, peer.rpcStream))
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
# The `dispatchMesssages` loop must be started after this.
|
|
|
|
# Otherwise, we risk that some of the handshake packets sent by
|
|
|
|
# the other peer may arrrive too early and be processed before
|
|
|
|
# the handshake code got a change to wait for them.
|
|
|
|
#
|
|
|
|
var messageProcessingLoop = peer.dispatchMessages()
|
|
|
|
messageProcessingLoop.callback = proc(p: pointer) {.gcsafe.} =
|
|
|
|
if messageProcessingLoop.failed:
|
|
|
|
debug "Ending dispatchMessages loop", peer,
|
|
|
|
err = messageProcessingLoop.error.msg
|
|
|
|
else:
|
|
|
|
debug "Ending dispatchMessages", peer,
|
|
|
|
exitCode = messageProcessingLoop.read
|
|
|
|
traceAsyncErrors peer.disconnect(ClientShutdown)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
# The handshake may involve multiple async steps, so we wait
|
|
|
|
# here for all of them to finish.
|
|
|
|
#
|
|
|
|
await all(subProtocolsHandshakes)
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
peer.connectionState = Connected
|
|
|
|
debug "Peer connection initialized", peer
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc initializeConnection*(peer: Peer) {.async.} =
|
|
|
|
let daemon = peer.network.daemon
|
|
|
|
try:
|
|
|
|
peer.connectionState = Connecting
|
|
|
|
peer.rpcStream = await daemon.openStream(peer.id, @[beaconChainProtocol])
|
|
|
|
await performProtocolHandshakes(peer)
|
|
|
|
except CatchableError:
|
|
|
|
await reraiseAsPeerDisconnected(peer, "Failed to perform handshake")
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc handleConnectingBeaconChainPeer(daemon: DaemonAPI, stream: P2PStream) {.async, gcsafe.} =
|
|
|
|
let peer = daemon.peerFromStream(stream)
|
|
|
|
peer.rpcStream = stream
|
|
|
|
peer.connectionState = Connecting
|
|
|
|
await performProtocolHandshakes(peer)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc resolvePendingFutures(peer: Peer, protocol: ProtocolInfo,
|
|
|
|
methodId: int, msg: pointer, reqFuture: FutureBase) =
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
let msgId = (protocolIdx: protocol.index, methodId: methodId)
|
2019-06-17 11:08:05 +00:00
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
if peer.awaitedMessages[msgId] != nil:
|
2019-06-17 11:08:05 +00:00
|
|
|
let msgInfo = protocol.messages[methodId]
|
2019-06-03 17:07:50 +00:00
|
|
|
msgInfo.nextMsgResolver(msg, peer.awaitedMessages[msgId])
|
|
|
|
peer.awaitedMessages[msgId] = nil
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
if reqFuture != nil and not reqFuture.finished:
|
|
|
|
protocol.messages[methodId].requestResolver(msg, reqFuture)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
proc initProtocol(name: string, version: int,
|
|
|
|
peerInit: PeerStateInitializer,
|
|
|
|
networkInit: NetworkStateInitializer): ProtocolInfoObj =
|
|
|
|
result.name = name
|
|
|
|
result.version = version
|
|
|
|
result.messages = @[]
|
|
|
|
result.peerStateInitializer = peerInit
|
|
|
|
result.networkStateInitializer = networkInit
|
|
|
|
|
|
|
|
proc registerMsg(protocol: ProtocolInfo,
|
|
|
|
id: int, name: string,
|
|
|
|
thunk: ThunkProc,
|
|
|
|
printer: MessageContentPrinter,
|
|
|
|
requestResolver: RequestResolver,
|
|
|
|
nextMsgResolver: NextMsgResolver) =
|
|
|
|
if protocol.messages.len <= id:
|
|
|
|
protocol.messages.setLen(id + 1)
|
|
|
|
protocol.messages[id] = MessageInfo(id: id,
|
|
|
|
name: name,
|
|
|
|
thunk: thunk,
|
|
|
|
printer: printer,
|
|
|
|
requestResolver: requestResolver,
|
|
|
|
nextMsgResolver: nextMsgResolver)
|
|
|
|
|
|
|
|
template applyDecorator(p: NimNode, decorator: NimNode) =
|
|
|
|
if decorator.kind != nnkNilLit: p.addPragma decorator
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
proc prepareRequest(peer: Peer,
|
|
|
|
protocol: ProtocolInfo,
|
|
|
|
requestMethodId, responseMethodId: uint16,
|
2019-05-31 18:36:32 +00:00
|
|
|
stream: OutputStreamVar,
|
2019-05-29 15:55:25 +00:00
|
|
|
timeout: Duration,
|
|
|
|
responseFuture: FutureBase): DelayedWriteCursor =
|
2019-06-17 11:08:05 +00:00
|
|
|
assert peer != nil and
|
|
|
|
protocol != nil and
|
|
|
|
responseFuture != nil and
|
|
|
|
responseMethodId.int < protocol.messages.len
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
doAssert timeout.milliseconds > 0
|
2019-05-29 15:55:25 +00:00
|
|
|
|
|
|
|
result = stream.delayFixedSizeWrite sizeof(SpecOuterMsgHeader)
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
inc peer.lastReqId, 2
|
|
|
|
let reqId = peer.lastReqId
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
stream.appendPackedObject SpecInnerMsgHeader(
|
2019-06-17 11:08:05 +00:00
|
|
|
reqId: reqId, methodId: requestMethodId)
|
|
|
|
|
|
|
|
template responseMsgInfo: auto =
|
|
|
|
protocol.messages[responseMethodId.int]
|
|
|
|
|
|
|
|
let
|
|
|
|
requestResolver = responseMsgInfo.requestResolver
|
|
|
|
timeoutAt = Moment.fromNow(timeout)
|
|
|
|
|
|
|
|
peer.outstandingRequests[reqId + 1] = OutstandingRequest(
|
|
|
|
id: reqId,
|
|
|
|
future: responseFuture,
|
|
|
|
timeoutAt: timeoutAt,
|
|
|
|
responseThunk: responseMsgInfo.thunk)
|
|
|
|
|
|
|
|
proc timeoutExpired(udata: pointer) =
|
|
|
|
requestResolver(nil, responseFuture)
|
|
|
|
peer.outstandingRequests.del(reqId + 1)
|
|
|
|
|
|
|
|
addTimer(timeoutAt, timeoutExpired, nil)
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
proc prepareResponse(responder: ResponderWithId,
|
|
|
|
stream: OutputStreamVar): DelayedWriteCursor =
|
|
|
|
result = stream.delayFixedSizeWrite sizeof(SpecOuterMsgHeader)
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
stream.appendPackedObject SpecInnerMsgHeader(
|
|
|
|
reqId: responder.reqId + 1,
|
|
|
|
methodId: uint16(Success))
|
|
|
|
|
|
|
|
proc prepareMsg(peer: Peer, methodId: uint16,
|
|
|
|
stream: OutputStreamVar): DelayedWriteCursor =
|
|
|
|
result = stream.delayFixedSizeWrite sizeof(SpecOuterMsgHeader)
|
|
|
|
|
|
|
|
inc peer.lastReqId, 2
|
|
|
|
stream.appendPackedObject SpecInnerMsgHeader(
|
|
|
|
reqId: peer.lastReqId, methodId: methodId)
|
|
|
|
|
|
|
|
proc finishOuterHeader(headerCursor: DelayedWriteCursor) =
|
|
|
|
var outerHeader = SpecOuterMsgHeader.init(
|
|
|
|
compression = NoCompression,
|
|
|
|
encoding = SszEncoding,
|
|
|
|
msgLen = uint64(headerCursor.totalBytesWrittenAfterCursor))
|
|
|
|
|
|
|
|
headerCursor.endWrite makeOpenArray(cast[ptr byte](addr outerHeader),
|
|
|
|
sizeof outerHeader)
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
proc implementSendProcBody(sendProc: SendProc) =
|
|
|
|
let
|
|
|
|
msg = sendProc.msg
|
|
|
|
delayedWriteCursor = ident "delayedWriteCursor"
|
2019-05-31 18:36:32 +00:00
|
|
|
peer = sendProc.peerParam
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
proc preSerializationStep(stream: NimNode): NimNode =
|
2019-05-31 18:36:32 +00:00
|
|
|
case msg.kind
|
|
|
|
of msgRequest:
|
2019-05-29 15:55:25 +00:00
|
|
|
let
|
|
|
|
requestMethodId = newLit(msg.id)
|
|
|
|
responseMethodId = newLit(msg.response.id)
|
|
|
|
protocol = sendProc.msg.protocol.protocolInfoVar
|
|
|
|
timeout = sendProc.timeoutParam
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
quote do:
|
|
|
|
var `delayedWriteCursor` = prepareRequest(
|
2019-05-30 18:57:12 +00:00
|
|
|
`peer`, `protocol`, `requestMethodId`, `responseMethodId`,
|
|
|
|
`stream`, `timeout`, `resultIdent`)
|
2019-06-17 11:08:05 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
of msgResponse:
|
2019-06-17 11:08:05 +00:00
|
|
|
quote do:
|
|
|
|
var `delayedWriteCursor` = prepareResponse(`peer`, `stream`)
|
|
|
|
|
|
|
|
of msgHandshake, msgNotification:
|
|
|
|
let methodId = newLit(msg.id)
|
|
|
|
quote do:
|
|
|
|
var `delayedWriteCursor` = prepareMsg(`peer`, `methodId`, `stream`)
|
|
|
|
|
|
|
|
proc postSerializationStep(stream: NimNode): NimNode =
|
|
|
|
newCall(bindSym "finishOuterHeader", delayedWriteCursor)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
proc sendCallGenerator(peer, bytes: NimNode): NimNode =
|
|
|
|
let
|
|
|
|
linkSendFailureToReqFuture = bindSym "linkSendFailureToReqFuture"
|
|
|
|
sendMsg = bindSym "sendMsg"
|
|
|
|
sendCall = newCall(sendMsg, peer, bytes)
|
|
|
|
|
|
|
|
if msg.kind == msgRequest:
|
|
|
|
# In RLPx requests, the returned future was allocated here and passed
|
2019-06-17 11:08:05 +00:00
|
|
|
# to `prepareRequest`. It's already assigned to the result variable
|
2019-05-29 08:21:03 +00:00
|
|
|
# of the proc, so we just wait for the sending operation to complete
|
|
|
|
# and we return in a normal way. (the waiting is done, so we can catch
|
|
|
|
# any possible errors).
|
|
|
|
quote: `linkSendFailureToReqFuture`(`sendCall`, `resultIdent`)
|
|
|
|
else:
|
|
|
|
# In normal RLPx messages, we are returning the future returned by the
|
|
|
|
# `sendMsg` call.
|
|
|
|
quote: return `sendCall`
|
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
sendProc.useStandardBody(
|
|
|
|
preSerializationStep,
|
|
|
|
postSerializationStep,
|
|
|
|
sendCallGenerator)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
proc p2pProtocolBackendImpl*(p: P2PProtocol): Backend =
|
|
|
|
let
|
|
|
|
Option = bindSym "Option"
|
|
|
|
Peer = bindSym "Peer"
|
|
|
|
EthereumNode = bindSym "EthereumNode"
|
2019-05-30 18:57:12 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
Format = ident "SSZ"
|
2019-05-29 08:21:03 +00:00
|
|
|
Response = bindSym "Response"
|
2019-05-30 18:57:12 +00:00
|
|
|
ResponderWithId = bindSym "ResponderWithId"
|
2019-06-17 11:08:05 +00:00
|
|
|
perProtocolMsgId = ident "perProtocolMsgId"
|
2019-05-29 08:21:03 +00:00
|
|
|
|
|
|
|
mount = bindSym "mount"
|
|
|
|
|
|
|
|
messagePrinter = bindSym "messagePrinter"
|
2019-06-03 17:07:50 +00:00
|
|
|
resolveFuture = bindSym "resolveFuture"
|
2019-05-29 08:21:03 +00:00
|
|
|
requestResolver = bindSym "requestResolver"
|
2019-06-03 17:07:50 +00:00
|
|
|
resolvePendingFutures = bindSym "resolvePendingFutures"
|
2019-05-29 08:21:03 +00:00
|
|
|
nextMsg = bindSym "nextMsg"
|
|
|
|
initProtocol = bindSym "initProtocol"
|
|
|
|
registerMsg = bindSym "registerMsg"
|
2019-05-30 18:57:12 +00:00
|
|
|
handshakeImpl = bindSym "handshakeImpl"
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-05-29 08:21:03 +00:00
|
|
|
stream = ident "stream"
|
|
|
|
protocol = ident "protocol"
|
2019-05-29 15:55:25 +00:00
|
|
|
response = ident "response"
|
2019-06-17 11:08:05 +00:00
|
|
|
reqFutureVar = ident "reqFuture"
|
2019-05-29 08:21:03 +00:00
|
|
|
msgContents = ident "msgContents"
|
|
|
|
receivedMsg = ident "receivedMsg"
|
|
|
|
|
|
|
|
ProtocolInfo = bindSym "ProtocolInfo"
|
|
|
|
P2PStream = bindSym "P2PStream"
|
|
|
|
ByteStreamVar = bindSym "ByteStreamVar"
|
|
|
|
|
|
|
|
new result
|
|
|
|
|
|
|
|
result.registerProtocol = bindSym "registerProtocol"
|
|
|
|
result.setEventHandlers = bindSym "setEventHandlers"
|
|
|
|
result.PeerType = Peer
|
|
|
|
result.NetworkType = EthereumNode
|
|
|
|
result.SerializationFormat = Format
|
|
|
|
|
2019-05-30 18:57:12 +00:00
|
|
|
p.useRequestIds = true
|
2019-06-05 02:00:07 +00:00
|
|
|
result.ReqIdType = ident "uint64"
|
2019-05-30 18:57:12 +00:00
|
|
|
result.ResponderType = ResponderWithId
|
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
result.afterProtocolInit = proc (p: P2PProtocol) =
|
|
|
|
p.onPeerConnected.params.add newIdentDefs(ident"handshakeStream", P2PStream)
|
|
|
|
|
2019-05-30 18:57:12 +00:00
|
|
|
result.implementMsg = proc (msg: Message) =
|
2019-05-29 08:21:03 +00:00
|
|
|
var
|
2019-05-29 15:55:25 +00:00
|
|
|
msgIdLit = newLit(msg.id)
|
2019-05-29 08:21:03 +00:00
|
|
|
msgRecName = msg.recIdent
|
2019-05-30 18:57:12 +00:00
|
|
|
msgIdent = msg.ident
|
2019-05-29 08:21:03 +00:00
|
|
|
msgName = $msgIdent
|
2019-05-30 18:57:12 +00:00
|
|
|
protocol = msg.protocol
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
##
|
|
|
|
## Implemenmt Thunk
|
|
|
|
##
|
2019-05-29 08:21:03 +00:00
|
|
|
let traceMsg = when tracingEnabled:
|
|
|
|
newCall(bindSym"logReceivedMsg", peer, receivedMsg)
|
|
|
|
else:
|
|
|
|
newStmtList()
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-17 11:08:05 +00:00
|
|
|
let callResolvePendingFutures = newCall(
|
|
|
|
resolvePendingFutures, peerVar,
|
|
|
|
protocol.protocolInfoVar,
|
|
|
|
msgIdLit,
|
|
|
|
newCall("addr", receivedMsg),
|
|
|
|
reqFutureVar)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-31 18:36:32 +00:00
|
|
|
var userHandlerParams = @[peerVar]
|
2019-05-30 18:57:12 +00:00
|
|
|
if msg.kind == msgRequest:
|
|
|
|
userHandlerParams.add reqIdVar
|
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
let
|
|
|
|
thunkName = ident(msgName & "_thunk")
|
2019-05-30 18:57:12 +00:00
|
|
|
awaitUserHandler = msg.genAwaitUserHandler(receivedMsg, userHandlerParams)
|
2019-05-29 15:55:25 +00:00
|
|
|
|
2019-06-05 02:00:07 +00:00
|
|
|
msg.defineThunk quote do:
|
2019-05-31 18:36:32 +00:00
|
|
|
proc `thunkName`(`peerVar`: `Peer`,
|
2019-05-29 08:21:03 +00:00
|
|
|
`stream`: `P2PStream`,
|
2019-05-30 18:57:12 +00:00
|
|
|
`reqIdVar`: uint64,
|
2019-06-17 11:08:05 +00:00
|
|
|
`reqFutureVar`: FutureBase,
|
2019-05-29 08:21:03 +00:00
|
|
|
`msgContents`: `ByteStreamVar`) {.async, gcsafe.} =
|
2019-05-30 18:57:12 +00:00
|
|
|
var `receivedMsg` = `mount`(`Format`, `msgContents`, `msgRecName`)
|
2019-05-29 08:21:03 +00:00
|
|
|
`traceMsg`
|
|
|
|
`awaitUserHandler`
|
2019-06-03 17:07:50 +00:00
|
|
|
`callResolvePendingFutures`
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
##
|
|
|
|
## Implement Senders and Handshake
|
|
|
|
##
|
2019-05-30 18:57:12 +00:00
|
|
|
var sendProc = msg.createSendProc(isRawSender = (msg.kind == msgHandshake))
|
|
|
|
implementSendProcBody sendProc
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
if msg.kind == msgHandshake:
|
2019-06-05 02:00:07 +00:00
|
|
|
discard msg.createHandshakeTemplate(sendProc.def.name, handshakeImpl, nextMsg)
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
protocol.outProcRegistrations.add(
|
2019-05-29 08:21:03 +00:00
|
|
|
newCall(registerMsg,
|
2019-05-29 15:55:25 +00:00
|
|
|
protocol.protocolInfoVar,
|
|
|
|
msgIdLit,
|
|
|
|
newLit(msgName),
|
2019-05-29 08:21:03 +00:00
|
|
|
thunkName,
|
|
|
|
newTree(nnkBracketExpr, messagePrinter, msgRecName),
|
|
|
|
newTree(nnkBracketExpr, requestResolver, msgRecName),
|
2019-06-03 17:07:50 +00:00
|
|
|
newTree(nnkBracketExpr, resolveFuture, msgRecName)))
|
2019-05-29 08:21:03 +00:00
|
|
|
|
2019-05-29 15:55:25 +00:00
|
|
|
result.implementProtocolInit = proc (protocol: P2PProtocol): NimNode =
|
2019-05-29 08:21:03 +00:00
|
|
|
return newCall(initProtocol,
|
2019-05-29 15:55:25 +00:00
|
|
|
newLit(protocol.shortName),
|
|
|
|
newLit(protocol.version),
|
|
|
|
protocol.peerInit, protocol.netInit)
|
2019-05-29 08:21:03 +00:00
|
|
|
|