2024-08-30 17:27:09 +00:00
|
|
|
# nim-eth
|
|
|
|
# Copyright (c) 2018-2024 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at
|
|
|
|
# https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at
|
|
|
|
# https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except
|
|
|
|
# according to those terms.
|
|
|
|
|
|
|
|
## This module defines a DSL for constructing communication message packet
|
|
|
|
## drivers to support the ones as defined with the Ethereum p2p protocols
|
|
|
|
## (see `devp2p <https://github.com/ethereum/devp2p/tree/master>`_.)
|
|
|
|
##
|
|
|
|
## Particular restictions apply to intrinsic message entities as message
|
|
|
|
## ID and request/response ID. Both must be unsigned. This is a consequence
|
|
|
|
## of message packets being serialised using RLP which is defined for
|
|
|
|
## non-negative scalar values only, see
|
|
|
|
## `Yellow Paper <https://ethereum.github.io/yellowpaper/paper.pdf#appendix.B>`_,
|
|
|
|
## Appx B, clauses (195) ff. and (199).)
|
|
|
|
|
|
|
|
|
2023-05-10 13:50:04 +00:00
|
|
|
{.push raises: [].}
|
2021-07-16 19:44:30 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
import
|
2024-01-22 09:47:46 +00:00
|
|
|
std/[options, sequtils, macrocache],
|
2024-08-30 17:27:09 +00:00
|
|
|
results,
|
2020-05-06 12:47:50 +00:00
|
|
|
stew/shims/macros, chronos, faststreams/outputs
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
MessageKind* = enum
|
|
|
|
msgHandshake
|
|
|
|
msgNotification
|
|
|
|
msgRequest
|
|
|
|
msgResponse
|
|
|
|
|
|
|
|
Message* = ref object
|
2024-08-30 17:27:09 +00:00
|
|
|
id*: Opt[uint]
|
2019-05-19 18:05:02 +00:00
|
|
|
ident*: NimNode
|
|
|
|
kind*: MessageKind
|
|
|
|
procDef*: NimNode
|
|
|
|
timeoutParam*: NimNode
|
2019-09-08 21:56:10 +00:00
|
|
|
recName*: NimNode
|
|
|
|
strongRecName*: NimNode
|
2019-05-19 18:05:02 +00:00
|
|
|
recBody*: NimNode
|
2019-05-29 08:16:59 +00:00
|
|
|
protocol*: P2PProtocol
|
2019-05-29 15:52:28 +00:00
|
|
|
response*: Message
|
2019-06-03 17:05:45 +00:00
|
|
|
userHandler*: NimNode
|
|
|
|
initResponderCall*: NimNode
|
2020-05-23 22:01:22 +00:00
|
|
|
outputParamDef*: NimNode
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
Request* = ref object
|
|
|
|
queries*: seq[Message]
|
|
|
|
response*: Message
|
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
SendProc* = object
|
2019-05-30 15:11:23 +00:00
|
|
|
## A `SendProc` is a proc used to send a single P2P message.
|
|
|
|
## If it's a Request, then the return type will be a Future
|
|
|
|
## of the respective Response type. All send procs also have
|
|
|
|
## an automatically inserted `timeout` parameter.
|
2019-05-29 15:52:28 +00:00
|
|
|
|
|
|
|
msg*: Message
|
|
|
|
## The message being implemented
|
|
|
|
|
|
|
|
def*: NimNode
|
|
|
|
## The definition of the proc
|
|
|
|
|
|
|
|
peerParam*: NimNode
|
|
|
|
## Cached ident for the peer param
|
|
|
|
|
|
|
|
msgParams*: seq[NimNode]
|
|
|
|
## Cached param ident for all values that must be written
|
|
|
|
## on the wire. The automatically inserted `timeout` is not
|
|
|
|
## included.
|
|
|
|
|
|
|
|
timeoutParam*: NimNode
|
|
|
|
## Cached ident for the timeout parameter
|
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
extraDefs*: NimNode
|
2022-11-16 16:44:00 +00:00
|
|
|
## The response procs have extra templates that must become
|
2019-06-05 01:59:35 +00:00
|
|
|
## part of the generated code
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
P2PProtocol* = ref object
|
|
|
|
# Settings
|
|
|
|
name*: string
|
|
|
|
version*: int
|
|
|
|
timeouts*: int64
|
|
|
|
useRequestIds*: bool
|
2019-10-23 10:36:22 +00:00
|
|
|
useSingleRecordInlining*: bool
|
2019-08-05 13:31:51 +00:00
|
|
|
rlpxName*: string
|
2019-05-19 18:05:02 +00:00
|
|
|
outgoingRequestDecorator*: NimNode
|
|
|
|
incomingRequestDecorator*: NimNode
|
|
|
|
incomingRequestThunkDecorator*: NimNode
|
|
|
|
incomingResponseDecorator*: NimNode
|
|
|
|
incomingResponseThunkDecorator*: NimNode
|
|
|
|
PeerStateType*: NimNode
|
|
|
|
NetworkStateType*: NimNode
|
|
|
|
backend*: Backend
|
|
|
|
|
|
|
|
# Cached properties
|
|
|
|
nameIdent*: NimNode
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolInfo*: NimNode
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
# All messages
|
|
|
|
messages*: seq[Message]
|
|
|
|
|
|
|
|
# Messages by type:
|
|
|
|
handshake*: Message
|
|
|
|
notifications*: seq[Message]
|
|
|
|
requests*: seq[Request]
|
|
|
|
|
|
|
|
# Output procs
|
|
|
|
outSendProcs*: NimNode
|
|
|
|
outRecvProcs*: NimNode
|
|
|
|
outProcRegistrations*: NimNode
|
|
|
|
|
|
|
|
# Event handlers
|
|
|
|
onPeerConnected*: NimNode
|
|
|
|
onPeerDisconnected*: NimNode
|
|
|
|
|
|
|
|
Backend* = ref object
|
|
|
|
# Code generators
|
2019-05-30 15:11:23 +00:00
|
|
|
implementMsg*: proc (msg: Message)
|
|
|
|
implementProtocolInit*: proc (protocol: P2PProtocol): NimNode
|
2019-06-03 17:05:45 +00:00
|
|
|
|
2019-05-30 15:11:23 +00:00
|
|
|
afterProtocolInit*: proc (protocol: P2PProtocol)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
# Bound symbols to the back-end run-time types and procs
|
|
|
|
PeerType*: NimNode
|
|
|
|
NetworkType*: NimNode
|
2019-05-29 08:16:59 +00:00
|
|
|
SerializationFormat*: NimNode
|
2019-05-30 15:11:23 +00:00
|
|
|
ResponderType*: NimNode
|
2020-05-12 22:36:29 +00:00
|
|
|
RequestResultsWrapper*: NimNode
|
2019-06-05 01:59:35 +00:00
|
|
|
ReqIdType*: NimNode
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
registerProtocol*: NimNode
|
|
|
|
setEventHandlers*: NimNode
|
|
|
|
|
|
|
|
BackendFactory* = proc (p: P2PProtocol): Backend
|
|
|
|
|
2019-05-29 08:16:59 +00:00
|
|
|
P2PBackendError* = object of CatchableError
|
|
|
|
InvalidMsgError* = object of P2PBackendError
|
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
const
|
|
|
|
defaultReqTimeout = 10.seconds
|
2019-06-05 01:59:35 +00:00
|
|
|
tracingEnabled = defined(p2pdump)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-30 15:11:23 +00:00
|
|
|
let
|
2019-05-31 18:35:57 +00:00
|
|
|
# Variable names affecting the public interface of the library:
|
2019-05-30 15:11:23 +00:00
|
|
|
reqIdVar* {.compileTime.} = ident "reqId"
|
|
|
|
# XXX: Binding the int type causes instantiation failure for some reason
|
2024-08-30 17:27:09 +00:00
|
|
|
ReqIdType* {.compileTime.} = ident "uint"
|
2019-05-30 15:11:23 +00:00
|
|
|
peerVar* {.compileTime.} = ident "peer"
|
|
|
|
responseVar* {.compileTime.} = ident "response"
|
2019-06-24 02:09:00 +00:00
|
|
|
streamVar* {.compileTime.} = ident "stream"
|
2020-05-23 22:01:22 +00:00
|
|
|
protocolVar* {.compileTime.} = ident "protocol"
|
2019-06-24 02:09:00 +00:00
|
|
|
deadlineVar* {.compileTime.} = ident "deadline"
|
2020-05-23 22:01:22 +00:00
|
|
|
timeoutVar* {.compileTime.} = ident "timeout"
|
2019-05-30 15:11:23 +00:00
|
|
|
perProtocolMsgIdVar* {.compileTime.} = ident "perProtocolMsgId"
|
|
|
|
currentProtocolSym* {.compileTime.} = ident "CurrentProtocol"
|
2019-05-31 18:35:57 +00:00
|
|
|
resultIdent* {.compileTime.} = ident "result"
|
|
|
|
|
|
|
|
# Locally used symbols:
|
|
|
|
Option {.compileTime.} = ident "Option"
|
|
|
|
Future {.compileTime.} = ident "Future"
|
|
|
|
Void {.compileTime.} = ident "void"
|
2020-03-18 18:22:32 +00:00
|
|
|
writeField {.compileTime.} = ident "writeField"
|
2019-05-31 18:35:57 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
PROTO {.compileTime.} = ident "PROTO"
|
|
|
|
MSG {.compileTime.} = ident "MSG"
|
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
const
|
|
|
|
protocolCounter = CacheCounter"protocolCounter"
|
|
|
|
|
2019-05-31 18:35:57 +00:00
|
|
|
template Fut(T): auto = newTree(nnkBracketExpr, Future, T)
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
proc initFuture*[T](loc: var Future[T]) =
|
|
|
|
loc = newFuture[T]()
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc isRlpx*(p: P2PProtocol): bool =
|
|
|
|
p.rlpxName.len > 0
|
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
template applyDecorator(p: NimNode, decorator: NimNode) =
|
|
|
|
if decorator.kind != nnkNilLit:
|
|
|
|
p.pragma.insert(0, decorator)
|
|
|
|
|
|
|
|
when tracingEnabled:
|
|
|
|
proc logSentMsgFields(peer: NimNode,
|
|
|
|
protocolInfo: NimNode,
|
|
|
|
msgName: string,
|
2020-05-23 22:01:22 +00:00
|
|
|
fields: openArray[NimNode]): NimNode =
|
2019-06-05 01:59:35 +00:00
|
|
|
## This generates the tracing code inserted in the message sending procs
|
|
|
|
## `fields` contains all the params that were serialized in the message
|
2020-03-18 18:22:32 +00:00
|
|
|
let
|
|
|
|
tracer = ident "tracer"
|
|
|
|
tracerStream = ident "tracerStream"
|
|
|
|
logMsgEventImpl = ident "logMsgEventImpl"
|
2019-06-05 01:59:35 +00:00
|
|
|
|
|
|
|
result = quote do:
|
2020-04-14 16:33:49 +00:00
|
|
|
var `tracerStream` = memoryOutput()
|
2020-03-18 18:22:32 +00:00
|
|
|
var `tracer` = JsonWriter.init(`tracerStream`)
|
2019-06-05 01:59:35 +00:00
|
|
|
beginRecord(`tracer`)
|
|
|
|
|
|
|
|
for f in fields:
|
2020-03-18 18:22:32 +00:00
|
|
|
result.add newCall(writeField, tracer, newLit($f), f)
|
2019-06-05 01:59:35 +00:00
|
|
|
|
|
|
|
result.add quote do:
|
|
|
|
endRecord(`tracer`)
|
2020-03-18 18:22:32 +00:00
|
|
|
`logMsgEventImpl`("outgoing_msg", `peer`,
|
|
|
|
`protocolInfo`, `msgName`,
|
|
|
|
getOutput(`tracerStream`, string))
|
2019-06-05 01:59:35 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
proc createPeerState[Peer, ProtocolState](peer: Peer): RootRef =
|
|
|
|
var res = new ProtocolState
|
|
|
|
mixin initProtocolState
|
|
|
|
initProtocolState(res, peer)
|
|
|
|
return cast[RootRef](res)
|
|
|
|
|
|
|
|
proc createNetworkState[NetworkNode, NetworkState](network: NetworkNode): RootRef {.gcsafe.} =
|
|
|
|
var res = new NetworkState
|
|
|
|
mixin initProtocolState
|
|
|
|
initProtocolState(res, network)
|
|
|
|
return cast[RootRef](res)
|
|
|
|
|
|
|
|
proc expectBlockWithProcs*(n: NimNode): seq[NimNode] =
|
|
|
|
template helperName: auto = $n[0]
|
|
|
|
|
|
|
|
if n.len != 2 or n[1].kind != nnkStmtList:
|
|
|
|
error(helperName & " expects a block", n)
|
|
|
|
|
|
|
|
for p in n[1]:
|
|
|
|
if p.kind == nnkProcDef:
|
|
|
|
result.add p
|
|
|
|
elif p.kind == nnkCommentStmt:
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
error(helperName & " expects a proc definition.", p)
|
|
|
|
|
|
|
|
proc nameOrNil*(procDef: NimNode): NimNode =
|
|
|
|
if procDef != nil:
|
|
|
|
procDef.name
|
|
|
|
else:
|
|
|
|
newNilLit()
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc isOutputParamName(paramName: NimNode): bool =
|
|
|
|
eqIdent(paramName, "output") or eqIdent(paramName, "response")
|
|
|
|
|
|
|
|
proc isOutputParam(param: NimNode): bool =
|
|
|
|
param.len > 0 and param[0].skipPragma.isOutputParamName
|
|
|
|
|
|
|
|
proc getOutputParam(procDef: NimNode): NimNode =
|
|
|
|
let params = procDef.params
|
|
|
|
for i in countdown(params.len - 1, 1):
|
|
|
|
let param = params[i]
|
|
|
|
if isOutputParam(param):
|
|
|
|
return param
|
|
|
|
|
|
|
|
proc outputParam*(msg: Message): NimNode =
|
|
|
|
case msg.kind
|
|
|
|
of msgRequest:
|
|
|
|
outputParam(msg.response)
|
|
|
|
of msgResponse:
|
|
|
|
msg.outputParamDef
|
|
|
|
else:
|
|
|
|
raiseAssert "Only requests (and the attached responses) can have output parameters"
|
|
|
|
|
|
|
|
proc outputParamIdent*(msg: Message): NimNode =
|
|
|
|
let outputParam = msg.outputParam
|
|
|
|
if outputParam != nil:
|
|
|
|
return outputParam[0].skipPragma
|
|
|
|
|
|
|
|
proc outputParamType*(msg: Message): NimNode =
|
|
|
|
let outputParam = msg.outputParam
|
|
|
|
if outputParam != nil:
|
|
|
|
return outputParam[1]
|
|
|
|
|
2020-10-11 14:56:40 +00:00
|
|
|
proc refreshParam(n: NimNode): NimNode =
|
|
|
|
result = copyNimTree(n)
|
|
|
|
if n.kind == nnkIdentDefs:
|
|
|
|
for i in 0..<n.len-2:
|
2022-11-16 16:44:00 +00:00
|
|
|
if n[i].kind == nnkSym:
|
2020-10-11 14:56:40 +00:00
|
|
|
result[i] = genSym(symKind(n[i]), $n[i])
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
iterator typedInputParams(procDef: NimNode, skip = 0): (NimNode, NimNode) =
|
|
|
|
for paramName, paramType in typedParams(procDef, skip):
|
|
|
|
if not isOutputParamName(paramName):
|
|
|
|
yield (paramName, paramType)
|
|
|
|
|
|
|
|
proc copyInputParams(params: NimNode): NimNode =
|
|
|
|
result = newTree(params.kind)
|
|
|
|
for param in params:
|
|
|
|
if not isOutputParam(param):
|
2020-10-11 14:56:40 +00:00
|
|
|
result.add param.refreshParam
|
2020-05-23 22:01:22 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
proc chooseFieldType(n: NimNode): NimNode =
|
|
|
|
## Examines the parameter types used in the message signature
|
|
|
|
## and selects the corresponding field type for use in the
|
|
|
|
## message object type (i.e. `p2p.hello`).
|
|
|
|
##
|
2021-12-20 12:14:50 +00:00
|
|
|
## For now, only openArray types are remapped to sequences.
|
2019-05-19 18:05:02 +00:00
|
|
|
result = n
|
2020-05-23 22:01:22 +00:00
|
|
|
if n.kind == nnkBracketExpr and eqIdent(n[0], "openArray"):
|
2019-05-19 18:05:02 +00:00
|
|
|
result = n.copyNimTree
|
|
|
|
result[0] = ident("seq")
|
|
|
|
|
|
|
|
proc verifyStateType(t: NimNode): NimNode =
|
|
|
|
result = t[1]
|
|
|
|
if result.kind == nnkSym and $result == "nil":
|
|
|
|
return nil
|
|
|
|
if result.kind != nnkBracketExpr or $result[0] != "ref":
|
|
|
|
error $result & " must be a ref type"
|
|
|
|
|
|
|
|
proc processProtocolBody*(p: P2PProtocol, protocolBody: NimNode)
|
|
|
|
|
|
|
|
proc init*(T: type P2PProtocol, backendFactory: BackendFactory,
|
|
|
|
name: string, version: int, body: NimNode,
|
2019-08-05 13:31:51 +00:00
|
|
|
timeouts: int64, useRequestIds: bool, rlpxName: string,
|
2019-05-19 18:05:02 +00:00
|
|
|
outgoingRequestDecorator: NimNode,
|
|
|
|
incomingRequestDecorator: NimNode,
|
|
|
|
incomingRequestThunkDecorator: NimNode,
|
|
|
|
incomingResponseDecorator: NimNode,
|
|
|
|
incomingResponseThunkDecorator: NimNode,
|
|
|
|
peerState, networkState: NimNode): P2PProtocol =
|
|
|
|
|
|
|
|
result = P2PProtocol(
|
|
|
|
name: name,
|
|
|
|
version: version,
|
|
|
|
timeouts: timeouts,
|
|
|
|
useRequestIds: useRequestIds,
|
2019-08-05 13:31:51 +00:00
|
|
|
rlpxName: rlpxName,
|
2019-05-19 18:05:02 +00:00
|
|
|
outgoingRequestDecorator: outgoingRequestDecorator,
|
|
|
|
incomingRequestDecorator: incomingRequestDecorator,
|
|
|
|
incomingRequestThunkDecorator: incomingRequestThunkDecorator,
|
|
|
|
incomingResponseDecorator: incomingResponseDecorator,
|
|
|
|
incomingResponseThunkDecorator: incomingResponseThunkDecorator,
|
|
|
|
PeerStateType: verifyStateType peerState,
|
|
|
|
NetworkStateType: verifyStateType networkState,
|
|
|
|
nameIdent: ident(name),
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolInfo: newCall(ident("protocolInfo"), ident(name)),
|
2019-05-19 18:05:02 +00:00
|
|
|
outSendProcs: newStmtList(),
|
|
|
|
outRecvProcs: newStmtList(),
|
|
|
|
outProcRegistrations: newStmtList())
|
|
|
|
|
|
|
|
result.backend = backendFactory(result)
|
2019-06-03 17:05:45 +00:00
|
|
|
assert(not result.backend.implementProtocolInit.isNil)
|
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
if result.backend.ReqIdType.isNil:
|
2024-08-30 17:27:09 +00:00
|
|
|
result.backend.ReqIdType = ident "uint"
|
2019-06-05 01:59:35 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
result.processProtocolBody body
|
|
|
|
|
|
|
|
if not result.backend.afterProtocolInit.isNil:
|
|
|
|
result.backend.afterProtocolInit(result)
|
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
proc augmentUserHandler(p: P2PProtocol, userHandlerProc: NimNode, msgId = Opt.none(uint)) =
|
2019-05-19 18:05:02 +00:00
|
|
|
## This procs adds a set of common helpers available in all messages handlers
|
|
|
|
## (e.g. `perProtocolMsgId`, `peer.state`, etc).
|
2019-05-30 15:11:23 +00:00
|
|
|
|
|
|
|
userHandlerProc.addPragma ident"gcsafe"
|
2020-05-23 22:01:22 +00:00
|
|
|
|
2024-02-19 07:16:33 +00:00
|
|
|
# we only take the pragma
|
|
|
|
let dummy = quote do:
|
|
|
|
proc dummy(): Future[void] {.async: (raises: [EthP2PError]).}
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
if p.isRlpx:
|
2024-02-19 07:16:33 +00:00
|
|
|
userHandlerProc.addPragma dummy.pragma[0]
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
var
|
|
|
|
getState = ident"getState"
|
|
|
|
getNetworkState = ident"getNetworkState"
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolInfo = p.protocolInfo
|
2019-05-19 18:05:02 +00:00
|
|
|
protocolNameIdent = p.nameIdent
|
|
|
|
PeerType = p.backend.PeerType
|
|
|
|
PeerStateType = p.PeerStateType
|
|
|
|
NetworkStateType = p.NetworkStateType
|
2019-05-30 15:11:23 +00:00
|
|
|
prelude = newStmtList()
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
userHandlerProc.body.insert 0, prelude
|
|
|
|
|
2021-12-20 12:14:50 +00:00
|
|
|
# We allow the user handler to use `openArray` params, but we turn
|
2019-05-19 18:05:02 +00:00
|
|
|
# those into sequences to make the `async` pragma happy.
|
|
|
|
for i in 1 ..< userHandlerProc.params.len:
|
|
|
|
var param = userHandlerProc.params[i]
|
|
|
|
param[^2] = chooseFieldType(param[^2])
|
|
|
|
|
|
|
|
prelude.add quote do:
|
2024-02-14 08:59:13 +00:00
|
|
|
type `currentProtocolSym` {.used.} = `protocolNameIdent`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
if msgId.isSome and p.isRlpx:
|
|
|
|
let msgId = msgId.value
|
2019-05-19 18:05:02 +00:00
|
|
|
prelude.add quote do:
|
2024-02-14 08:59:13 +00:00
|
|
|
const `perProtocolMsgIdVar` {.used.} = `msgId`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
# Define local accessors for the peer and the network protocol states
|
|
|
|
# inside each user message handler proc (e.g. peer.state.foo = bar)
|
|
|
|
if PeerStateType != nil:
|
|
|
|
prelude.add quote do:
|
2024-02-14 08:59:13 +00:00
|
|
|
template state(`peerVar`: `PeerType`): `PeerStateType` {.used.} =
|
2024-01-22 09:47:46 +00:00
|
|
|
`PeerStateType`(`getState`(`peerVar`, `protocolInfo`))
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
if NetworkStateType != nil:
|
|
|
|
prelude.add quote do:
|
2024-02-14 08:59:13 +00:00
|
|
|
template networkState(`peerVar`: `PeerType`): `NetworkStateType` {.used.} =
|
2024-01-22 09:47:46 +00:00
|
|
|
`NetworkStateType`(`getNetworkState`(`peerVar`.network, `protocolInfo`))
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2024-02-19 07:16:33 +00:00
|
|
|
proc addExceptionHandler(userHandlerProc: NimNode) =
|
|
|
|
let bodyTemp = userHandlerProc.body
|
|
|
|
userHandlerProc.body = quote do:
|
|
|
|
try:
|
|
|
|
`bodyTemp`
|
|
|
|
except CancelledError as exc:
|
|
|
|
raise newException(EthP2PError, exc.msg)
|
|
|
|
except CatchableError as exc:
|
|
|
|
raise newException(EthP2PError, exc.msg)
|
|
|
|
|
|
|
|
proc addPreludeDefs(userHandlerProc: NimNode, definitions: NimNode) =
|
2019-05-19 18:05:02 +00:00
|
|
|
userHandlerProc.body[0].add definitions
|
|
|
|
|
|
|
|
proc eventHandlerToProc(p: P2PProtocol, doBlock: NimNode, handlerName: string): NimNode =
|
|
|
|
## Turns a "named" do block to a regular async proc
|
|
|
|
## (e.g. onPeerConnected do ...)
|
|
|
|
result = newTree(nnkProcDef)
|
|
|
|
doBlock.copyChildrenTo(result)
|
|
|
|
result.name = ident(p.name & handlerName) # genSym(nskProc, p.name & handlerName)
|
|
|
|
p.augmentUserHandler result
|
2024-02-19 07:16:33 +00:00
|
|
|
result.addExceptionHandler()
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc addTimeoutParam(procDef: NimNode, defaultValue: int64) =
|
2019-05-19 18:05:02 +00:00
|
|
|
var
|
|
|
|
Duration = bindSym"Duration"
|
|
|
|
milliseconds = bindSym"milliseconds"
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
procDef.params.add newTree(nnkIdentDefs,
|
|
|
|
timeoutVar,
|
|
|
|
Duration,
|
|
|
|
newCall(milliseconds, newLit(defaultValue)))
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-30 15:11:23 +00:00
|
|
|
proc hasReqId*(msg: Message): bool =
|
|
|
|
msg.protocol.useRequestIds and msg.kind in {msgRequest, msgResponse}
|
|
|
|
|
2019-06-03 17:05:45 +00:00
|
|
|
proc ResponderType(msg: Message): NimNode =
|
|
|
|
var resp = if msg.kind == msgRequest: msg.response else: msg
|
|
|
|
newTree(nnkBracketExpr,
|
2019-09-09 02:36:37 +00:00
|
|
|
msg.protocol.backend.ResponderType, resp.strongRecName)
|
2019-06-03 17:05:45 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc needsSingleParamInlining(msg: Message): bool =
|
|
|
|
msg.recBody.kind == nnkDistinctTy
|
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
proc newMsg(protocol: P2PProtocol, kind: MessageKind, msgId: uint,
|
2020-05-23 22:01:22 +00:00
|
|
|
procDef: NimNode, response: Message = nil): Message =
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
if procDef[0].kind == nnkPostfix:
|
2022-11-16 16:44:00 +00:00
|
|
|
error("p2pProtocol procs are public by default. " &
|
2019-05-19 18:05:02 +00:00
|
|
|
"Please remove the postfix `*`.", procDef)
|
|
|
|
|
|
|
|
var
|
|
|
|
msgIdent = procDef.name
|
|
|
|
msgName = $msgIdent
|
|
|
|
recFields = newTree(nnkRecList)
|
|
|
|
recBody = newTree(nnkObjectTy, newEmptyNode(), newEmptyNode(), recFields)
|
2019-09-08 21:56:10 +00:00
|
|
|
strongRecName = ident(msgName & "Obj")
|
|
|
|
recName = strongRecName
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
for param, paramType in procDef.typedInputParams(skip = 1):
|
2019-05-19 18:05:02 +00:00
|
|
|
recFields.add newTree(nnkIdentDefs,
|
|
|
|
newTree(nnkPostfix, ident("*"), param), # The fields are public
|
2021-12-20 12:14:50 +00:00
|
|
|
chooseFieldType(paramType), # some types such as openArray
|
2019-09-08 21:56:10 +00:00
|
|
|
newEmptyNode()) # are automatically remapped
|
|
|
|
|
2019-10-23 10:36:22 +00:00
|
|
|
if recFields.len == 1 and protocol.useSingleRecordInlining:
|
2019-09-08 21:56:10 +00:00
|
|
|
# When we have a single parameter, it's treated as the transferred message
|
|
|
|
# type. `recName` will be resolved to the message type that's intended
|
|
|
|
# for serialization while `strongRecName` will be a distinct type over
|
|
|
|
# which overloads such as `msgId` can be defined. We must use a distinct
|
|
|
|
# type because otherwise Nim may see multiple overloads defined over the
|
|
|
|
# same request parameter type and this will be an ambiguity error.
|
|
|
|
recName = recFields[0][1]
|
|
|
|
recBody = newTree(nnkDistinctTy, recName)
|
|
|
|
|
|
|
|
result = Message(protocol: protocol,
|
2024-08-30 17:27:09 +00:00
|
|
|
id: Opt.some(msgId),
|
2019-09-08 21:56:10 +00:00
|
|
|
ident: msgIdent,
|
|
|
|
kind: kind,
|
|
|
|
procDef: procDef,
|
|
|
|
recName: recName,
|
|
|
|
strongRecName: strongRecName,
|
|
|
|
recBody: recBody,
|
|
|
|
response: response)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
if procDef.body.kind != nnkEmpty:
|
2019-05-30 15:11:23 +00:00
|
|
|
var userHandler = copy procDef
|
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
protocol.augmentUserHandler userHandler, Opt.some(msgId)
|
2020-05-23 22:01:22 +00:00
|
|
|
userHandler.name = ident(msgName & "UserHandler")
|
2019-05-30 15:11:23 +00:00
|
|
|
|
|
|
|
# Request and Response handlers get an extra `reqId` parameter if the
|
|
|
|
# protocol uses them:
|
|
|
|
if result.hasReqId:
|
2019-06-05 01:59:35 +00:00
|
|
|
userHandler.params.insert(2, newIdentDefs(reqIdVar, protocol.backend.ReqIdType))
|
2019-05-30 15:11:23 +00:00
|
|
|
|
|
|
|
# All request handlers get an automatically inserter `response` variable:
|
2020-05-23 22:01:22 +00:00
|
|
|
if kind == msgRequest and protocol.isRlpx:
|
2019-05-30 15:11:23 +00:00
|
|
|
assert response != nil
|
|
|
|
let
|
|
|
|
peerParam = userHandler.params[1][0]
|
2019-06-03 17:05:45 +00:00
|
|
|
ResponderType = result.ResponderType
|
|
|
|
initResponderCall = newCall(ident"init", ResponderType, peerParam)
|
2019-05-30 15:11:23 +00:00
|
|
|
|
|
|
|
if protocol.useRequestIds:
|
2019-06-03 17:05:45 +00:00
|
|
|
initResponderCall.add reqIdVar
|
|
|
|
|
2024-02-19 07:16:33 +00:00
|
|
|
userHandler.addPreludeDefs quote do:
|
|
|
|
var `responseVar` {.used.} = `initResponderCall`
|
2019-06-03 17:05:45 +00:00
|
|
|
|
|
|
|
result.initResponderCall = initResponderCall
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
case kind
|
|
|
|
of msgRequest: userHandler.applyDecorator protocol.incomingRequestDecorator
|
|
|
|
of msgResponse: userHandler.applyDecorator protocol.incomingResponseDecorator
|
|
|
|
else: discard
|
|
|
|
|
2024-02-19 07:16:33 +00:00
|
|
|
userHandler.addExceptionHandler()
|
2019-05-30 15:11:23 +00:00
|
|
|
result.userHandler = userHandler
|
2019-06-05 01:59:35 +00:00
|
|
|
protocol.outRecvProcs.add result.userHandler
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
protocol.messages.add result
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc isVoid(t: NimNode): bool =
|
|
|
|
t.kind == nnkEmpty or eqIdent(t, "void")
|
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
proc addMsg(p: P2PProtocol, msgId: uint, procDef: NimNode) =
|
2020-05-23 22:01:22 +00:00
|
|
|
var
|
|
|
|
returnType = procDef.params[0]
|
|
|
|
hasReturnValue = not isVoid(returnType)
|
|
|
|
outputParam = procDef.getOutputParam()
|
|
|
|
|
|
|
|
if outputParam != nil:
|
|
|
|
if hasReturnValue:
|
|
|
|
error "A request proc should either use a return value or an output parameter"
|
|
|
|
returnType = outputParam[1]
|
|
|
|
hasReturnValue = true
|
|
|
|
|
|
|
|
if hasReturnValue:
|
|
|
|
let
|
|
|
|
responseIdent = ident($procDef.name & "Response")
|
|
|
|
response = Message(protocol: p,
|
2024-08-30 17:27:09 +00:00
|
|
|
id: Opt.none(uint),
|
2020-05-23 22:01:22 +00:00
|
|
|
ident: responseIdent,
|
|
|
|
kind: msgResponse,
|
|
|
|
recName: returnType,
|
|
|
|
strongRecName: returnType,
|
|
|
|
recBody: returnType,
|
|
|
|
outputParamDef: outputParam)
|
|
|
|
|
|
|
|
p.messages.add response
|
2024-08-30 17:27:09 +00:00
|
|
|
let msg = p.newMsg(msgRequest, msgId, procDef, response = response)
|
2020-05-23 22:01:22 +00:00
|
|
|
p.requests.add Request(queries: @[msg], response: response)
|
|
|
|
else:
|
2024-08-30 17:27:09 +00:00
|
|
|
p.notifications.add p.newMsg(msgNotification, msgId, procDef)
|
2020-05-23 22:01:22 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
proc identWithExportMarker*(msg: Message): NimNode =
|
|
|
|
newTree(nnkPostfix, ident("*"), msg.ident)
|
|
|
|
|
2020-05-12 22:36:29 +00:00
|
|
|
proc requestResultType*(msg: Message): NimNode =
|
|
|
|
let
|
|
|
|
protocol = msg.protocol
|
|
|
|
backend = protocol.backend
|
|
|
|
responseRec = msg.response.recName
|
|
|
|
|
|
|
|
var wrapperType = backend.RequestResultsWrapper
|
|
|
|
if wrapperType != nil:
|
|
|
|
if eqIdent(wrapperType, "void"):
|
|
|
|
return responseRec
|
|
|
|
else:
|
|
|
|
return newTree(nnkBracketExpr, wrapperType, responseRec)
|
|
|
|
else:
|
|
|
|
return newTree(nnkBracketExpr, Option, responseRec)
|
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
proc createSendProc*(msg: Message,
|
|
|
|
procType = nnkProcDef,
|
2019-06-24 02:09:00 +00:00
|
|
|
isRawSender = false,
|
|
|
|
nameSuffix = ""): SendProc =
|
2019-05-19 18:05:02 +00:00
|
|
|
# TODO: file an issue:
|
|
|
|
# macros.newProc and macros.params doesn't work with nnkMacroDef
|
|
|
|
|
2019-05-29 08:16:59 +00:00
|
|
|
let
|
2019-06-24 02:09:00 +00:00
|
|
|
nameSuffix = if nameSuffix.len == 0: (if isRawSender: "RawSender" else: "")
|
|
|
|
else: nameSuffix
|
|
|
|
|
|
|
|
name = if nameSuffix.len == 0: msg.identWithExportMarker
|
|
|
|
else: ident($msg.ident & nameSuffix)
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2019-05-29 08:16:59 +00:00
|
|
|
pragmas = if procType == nnkProcDef: newTree(nnkPragma, ident"gcsafe")
|
|
|
|
else: newEmptyNode()
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
var def = newNimNode(procType).add(
|
|
|
|
name,
|
2019-05-19 18:05:02 +00:00
|
|
|
newEmptyNode(),
|
|
|
|
newEmptyNode(),
|
2020-05-23 22:01:22 +00:00
|
|
|
copyInputParams msg.procDef.params,
|
2019-05-19 18:05:02 +00:00
|
|
|
pragmas,
|
|
|
|
newEmptyNode(),
|
|
|
|
newStmtList()) ## body
|
|
|
|
|
2021-12-20 12:14:50 +00:00
|
|
|
if procType == nnkProcDef:
|
2019-06-05 01:59:35 +00:00
|
|
|
for p in msg.procDef.pragma:
|
2020-05-23 22:01:22 +00:00
|
|
|
if not eqIdent(p, "async"):
|
|
|
|
def.addPragma p
|
2019-06-05 01:59:35 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
result.msg = msg
|
|
|
|
result.def = def
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
for param, paramType in def.typedInputParams():
|
2019-05-29 15:52:28 +00:00
|
|
|
if result.peerParam.isNil:
|
|
|
|
result.peerParam = param
|
2019-05-29 08:16:59 +00:00
|
|
|
else:
|
2019-05-29 15:52:28 +00:00
|
|
|
result.msgParams.add param
|
|
|
|
|
|
|
|
case msg.kind
|
|
|
|
of msgHandshake, msgRequest:
|
|
|
|
# Add a timeout parameter for all request procs
|
2020-05-23 22:01:22 +00:00
|
|
|
def.addTimeoutParam(msg.protocol.timeouts)
|
2019-05-29 15:52:28 +00:00
|
|
|
|
|
|
|
of msgResponse:
|
2020-05-23 22:01:22 +00:00
|
|
|
if msg.ResponderType != nil:
|
|
|
|
# A response proc must be called with a response object that originates
|
|
|
|
# from a certain request. Here we change the Peer parameter at position
|
|
|
|
# 1 to the correct strongly-typed ResponderType. The incoming procs still
|
2022-11-16 16:44:00 +00:00
|
|
|
# gets the normal Peer parameter.
|
2020-05-23 22:01:22 +00:00
|
|
|
let
|
|
|
|
ResponderType = msg.ResponderType
|
|
|
|
sendProcName = msg.ident
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
def[3][1][1] = ResponderType
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
# We create a helper that enables the `response.send()` syntax
|
|
|
|
# inside the user handler of the request proc:
|
|
|
|
result.extraDefs = quote do:
|
|
|
|
template send*(r: `ResponderType`, args: varargs[untyped]): auto =
|
|
|
|
`sendProcName`(r, args)
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
of msgNotification:
|
|
|
|
discard
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
def[3][0] = if procType == nnkMacroDef:
|
|
|
|
ident "untyped"
|
|
|
|
elif msg.kind == msgRequest and not isRawSender:
|
2020-05-12 22:36:29 +00:00
|
|
|
Fut(msg.requestResultType)
|
2019-05-29 15:52:28 +00:00
|
|
|
elif msg.kind == msgHandshake and not isRawSender:
|
2019-09-08 21:56:10 +00:00
|
|
|
Fut(msg.recName)
|
2019-05-29 15:52:28 +00:00
|
|
|
else:
|
2019-05-31 18:35:57 +00:00
|
|
|
Fut(Void)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
proc setBody*(sendProc: SendProc, body: NimNode) =
|
|
|
|
var
|
|
|
|
msg = sendProc.msg
|
|
|
|
protocol = msg.protocol
|
|
|
|
def = sendProc.def
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
# TODO: macros.body triggers an assertion error when the proc type is nnkMacroDef
|
|
|
|
def[6] = body
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
if msg.kind == msgRequest:
|
|
|
|
def.applyDecorator protocol.outgoingRequestDecorator
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
msg.protocol.outSendProcs.add def
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
if sendProc.extraDefs != nil:
|
|
|
|
msg.protocol.outSendProcs.add sendProc.extraDefs
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc writeParamsAsRecord*(params: openArray[NimNode],
|
2019-06-24 02:09:00 +00:00
|
|
|
outputStream, Format, RecordType: NimNode): NimNode =
|
2020-04-15 02:33:52 +00:00
|
|
|
if params.len == 0:
|
|
|
|
return newStmtList()
|
|
|
|
|
2019-06-24 02:09:00 +00:00
|
|
|
var
|
|
|
|
appendParams = newStmtList()
|
2019-08-05 13:31:51 +00:00
|
|
|
recordWriterCtx = ident "recordWriterCtx"
|
2019-06-24 02:09:00 +00:00
|
|
|
writer = ident "writer"
|
|
|
|
|
|
|
|
for param in params:
|
2019-08-05 13:31:51 +00:00
|
|
|
appendParams.add newCall(writeField,
|
|
|
|
writer, recordWriterCtx,
|
|
|
|
newLit($param), param)
|
2019-06-24 02:09:00 +00:00
|
|
|
|
2019-10-23 10:36:22 +00:00
|
|
|
# TODO: this doesn't respect the `useSingleRecordInlining` option.
|
2019-10-23 10:01:53 +00:00
|
|
|
# Right now, it's not a problem because it's used only in the libp2p back-end
|
2019-09-08 21:56:10 +00:00
|
|
|
if params.len > 1:
|
|
|
|
result = quote do:
|
|
|
|
mixin init, writerType, beginRecord, endRecord
|
|
|
|
|
|
|
|
var `writer` = init(WriterType(`Format`), `outputStream`)
|
|
|
|
var `recordWriterCtx` = beginRecord(`writer`, `RecordType`)
|
|
|
|
`appendParams`
|
|
|
|
endRecord(`writer`, `recordWriterCtx`)
|
|
|
|
else:
|
|
|
|
let param = params[0]
|
2019-06-24 02:09:00 +00:00
|
|
|
|
2019-09-08 21:56:10 +00:00
|
|
|
result = quote do:
|
|
|
|
var `writer` = init(WriterType(`Format`), `outputStream`)
|
|
|
|
writeValue(`writer`, `param`)
|
2019-06-24 02:09:00 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
proc useStandardBody*(sendProc: SendProc,
|
2019-06-17 11:19:13 +00:00
|
|
|
preSerializationStep: proc(stream: NimNode): NimNode,
|
|
|
|
postSerializationStep: proc(stream: NimNode): NimNode,
|
2019-06-05 01:59:35 +00:00
|
|
|
sendCallGenerator: proc (peer, bytes: NimNode): NimNode) =
|
2019-05-29 08:16:59 +00:00
|
|
|
let
|
2019-05-29 15:52:28 +00:00
|
|
|
msg = sendProc.msg
|
2019-05-29 08:16:59 +00:00
|
|
|
msgBytes = ident "msgBytes"
|
2019-05-29 15:52:28 +00:00
|
|
|
recipient = sendProc.peerParam
|
2020-05-23 22:01:22 +00:00
|
|
|
sendCall = sendCallGenerator(recipient, msgBytes)
|
|
|
|
|
|
|
|
if sendProc.msgParams.len == 0:
|
|
|
|
sendProc.setBody quote do:
|
|
|
|
var `msgBytes`: seq[byte]
|
|
|
|
`sendCall`
|
|
|
|
return
|
|
|
|
|
|
|
|
let
|
|
|
|
outputStream = ident "outputStream"
|
|
|
|
|
2019-09-08 21:56:10 +00:00
|
|
|
msgRecName = msg.recName
|
2019-05-29 08:16:59 +00:00
|
|
|
Format = msg.protocol.backend.SerializationFormat
|
|
|
|
|
2019-06-17 11:19:13 +00:00
|
|
|
preSerialization = if preSerializationStep.isNil: newStmtList()
|
|
|
|
else: preSerializationStep(outputStream)
|
|
|
|
|
2022-11-16 16:44:00 +00:00
|
|
|
serialization = writeParamsAsRecord(sendProc.msgParams,
|
2019-06-24 02:09:00 +00:00
|
|
|
outputStream, Format, msgRecName)
|
|
|
|
|
2019-06-17 11:19:13 +00:00
|
|
|
postSerialization = if postSerializationStep.isNil: newStmtList()
|
|
|
|
else: postSerializationStep(outputStream)
|
|
|
|
|
2020-03-18 18:22:32 +00:00
|
|
|
tracing = when not tracingEnabled:
|
|
|
|
newStmtList()
|
|
|
|
else:
|
|
|
|
logSentMsgFields(recipient,
|
2024-01-22 09:47:46 +00:00
|
|
|
msg.protocol.protocolInfo,
|
2020-03-18 18:22:32 +00:00
|
|
|
$msg.ident,
|
|
|
|
sendProc.msgParams)
|
2019-05-29 08:16:59 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
sendProc.setBody quote do:
|
2019-05-29 08:16:59 +00:00
|
|
|
mixin init, WriterType, beginRecord, endRecord, getOutput
|
|
|
|
|
2020-04-14 16:33:49 +00:00
|
|
|
var `outputStream` = memoryOutput()
|
2019-06-17 11:19:13 +00:00
|
|
|
`preSerialization`
|
2022-11-16 16:44:00 +00:00
|
|
|
`serialization`
|
2019-06-17 11:19:13 +00:00
|
|
|
`postSerialization`
|
2019-06-24 02:09:00 +00:00
|
|
|
`tracing`
|
2019-05-29 08:16:59 +00:00
|
|
|
let `msgBytes` = getOutput(`outputStream`)
|
|
|
|
`sendCall`
|
|
|
|
|
2019-06-24 02:09:00 +00:00
|
|
|
proc correctSerializerProcParams(params: NimNode) =
|
|
|
|
# A serializer proc is just like a send proc, but:
|
|
|
|
# 1. it has a void return type
|
|
|
|
params[0] = ident "void"
|
|
|
|
# 2. The peer params is replaced with OutputStream
|
2020-04-14 16:33:49 +00:00
|
|
|
params[1] = newIdentDefs(streamVar, bindSym "OutputStream")
|
2019-06-24 02:09:00 +00:00
|
|
|
# 3. The timeout param is removed
|
|
|
|
params.del(params.len - 1)
|
|
|
|
|
|
|
|
proc createSerializer*(msg: Message, procType = nnkProcDef): NimNode =
|
|
|
|
var serializer = msg.createSendProc(procType, nameSuffix = "Serializer")
|
|
|
|
correctSerializerProcParams serializer.def.params
|
|
|
|
|
|
|
|
serializer.setBody writeParamsAsRecord(
|
|
|
|
serializer.msgParams,
|
|
|
|
streamVar,
|
|
|
|
msg.protocol.backend.SerializationFormat,
|
2019-09-08 21:56:10 +00:00
|
|
|
msg.recName)
|
2019-06-24 02:09:00 +00:00
|
|
|
|
|
|
|
return serializer.def
|
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
proc defineThunk*(msg: Message, thunk: NimNode) =
|
|
|
|
let protocol = msg.protocol
|
|
|
|
|
|
|
|
case msg.kind
|
|
|
|
of msgRequest: thunk.applyDecorator protocol.incomingRequestThunkDecorator
|
|
|
|
of msgResponse: thunk.applyDecorator protocol.incomingResponseThunkDecorator
|
|
|
|
else: discard
|
|
|
|
|
|
|
|
protocol.outRecvProcs.add thunk
|
|
|
|
|
2019-12-09 14:18:22 +00:00
|
|
|
proc genUserHandlerCall*(msg: Message, receivedMsg: NimNode,
|
2020-05-23 22:01:22 +00:00
|
|
|
leadingParams: openArray[NimNode],
|
|
|
|
outputParam: NimNode = nil): NimNode =
|
2019-05-29 15:52:28 +00:00
|
|
|
if msg.userHandler == nil:
|
|
|
|
return newStmtList()
|
|
|
|
|
2019-12-09 14:18:22 +00:00
|
|
|
result = newCall(msg.userHandler.name, leadingParams)
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
if msg.needsSingleParamInlining:
|
2019-12-09 14:18:22 +00:00
|
|
|
result.add receivedMsg
|
2019-10-23 10:01:53 +00:00
|
|
|
else:
|
2020-05-23 22:01:22 +00:00
|
|
|
var params = toSeq(msg.procDef.typedInputParams(skip = 1))
|
2019-09-08 21:56:10 +00:00
|
|
|
for p in params:
|
2019-12-09 14:18:22 +00:00
|
|
|
result.add newDotExpr(receivedMsg, p[0])
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
if outputParam != nil:
|
|
|
|
result.add outputParam
|
|
|
|
|
2019-12-09 14:18:22 +00:00
|
|
|
proc genAwaitUserHandler*(msg: Message, receivedMsg: NimNode,
|
2020-05-23 22:01:22 +00:00
|
|
|
leadingParams: openArray[NimNode],
|
|
|
|
outputParam: NimNode = nil): NimNode =
|
|
|
|
result = msg.genUserHandlerCall(receivedMsg, leadingParams, outputParam)
|
2019-12-09 21:14:11 +00:00
|
|
|
if result.len > 0: result = newCall("await", result)
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc appendAllInputParams*(node: NimNode, procDef: NimNode): NimNode =
|
2019-05-19 18:05:02 +00:00
|
|
|
result = node
|
2020-05-23 22:01:22 +00:00
|
|
|
for p, _ in procDef.typedInputParams():
|
2019-05-19 18:05:02 +00:00
|
|
|
result.add p
|
|
|
|
|
2019-06-24 02:09:00 +00:00
|
|
|
proc paramNames*(procDef: NimNode, skipFirst = 0): seq[NimNode] =
|
|
|
|
result = newSeq[NimNode]()
|
|
|
|
for name, _ in procDef.typedParams(skip = skipFirst):
|
|
|
|
result.add name
|
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
proc netInit*(p: P2PProtocol): NimNode =
|
|
|
|
if p.NetworkStateType == nil:
|
|
|
|
newNilLit()
|
|
|
|
else:
|
|
|
|
newTree(nnkBracketExpr, bindSym"createNetworkState",
|
|
|
|
p.backend.NetworkType,
|
|
|
|
p.NetworkStateType)
|
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
proc createHandshakeTemplate*(msg: Message,
|
|
|
|
rawSendProc, handshakeImpl,
|
|
|
|
nextMsg: NimNode): SendProc =
|
2019-05-30 15:11:23 +00:00
|
|
|
let
|
|
|
|
handshakeExchanger = msg.createSendProc(procType = nnkTemplateDef)
|
2020-05-23 22:01:22 +00:00
|
|
|
forwardCall = newCall(rawSendProc).appendAllInputParams(handshakeExchanger.def)
|
2019-05-30 15:11:23 +00:00
|
|
|
peerValue = forwardCall[1]
|
2019-09-08 21:56:10 +00:00
|
|
|
msgRecName = msg.recName
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
forwardCall[1] = peerVar
|
2019-05-30 15:11:23 +00:00
|
|
|
forwardCall.del(forwardCall.len - 1)
|
|
|
|
|
2020-10-11 14:56:40 +00:00
|
|
|
let peerVar = genSym(nskLet ,"peer")
|
2019-06-05 01:59:35 +00:00
|
|
|
handshakeExchanger.setBody quote do:
|
2024-02-19 07:16:33 +00:00
|
|
|
try:
|
|
|
|
let `peerVar` = `peerValue`
|
|
|
|
let sendingFuture = `forwardCall`
|
|
|
|
`handshakeImpl`(`peerVar`,
|
|
|
|
sendingFuture,
|
|
|
|
`nextMsg`(`peerVar`, `msgRecName`),
|
|
|
|
`timeoutVar`)
|
|
|
|
except PeerDisconnected as exc:
|
|
|
|
raise newException(EthP2PError, exc.msg)
|
|
|
|
except P2PInternalError as exc:
|
|
|
|
raise newException(EthP2PError, exc.msg)
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2019-06-05 01:59:35 +00:00
|
|
|
return handshakeExchanger
|
2019-05-30 15:11:23 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
proc peerInit*(p: P2PProtocol): NimNode =
|
|
|
|
if p.PeerStateType == nil:
|
|
|
|
newNilLit()
|
|
|
|
else:
|
|
|
|
newTree(nnkBracketExpr, bindSym"createPeerState",
|
|
|
|
p.backend.PeerType,
|
|
|
|
p.PeerStateType)
|
|
|
|
|
|
|
|
proc processProtocolBody*(p: P2PProtocol, protocolBody: NimNode) =
|
|
|
|
## This procs handles all DSL statements valid inside a p2pProtocol.
|
|
|
|
##
|
|
|
|
## It will populate the protocol's fields such as:
|
|
|
|
## * handshake
|
|
|
|
## * requests
|
|
|
|
## * notifications
|
|
|
|
## * onPeerConnected
|
|
|
|
## * onPeerDisconnected
|
|
|
|
##
|
|
|
|
## All messages will have properly computed numeric IDs
|
|
|
|
##
|
2024-08-30 17:27:09 +00:00
|
|
|
var nextId = 0u
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
for n in protocolBody:
|
|
|
|
case n.kind
|
|
|
|
of {nnkCall, nnkCommand}:
|
|
|
|
if eqIdent(n[0], "nextID"):
|
|
|
|
# By default message IDs are assigned in increasing order
|
|
|
|
# `nextID` can be used to skip some of the numeric slots
|
|
|
|
if n.len == 2 and n[1].kind == nnkIntLit:
|
2024-08-30 17:27:09 +00:00
|
|
|
nextId = n[1].intVal.uint
|
2019-05-19 18:05:02 +00:00
|
|
|
else:
|
|
|
|
error("nextID expects a single int value", n)
|
|
|
|
|
|
|
|
elif eqIdent(n[0], "requestResponse"):
|
|
|
|
# `requestResponse` can be given a block of 2 or more procs.
|
|
|
|
# The last one is considered to be a response message, while
|
2022-11-16 16:44:00 +00:00
|
|
|
# all preceding ones are requests triggering the response.
|
2019-05-19 18:05:02 +00:00
|
|
|
# The system makes sure to automatically insert a hidden `reqId`
|
|
|
|
# parameter used to discriminate the individual messages.
|
|
|
|
let procs = expectBlockWithProcs(n)
|
|
|
|
if procs.len < 2:
|
|
|
|
error "requestResponse expects a block with at least two proc definitions"
|
|
|
|
|
|
|
|
var queries = newSeq[Message]()
|
2024-08-30 17:27:09 +00:00
|
|
|
let responseMsg = p.newMsg(msgResponse, nextId + procs.len.uint - 1, procs[^1])
|
2019-05-29 15:52:28 +00:00
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
for i in 0 .. procs.len - 2:
|
2024-08-30 17:27:09 +00:00
|
|
|
queries.add p.newMsg(msgRequest, nextId + i.uint, procs[i], response = responseMsg)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2019-05-29 15:52:28 +00:00
|
|
|
p.requests.add Request(queries: queries, response: responseMsg)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
inc nextId, procs.len
|
|
|
|
|
|
|
|
elif eqIdent(n[0], "handshake"):
|
|
|
|
let procs = expectBlockWithProcs(n)
|
|
|
|
if procs.len != 1:
|
|
|
|
error "handshake expects a block with a single proc definition", n
|
|
|
|
|
|
|
|
if p.handshake != nil:
|
|
|
|
error "The handshake for the protocol is already defined", n
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
p.handshake = p.newMsg(msgHandshake, nextId, procs[0])
|
2019-05-19 18:05:02 +00:00
|
|
|
inc nextId
|
|
|
|
|
|
|
|
elif eqIdent(n[0], "onPeerConnected"):
|
|
|
|
p.onPeerConnected = p.eventHandlerToProc(n[1], "PeerConnected")
|
|
|
|
|
|
|
|
elif eqIdent(n[0], "onPeerDisconnected"):
|
|
|
|
p.onPeerDisconnected = p.eventHandlerToProc(n[1], "PeerDisconnected")
|
|
|
|
|
|
|
|
else:
|
|
|
|
error(repr(n) & " is not a recognized call in P2P protocol definitions", n)
|
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
of nnkProcDef, nnkIteratorDef:
|
|
|
|
p.addMsg(nextId, n)
|
2019-05-19 18:05:02 +00:00
|
|
|
inc nextId
|
|
|
|
|
|
|
|
of nnkCommentStmt:
|
|
|
|
discard
|
|
|
|
|
|
|
|
else:
|
|
|
|
error "Illegal syntax in a P2P protocol definition", n
|
|
|
|
|
|
|
|
proc genTypeSection*(p: P2PProtocol): NimNode =
|
|
|
|
var
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolIdx = protocolCounter.value
|
2019-05-19 18:05:02 +00:00
|
|
|
protocolName = p.nameIdent
|
|
|
|
peerState = p.PeerStateType
|
|
|
|
networkState= p.NetworkStateType
|
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolCounter.inc
|
2019-05-19 18:05:02 +00:00
|
|
|
result = newStmtList()
|
|
|
|
result.add quote do:
|
|
|
|
# Create a type acting as a pseudo-object representing the protocol
|
|
|
|
# (e.g. p2p)
|
|
|
|
type `protocolName`* = object
|
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
# The protocol run-time index is available as a pseudo-field
|
|
|
|
# (e.g. `p2p.index`)
|
|
|
|
template index*(`PROTO`: type `protocolName`): auto = `protocolIdx`
|
|
|
|
template protocolInfo*(`PROTO`: type `protocolName`): auto =
|
|
|
|
getProtocol(`protocolIdx`)
|
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
if peerState != nil:
|
|
|
|
result.add quote do:
|
2020-05-23 22:01:22 +00:00
|
|
|
template State*(`PROTO`: type `protocolName`): type = `peerState`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
if networkState != nil:
|
|
|
|
result.add quote do:
|
2020-05-23 22:01:22 +00:00
|
|
|
template NetworkState*(`PROTO`: type `protocolName`): type = `networkState`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
for msg in p.messages:
|
2020-05-23 22:01:22 +00:00
|
|
|
if msg.procDef == nil:
|
|
|
|
continue
|
|
|
|
|
2024-08-30 17:27:09 +00:00
|
|
|
# FIXME: Can `msg.id` be missing, at all?
|
|
|
|
doAssert msg.id.isSome()
|
|
|
|
|
2019-05-19 18:05:02 +00:00
|
|
|
let
|
2024-08-30 17:27:09 +00:00
|
|
|
msgId = msg.id.value
|
2019-05-19 18:05:02 +00:00
|
|
|
msgName = msg.ident
|
2019-09-08 21:56:10 +00:00
|
|
|
msgRecName = msg.recName
|
|
|
|
msgStrongRecName = msg.strongRecName
|
2019-05-19 18:05:02 +00:00
|
|
|
msgRecBody = msg.recBody
|
|
|
|
|
|
|
|
result.add quote do:
|
|
|
|
# This is a type featuring a single field for each message param:
|
2019-09-08 21:56:10 +00:00
|
|
|
type `msgStrongRecName`* = `msgRecBody`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
# Add a helper template for accessing the message type:
|
|
|
|
# e.g. p2p.hello:
|
2020-05-23 22:01:22 +00:00
|
|
|
template `msgName`*(`PROTO`: type `protocolName`): type = `msgRecName`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
# Add a helper template for obtaining the message Id for
|
|
|
|
# a particular message type:
|
2020-05-23 22:01:22 +00:00
|
|
|
template msgProtocol*(`MSG`: type `msgStrongRecName`): type = `protocolName`
|
|
|
|
template RecType*(`MSG`: type `msgStrongRecName`): untyped = `msgRecName`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
if p.isRlpx:
|
|
|
|
result.add quote do:
|
2024-08-30 17:27:09 +00:00
|
|
|
template msgId*(`MSG`: type `msgStrongRecName`): uint = `msgId`
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2020-05-23 22:01:22 +00:00
|
|
|
proc genCode*(p: P2PProtocol): NimNode =
|
|
|
|
for msg in p.messages:
|
|
|
|
p.backend.implementMsg msg
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
result = newStmtList()
|
|
|
|
result.add p.genTypeSection()
|
|
|
|
|
|
|
|
let
|
|
|
|
protocolInit = p.backend.implementProtocolInit(p)
|
2024-01-22 09:47:46 +00:00
|
|
|
protocolReg = ident($p.nameIdent & "Registration")
|
|
|
|
regBody = newStmtList()
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
result.add p.outSendProcs,
|
2024-01-22 09:47:46 +00:00
|
|
|
p.outRecvProcs
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
if p.onPeerConnected != nil: result.add p.onPeerConnected
|
|
|
|
if p.onPeerDisconnected != nil: result.add p.onPeerDisconnected
|
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
regBody.add newCall(p.backend.setEventHandlers,
|
|
|
|
protocolVar,
|
|
|
|
nameOrNil p.onPeerConnected,
|
|
|
|
nameOrNil p.onPeerDisconnected)
|
2019-05-19 18:05:02 +00:00
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
regBody.add p.outProcRegistrations
|
|
|
|
regBody.add newCall(p.backend.registerProtocol, protocolVar)
|
|
|
|
|
|
|
|
result.add quote do:
|
2024-02-14 08:59:13 +00:00
|
|
|
proc `protocolReg`() {.raises: [RlpError].} =
|
2024-01-22 09:47:46 +00:00
|
|
|
let `protocolVar` = `protocolInit`
|
|
|
|
`regBody`
|
|
|
|
`protocolReg`()
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
macro emitForSingleBackend(
|
|
|
|
name: static[string],
|
|
|
|
version: static[int],
|
|
|
|
backend: static[BackendFactory],
|
|
|
|
body: untyped,
|
2022-11-16 16:44:00 +00:00
|
|
|
# TODO Nim can't handle a proper duration parameter here
|
2019-05-19 18:05:02 +00:00
|
|
|
timeouts: static[int64] = defaultReqTimeout.milliseconds,
|
|
|
|
useRequestIds: static[bool] = true,
|
2019-08-05 13:31:51 +00:00
|
|
|
rlpxName: static[string] = "",
|
2019-05-19 18:05:02 +00:00
|
|
|
outgoingRequestDecorator: untyped = nil,
|
|
|
|
incomingRequestDecorator: untyped = nil,
|
|
|
|
incomingRequestThunkDecorator: untyped = nil,
|
|
|
|
incomingResponseDecorator: untyped = nil,
|
|
|
|
incomingResponseThunkDecorator: untyped = nil,
|
|
|
|
peerState = type(nil),
|
|
|
|
networkState = type(nil)): untyped =
|
|
|
|
|
|
|
|
var p = P2PProtocol.init(
|
|
|
|
backend,
|
|
|
|
name, version, body, timeouts,
|
2019-08-05 13:31:51 +00:00
|
|
|
useRequestIds, rlpxName,
|
2019-05-19 18:05:02 +00:00
|
|
|
outgoingRequestDecorator,
|
|
|
|
incomingRequestDecorator,
|
|
|
|
incomingRequestThunkDecorator,
|
|
|
|
incomingResponseDecorator,
|
|
|
|
incomingResponseThunkDecorator,
|
|
|
|
peerState.getType, networkState.getType)
|
|
|
|
|
|
|
|
result = p.genCode()
|
2024-02-16 07:13:03 +00:00
|
|
|
|
|
|
|
when defined(p2pProtocolDebug):
|
|
|
|
try:
|
|
|
|
result.storeMacroResult true
|
|
|
|
except IOError:
|
|
|
|
# IO error so the generated nim code might not be stored, don't sweat it.
|
|
|
|
discard
|
2019-05-19 18:05:02 +00:00
|
|
|
|
|
|
|
macro emitForAllBackends(backendSyms: typed, options: untyped, body: untyped): untyped =
|
|
|
|
let name = $(options[0])
|
|
|
|
|
|
|
|
var backends = newSeq[NimNode]()
|
|
|
|
if backendSyms.kind == nnkSym:
|
|
|
|
backends.add backendSyms
|
|
|
|
else:
|
|
|
|
for backend in backendSyms:
|
|
|
|
backends.add backend
|
|
|
|
|
|
|
|
result = newStmtList()
|
|
|
|
|
|
|
|
for backend in backends:
|
|
|
|
let call = copy options
|
|
|
|
call[0] = bindSym"emitForSingleBackend"
|
|
|
|
call.add newTree(nnkExprEqExpr, ident("name"), newLit(name))
|
|
|
|
call.add newTree(nnkExprEqExpr, ident("backend"), backend)
|
|
|
|
call.add newTree(nnkExprEqExpr, ident("body"), body)
|
|
|
|
result.add call
|
|
|
|
|
|
|
|
template p2pProtocol*(options: untyped, body: untyped) {.dirty.} =
|
|
|
|
bind emitForAllBackends
|
|
|
|
emitForAllBackends(p2pProtocolBackendImpl, options, body)
|
|
|
|
|