2019-03-05 22:54:08 +00:00
|
|
|
import
|
2020-03-22 21:55:01 +00:00
|
|
|
# Std lib
|
2020-05-28 01:14:01 +00:00
|
|
|
typetraits, strutils, os, random, algorithm, sequtils,
|
2020-06-05 15:08:50 +00:00
|
|
|
options as stdOptions,
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
# Status libs
|
2020-06-03 13:52:02 +00:00
|
|
|
stew/[varints, base58, endians2, results, byteutils],
|
2020-06-05 15:08:50 +00:00
|
|
|
stew/shims/net as stewNet,
|
2020-05-20 17:05:22 +00:00
|
|
|
stew/shims/[macros, tables],
|
|
|
|
faststreams/[inputs, outputs, buffers], snappy, snappy/framing,
|
2020-03-22 21:55:01 +00:00
|
|
|
json_serialization, json_serialization/std/[net, options],
|
|
|
|
chronos, chronicles, metrics,
|
|
|
|
# TODO: create simpler to use libp2p modules that use re-exports
|
2020-03-24 11:13:07 +00:00
|
|
|
libp2p/[switch, standard_setup, peerinfo, peer, connection, errors,
|
2020-04-17 13:29:49 +00:00
|
|
|
multiaddress, multicodec, crypto/crypto, crypto/secp,
|
2020-03-22 21:55:01 +00:00
|
|
|
protocols/identify, protocols/protocol],
|
|
|
|
libp2p/protocols/secure/[secure, secio],
|
2020-03-31 18:39:02 +00:00
|
|
|
libp2p/protocols/pubsub/[pubsub, floodsub, rpc/messages],
|
2020-05-20 04:57:39 +00:00
|
|
|
libp2p/transports/tcptransport,
|
2020-03-23 19:53:46 +00:00
|
|
|
libp2p/stream/lpstream,
|
2020-05-29 10:03:29 +00:00
|
|
|
eth/[keys, async_utils], eth/p2p/p2p_protocol_dsl,
|
2020-03-22 21:55:01 +00:00
|
|
|
eth/net/nat, eth/p2p/discoveryv5/[enr, node],
|
|
|
|
# Beacon node modules
|
2020-06-03 13:52:02 +00:00
|
|
|
version, conf, eth2_discovery, libp2p_json_serialization, conf,
|
|
|
|
ssz/ssz_serialization,
|
2020-04-15 02:41:22 +00:00
|
|
|
peer_pool, spec/[datatypes, network]
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
export
|
|
|
|
version, multiaddress, peer_pool, peerinfo, p2pProtocol,
|
2020-06-03 13:52:02 +00:00
|
|
|
libp2p_json_serialization, ssz_serialization, peer, results
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
logScope:
|
|
|
|
topics = "networking"
|
2020-02-05 20:40:14 +00:00
|
|
|
|
|
|
|
type
|
2020-02-19 08:58:10 +00:00
|
|
|
KeyPair* = crypto.KeyPair
|
|
|
|
PublicKey* = crypto.PublicKey
|
|
|
|
PrivateKey* = crypto.PrivateKey
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
Bytes = seq[byte]
|
2020-05-21 13:21:29 +00:00
|
|
|
ErrorMsg = List[byte, 256]
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
# TODO: This is here only to eradicate a compiler
|
|
|
|
# warning about unused import (rpc/messages).
|
|
|
|
GossipMsg = messages.Message
|
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
SeenItem* = object
|
|
|
|
pinfo*: PeerInfo
|
|
|
|
stamp*: chronos.Moment
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
# TODO Is this really needed?
|
|
|
|
Eth2Node* = ref object of RootObj
|
|
|
|
switch*: Switch
|
|
|
|
discovery*: Eth2DiscoveryProtocol
|
|
|
|
wantedPeers*: int
|
|
|
|
peerPool*: PeerPool[Peer, PeerID]
|
|
|
|
protocolStates*: seq[RootRef]
|
|
|
|
libp2pTransportLoops*: seq[Future[void]]
|
2020-03-24 11:13:07 +00:00
|
|
|
discoveryLoop: Future[void]
|
2020-04-15 02:41:22 +00:00
|
|
|
metadata*: Eth2Metadata
|
2020-06-03 08:46:29 +00:00
|
|
|
connectTimeout*: chronos.Duration
|
|
|
|
seenThreshold*: chronos.Duration
|
|
|
|
connQueue: AsyncQueue[PeerInfo]
|
|
|
|
seenTable: Table[PeerID, SeenItem]
|
|
|
|
connWorkers: seq[Future[void]]
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
EthereumNode = Eth2Node # needed for the definitions in p2p_backends_helpers
|
|
|
|
|
2020-04-15 02:41:22 +00:00
|
|
|
Eth2MetaData* = object
|
|
|
|
seq_number*: uint64
|
|
|
|
attnets*: BitArray[ATTESTATION_SUBNET_COUNT]
|
|
|
|
|
|
|
|
ENRForkID* = object
|
|
|
|
fork_digest*: ForkDigest
|
|
|
|
next_fork_version*: Version
|
|
|
|
next_fork_epoch*: Epoch
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
Peer* = ref object
|
|
|
|
network*: Eth2Node
|
|
|
|
info*: PeerInfo
|
|
|
|
wasDialed*: bool
|
|
|
|
discoveryId*: Eth2DiscoveryId
|
|
|
|
connectionState*: ConnectionState
|
|
|
|
protocolStates*: seq[RootRef]
|
|
|
|
maxInactivityAllowed*: Duration
|
|
|
|
score*: int
|
2020-05-12 22:37:07 +00:00
|
|
|
lacksSnappy: bool
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
ConnectionState* = enum
|
|
|
|
None,
|
|
|
|
Connecting,
|
|
|
|
Connected,
|
|
|
|
Disconnecting,
|
|
|
|
Disconnected
|
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
UntypedResponse = ref object
|
2020-03-22 21:55:01 +00:00
|
|
|
peer*: Peer
|
2020-03-22 23:23:21 +00:00
|
|
|
stream*: Connection
|
2020-05-12 22:37:07 +00:00
|
|
|
noSnappy*: bool
|
2020-05-23 22:24:47 +00:00
|
|
|
writtenChunks*: int
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
SingleChunkResponse*[MsgType] = distinct UntypedResponse
|
|
|
|
## Protocol requests using this type will produce request-making
|
|
|
|
## client-side procs that return `NetRes[MsgType]`
|
|
|
|
|
|
|
|
MultipleChunksResponse*[MsgType] = distinct UntypedResponse
|
|
|
|
## Protocol requests using this type will produce request-making
|
|
|
|
## client-side procs that return `NetRes[seq[MsgType]]`.
|
|
|
|
## In the future, such procs will return an `InputStream[NetRes[MsgType]]`.
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
MessageInfo* = object
|
|
|
|
name*: string
|
|
|
|
|
|
|
|
# Private fields:
|
|
|
|
libp2pCodecName: string
|
|
|
|
protocolMounter*: MounterProc
|
|
|
|
|
|
|
|
ProtocolInfoObj* = object
|
|
|
|
name*: string
|
|
|
|
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
|
|
|
|
|
|
|
|
ResponseCode* = enum
|
|
|
|
Success
|
|
|
|
InvalidRequest
|
|
|
|
ServerError
|
|
|
|
|
|
|
|
PeerStateInitializer* = proc(peer: Peer): RootRef {.gcsafe.}
|
|
|
|
NetworkStateInitializer* = proc(network: EthereumNode): RootRef {.gcsafe.}
|
2020-03-22 23:23:21 +00:00
|
|
|
HandshakeStep* = proc(peer: Peer, conn: Connection): Future[void] {.gcsafe.}
|
2020-03-22 21:55:01 +00:00
|
|
|
DisconnectionHandler* = proc(peer: Peer): Future[void] {.gcsafe.}
|
|
|
|
ThunkProc* = LPProtoHandler
|
|
|
|
MounterProc* = proc(network: Eth2Node) {.gcsafe.}
|
|
|
|
MessageContentPrinter* = proc(msg: pointer): string {.gcsafe.}
|
|
|
|
|
|
|
|
DisconnectionReason* = enum
|
|
|
|
ClientShutDown
|
|
|
|
IrrelevantNetwork
|
|
|
|
FaultOrError
|
|
|
|
|
|
|
|
PeerDisconnected* = object of CatchableError
|
|
|
|
reason*: DisconnectionReason
|
|
|
|
|
|
|
|
TransmissionError* = object of CatchableError
|
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
Eth2NetworkingErrorKind* = enum
|
|
|
|
BrokenConnection
|
|
|
|
ReceivedErrorResponse
|
|
|
|
UnexpectedEOF
|
|
|
|
PotentiallyExpectedEOF
|
|
|
|
InvalidResponseCode
|
|
|
|
InvalidSnappyBytes
|
|
|
|
InvalidSszBytes
|
|
|
|
StreamOpenTimeout
|
|
|
|
ReadResponseTimeout
|
|
|
|
ZeroSizePrefix
|
|
|
|
SizePrefixOverflow
|
|
|
|
|
|
|
|
Eth2NetworkingError = object
|
|
|
|
case kind*: Eth2NetworkingErrorKind
|
|
|
|
of ReceivedErrorResponse:
|
|
|
|
responseCode: ResponseCode
|
2020-05-21 13:21:29 +00:00
|
|
|
errorMsg: ErrorMsg
|
2020-05-12 22:37:07 +00:00
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
NetRes*[T] = Result[T, Eth2NetworkingError]
|
|
|
|
## This is type returned from all network requests
|
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
const
|
2019-11-12 00:05:35 +00:00
|
|
|
clientId* = "Nimbus beacon node v" & fullVersionStr
|
2020-03-22 21:55:01 +00:00
|
|
|
networkKeyFilename = "privkey.protobuf"
|
2020-04-15 02:41:22 +00:00
|
|
|
nodeMetadataFilename = "node-metadata.json"
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
TCP = net.Protocol.IPPROTO_TCP
|
|
|
|
HandshakeTimeout = FaultOrError
|
|
|
|
|
|
|
|
# Spec constants
|
|
|
|
# https://github.com/ethereum/eth2.0-specs/blob/dev/specs/networking/p2p-interface.md#eth-20-network-interaction-domains
|
2020-04-15 02:41:22 +00:00
|
|
|
MAX_CHUNK_SIZE* = 1 * 1024 * 1024 # bytes
|
2020-03-22 21:55:01 +00:00
|
|
|
GOSSIP_MAX_SIZE* = 1 * 1024 * 1024 # bytes
|
|
|
|
TTFB_TIMEOUT* = 5.seconds
|
|
|
|
RESP_TIMEOUT* = 10.seconds
|
|
|
|
|
|
|
|
readTimeoutErrorMsg = "Exceeded read timeout for a request"
|
2019-06-12 18:22:05 +00:00
|
|
|
|
2020-04-23 15:31:00 +00:00
|
|
|
NewPeerScore* = 200
|
|
|
|
## Score which will be assigned to new connected Peer
|
2020-05-28 05:02:28 +00:00
|
|
|
PeerScoreLowLimit* = 0
|
2020-04-23 15:31:00 +00:00
|
|
|
## Score after which peer will be kicked
|
2020-05-28 05:02:28 +00:00
|
|
|
PeerScoreHighLimit* = 1000
|
|
|
|
## Max value of peer's score
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
ConcurrentConnections* = 10
|
|
|
|
## Maximum number of active concurrent connection requests.
|
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
template neterr(kindParam: Eth2NetworkingErrorKind): auto =
|
|
|
|
err(type(result), Eth2NetworkingError(kind: kindParam))
|
|
|
|
|
2019-10-25 17:15:12 +00:00
|
|
|
# Metrics for tracking attestation and beacon block loss
|
|
|
|
declareCounter gossip_messages_sent,
|
|
|
|
"Number of gossip messages sent by this peer"
|
|
|
|
|
|
|
|
declareCounter gossip_messages_received,
|
|
|
|
"Number of gossip messages received by this peer"
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
declarePublicGauge libp2p_successful_dials,
|
2020-03-22 23:23:21 +00:00
|
|
|
"Number of successfully dialed peers"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
declarePublicGauge libp2p_failed_dials,
|
|
|
|
"Number of dialing attempts that failed"
|
|
|
|
|
|
|
|
declarePublicGauge libp2p_timeout_dials,
|
|
|
|
"Number of dialing attempts that exceeded timeout"
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
declarePublicGauge libp2p_peers,
|
2020-03-22 23:23:21 +00:00
|
|
|
"Number of active libp2p peers"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-06 22:24:55 +00:00
|
|
|
proc safeClose(conn: Connection) {.async.} =
|
|
|
|
if not conn.closed:
|
|
|
|
await close(conn)
|
|
|
|
|
2020-05-12 22:35:40 +00:00
|
|
|
const
|
|
|
|
snappy_implementation {.strdefine.} = "libp2p"
|
|
|
|
|
|
|
|
const useNativeSnappy = when snappy_implementation == "native": true
|
|
|
|
elif snappy_implementation == "libp2p": false
|
|
|
|
else: {.fatal: "Please set snappy_implementation to either 'libp2p' or 'native'".}
|
2020-05-06 22:24:55 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
template libp2pProtocol*(name: string, version: int) {.pragma.}
|
|
|
|
|
|
|
|
template `$`*(peer: Peer): string = id(peer.info)
|
|
|
|
chronicles.formatIt(Peer): $it
|
|
|
|
|
|
|
|
template remote*(peer: Peer): untyped =
|
|
|
|
peer.info.peerId
|
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
proc openStream(node: Eth2Node,
|
|
|
|
peer: Peer,
|
|
|
|
protocolId: string): Future[Connection] {.async.} =
|
|
|
|
let protocolId = protocolId & (if peer.lacksSnappy: "ssz" else: "ssz_snappy")
|
|
|
|
try:
|
|
|
|
result = await dial(node.switch, peer.info, protocolId)
|
|
|
|
except CancelledError:
|
|
|
|
raise
|
|
|
|
except CatchableError:
|
|
|
|
# TODO: LibP2P should raise a more specific exception here
|
|
|
|
if peer.lacksSnappy == false:
|
|
|
|
peer.lacksSnappy = true
|
|
|
|
trace "Snappy connection failed. Trying without Snappy",
|
|
|
|
peer, protocolId
|
|
|
|
return await openStream(node, peer, protocolId)
|
|
|
|
else:
|
|
|
|
raise
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-03-22 23:23:21 +00:00
|
|
|
func peerId(conn: Connection): PeerID =
|
2020-03-22 21:55:01 +00:00
|
|
|
# TODO: Can this be `nil`?
|
2020-03-22 23:23:21 +00:00
|
|
|
conn.peerInfo.peerId
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc init*(T: type Peer, network: Eth2Node, info: PeerInfo): Peer {.gcsafe.}
|
|
|
|
|
|
|
|
proc getPeer*(node: Eth2Node, peerInfo: PeerInfo): Peer {.gcsafe.} =
|
|
|
|
let peerId = peerInfo.peerId
|
|
|
|
result = node.peerPool.getOrDefault(peerId)
|
|
|
|
if result == nil:
|
2020-03-22 23:23:21 +00:00
|
|
|
# TODO: We should register this peer in the pool!
|
2020-03-22 21:55:01 +00:00
|
|
|
result = Peer.init(node, peerInfo)
|
|
|
|
|
2020-03-22 23:23:21 +00:00
|
|
|
proc peerFromStream(network: Eth2Node, conn: Connection): Peer {.gcsafe.} =
|
2020-03-22 21:55:01 +00:00
|
|
|
# TODO: Can this be `nil`?
|
2020-03-22 23:23:21 +00:00
|
|
|
return network.getPeer(conn.peerInfo)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc getKey*(peer: Peer): PeerID {.inline.} =
|
|
|
|
result = peer.info.peerId
|
|
|
|
|
|
|
|
proc getFuture*(peer: Peer): Future[void] {.inline.} =
|
|
|
|
result = peer.info.lifeFuture()
|
|
|
|
|
|
|
|
proc `<`*(a, b: Peer): bool =
|
|
|
|
result = `<`(a.score, b.score)
|
|
|
|
|
2020-04-20 14:59:18 +00:00
|
|
|
proc getScore*(a: Peer): int =
|
|
|
|
result = a.score
|
|
|
|
|
2020-05-28 05:02:28 +00:00
|
|
|
proc updateScore*(peer: Peer, score: int) {.inline.} =
|
2020-04-23 15:31:00 +00:00
|
|
|
## Update peer's ``peer`` score with value ``score``.
|
|
|
|
peer.score = peer.score + score
|
2020-05-28 05:02:28 +00:00
|
|
|
if peer.score > PeerScoreHighLimit:
|
|
|
|
peer.score = PeerScoreHighLimit
|
2020-04-23 15:31:00 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
proc disconnect*(peer: Peer, reason: DisconnectionReason,
|
|
|
|
notifyOtherPeer = false) {.async.} =
|
|
|
|
# TODO: How should we notify the other peer?
|
|
|
|
if peer.connectionState notin {Disconnecting, Disconnected}:
|
|
|
|
peer.connectionState = Disconnecting
|
|
|
|
await peer.network.switch.disconnect(peer.info)
|
|
|
|
peer.connectionState = Disconnected
|
|
|
|
peer.network.peerPool.release(peer)
|
|
|
|
peer.info.close()
|
|
|
|
|
|
|
|
include eth/p2p/p2p_backends_helpers
|
|
|
|
include eth/p2p/p2p_tracing
|
|
|
|
|
|
|
|
proc getRequestProtoName(fn: NimNode): NimNode =
|
|
|
|
# `getCustomPragmaVal` doesn't work yet on regular nnkProcDef nodes
|
|
|
|
# (TODO: file as an issue)
|
|
|
|
|
|
|
|
let pragmas = fn.pragma
|
|
|
|
if pragmas.kind == nnkPragma and pragmas.len > 0:
|
|
|
|
for pragma in pragmas:
|
|
|
|
if pragma.len > 0 and $pragma[0] == "libp2pProtocol":
|
|
|
|
let protoName = $(pragma[1])
|
|
|
|
let protoVer = $(pragma[2].intVal)
|
2020-04-15 02:41:22 +00:00
|
|
|
return newLit("/eth2/beacon_chain/req/" & protoName & "/" & protoVer & "/")
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
return newLit("")
|
|
|
|
|
|
|
|
template raisePeerDisconnected(msg: string, r: DisconnectionReason) =
|
|
|
|
var e = newException(PeerDisconnected, msg)
|
|
|
|
e.reason = r
|
|
|
|
raise e
|
|
|
|
|
|
|
|
proc disconnectAndRaise(peer: Peer,
|
|
|
|
reason: DisconnectionReason,
|
|
|
|
msg: string) {.async.} =
|
|
|
|
let r = reason
|
|
|
|
await peer.disconnect(r)
|
|
|
|
raisePeerDisconnected(msg, r)
|
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
proc writeChunk*(conn: Connection,
|
|
|
|
responseCode: Option[ResponseCode],
|
|
|
|
payload: Bytes,
|
|
|
|
noSnappy: bool) {.async.} =
|
|
|
|
var output = memoryOutput()
|
|
|
|
|
|
|
|
if responseCode.isSome:
|
|
|
|
output.write byte(responseCode.get)
|
|
|
|
|
|
|
|
output.write varintBytes(payload.len.uint64)
|
|
|
|
|
|
|
|
if noSnappy:
|
|
|
|
output.write(payload)
|
|
|
|
else:
|
|
|
|
output.write(framingFormatCompress payload)
|
|
|
|
|
|
|
|
await conn.write(output.getOutput)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-21 13:21:29 +00:00
|
|
|
template errorMsgLit(x: static string): ErrorMsg =
|
|
|
|
const val = ErrorMsg toBytes(x)
|
|
|
|
val
|
|
|
|
|
2020-06-04 06:19:25 +00:00
|
|
|
proc formatErrorMsg(msg: ErrorMSg): string =
|
|
|
|
let candidate = string.fromBytes(asSeq(msg))
|
|
|
|
for c in candidate:
|
|
|
|
# TODO UTF-8 - but let's start with ASCII
|
|
|
|
if ord(c) < 32 or ord(c) > 127:
|
|
|
|
return byteutils.toHex(asSeq(msg))
|
|
|
|
|
|
|
|
return candidate
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
proc sendErrorResponse(peer: Peer,
|
2020-03-22 23:23:21 +00:00
|
|
|
conn: Connection,
|
2020-05-12 22:37:07 +00:00
|
|
|
noSnappy: bool,
|
2020-03-22 21:55:01 +00:00
|
|
|
responseCode: ResponseCode,
|
2020-05-21 13:21:29 +00:00
|
|
|
errMsg: ErrorMsg) {.async.} =
|
2020-06-04 06:19:25 +00:00
|
|
|
debug "Error processing request",
|
|
|
|
peer, responseCode, errMsg = formatErrorMsg(errMsg)
|
2020-05-12 22:37:07 +00:00
|
|
|
await conn.writeChunk(some responseCode, SSZ.encode(errMsg), noSnappy)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc sendNotificationMsg(peer: Peer, protocolId: string, requestBytes: Bytes) {.async} =
|
2020-04-15 02:41:22 +00:00
|
|
|
var
|
|
|
|
deadline = sleepAsync RESP_TIMEOUT
|
|
|
|
streamFut = peer.network.openStream(peer, protocolId)
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
await streamFut or deadline
|
2020-04-15 02:41:22 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
if not streamFut.finished:
|
2020-04-15 02:41:22 +00:00
|
|
|
streamFut.cancel()
|
2020-03-22 21:55:01 +00:00
|
|
|
raise newException(TransmissionError, "Failed to open LibP2P stream")
|
|
|
|
|
|
|
|
let stream = streamFut.read
|
2020-04-14 16:49:46 +00:00
|
|
|
try:
|
2020-05-12 22:37:07 +00:00
|
|
|
await stream.writeChunk(none ResponseCode, requestBytes, peer.lacksSnappy)
|
2020-04-14 16:49:46 +00:00
|
|
|
finally:
|
2020-03-22 21:55:01 +00:00
|
|
|
await safeClose(stream)
|
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
proc sendResponseChunkBytes(response: UntypedResponse, payload: Bytes) {.async.} =
|
|
|
|
inc response.writtenChunks
|
|
|
|
await response.stream.writeChunk(some Success, payload, response.noSnappy)
|
|
|
|
|
|
|
|
proc sendResponseChunkObj(response: UntypedResponse, val: auto) {.async.} =
|
|
|
|
inc response.writtenChunks
|
|
|
|
await response.stream.writeChunk(some Success, SSZ.encode(val), response.noSnappy)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
template sendUserHandlerResultAsChunkImpl*(stream: Connection,
|
|
|
|
noSnappy: bool,
|
|
|
|
handlerResultFut: Future): untyped =
|
|
|
|
let handlerRes = await handlerResultFut
|
|
|
|
writeChunk(stream, some Success, SSZ.encode(handlerRes), noSnappy)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
template sendUserHandlerResultAsChunkImpl*(stream: Connection,
|
|
|
|
noSnappy: bool,
|
|
|
|
handlerResult: auto): untyped =
|
|
|
|
writeChunk(stream, some Success, SSZ.encode(handlerResult), noSnappy)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-12 22:35:40 +00:00
|
|
|
when useNativeSnappy:
|
|
|
|
include faststreams_backend
|
|
|
|
else:
|
|
|
|
include libp2p_streams_backend
|
|
|
|
|
|
|
|
template awaitWithTimeout[T](operation: Future[T],
|
|
|
|
deadline: Future[void],
|
|
|
|
onTimeout: untyped): T =
|
|
|
|
let f = operation
|
|
|
|
await f or deadline
|
|
|
|
if not f.finished:
|
|
|
|
cancel f
|
|
|
|
onTimeout
|
|
|
|
else:
|
|
|
|
f.read
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
proc makeEth2Request(peer: Peer, protocolId: string, requestBytes: Bytes,
|
|
|
|
ResponseMsg: type,
|
2020-05-12 22:37:07 +00:00
|
|
|
timeout: Duration): Future[NetRes[ResponseMsg]]
|
|
|
|
{.gcsafe, async.} =
|
|
|
|
var deadline = sleepAsync timeout
|
2020-05-06 22:24:55 +00:00
|
|
|
|
2020-05-12 22:35:40 +00:00
|
|
|
let stream = awaitWithTimeout(peer.network.openStream(peer, protocolId),
|
2020-05-12 22:37:07 +00:00
|
|
|
deadline): return neterr StreamOpenTimeout
|
2020-04-14 16:49:46 +00:00
|
|
|
try:
|
|
|
|
# Send the request
|
2020-05-12 22:37:07 +00:00
|
|
|
await stream.writeChunk(none ResponseCode, requestBytes, peer.lacksSnappy)
|
2020-04-14 16:49:46 +00:00
|
|
|
|
|
|
|
# Read the response
|
2020-05-12 22:37:07 +00:00
|
|
|
return awaitWithTimeout(
|
|
|
|
readResponse(when useNativeSnappy: libp2pInput(stream)
|
|
|
|
else: stream,
|
|
|
|
peer.lacksSnappy,
|
|
|
|
ResponseMsg),
|
|
|
|
deadline, neterr(ReadResponseTimeout))
|
2020-04-14 16:49:46 +00:00
|
|
|
finally:
|
2020-03-22 21:55:01 +00:00
|
|
|
await safeClose(stream)
|
|
|
|
|
2020-05-23 22:24:47 +00:00
|
|
|
proc init*[MsgType](T: type MultipleChunksResponse[MsgType],
|
2020-05-12 22:37:07 +00:00
|
|
|
peer: Peer, conn: Connection, noSnappy: bool): T =
|
2020-05-23 22:24:47 +00:00
|
|
|
T(UntypedResponse(peer: peer, stream: conn, noSnappy: noSnappy))
|
|
|
|
|
|
|
|
proc init*[MsgType](T: type SingleChunkResponse[MsgType],
|
|
|
|
peer: Peer, conn: Connection, noSnappy: bool): T =
|
|
|
|
T(UntypedResponse(peer: peer, stream: conn, noSnappy: noSnappy))
|
|
|
|
|
|
|
|
template write*[M](r: MultipleChunksResponse[M], val: M): untyped =
|
|
|
|
sendResponseChunkObj(UntypedResponse(r), val)
|
|
|
|
|
|
|
|
template send*[M](r: SingleChunkResponse[M], val: auto): untyped =
|
|
|
|
doAssert UntypedResponse(r).writtenChunks == 0
|
|
|
|
sendResponseChunkObj(UntypedResponse(r), val)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc performProtocolHandshakes*(peer: Peer) {.async.} =
|
|
|
|
var subProtocolsHandshakes = newSeqOfCap[Future[void]](allProtocols.len)
|
|
|
|
for protocol in allProtocols:
|
|
|
|
if protocol.handshake != nil:
|
|
|
|
subProtocolsHandshakes.add((protocol.handshake)(peer, nil))
|
|
|
|
|
2020-03-24 11:13:07 +00:00
|
|
|
await allFuturesThrowing(subProtocolsHandshakes)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
template initializeConnection*(peer: Peer): auto =
|
|
|
|
performProtocolHandshakes(peer)
|
|
|
|
|
|
|
|
proc initProtocol(name: string,
|
|
|
|
peerInit: PeerStateInitializer,
|
|
|
|
networkInit: NetworkStateInitializer): ProtocolInfoObj =
|
|
|
|
result.name = name
|
|
|
|
result.messages = @[]
|
|
|
|
result.peerStateInitializer = peerInit
|
|
|
|
result.networkStateInitializer = networkInit
|
|
|
|
|
|
|
|
proc registerProtocol(protocol: ProtocolInfo) =
|
|
|
|
# TODO: This can be done at compile-time in the future
|
|
|
|
let pos = lowerBound(gProtocols, protocol)
|
|
|
|
gProtocols.insert(protocol, pos)
|
|
|
|
for i in 0 ..< gProtocols.len:
|
|
|
|
gProtocols[i].index = i
|
|
|
|
|
|
|
|
proc setEventHandlers(p: ProtocolInfo,
|
|
|
|
handshake: HandshakeStep,
|
|
|
|
disconnectHandler: DisconnectionHandler) =
|
|
|
|
p.handshake = handshake
|
|
|
|
p.disconnectHandler = disconnectHandler
|
|
|
|
|
|
|
|
proc implementSendProcBody(sendProc: SendProc) =
|
|
|
|
let
|
|
|
|
msg = sendProc.msg
|
2020-05-23 22:24:47 +00:00
|
|
|
UntypedResponse = bindSym "UntypedResponse"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc sendCallGenerator(peer, bytes: NimNode): NimNode =
|
|
|
|
if msg.kind != msgResponse:
|
|
|
|
let msgProto = getRequestProtoName(msg.procDef)
|
|
|
|
case msg.kind
|
|
|
|
of msgRequest:
|
2020-05-23 22:24:47 +00:00
|
|
|
let ResponseRecord = msg.response.recName
|
2020-03-22 21:55:01 +00:00
|
|
|
quote:
|
|
|
|
makeEth2Request(`peer`, `msgProto`, `bytes`,
|
2020-05-23 22:24:47 +00:00
|
|
|
`ResponseRecord`, `timeoutVar`)
|
2020-03-22 21:55:01 +00:00
|
|
|
else:
|
|
|
|
quote: sendNotificationMsg(`peer`, `msgProto`, `bytes`)
|
|
|
|
else:
|
2020-05-23 22:24:47 +00:00
|
|
|
quote: sendResponseChunkBytes(`UntypedResponse`(`peer`), `bytes`)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
sendProc.useStandardBody(nil, nil, sendCallGenerator)
|
|
|
|
|
2020-05-06 22:24:55 +00:00
|
|
|
proc handleIncomingStream(network: Eth2Node,
|
|
|
|
conn: Connection,
|
2020-05-12 22:37:07 +00:00
|
|
|
noSnappy: bool,
|
2020-05-06 22:24:55 +00:00
|
|
|
MsgType: type) {.async, gcsafe.} =
|
2020-03-22 21:55:01 +00:00
|
|
|
mixin callUserHandler, RecType
|
2020-05-12 22:35:40 +00:00
|
|
|
|
|
|
|
type MsgRec = RecType(MsgType)
|
2020-05-15 12:41:00 +00:00
|
|
|
const msgName {.used.} = typetraits.name(MsgType)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
## Uncomment this to enable tracing on all incoming requests
|
|
|
|
## You can include `msgNameLit` in the condition to select
|
|
|
|
## more specific requests:
|
|
|
|
# when chronicles.runtimeFilteringEnabled:
|
|
|
|
# setLogLevel(LogLevel.TRACE)
|
|
|
|
# defer: setLogLevel(LogLevel.DEBUG)
|
2020-03-22 23:23:21 +00:00
|
|
|
# trace "incoming " & `msgNameLit` & " conn"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
try:
|
2020-05-06 22:24:55 +00:00
|
|
|
let peer = peerFromStream(network, conn)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-21 13:21:29 +00:00
|
|
|
template returnInvalidRequest(msg: ErrorMsg) =
|
2020-05-12 22:37:07 +00:00
|
|
|
await sendErrorResponse(peer, conn, noSnappy, InvalidRequest, msg)
|
|
|
|
return
|
2020-05-06 22:24:55 +00:00
|
|
|
|
2020-05-21 13:21:29 +00:00
|
|
|
template returnInvalidRequest(msg: string) =
|
|
|
|
returnInvalidRequest(ErrorMsg msg.toBytes)
|
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
let s = when useNativeSnappy:
|
|
|
|
let fs = libp2pInput(conn)
|
2020-04-14 16:49:46 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
if fs.timeoutToNextByte(TTFB_TIMEOUT):
|
2020-05-21 13:21:29 +00:00
|
|
|
returnInvalidRequest(errorMsgLit "Request first byte not sent in time")
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
fs
|
|
|
|
else:
|
|
|
|
# TODO The TTFB timeout is not implemented in LibP2P streams back-end
|
|
|
|
conn
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
let deadline = sleepAsync RESP_TIMEOUT
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-15 17:56:34 +00:00
|
|
|
let msg = if sizeof(MsgRec) > 0:
|
|
|
|
try:
|
|
|
|
awaitWithTimeout(readChunkPayload(s, noSnappy, MsgRec), deadline):
|
2020-05-21 13:21:29 +00:00
|
|
|
returnInvalidRequest(errorMsgLit "Request full data not sent in time")
|
2020-05-06 22:24:55 +00:00
|
|
|
|
2020-05-15 17:56:34 +00:00
|
|
|
except SerializationError as err:
|
|
|
|
returnInvalidRequest err.formatMsg("msg")
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-15 17:56:34 +00:00
|
|
|
except SnappyError as err:
|
|
|
|
returnInvalidRequest err.msg
|
|
|
|
else:
|
|
|
|
NetRes[MsgRec].ok default(MsgRec)
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
if msg.isErr:
|
|
|
|
let (responseCode, errMsg) = case msg.error.kind
|
|
|
|
of UnexpectedEOF, PotentiallyExpectedEOF:
|
2020-05-21 13:21:29 +00:00
|
|
|
(InvalidRequest, errorMsgLit "Incomplete request")
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
of InvalidSnappyBytes:
|
2020-05-21 13:21:29 +00:00
|
|
|
(InvalidRequest, errorMsgLit "Failed to decompress snappy payload")
|
2020-05-12 22:35:40 +00:00
|
|
|
|
2020-05-12 22:37:07 +00:00
|
|
|
of InvalidSszBytes:
|
2020-05-21 13:21:29 +00:00
|
|
|
(InvalidRequest, errorMsgLit "Failed to decode SSZ payload")
|
2020-05-12 22:37:07 +00:00
|
|
|
|
|
|
|
of ZeroSizePrefix:
|
2020-05-21 13:21:29 +00:00
|
|
|
(InvalidRequest, errorMsgLit "The request chunk cannot have a size of zero")
|
2020-05-12 22:37:07 +00:00
|
|
|
|
|
|
|
of SizePrefixOverflow:
|
2020-05-21 13:21:29 +00:00
|
|
|
(InvalidRequest, errorMsgLit "The chunk size exceed the maximum allowed")
|
2020-05-12 22:37:07 +00:00
|
|
|
|
|
|
|
of InvalidResponseCode, ReceivedErrorResponse,
|
|
|
|
StreamOpenTimeout, ReadResponseTimeout:
|
|
|
|
# These shouldn't be possible in a request, because
|
|
|
|
# there are no response codes being read, no stream
|
|
|
|
# openings and no reading of responses:
|
2020-05-21 13:21:29 +00:00
|
|
|
(ServerError, errorMsgLit "Internal server error")
|
2020-05-12 22:37:07 +00:00
|
|
|
|
|
|
|
of BrokenConnection:
|
|
|
|
return
|
|
|
|
|
|
|
|
await sendErrorResponse(peer, conn, noSnappy, responseCode, errMsg)
|
|
|
|
return
|
|
|
|
|
|
|
|
try:
|
|
|
|
logReceivedMsg(peer, MsgType(msg.get))
|
2020-05-26 17:07:18 +00:00
|
|
|
await callUserHandler(MsgType, peer, conn, noSnappy, msg.get)
|
2020-05-12 22:37:07 +00:00
|
|
|
except CatchableError as err:
|
2020-05-21 13:21:29 +00:00
|
|
|
await sendErrorResponse(peer, conn, noSnappy, ServerError,
|
|
|
|
ErrorMsg err.msg.toBytes)
|
2020-05-06 22:24:55 +00:00
|
|
|
|
|
|
|
except CatchableError as err:
|
2020-05-15 17:56:34 +00:00
|
|
|
debug "Error processing an incoming request", err = err.msg, msgName
|
2020-05-06 22:24:55 +00:00
|
|
|
|
2020-04-14 16:49:46 +00:00
|
|
|
finally:
|
|
|
|
await safeClose(conn)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
proc handleOutgoingPeer*(peer: Peer): Future[bool] {.async.} =
|
2020-03-22 21:55:01 +00:00
|
|
|
let network = peer.network
|
|
|
|
|
|
|
|
proc onPeerClosed(udata: pointer) {.gcsafe.} =
|
|
|
|
debug "Peer (outgoing) lost", peer = $peer.info
|
|
|
|
libp2p_peers.set int64(len(network.peerPool))
|
|
|
|
|
|
|
|
let res = await network.peerPool.addOutgoingPeer(peer)
|
|
|
|
if res:
|
2020-04-23 15:31:00 +00:00
|
|
|
peer.updateScore(NewPeerScore)
|
2020-03-22 21:55:01 +00:00
|
|
|
debug "Peer (outgoing) has been added to PeerPool", peer = $peer.info
|
|
|
|
peer.getFuture().addCallback(onPeerClosed)
|
2020-05-13 06:37:58 +00:00
|
|
|
result = true
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
libp2p_peers.set int64(len(network.peerPool))
|
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
proc handleIncomingPeer*(peer: Peer): Future[bool] {.async.} =
|
2020-03-22 21:55:01 +00:00
|
|
|
let network = peer.network
|
|
|
|
|
|
|
|
proc onPeerClosed(udata: pointer) {.gcsafe.} =
|
|
|
|
debug "Peer (incoming) lost", peer = $peer.info
|
|
|
|
libp2p_peers.set int64(len(network.peerPool))
|
|
|
|
|
2020-05-13 06:37:58 +00:00
|
|
|
let res = await network.peerPool.addIncomingPeer(peer)
|
2020-03-22 21:55:01 +00:00
|
|
|
if res:
|
2020-04-23 15:31:00 +00:00
|
|
|
peer.updateScore(NewPeerScore)
|
2020-03-22 21:55:01 +00:00
|
|
|
debug "Peer (incoming) has been added to PeerPool", peer = $peer.info
|
|
|
|
peer.getFuture().addCallback(onPeerClosed)
|
2020-05-13 06:37:58 +00:00
|
|
|
result = true
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
libp2p_peers.set int64(len(network.peerPool))
|
|
|
|
|
|
|
|
proc toPeerInfo*(r: enr.TypedRecord): PeerInfo =
|
|
|
|
if r.secp256k1.isSome:
|
2020-04-05 09:50:31 +00:00
|
|
|
var pubKey = keys.PublicKey.fromRaw(r.secp256k1.get)
|
|
|
|
if pubkey.isErr:
|
2020-03-22 21:55:01 +00:00
|
|
|
return # TODO
|
|
|
|
|
2020-04-03 09:12:38 +00:00
|
|
|
let peerId = PeerID.init crypto.PublicKey(
|
2020-04-17 13:29:49 +00:00
|
|
|
scheme: Secp256k1, skkey: secp.SkPublicKey(pubKey[]))
|
2020-03-22 21:55:01 +00:00
|
|
|
var addresses = newSeq[MultiAddress]()
|
|
|
|
|
|
|
|
if r.ip.isSome and r.tcp.isSome:
|
2020-06-05 15:08:50 +00:00
|
|
|
let ip = ipv4(r.ip.get)
|
|
|
|
addresses.add MultiAddress.init(ip, tcpProtocol, Port r.tcp.get)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
if r.ip6.isSome:
|
2020-06-05 15:08:50 +00:00
|
|
|
let ip = ipv6(r.ip6.get)
|
2020-03-22 21:55:01 +00:00
|
|
|
if r.tcp6.isSome:
|
2020-06-05 15:08:50 +00:00
|
|
|
addresses.add MultiAddress.init(ip, tcpProtocol, Port r.tcp6.get)
|
2020-03-22 21:55:01 +00:00
|
|
|
elif r.tcp.isSome:
|
2020-06-05 15:08:50 +00:00
|
|
|
addresses.add MultiAddress.init(ip, tcpProtocol, Port r.tcp.get)
|
2020-03-22 21:55:01 +00:00
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
if addresses.len > 0:
|
|
|
|
return PeerInfo.init(peerId, addresses)
|
|
|
|
|
|
|
|
proc toPeerInfo(r: Option[enr.TypedRecord]): PeerInfo =
|
|
|
|
if r.isSome:
|
|
|
|
return r.get.toPeerInfo
|
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
proc isSeen*(network: ETh2Node, pinfo: PeerInfo): bool =
|
|
|
|
let currentTime = now(chronos.Moment)
|
|
|
|
let item = network.seenTable.getOrDefault(pinfo.peerId)
|
|
|
|
if isNil(item.pinfo):
|
|
|
|
# Peer is not in SeenTable.
|
|
|
|
return false
|
|
|
|
if currentTime - item.stamp >= network.seenThreshold:
|
|
|
|
network.seenTable.del(pinfo.peerId)
|
|
|
|
return false
|
|
|
|
return true
|
|
|
|
|
|
|
|
proc addSeen*(network: ETh2Node, pinfo: PeerInfo) =
|
|
|
|
let item = SeenItem(pinfo: pinfo, stamp: now(chronos.Moment))
|
|
|
|
network.seenTable[pinfo.peerId] = item
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
proc dialPeer*(node: Eth2Node, peerInfo: PeerInfo) {.async.} =
|
|
|
|
logScope: peer = $peerInfo
|
|
|
|
|
|
|
|
debug "Connecting to peer"
|
2020-06-03 08:46:29 +00:00
|
|
|
await node.switch.connect(peerInfo)
|
|
|
|
var peer = node.getPeer(peerInfo)
|
|
|
|
peer.wasDialed = true
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
#let msDial = newMultistream()
|
|
|
|
#let conn = node.switch.connections.getOrDefault(peerInfo.id)
|
|
|
|
#let ls = await msDial.list(conn)
|
|
|
|
#debug "Supported protocols", ls
|
2020-04-27 22:39:04 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
debug "Initializing connection"
|
|
|
|
await initializeConnection(peer)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
inc libp2p_successful_dials
|
|
|
|
debug "Network handshakes completed"
|
|
|
|
|
|
|
|
proc connectWorker(network: Eth2Node) {.async.} =
|
|
|
|
debug "Connection worker started"
|
|
|
|
while true:
|
|
|
|
let pi = await network.connQueue.popFirst()
|
|
|
|
let r1 = network.peerPool.hasPeer(pi.peerId)
|
|
|
|
let r2 = network.isSeen(pi)
|
|
|
|
|
|
|
|
if not(r1) and not(r2):
|
|
|
|
# We trying to connect to peers which are not present in our PeerPool and
|
|
|
|
# not present in our SeenTable.
|
|
|
|
var fut = network.dialPeer(pi)
|
|
|
|
# We discarding here just because we going to check future state, to avoid
|
|
|
|
# condition where connection happens and timeout reached.
|
|
|
|
let res = await withTimeout(fut, network.connectTimeout)
|
|
|
|
# We handling only timeout and errors, because successfull connections
|
|
|
|
# will be stored in PeerPool.
|
|
|
|
if fut.finished():
|
|
|
|
if fut.failed() and not(fut.cancelled()):
|
|
|
|
debug "Unable to establish connection with peer", peer = $pi,
|
|
|
|
errMsg = fut.readError().msg
|
|
|
|
inc libp2p_failed_dials
|
|
|
|
network.addSeen(pi)
|
2020-06-03 10:48:01 +00:00
|
|
|
continue
|
2020-06-03 08:46:29 +00:00
|
|
|
debug "Connection to remote peer timed out", peer = $pi
|
|
|
|
inc libp2p_timeout_dials
|
|
|
|
network.addSeen(pi)
|
|
|
|
else:
|
|
|
|
debug "Peer is already connected or already seen", peer = $pi,
|
|
|
|
peer_pool_has_peer = $r1, seen_table_has_peer = $r2,
|
|
|
|
seen_table_size = len(network.seenTable)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc runDiscoveryLoop*(node: Eth2Node) {.async.} =
|
|
|
|
debug "Starting discovery loop"
|
|
|
|
|
|
|
|
while true:
|
|
|
|
let currentPeerCount = node.peerPool.len
|
|
|
|
if currentPeerCount < node.wantedPeers:
|
|
|
|
try:
|
|
|
|
let discoveredPeers =
|
|
|
|
node.discovery.randomNodes(node.wantedPeers - currentPeerCount)
|
|
|
|
for peer in discoveredPeers:
|
|
|
|
try:
|
2020-05-29 10:03:29 +00:00
|
|
|
let peerRecord = peer.record.toTypedRecord
|
|
|
|
if peerRecord.isOk:
|
|
|
|
let peerInfo = peerRecord.value.toPeerInfo
|
|
|
|
if peerInfo != nil:
|
|
|
|
if peerInfo.id notin node.switch.connections:
|
|
|
|
debug "Discovered new peer", peer = $peer
|
2020-06-03 08:46:29 +00:00
|
|
|
await node.connQueue.addLast(peerInfo)
|
2020-05-29 10:03:29 +00:00
|
|
|
else:
|
|
|
|
peerInfo.close()
|
2020-03-22 21:55:01 +00:00
|
|
|
except CatchableError as err:
|
|
|
|
debug "Failed to connect to peer", peer = $peer, err = err.msg
|
|
|
|
except CatchableError as err:
|
|
|
|
debug "Failure in discovery", err = err.msg
|
|
|
|
|
|
|
|
await sleepAsync seconds(1)
|
|
|
|
|
2020-04-15 02:41:22 +00:00
|
|
|
proc getPersistentNetMetadata*(conf: BeaconNodeConf): Eth2Metadata =
|
|
|
|
let metadataPath = conf.dataDir / nodeMetadataFilename
|
|
|
|
if not fileExists(metadataPath):
|
|
|
|
result = Eth2Metadata()
|
|
|
|
for i in 0 ..< ATTESTATION_SUBNET_COUNT:
|
|
|
|
# TODO: For now, we indicate that we participate in all subnets
|
|
|
|
result.attnets[i] = true
|
|
|
|
Json.saveFile(metadataPath, result)
|
|
|
|
else:
|
|
|
|
result = Json.loadFile(metadataPath, Eth2Metadata)
|
|
|
|
|
|
|
|
proc init*(T: type Eth2Node, conf: BeaconNodeConf, enrForkId: ENRForkID,
|
2020-06-05 15:08:50 +00:00
|
|
|
switch: Switch, ip: Option[ValidIpAddress], tcpPort, udpPort: Port,
|
2020-03-31 10:02:13 +00:00
|
|
|
privKey: keys.PrivateKey): T =
|
2020-03-22 21:55:01 +00:00
|
|
|
new result
|
|
|
|
result.switch = switch
|
|
|
|
result.wantedPeers = conf.maxPeers
|
|
|
|
result.peerPool = newPeerPool[Peer, PeerID](maxPeers = conf.maxPeers)
|
2020-06-03 08:46:29 +00:00
|
|
|
result.connectTimeout = 10.seconds
|
|
|
|
result.seenThreshold = 10.minutes
|
|
|
|
result.seenTable = initTable[PeerID, SeenItem]()
|
|
|
|
result.connQueue = newAsyncQueue[PeerInfo](ConcurrentConnections)
|
2020-04-15 02:41:22 +00:00
|
|
|
result.metadata = getPersistentNetMetadata(conf)
|
|
|
|
result.discovery = Eth2DiscoveryProtocol.new(
|
|
|
|
conf, ip, tcpPort, udpPort, privKey.toRaw,
|
|
|
|
{"eth2": SSZ.encode(enrForkId), "attnets": SSZ.encode(result.metadata.attnets)})
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
newSeq result.protocolStates, allProtocols.len
|
|
|
|
for proto in allProtocols:
|
|
|
|
if proto.networkStateInitializer != nil:
|
|
|
|
result.protocolStates[proto.index] = proto.networkStateInitializer(result)
|
|
|
|
|
|
|
|
for msg in proto.messages:
|
|
|
|
if msg.protocolMounter != nil:
|
|
|
|
msg.protocolMounter result
|
|
|
|
|
2020-06-03 08:46:29 +00:00
|
|
|
for i in 0 ..< ConcurrentConnections:
|
|
|
|
result.connWorkers.add(connectWorker(result))
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
template publicKey*(node: Eth2Node): keys.PublicKey =
|
2020-04-05 09:50:31 +00:00
|
|
|
node.discovery.privKey.toPublicKey.tryGet()
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-29 10:03:29 +00:00
|
|
|
template addKnownPeer*(node: Eth2Node, peer: enr.Record) =
|
2020-03-22 21:55:01 +00:00
|
|
|
node.discovery.addNode peer
|
|
|
|
|
|
|
|
proc start*(node: Eth2Node) {.async.} =
|
|
|
|
node.discovery.open()
|
2020-03-24 09:54:17 +00:00
|
|
|
node.discovery.start()
|
2020-03-22 21:55:01 +00:00
|
|
|
node.libp2pTransportLoops = await node.switch.start()
|
2020-03-24 11:13:07 +00:00
|
|
|
node.discoveryLoop = node.runDiscoveryLoop()
|
|
|
|
traceAsyncErrors node.discoveryLoop
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-05-19 18:57:35 +00:00
|
|
|
proc stop*(node: Eth2Node) {.async.} =
|
2020-05-28 01:14:01 +00:00
|
|
|
# Ignore errors in futures, since we're shutting down (but log them on the
|
|
|
|
# TRACE level, if a timeout is reached).
|
|
|
|
let
|
|
|
|
waitedFutures = @[
|
|
|
|
node.discovery.closeWait(),
|
|
|
|
node.switch.stop(),
|
|
|
|
]
|
|
|
|
timeout = 5.seconds
|
|
|
|
completed = await withTimeout(allFutures(waitedFutures), timeout)
|
|
|
|
if not completed:
|
|
|
|
trace "Eth2Node.stop(): timeout reached", timeout, futureErrors = waitedFutures.filterIt(it.error != nil).mapIt(it.error.msg)
|
2020-05-19 18:57:35 +00:00
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
proc init*(T: type Peer, network: Eth2Node, info: PeerInfo): Peer =
|
|
|
|
new result
|
|
|
|
result.info = info
|
|
|
|
result.network = network
|
|
|
|
result.connectionState = Connected
|
|
|
|
result.maxInactivityAllowed = 15.minutes # TODO: Read this from the config
|
|
|
|
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)
|
|
|
|
|
|
|
|
proc registerMsg(protocol: ProtocolInfo,
|
|
|
|
name: string,
|
|
|
|
mounter: MounterProc,
|
2020-03-22 23:23:21 +00:00
|
|
|
libp2pCodecName: string) =
|
2020-03-22 21:55:01 +00:00
|
|
|
protocol.messages.add MessageInfo(name: name,
|
|
|
|
protocolMounter: mounter,
|
2020-03-22 23:23:21 +00:00
|
|
|
libp2pCodecName: libp2pCodecName)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
proc p2pProtocolBackendImpl*(p: P2PProtocol): Backend =
|
|
|
|
var
|
|
|
|
Format = ident "SSZ"
|
2020-05-12 22:37:07 +00:00
|
|
|
Bool = bindSym "bool"
|
2020-03-22 23:23:21 +00:00
|
|
|
Connection = bindSym "Connection"
|
2020-03-22 21:55:01 +00:00
|
|
|
Peer = bindSym "Peer"
|
|
|
|
Eth2Node = bindSym "Eth2Node"
|
|
|
|
registerMsg = bindSym "registerMsg"
|
|
|
|
initProtocol = bindSym "initProtocol"
|
|
|
|
msgVar = ident "msg"
|
|
|
|
networkVar = ident "network"
|
|
|
|
callUserHandler = ident "callUserHandler"
|
2020-05-12 22:37:07 +00:00
|
|
|
noSnappyVar = ident "noSnappy"
|
2020-05-23 22:24:47 +00:00
|
|
|
MSG = ident "MSG"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
p.useRequestIds = false
|
|
|
|
p.useSingleRecordInlining = true
|
|
|
|
|
|
|
|
new result
|
|
|
|
|
|
|
|
result.PeerType = Peer
|
|
|
|
result.NetworkType = Eth2Node
|
|
|
|
result.registerProtocol = bindSym "registerProtocol"
|
|
|
|
result.setEventHandlers = bindSym "setEventHandlers"
|
|
|
|
result.SerializationFormat = Format
|
2020-05-12 22:37:07 +00:00
|
|
|
result.RequestResultsWrapper = ident "NetRes"
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
result.afterProtocolInit = proc (p: P2PProtocol) =
|
2020-03-22 23:23:21 +00:00
|
|
|
p.onPeerConnected.params.add newIdentDefs(streamVar, Connection)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
result.implementMsg = proc (msg: p2p_protocol_dsl.Message) =
|
2020-05-23 22:24:47 +00:00
|
|
|
if msg.kind == msgResponse:
|
|
|
|
return
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
let
|
|
|
|
protocol = msg.protocol
|
|
|
|
msgName = $msg.ident
|
|
|
|
msgNameLit = newLit msgName
|
|
|
|
MsgRecName = msg.recName
|
|
|
|
MsgStrongRecName = msg.strongRecName
|
|
|
|
codecNameLit = getRequestProtoName(msg.procDef)
|
2020-05-26 17:07:18 +00:00
|
|
|
protocolMounterName = ident(msgName & "Mounter")
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
##
|
|
|
|
## Implement the Thunk:
|
|
|
|
##
|
2020-03-22 23:23:21 +00:00
|
|
|
## The protocol handlers in nim-libp2p receive only a `Connection`
|
2020-03-22 21:55:01 +00:00
|
|
|
## parameter and there is no way to access the wider context (such
|
|
|
|
## as the current `Switch`). In our handlers, we may need to list all
|
|
|
|
## peers in the current network, so we must keep a reference to the
|
|
|
|
## network object in the closure environment of the installed handlers.
|
|
|
|
##
|
|
|
|
## For this reason, we define a `protocol mounter` proc that will
|
|
|
|
## initialize the network object by creating handlers bound to the
|
|
|
|
## specific network.
|
|
|
|
##
|
2020-05-26 17:07:18 +00:00
|
|
|
var userHandlerCall = newTree(nnkDiscardStmt)
|
|
|
|
|
2020-03-22 21:55:01 +00:00
|
|
|
if msg.userHandler != nil:
|
2020-05-26 17:07:18 +00:00
|
|
|
var OutputParamType = if msg.kind == msgRequest: msg.outputParamType
|
|
|
|
else: nil
|
2020-05-23 22:24:47 +00:00
|
|
|
|
|
|
|
if OutputParamType == nil:
|
2020-05-26 17:07:18 +00:00
|
|
|
userHandlerCall = msg.genUserHandlerCall(msgVar, [peerVar])
|
|
|
|
if msg.kind == msgRequest:
|
|
|
|
userHandlerCall = newCall(ident"sendUserHandlerResultAsChunkImpl",
|
|
|
|
streamVar,
|
|
|
|
noSnappyVar,
|
|
|
|
userHandlerCall)
|
2020-05-23 22:24:47 +00:00
|
|
|
else:
|
|
|
|
if OutputParamType.kind == nnkVarTy:
|
|
|
|
OutputParamType = OutputParamType[0]
|
|
|
|
|
|
|
|
let isChunkStream = eqIdent(OutputParamType[0], "MultipleChunksResponse")
|
|
|
|
msg.response.recName = if isChunkStream:
|
|
|
|
newTree(nnkBracketExpr, ident"seq", OutputParamType[1])
|
|
|
|
else:
|
|
|
|
OutputParamType[1]
|
|
|
|
|
|
|
|
let responseVar = ident("response")
|
|
|
|
userHandlerCall = newStmtList(
|
|
|
|
newVarStmt(responseVar,
|
|
|
|
newCall(ident"init", OutputParamType,
|
|
|
|
peerVar, streamVar, noSnappyVar)),
|
|
|
|
msg.genUserHandlerCall(msgVar, [peerVar], outputParam = responseVar))
|
|
|
|
|
2020-05-26 17:07:18 +00:00
|
|
|
protocol.outRecvProcs.add quote do:
|
|
|
|
template `callUserHandler`(`MSG`: type `MsgStrongRecName`,
|
|
|
|
`peerVar`: `Peer`,
|
|
|
|
`streamVar`: `Connection`,
|
|
|
|
`noSnappyVar`: bool,
|
|
|
|
`msgVar`: `MsgRecName`): untyped =
|
|
|
|
`userHandlerCall`
|
|
|
|
|
|
|
|
proc `protocolMounterName`(`networkVar`: `Eth2Node`) =
|
|
|
|
proc sszThunk(`streamVar`: `Connection`,
|
|
|
|
`protocolVar`: string): Future[void] {.gcsafe.} =
|
|
|
|
return handleIncomingStream(`networkVar`, `streamVar`, true,
|
|
|
|
`MsgStrongRecName`)
|
|
|
|
|
|
|
|
mount `networkVar`.switch,
|
|
|
|
LPProtocol(codec: `codecNameLit` & "ssz",
|
|
|
|
handler: sszThunk)
|
|
|
|
|
|
|
|
proc snappyThunk(`streamVar`: `Connection`,
|
|
|
|
`protocolVar`: string): Future[void] {.gcsafe.} =
|
|
|
|
return handleIncomingStream(`networkVar`, `streamVar`, false,
|
|
|
|
`MsgStrongRecName`)
|
|
|
|
|
|
|
|
mount `networkVar`.switch,
|
|
|
|
LPProtocol(codec: `codecNameLit` & "ssz_snappy",
|
|
|
|
handler: snappyThunk)
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
##
|
|
|
|
## Implement Senders and Handshake
|
|
|
|
##
|
|
|
|
if msg.kind == msgHandshake:
|
|
|
|
macros.error "Handshake messages are not supported in LibP2P protocols"
|
|
|
|
else:
|
|
|
|
var sendProc = msg.createSendProc()
|
|
|
|
implementSendProcBody sendProc
|
|
|
|
|
|
|
|
protocol.outProcRegistrations.add(
|
|
|
|
newCall(registerMsg,
|
|
|
|
protocol.protocolInfoVar,
|
|
|
|
msgNameLit,
|
2020-05-26 17:07:18 +00:00
|
|
|
protocolMounterName,
|
2020-03-22 23:23:21 +00:00
|
|
|
codecNameLit))
|
2020-03-22 21:55:01 +00:00
|
|
|
|
|
|
|
result.implementProtocolInit = proc (p: P2PProtocol): NimNode =
|
|
|
|
return newCall(initProtocol, newLit(p.name), p.peerInit, p.netInit)
|
|
|
|
|
2020-06-05 15:08:50 +00:00
|
|
|
proc setupNat(conf: BeaconNodeConf): tuple[ip: Option[ValidIpAddress],
|
2019-06-12 18:22:05 +00:00
|
|
|
tcpPort: Port,
|
2020-03-24 16:06:36 +00:00
|
|
|
udpPort: Port] {.gcsafe.} =
|
2019-06-12 18:22:05 +00:00
|
|
|
# defaults
|
2020-03-22 21:55:01 +00:00
|
|
|
result.tcpPort = conf.tcpPort
|
|
|
|
result.udpPort = conf.udpPort
|
2019-06-12 18:22:05 +00:00
|
|
|
|
|
|
|
var nat: NatStrategy
|
|
|
|
case conf.nat.toLowerAscii:
|
|
|
|
of "any":
|
|
|
|
nat = NatAny
|
|
|
|
of "none":
|
|
|
|
nat = NatNone
|
|
|
|
of "upnp":
|
|
|
|
nat = NatUpnp
|
|
|
|
of "pmp":
|
|
|
|
nat = NatPmp
|
|
|
|
else:
|
2020-06-05 15:08:50 +00:00
|
|
|
if conf.nat.startsWith("extip:"):
|
|
|
|
try:
|
|
|
|
# any required port redirection is assumed to be done by hand
|
|
|
|
result.ip = some(ValidIpAddress.init(conf.nat[6..^1]))
|
|
|
|
nat = NatNone
|
|
|
|
except ValueError:
|
|
|
|
error "nor a valid IP address", address = conf.nat[6..^1]
|
|
|
|
quit QuitFailure
|
2019-06-12 18:22:05 +00:00
|
|
|
else:
|
2020-06-05 15:08:50 +00:00
|
|
|
error "not a valid NAT mechanism", value = conf.nat
|
|
|
|
quit QuitFailure
|
2019-06-12 18:22:05 +00:00
|
|
|
|
|
|
|
if nat != NatNone:
|
2020-06-05 15:08:50 +00:00
|
|
|
let extIp = getExternalIP(nat)
|
|
|
|
if extIP.isSome:
|
|
|
|
result.ip = some(ValidIpAddress.init extIp.get)
|
2020-03-24 16:06:36 +00:00
|
|
|
# TODO redirectPorts in considered a gcsafety violation
|
|
|
|
# because it obtains the address of a non-gcsafe proc?
|
|
|
|
let extPorts = ({.gcsafe.}:
|
|
|
|
redirectPorts(tcpPort = result.tcpPort,
|
|
|
|
udpPort = result.udpPort,
|
|
|
|
description = clientId))
|
2019-06-12 18:22:05 +00:00
|
|
|
if extPorts.isSome:
|
|
|
|
(result.tcpPort, result.udpPort) = extPorts.get()
|
|
|
|
|
2020-03-22 20:54:47 +00:00
|
|
|
func asLibp2pKey*(key: keys.PublicKey): PublicKey =
|
2020-04-17 13:29:49 +00:00
|
|
|
PublicKey(scheme: Secp256k1, skkey: secp.SkPublicKey(key))
|
2019-11-03 23:02:27 +00:00
|
|
|
|
2020-03-22 20:54:47 +00:00
|
|
|
func asEthKey*(key: PrivateKey): keys.PrivateKey =
|
2020-04-17 13:29:49 +00:00
|
|
|
keys.PrivateKey(key.skkey)
|
2019-11-03 23:02:27 +00:00
|
|
|
|
2020-03-22 20:54:47 +00:00
|
|
|
proc initAddress*(T: type MultiAddress, str: string): T =
|
|
|
|
let address = MultiAddress.init(str)
|
|
|
|
if IPFS.match(address) and matchPartial(multiaddress.TCP, address):
|
|
|
|
result = address
|
|
|
|
else:
|
|
|
|
raise newException(MultiAddressError,
|
|
|
|
"Invalid bootstrap node multi-address")
|
|
|
|
|
|
|
|
template tcpEndPoint(address, port): auto =
|
2020-06-05 15:08:50 +00:00
|
|
|
MultiAddress.init(address, tcpProtocol, port)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
proc getPersistentNetKeys*(conf: BeaconNodeConf): KeyPair =
|
2020-05-18 08:11:21 +00:00
|
|
|
let
|
|
|
|
privKeyPath = conf.dataDir / networkKeyFilename
|
|
|
|
privKey =
|
|
|
|
if not fileExists(privKeyPath):
|
|
|
|
createDir conf.dataDir.string
|
|
|
|
let key = PrivateKey.random(Secp256k1).tryGet()
|
|
|
|
writeFile(privKeyPath, key.getBytes().tryGet())
|
|
|
|
key
|
|
|
|
else:
|
|
|
|
let keyBytes = readFile(privKeyPath)
|
|
|
|
PrivateKey.init(keyBytes.toOpenArrayByte(0, keyBytes.high)).tryGet()
|
2020-03-22 20:54:47 +00:00
|
|
|
|
2020-05-18 08:11:21 +00:00
|
|
|
KeyPair(seckey: privKey, pubkey: privKey.getKey().tryGet())
|
2020-03-22 20:54:47 +00:00
|
|
|
|
2020-04-15 02:41:22 +00:00
|
|
|
proc createEth2Node*(conf: BeaconNodeConf, enrForkId: ENRForkID): Future[Eth2Node] {.async, gcsafe.} =
|
2020-03-22 20:54:47 +00:00
|
|
|
var
|
2020-03-31 10:02:13 +00:00
|
|
|
(extIp, extTcpPort, extUdpPort) = setupNat(conf)
|
2020-03-22 20:54:47 +00:00
|
|
|
hostAddress = tcpEndPoint(conf.libp2pAddress, conf.tcpPort)
|
2020-03-31 10:02:13 +00:00
|
|
|
announcedAddresses = if extIp.isNone(): @[]
|
|
|
|
else: @[tcpEndPoint(extIp.get(), extTcpPort)]
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
info "Initializing networking", hostAddress,
|
2020-03-22 23:23:21 +00:00
|
|
|
announcedAddresses
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
let keys = conf.getPersistentNetKeys
|
|
|
|
# TODO nim-libp2p still doesn't have support for announcing addresses
|
|
|
|
# that are different from the host address (this is relevant when we
|
|
|
|
# are running behind a NAT).
|
|
|
|
var switch = newStandardSwitch(some keys.seckey, hostAddress,
|
2020-05-06 15:42:59 +00:00
|
|
|
triggerSelf = true, gossip = true,
|
2020-05-18 19:56:11 +00:00
|
|
|
sign = false, verifySignature = false,
|
|
|
|
transportFlags = {ServerFlags.ReuseAddr})
|
2020-04-15 02:41:22 +00:00
|
|
|
result = Eth2Node.init(conf, enrForkId, switch,
|
|
|
|
extIp, extTcpPort, extUdpPort,
|
2020-03-31 10:02:13 +00:00
|
|
|
keys.seckey.asEthKey)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
proc getPersistenBootstrapAddr*(conf: BeaconNodeConf,
|
2020-06-05 15:08:50 +00:00
|
|
|
ip: ValidIpAddress, port: Port): EnrResult[enr.Record] =
|
2020-03-31 10:02:13 +00:00
|
|
|
let pair = getPersistentNetKeys(conf)
|
2020-03-22 23:23:21 +00:00
|
|
|
return enr.Record.init(1'u64, # sequence number
|
|
|
|
pair.seckey.asEthKey,
|
2020-04-15 02:41:22 +00:00
|
|
|
some(ip), port, port, @[])
|
2020-03-23 11:26:44 +00:00
|
|
|
|
|
|
|
proc announcedENR*(node: Eth2Node): enr.Record =
|
|
|
|
doAssert node.discovery != nil, "The Eth2Node must be initialized"
|
|
|
|
node.discovery.localNode.record
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
proc shortForm*(id: KeyPair): string =
|
|
|
|
$PeerID.init(id.pubkey)
|
|
|
|
|
2020-03-24 09:54:17 +00:00
|
|
|
proc connectToNetwork*(node: Eth2Node) {.async.} =
|
2020-03-22 20:54:47 +00:00
|
|
|
await node.start()
|
|
|
|
|
|
|
|
proc checkIfConnectedToBootstrapNode {.async.} =
|
|
|
|
await sleepAsync(30.seconds)
|
2020-03-24 09:54:17 +00:00
|
|
|
if node.discovery.bootstrapRecords.len > 0 and libp2p_successful_dials.value == 0:
|
|
|
|
fatal "Failed to connect to any bootstrap node. Quitting",
|
|
|
|
bootstrapEnrs = node.discovery.bootstrapRecords
|
2020-03-22 20:54:47 +00:00
|
|
|
quit 1
|
|
|
|
|
2020-03-23 20:29:50 +00:00
|
|
|
# TODO: The initial sync forces this to time out.
|
|
|
|
# Revisit when the new Sync manager is integrated.
|
|
|
|
# traceAsyncErrors checkIfConnectedToBootstrapNode()
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
func peersCount*(node: Eth2Node): int =
|
|
|
|
len(node.peerPool)
|
|
|
|
|
|
|
|
proc subscribe*[MsgType](node: Eth2Node,
|
|
|
|
topic: string,
|
2020-03-31 18:39:02 +00:00
|
|
|
msgHandler: proc(msg: MsgType) {.gcsafe.},
|
|
|
|
msgValidator: proc(msg: MsgType): bool {.gcsafe.} ) {.async, gcsafe.} =
|
2020-04-27 16:10:46 +00:00
|
|
|
template execMsgHandler(peerExpr, gossipBytes, gossipTopic, useSnappy) =
|
2020-03-22 20:54:47 +00:00
|
|
|
inc gossip_messages_received
|
|
|
|
trace "Incoming pubsub message received",
|
|
|
|
peer = peerExpr, len = gossipBytes.len, topic = gossipTopic,
|
|
|
|
message_id = `$`(sha256.digest(gossipBytes))
|
2020-04-27 16:34:17 +00:00
|
|
|
when useSnappy:
|
2020-04-27 14:49:02 +00:00
|
|
|
msgHandler SSZ.decode(snappy.decode(gossipBytes), MsgType)
|
|
|
|
else:
|
|
|
|
msgHandler SSZ.decode(gossipBytes, MsgType)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
# All message types which are subscribed to should be validated; putting
|
|
|
|
# this in subscribe(...) ensures that the default approach is correct.
|
2020-04-27 16:10:46 +00:00
|
|
|
template execMsgValidator(gossipBytes, gossipTopic, useSnappy): bool =
|
2020-03-31 18:39:02 +00:00
|
|
|
trace "Incoming pubsub message received for validation",
|
|
|
|
len = gossipBytes.len, topic = gossipTopic,
|
|
|
|
message_id = `$`(sha256.digest(gossipBytes))
|
2020-04-27 16:34:17 +00:00
|
|
|
when useSnappy:
|
2020-04-27 14:49:02 +00:00
|
|
|
msgValidator SSZ.decode(snappy.decode(gossipBytes), MsgType)
|
|
|
|
else:
|
|
|
|
msgValidator SSZ.decode(gossipBytes, MsgType)
|
2020-03-31 18:39:02 +00:00
|
|
|
|
|
|
|
# Validate messages as soon as subscribed
|
2020-03-24 11:13:07 +00:00
|
|
|
let incomingMsgValidator = proc(topic: string,
|
|
|
|
message: GossipMsg): Future[bool]
|
|
|
|
{.async, gcsafe.} =
|
2020-04-27 16:10:46 +00:00
|
|
|
return execMsgValidator(message.data, topic, false)
|
|
|
|
let incomingMsgValidatorSnappy = proc(topic: string,
|
|
|
|
message: GossipMsg): Future[bool]
|
|
|
|
{.async, gcsafe.} =
|
|
|
|
return execMsgValidator(message.data, topic, true)
|
2020-03-24 11:13:07 +00:00
|
|
|
|
2020-03-31 18:39:02 +00:00
|
|
|
node.switch.addValidator(topic, incomingMsgValidator)
|
2020-04-27 16:10:46 +00:00
|
|
|
node.switch.addValidator(topic & "_snappy", incomingMsgValidatorSnappy)
|
2020-03-31 18:39:02 +00:00
|
|
|
|
2020-03-22 20:54:47 +00:00
|
|
|
let incomingMsgHandler = proc(topic: string,
|
|
|
|
data: seq[byte]) {.async, gcsafe.} =
|
2020-04-27 16:10:46 +00:00
|
|
|
execMsgHandler "unknown", data, topic, false
|
|
|
|
let incomingMsgHandlerSnappy = proc(topic: string,
|
|
|
|
data: seq[byte]) {.async, gcsafe.} =
|
|
|
|
execMsgHandler "unknown", data, topic, true
|
2020-03-22 20:54:47 +00:00
|
|
|
|
2020-04-27 14:49:02 +00:00
|
|
|
var switchSubscriptions: seq[Future[void]] = @[]
|
|
|
|
switchSubscriptions.add(node.switch.subscribe(topic, incomingMsgHandler))
|
2020-04-27 16:10:46 +00:00
|
|
|
switchSubscriptions.add(node.switch.subscribe(topic & "_snappy", incomingMsgHandlerSnappy))
|
2020-05-06 15:42:59 +00:00
|
|
|
|
2020-04-27 16:10:46 +00:00
|
|
|
await allFutures(switchSubscriptions)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
proc traceMessage(fut: FutureBase, digest: MDigest[256]) =
|
|
|
|
fut.addCallback do (arg: pointer):
|
|
|
|
if not(fut.failed):
|
2020-05-15 17:56:34 +00:00
|
|
|
trace "Outgoing pubsub message sent", message_id = `$`(digest)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
proc broadcast*(node: Eth2Node, topic: string, msg: auto) =
|
|
|
|
inc gossip_messages_sent
|
|
|
|
let broadcastBytes = SSZ.encode(msg)
|
|
|
|
var fut = node.switch.publish(topic, broadcastBytes)
|
|
|
|
traceMessage(fut, sha256.digest(broadcastBytes))
|
|
|
|
traceAsyncErrors(fut)
|
2020-04-27 14:49:02 +00:00
|
|
|
# also publish to the snappy-compressed topics
|
2020-04-27 16:10:46 +00:00
|
|
|
let snappyEncoded = snappy.encode(broadcastBytes)
|
|
|
|
var futSnappy = node.switch.publish(topic & "_snappy", snappyEncoded)
|
|
|
|
traceMessage(futSnappy, sha256.digest(snappyEncoded))
|
|
|
|
traceAsyncErrors(futSnappy)
|
2020-03-22 20:54:47 +00:00
|
|
|
|
|
|
|
# TODO:
|
|
|
|
# At the moment, this is just a compatiblity shim for the existing RLPx functionality.
|
|
|
|
# The filtering is not implemented properly yet.
|
|
|
|
iterator randomPeers*(node: Eth2Node, maxPeers: int, Protocol: type): Peer =
|
|
|
|
var peers = newSeq[Peer]()
|
|
|
|
for _, peer in pairs(node.peers): peers.add peer
|
|
|
|
shuffle peers
|
|
|
|
if peers.len > maxPeers: peers.setLen(maxPeers)
|
|
|
|
for p in peers: yield p
|