nim-eth-p2p/eth_p2p/rlpx.nim

676 lines
22 KiB
Nim
Raw Normal View History

2018-04-30 18:08:18 +00:00
#
# Ethereum P2P
# (c) Copyright 2018
# Status Research & Development GmbH
#
# Licensed under either of
# Apache License, version 2.0, (LICENSE-APACHEv2)
# MIT license (LICENSE-MIT)
#
import macros, sets, algorithm, logging, hashes
import rlp, ranges/[stackarrays, ptr_arith], eth_keys, ethereum_types,
nimcrypto, asyncdispatch2
import kademlia, discovery, auth, rlpxcrypt, enode
2018-04-01 02:41:05 +00:00
type
2018-04-13 12:59:08 +00:00
ConnectionState = enum
None,
Connected,
Disconnecting,
Disconnected
2018-04-01 02:41:05 +00:00
Peer* = ref object
transp: StreamTransport
2018-04-01 02:41:05 +00:00
dispatcher: Dispatcher
networkId: int
secretsState: SecretState
2018-04-13 12:59:08 +00:00
connectionState: ConnectionState
protocolStates: seq[RootRef]
2018-04-19 12:16:38 +00:00
remote*: Node
2018-04-01 02:41:05 +00:00
MessageHandler* = proc(x: Peer, data: var Rlp)
2018-04-13 12:59:08 +00:00
MessageInfo* = object
2018-04-01 02:41:05 +00:00
id*: int
name*: string
thunk*: MessageHandler
CapabilityName* = array[3, char]
Capability* = object
name*: CapabilityName
version*: int
2018-04-13 12:59:08 +00:00
ProtocolInfo* = ref object
2018-04-01 02:41:05 +00:00
name*: CapabilityName
version*: int
2018-04-13 12:59:08 +00:00
messages*: seq[MessageInfo]
2018-04-01 02:41:05 +00:00
index: int # the position of the protocol in the
# ordered list of supported protocols
Dispatcher = ref object
# The dispatcher stores the mapping of negotiated message IDs between
# two connected peers. The dispatcher objects are shared between
# connections running with the same set of supported protocols.
#
# `protocolOffsets` will hold one slot of each locally supported
# protocol. If the other peer also supports the protocol, the stored
# offset indicates the numeric value of the first message of the protocol
# (for this particular connection). If the other peer doesn't support the
# particular protocol, the stored offset is -1.
#
# `thunks` holds a mapping from valid message IDs to their handler procs.
#
protocolOffsets: seq[int]
thunks: seq[MessageHandler]
UnsupportedProtocol* = object of Exception
# This is raised when you attempt to send a message from a particular
# protocol to a peer that doesn't support the protocol.
MalformedMessageError* = object of Exception
const
baseProtocolVersion = 4
clienId = "Nimbus 0.1.0"
# TODO: Usage of this variables causes GCSAFE problems.
2018-04-01 02:41:05 +00:00
var
2018-05-22 06:38:36 +00:00
gProtocols: seq[ProtocolInfo]
gCapabilities: seq[Capability]
2018-04-01 02:41:05 +00:00
gDispatchers = initSet[Dispatcher]()
2018-04-13 12:59:08 +00:00
devp2p: ProtocolInfo
2018-04-01 02:41:05 +00:00
# The variables above are immutable RTTI information. We need to tell
# Nim to not consider them GcSafe violations:
template rlpxProtocols: auto = {.gcsafe.}: gProtocols
template rlpxCapabilities: auto = {.gcsafe.}: gCapabilities
template devp2pProtocolInfo: auto = {.gcsafe.}: devp2p
2018-04-01 02:41:05 +00:00
# Dispatcher
#
2018-04-19 12:16:38 +00:00
proc `$`*(p: Peer): string {.inline.} = $p.remote
2018-04-01 02:41:05 +00:00
proc hash(d: Dispatcher): int =
hash(d.protocolOffsets)
proc `==`(lhs, rhs: Dispatcher): bool =
lhs.protocolOffsets == rhs.protocolOffsets
template totalThunks(d: Dispatcher): int =
d.thunks.len
template getThunk(d: Dispatcher, idx: int): MessageHandler =
rlpxProtocols.thunks[idx]
2018-04-01 02:41:05 +00:00
proc describeProtocols(d: Dispatcher): string =
result = ""
for i in 0 ..< rlpxProtocols.len:
2018-04-01 02:41:05 +00:00
if d.protocolOffsets[i] != -1:
if result.len != 0: result.add(',')
for c in rlpxProtocols[i].name: result.add(c)
2018-04-01 02:41:05 +00:00
2018-04-13 12:59:08 +00:00
proc getDispatcher(otherPeerCapabilities: openarray[Capability]): Dispatcher =
2018-04-01 02:41:05 +00:00
# XXX: sub-optimal solution until progress is made here:
# https://github.com/nim-lang/Nim/issues/7457
# We should be able to find an existing dispatcher without allocating a new one
new(result)
newSeq(result.protocolOffsets, rlpxProtocols.len)
2018-04-01 02:41:05 +00:00
2018-05-22 06:38:36 +00:00
var nextUserMsgId = 0x10
2018-04-01 02:41:05 +00:00
for i in 0 ..< rlpxProtocols.len:
let localProtocol = rlpxProtocols[i]
2018-04-01 02:41:05 +00:00
block findMatchingProtocol:
for remoteCapability in otherPeerCapabilities:
if localProtocol.name == remoteCapability.name and
localProtocol.version == remoteCapability.version:
result.protocolOffsets[i] = nextUserMsgId
nextUserMsgId += localProtocol.messages.len
break findMatchingProtocol
# the local protocol is not supported by the other peer
# indicate this by a -1 offset:
result.protocolOffsets[i] = -1
if result in gDispatchers:
return gDispatchers[result]
else:
template copyTo(src, dest; index: int) =
for i in 0 ..< src.len:
dest[index + i] = src[i].thunk
result.thunks = newSeq[MessageHandler](nextUserMsgId)
devp2pProtocolInfo.messages.copyTo(result.thunks, 0)
2018-04-01 02:41:05 +00:00
for i in 0 ..< rlpxProtocols.len:
2018-04-01 02:41:05 +00:00
if result.protocolOffsets[i] != -1:
rlpxProtocols[i].messages.copyTo(result.thunks, result.protocolOffsets[i])
2018-04-01 02:41:05 +00:00
gDispatchers.incl result
2018-04-13 12:59:08 +00:00
# Protocol info objects
2018-04-01 02:41:05 +00:00
#
2018-04-13 12:59:08 +00:00
proc newProtocol(name: string, version: int): ProtocolInfo =
2018-04-01 02:41:05 +00:00
new result
result.name[0] = name[0]
result.name[1] = name[1]
result.name[2] = name[2]
result.version = version
result.messages = @[]
2018-04-13 12:59:08 +00:00
proc nameStr*(p: ProtocolInfo): string =
2018-04-01 02:41:05 +00:00
result = newStringOfCap(3)
for c in p.name: result.add(c)
2018-04-13 12:59:08 +00:00
proc cmp*(lhs, rhs: ProtocolInfo): int {.inline.} =
2018-04-01 02:41:05 +00:00
for i in 0..2:
if lhs.name[i] != rhs.name[i]:
return int16(lhs.name[i]) - int16(rhs.name[i])
return 0
2018-04-13 12:59:08 +00:00
proc registerMsg(protocol: var ProtocolInfo,
id: int, name: string, thunk: MessageHandler) =
protocol.messages.add MessageInfo(id: id, name: name, thunk: thunk)
2018-04-01 02:41:05 +00:00
2018-04-13 12:59:08 +00:00
proc registerProtocol(protocol: ProtocolInfo) =
2018-04-01 02:41:05 +00:00
# XXX: This can be done at compile-time in the future
if protocol.version > 0:
2018-05-22 06:38:36 +00:00
if gProtocols.isNil: gProtocols = @[]
if gCapabilities.isNil: gCapabilities = @[]
2018-04-13 12:59:08 +00:00
let pos = lowerBound(gProtocols, protocol)
gProtocols.insert(protocol, pos)
gCapabilities.insert(Capability(name: protocol.name, version: protocol.version), pos)
2018-04-01 02:41:05 +00:00
for i in 0 ..< gProtocols.len:
gProtocols[i].index = i
else:
devp2p = protocol
# RLP serialization
#
proc append*(rlpWriter: var RlpWriter, hash: KeccakHash) =
rlpWriter.append(hash.data)
proc read*(rlp: var Rlp, T: typedesc[KeccakHash]): T =
result.data = rlp.read(type(result.data))
# Message composition and encryption
#
proc writeMsgId(p: ProtocolInfo, msgId: int, peer: Peer,
rlpOut: var RlpWriter) =
2018-04-01 02:41:05 +00:00
let baseMsgId = peer.dispatcher.protocolOffsets[p.index]
if baseMsgId == -1:
raise newException(UnsupportedProtocol,
p.nameStr & " is not supported by peer " &
$peer.remote.id)
2018-04-01 02:41:05 +00:00
rlpOut.append(baseMsgId + msgId)
2018-04-13 12:59:08 +00:00
proc dispatchMsg(peer: Peer, msgId: int, msgData: var Rlp) =
template invalidIdError: untyped =
raise newException(ValueError,
"RLPx message with an invalid id " & $msgId &
" on a connection supporting " & peer.dispatcher.describeProtocols)
if msgId >= peer.dispatcher.thunks.len: invalidIdError()
let thunk = peer.dispatcher.thunks[msgId]
if thunk == nil: invalidIdError()
thunk(peer, msgData)
proc send(p: Peer, data: BytesRange) {.async.} =
# var rlp = rlpFromBytes(data)
# echo "sending: ", rlp.read(int)
# echo "payload: ", rlp.inspect
var cipherText = encryptMsg(data, p.secretsState)
var res = await p.transp.write(cipherText)
2018-04-13 12:59:08 +00:00
proc recvMsg*(peer: Peer): Future[tuple[msgId: int, msgData: Rlp]] {.async.} =
## This procs awaits the next complete RLPx message in the TCP stream
2018-04-01 02:41:05 +00:00
var headerBytes: array[32, byte]
await peer.transp.readExactly(addr headerBytes[0], 32)
var msgSize: int
if decryptHeaderAndGetMsgSize(peer.secretsState,
headerBytes, msgSize) != RlpxStatus.Success:
return (-1, zeroBytesRlp)
let remainingBytes = encryptedLength(msgSize) - 32
# XXX: Migrate this to a thread-local seq
var encryptedBytes = newSeq[byte](remainingBytes)
await peer.transp.readExactly(addr encryptedBytes[0], len(encryptedBytes))
let decryptedMaxLength = decryptedLength(msgSize)
var
decryptedBytes = newSeq[byte](decryptedMaxLength)
decryptedBytesCount = 0
2018-04-01 02:41:05 +00:00
if decryptBody(peer.secretsState, encryptedBytes, msgSize,
decryptedBytes, decryptedBytesCount) != RlpxStatus.Success:
return (-1, zeroBytesRlp)
2018-04-01 02:41:05 +00:00
decryptedBytes.setLen(decryptedBytesCount)
var rlp = rlpFromBytes(decryptedBytes.toRange)
2018-04-13 12:59:08 +00:00
let msgId = rlp.read(int)
return (msgId, rlp)
proc nextMsg*(peer: Peer, MsgType: typedesc,
discardOthers = false): Future[MsgType] {.async.} =
## This procs awaits a specific RLPx message.
## By default, other messages will be automatically dispatched
## to their responsive handlers unless `discardOthers` is set to
## true. This may be useful when the protocol requires a very
## specific response to a given request. Use with caution.
const wantedId = MsgType.msgId
while true:
var (nextMsgId, nextMsgData) = await peer.recvMsg()
2018-05-22 06:38:36 +00:00
# echo "got msg(", nextMsgId, "): ", nextMsgData.inspect
2018-04-13 12:59:08 +00:00
if nextMsgId == wantedId:
return nextMsgData.read(MsgType)
elif not discardOthers:
2018-05-22 06:38:36 +00:00
if nextMsgData.listLen != 0:
nextMsgData = nextMsgData.listElem(0)
2018-04-13 12:59:08 +00:00
peer.dispatchMsg(nextMsgId, nextMsgData)
iterator typedParams(n: NimNode, skip = 0): (NimNode, NimNode) =
2018-04-01 02:41:05 +00:00
for i in (1 + skip) ..< n.params.len:
let paramNodes = n.params[i]
let paramType = paramNodes[^2]
for j in 0 ..< paramNodes.len - 2:
2018-04-01 02:41:05 +00:00
yield (paramNodes[j], paramType)
2018-04-13 12:59:08 +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`).
##
## For now, only openarray types are remapped to sequences.
result = n
if n.kind == nnkBracketExpr and eqIdent(n[0], "openarray"):
2018-04-13 12:59:08 +00:00
result = n.copyNimTree
result[0] = newIdentNode("seq")
proc getState(peer: Peer, proto: ProtocolInfo): RootRef =
peer.protocolStates[proto.index]
template state*(connection: Peer, Protocol: typedesc): untyped =
## Returns the state object of a particular protocol for a
## particular connection.
cast[ref Protocol.State](connection.getState(Protocol.protocolInfo))
2018-04-13 12:59:08 +00:00
macro rlpxProtocol*(protoIdentifier: untyped,
2018-04-01 02:41:05 +00:00
version: static[int],
body: untyped): untyped =
2018-04-13 12:59:08 +00:00
## The macro used to defined RLPx sub-protocols. See README.
2018-04-01 02:41:05 +00:00
var
2018-04-13 12:59:08 +00:00
protoName = $protoIdentifier
protoNameIdent = newIdentNode(protoName)
2018-04-01 02:41:05 +00:00
nextId = BiggestInt 0
2018-04-13 12:59:08 +00:00
protocol = genSym(nskVar, protoName & "Proto")
2018-04-01 02:41:05 +00:00
newProtocol = bindSym "newProtocol"
rlpFromBytes = bindSym "rlpFromBytes"
read = bindSym "read"
initRlpWriter = bindSym "initRlpWriter"
finish = bindSym "finish"
append = bindSym "append"
send = bindSym "send"
Peer = bindSym "Peer"
2018-04-13 12:59:08 +00:00
writeMsgId = bindSym "writeMsgId"
2018-04-01 02:41:05 +00:00
isSubprotocol = version > 0
2018-04-13 12:59:08 +00:00
stateType: NimNode = nil
2018-05-22 06:38:36 +00:00
msgThunksAndRegistrations = newNimNode(nnkStmtList)
2018-04-13 12:59:08 +00:00
# By convention, all Ethereum protocol names must be abbreviated to 3 letters
assert protoName.len == 3
2018-04-01 02:41:05 +00:00
result = newNimNode(nnkStmtList)
result.add quote do:
2018-04-13 12:59:08 +00:00
# One global variable per protocol holds the protocol run-time data
var `protocol` = `newProtocol`(`protoName`, `version`)
# Create a type actining as a pseudo-object representing the protocol (e.g. p2p)
type `protoNameIdent`* = object
# The protocol run-time data is available as a pseudo-field (e.g. `p2p.protocolInfo`)
template protocolInfo*(P: type `protoNameIdent`): ProtocolInfo = `protocol`
2018-04-01 02:41:05 +00:00
for n in body:
case n.kind
of {nnkCall, nnkCommand}:
if n.len == 2 and eqIdent(n[0], "nextID"):
2018-04-01 02:41:05 +00:00
if n[1].kind == nnkIntLit:
nextId = n[1].intVal
else:
error("nextID expects a single int value", n)
else:
error(repr(n) & " is not a recognized call in RLPx protocol definitions", n)
2018-04-13 12:59:08 +00:00
of nnkTypeSection:
if n.len == 1 and eqIdent(n[0][0], "State"):
2018-04-13 12:59:08 +00:00
stateType = genSym(nskType, protoName & "State")
n[0][0] = stateType
result.add n
# Create a pseudo-field for the protocol State type (e.g. `p2p.State`)
result.add quote do:
template State*(P: type `protoNameIdent`): typedesc = `stateType`
else:
error("The only type that can be defined inside a RLPx protocol is the protocol's State type.")
2018-04-01 02:41:05 +00:00
of nnkProcDef:
2018-04-13 12:59:08 +00:00
let
msgIdent = n.name
msgName = $n.name
2018-04-01 02:41:05 +00:00
var
thunkName = newNilLit()
rlpWriter = genSym(nskVar, "writer")
appendParams = newNimNode(nnkStmtList)
peer = genSym(nskParam, "peer")
if n.body.kind != nnkEmpty:
2018-04-13 12:59:08 +00:00
# implement the receiving thunk proc that deserialzed the
# message parameters and calls the user proc:
2018-04-01 02:41:05 +00:00
var
nCopy = n.copyNimTree
rlp = genSym(nskParam, "rlp")
connection = genSym(nskParam, "connection")
2018-04-13 12:59:08 +00:00
nCopy.name = genSym(nskProc, msgName)
2018-04-01 02:41:05 +00:00
var callUserProc = newCall(nCopy.name, connection)
var readParams = newNimNode(nnkStmtList)
for i in 2 ..< n.params.len: # we skip the return type and the
# first param of type Peer
let paramNodes = n.params[i]
let paramType = paramNodes[^2]
for j in 0 ..< paramNodes.len - 2:
2018-04-01 02:41:05 +00:00
var deserializedParam = genSym(nskLet)
readParams.add quote do:
let `deserializedParam` = `read`(`rlp`, `paramType`)
callUserProc.add deserializedParam
2018-04-13 12:59:08 +00:00
thunkName = newIdentNode(msgName & "_thunk")
2018-04-01 02:41:05 +00:00
var thunk = quote do:
proc `thunkName`(`connection`: `Peer`, `rlp`: var Rlp) =
`readParams`
`callUserProc`
2018-04-13 12:59:08 +00:00
if stateType != nil:
# Define a local accessor for the current protocol state
# inside each handler (e.g. peer.state.foo = bar)
var localStateAccessor = quote:
template state(connection: `Peer`): ref `stateType` =
cast[ref `stateType`](connection.getState(`protocol`))
nCopy.body.insert 0, localStateAccessor
2018-05-22 06:38:36 +00:00
msgThunksAndRegistrations.add(nCopy, thunk)
2018-04-01 02:41:05 +00:00
2018-04-13 12:59:08 +00:00
var
msgType = genSym(nskType, msgName & "Obj")
msgTypeFields = newTree(nnkRecList)
msgTypeBody = newTree(nnkObjectTy,
newEmptyNode(),
newEmptyNode(),
msgTypeFields)
var paramCount = 0
2018-04-01 02:41:05 +00:00
# implement sending proc
for param, paramType in n.typedParams(skip = 1):
inc paramCount
2018-04-01 02:41:05 +00:00
appendParams.add quote do:
`append`(`rlpWriter`, `param`)
2018-04-13 12:59:08 +00:00
msgTypeFields.add newTree(nnkIdentDefs,
param, chooseFieldType(paramType), newEmptyNode())
result.add quote do:
# This is a type featuring a single field for each message param:
type `msgType`* = `msgTypeBody`
# Add a helper template for accessing the message type:
# e.g. p2p.hello:
template `msgIdent`*(T: type `protoNameIdent`): typedesc = `msgType`
# Add a helper template for obtaining the message Id for
# a particular message type:
template msgId*(T: type `msgType`): int = `nextId`
2018-04-01 02:41:05 +00:00
# XXX TODO: check that the first param has the correct type
n.params[1][0] = peer
# echo n.params.treeRepr
n.params[0] = newTree(nnkBracketExpr,
newIdentNode("Future"), newIdentNode("void"))
2018-04-01 02:41:05 +00:00
let writeMsgId = if isSubprotocol:
2018-04-13 12:59:08 +00:00
quote: `writeMsgId`(`protocol`, `nextId`, `peer`, `rlpWriter`)
2018-04-01 02:41:05 +00:00
else:
quote: `append`(`rlpWriter`, `nextId`)
let paramCountNode = newLit(paramCount)
2018-04-01 02:41:05 +00:00
n.body = quote do:
var `rlpWriter` = `initRlpWriter`()
`writeMsgId`
`rlpWriter`.startList(`paramCountNode`)
2018-04-01 02:41:05 +00:00
`appendParams`
return `send`(`peer`, `finish`(`rlpWriter`))
2018-04-01 02:41:05 +00:00
result.add n
2018-05-22 06:38:36 +00:00
msgThunksAndRegistrations.add newCall(bindSym("registerMsg"),
2018-04-01 02:41:05 +00:00
protocol,
newIntLitNode(nextId),
newStrLitNode($n.name),
thunkName)
2018-05-15 18:31:56 +00:00
inc nextId
2018-04-01 02:41:05 +00:00
else:
error("illegal syntax in a RLPx protocol definition", n)
2018-05-22 06:38:36 +00:00
result.add(msgThunksAndRegistrations)
2018-04-01 02:41:05 +00:00
result.add newCall(bindSym("registerProtocol"), protocol)
2018-04-13 12:59:08 +00:00
when isMainModule: echo repr(result)
2018-04-01 02:41:05 +00:00
type
DisconnectionReason* = enum
DisconnectRequested,
TcpError,
BreachOfProtocol,
UselessPeer,
TooManyPeers,
AlreadyConnected,
IncompatibleProtocolVersion,
NullNodeIdentityReceived,
ClientQuitting,
UnexpectedIdentity,
SelfConnection,
MessageTimeout,
SubprotocolReason = 0x10
2018-04-13 12:59:08 +00:00
rlpxProtocol p2p, 0:
2018-04-01 02:41:05 +00:00
proc hello(peer: Peer,
version: uint,
clientId: string,
2018-04-13 12:59:08 +00:00
capabilities: openarray[Capability],
2018-04-01 02:41:05 +00:00
listenPort: uint,
nodeId: array[RawPublicKeySize, byte]) =
# peer.id = nodeId
2018-04-13 12:59:08 +00:00
peer.dispatcher = getDispatcher(capabilities)
2018-04-01 02:41:05 +00:00
proc disconnect(peer: Peer, reason: DisconnectionReason)
2018-05-22 06:38:36 +00:00
proc ping(peer: Peer) =
discard peer.pong()
2018-04-01 02:41:05 +00:00
proc pong(peer: Peer) =
discard
template `^`(arr): auto =
# passes a stack array with a matching `arrLen`
# variable as an open array
arr.toOpenArray(0, `arr Len` - 1)
proc validatePubKeyInHello(msg: p2p.hello, pubKey: PublicKey): bool =
var pk: PublicKey
recoverPublicKey(msg.nodeId, pk) == EthKeysStatus.Success and pk == pubKey
proc check(status: AuthStatus) =
if status != AuthStatus.Success:
raise newException(Exception, "Error: " & $status)
proc connectionEstablished(p: Peer, h: p2p.hello) =
p.dispatcher = getDispatcher(h.capabilities)
# p.id = h.nodeId
p.connectionState = Connected
newSeq(p.protocolStates, rlpxProtocols.len)
# XXX: initialize the sub-protocol states
2018-04-13 12:59:08 +00:00
proc initSecretState(hs: var Handshake, authMsg, ackMsg: openarray[byte],
p: Peer) =
2018-05-11 10:08:55 +00:00
var secrets: ConnectionSecret
check hs.getSecrets(authMsg, ackMsg, secrets)
initSecretState(secrets, p.secretsState)
burnMem(secrets)
proc rlpxConnect*(remote: Node, myKeys: KeyPair,
listenPort: Port): Future[Peer] {.async.} =
new result
result.remote = remote
let ta = initTAddress(remote.node.address.ip, remote.node.address.tcpPort)
try:
result.transp = await connect(ta)
2018-04-01 02:41:05 +00:00
var handshake = newHandshake({Initiator})
handshake.host = myKeys
2018-04-03 23:47:31 +00:00
var authMsg: array[AuthMessageMaxEIP8, byte]
var authMsgLen = 0
check authMessage(handshake, remote.node.pubkey, authMsg, authMsgLen)
var res = result.transp.write(addr authMsg[0], authMsgLen)
2018-04-01 02:41:05 +00:00
let initialSize = handshake.expectedLength
var ackMsg = newSeqOfCap[byte](1024)
ackMsg.setLen(initialSize)
2018-04-01 02:41:05 +00:00
await result.transp.readExactly(addr ackMsg[0], len(ackMsg))
2018-04-01 02:41:05 +00:00
var ret = handshake.decodeAckMessage(ackMsg)
if ret == AuthStatus.IncompleteError:
ackMsg.setLen(handshake.expectedLength)
await result.transp.readExactly(addr ackMsg[initialSize],
len(ackMsg) - initialSize)
ret = handshake.decodeAckMessage(ackMsg)
check ret
initSecretState(handshake, ^authMsg, ackMsg, result)
# if handshake.remoteHPubkey != remote.node.pubKey:
# raise newException(Exception, "Remote pubkey is wrong")
2018-04-01 02:41:05 +00:00
discard result.hello(baseProtocolVersion, clienId, rlpxCapabilities,
uint(listenPort), myKeys.pubkey.getRaw())
var response = await result.nextMsg(p2p.hello, discardOthers = true)
if not validatePubKeyInHello(response, remote.node.pubKey):
warn "Remote nodeId is not its public key" # XXX: Do we care?
connectionEstablished(result, response)
except:
if not isNil(result.transp):
result.transp.close()
proc rlpxAccept*(transp: StreamTransport,
myKeys: KeyPair): Future[Peer] {.async.} =
new result
result.transp = transp
2018-05-10 12:51:33 +00:00
var handshake = newHandshake({Responder})
handshake.host = myKeys
try:
let initialSize = handshake.expectedLength
var authMsg = newSeqOfCap[byte](1024)
authMsg.setLen(initialSize)
await transp.readExactly(addr authMsg[0], len(authMsg))
var ret = handshake.decodeAuthMessage(authMsg)
if ret == AuthStatus.IncompleteError: # Eip8 auth message is likely
authMsg.setLen(handshake.expectedLength)
await transp.readExactly(addr authMsg[initialSize],
len(authMsg) - initialSize)
ret = handshake.decodeAuthMessage(authMsg)
check ret
var ackMsg: array[AckMessageMaxEIP8, byte]
var ackMsgLen: int
check handshake.ackMessage(ackMsg, ackMsgLen)
var res = transp.write(addr ackMsg[0], ackMsgLen)
initSecretState(handshake, authMsg, ^ackMsg, result)
var response = await result.nextMsg(p2p.hello, discardOthers = true)
let listenPort = transp.localAddress().port
discard result.hello(baseProtocolVersion, clienId,
rlpxCapabilities, listenPort.uint, myKeys.pubkey.getRaw())
if validatePubKeyInHello(response, handshake.remoteHPubkey):
warn "Remote nodeId is not its public key" # XXX: Do we care?
let port = Port(response.listenPort)
let remote = transp.remoteAddress()
let address = Address(ip: remote.address, tcpPort: remote.port,
udpPort: remote.port)
result.remote = newNode(initEnode(handshake.remoteHPubkey, address))
connectionEstablished(result, response)
except:
transp.close()
2018-05-10 12:51:33 +00:00
2018-04-01 02:41:05 +00:00
when isMainModule:
import rlp
2018-04-13 12:59:08 +00:00
rlpxProtocol aaa, 1:
type State = object
peerName: string
proc hi(p: Peer, name: string) =
p.state.peerName = name
rlpxProtocol bbb, 1:
type State = object
messages: int
2018-04-01 02:41:05 +00:00
proc foo(p: Peer, s: string, a, z: int) =
2018-04-13 12:59:08 +00:00
p.state.messages += 1
echo p.state(aaa).peerName
2018-04-01 02:41:05 +00:00
proc bar(p: Peer, i: int, s: string)
var p = Peer()
discard p.bar(10, "test")
2018-04-01 02:41:05 +00:00
when false:
# The assignment below can be used to investigate if the RLPx procs
# are considered GcSafe. The short answer is that they aren't, because
# they dispatch into user code that might use the GC.
type
GcSafeRecvMsg = proc (peer: Peer):
Future[tuple[msgId: int, msgData: Rlp]] {.gcsafe.}
GcSafeAccept = proc (transp: StreamTransport, myKeys: KeyPair):
Future[Peer] {.gcsafe.}
var
recvMsgPtr: GcSafeRecvMsg = recvMsg
acceptPtr: GcSafeAccept = rlpxAccept