2019-03-05 22:54:08 +00:00
|
|
|
import
|
2020-02-05 20:40:14 +00:00
|
|
|
options, tables, strutils, sequtils,
|
2020-02-11 17:35:42 +00:00
|
|
|
json_serialization, json_serialization/std/net,
|
2020-02-19 08:58:10 +00:00
|
|
|
metrics, chronos, chronicles, metrics, libp2p/crypto/crypto,
|
2020-02-05 20:40:14 +00:00
|
|
|
eth/keys, eth/p2p/enode, eth/net/nat, eth/p2p/discoveryv5/enr,
|
|
|
|
eth2_discovery, version, conf
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
const
|
2019-11-12 00:05:35 +00:00
|
|
|
clientId* = "Nimbus beacon node v" & fullVersionStr
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2019-06-12 18:22:05 +00:00
|
|
|
export
|
|
|
|
version
|
|
|
|
|
|
|
|
let
|
|
|
|
globalListeningAddr = parseIpAddress("0.0.0.0")
|
|
|
|
|
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"
|
|
|
|
|
2019-06-12 18:22:05 +00:00
|
|
|
proc setupNat(conf: BeaconNodeConf): tuple[ip: IpAddress,
|
|
|
|
tcpPort: Port,
|
|
|
|
udpPort: Port] =
|
|
|
|
# defaults
|
|
|
|
result.ip = globalListeningAddr
|
|
|
|
result.tcpPort = Port(conf.tcpPort)
|
|
|
|
result.udpPort = Port(conf.udpPort)
|
|
|
|
|
|
|
|
var nat: NatStrategy
|
|
|
|
case conf.nat.toLowerAscii:
|
|
|
|
of "any":
|
|
|
|
nat = NatAny
|
|
|
|
of "none":
|
|
|
|
nat = NatNone
|
|
|
|
of "upnp":
|
|
|
|
nat = NatUpnp
|
|
|
|
of "pmp":
|
|
|
|
nat = NatPmp
|
|
|
|
else:
|
|
|
|
if conf.nat.startsWith("extip:") and isIpAddress(conf.nat[6..^1]):
|
|
|
|
# any required port redirection is assumed to be done by hand
|
|
|
|
result.ip = parseIpAddress(conf.nat[6..^1])
|
|
|
|
nat = NatNone
|
|
|
|
else:
|
|
|
|
error "not a valid NAT mechanism, nor a valid IP address", value = conf.nat
|
|
|
|
quit(QuitFailure)
|
|
|
|
|
|
|
|
if nat != NatNone:
|
|
|
|
let extIP = getExternalIP(nat)
|
|
|
|
if extIP.isSome:
|
|
|
|
result.ip = extIP.get()
|
|
|
|
let extPorts = redirectPorts(tcpPort = result.tcpPort,
|
|
|
|
udpPort = result.udpPort,
|
|
|
|
description = clientId)
|
|
|
|
if extPorts.isSome:
|
|
|
|
(result.tcpPort, result.udpPort) = extPorts.get()
|
|
|
|
|
2020-01-24 08:32:52 +00:00
|
|
|
when networkBackend in [libp2p, libp2pDaemon]:
|
2019-06-03 17:07:50 +00:00
|
|
|
import
|
2019-10-28 23:04:52 +00:00
|
|
|
os, random,
|
2019-11-03 23:02:27 +00:00
|
|
|
stew/io, eth/async_utils,
|
2020-02-19 08:58:10 +00:00
|
|
|
libp2p/[multiaddress, multicodec],
|
2019-10-28 23:04:52 +00:00
|
|
|
ssz
|
2019-05-31 18:36:32 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
export
|
|
|
|
multiaddress
|
|
|
|
|
|
|
|
when networkBackend == libp2p:
|
2019-10-23 10:44:31 +00:00
|
|
|
import
|
2019-11-03 23:02:27 +00:00
|
|
|
libp2p/standard_setup, libp2p_backend
|
2019-10-23 10:44:31 +00:00
|
|
|
|
|
|
|
export
|
|
|
|
libp2p_backend
|
|
|
|
|
|
|
|
else:
|
|
|
|
import
|
2019-11-03 23:02:27 +00:00
|
|
|
libp2p/daemon/daemonapi, libp2p_daemon_backend
|
2019-10-23 10:44:31 +00:00
|
|
|
|
|
|
|
export
|
|
|
|
libp2p_daemon_backend
|
2019-06-03 17:07:50 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
var mainDaemon: DaemonAPI
|
|
|
|
|
|
|
|
proc closeDaemon() {.noconv.} =
|
|
|
|
if mainDaemon != nil:
|
|
|
|
info "Shutting down the LibP2P daemon"
|
|
|
|
waitFor mainDaemon.close()
|
|
|
|
|
|
|
|
addQuitProc(closeDaemon)
|
|
|
|
|
2019-08-05 00:00:49 +00:00
|
|
|
const
|
|
|
|
netBackendName* = "libp2p"
|
|
|
|
networkKeyFilename = "privkey.protobuf"
|
2019-06-03 17:07:50 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
func asLibp2pKey*(key: keys.PublicKey): PublicKey =
|
|
|
|
PublicKey(scheme: Secp256k1, skkey: key)
|
2020-02-05 20:40:14 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
func asEthKey*(key: PrivateKey): keys.PrivateKey =
|
|
|
|
keys.PrivateKey(data: key.skkey.data)
|
2019-11-12 19:56:37 +00:00
|
|
|
|
2020-02-05 20:40:14 +00:00
|
|
|
proc initAddress*(T: type MultiAddress, str: string): T =
|
2019-11-12 19:56:37 +00:00
|
|
|
let address = MultiAddress.init(str)
|
|
|
|
if IPFS.match(address) and matchPartial(multiaddress.TCP, address):
|
|
|
|
result = address
|
2019-10-28 23:04:52 +00:00
|
|
|
else:
|
2019-11-12 19:56:37 +00:00
|
|
|
raise newException(MultiAddressError,
|
|
|
|
"Invalid bootstrap node multi-address")
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2019-12-13 17:30:39 +00:00
|
|
|
template tcpEndPoint(address, port): auto =
|
|
|
|
MultiAddress.init(address, Protocol.IPPROTO_TCP, port)
|
|
|
|
|
2019-06-12 12:23:05 +00:00
|
|
|
proc ensureNetworkIdFile(conf: BeaconNodeConf): string =
|
|
|
|
result = conf.dataDir / networkKeyFilename
|
|
|
|
if not fileExists(result):
|
|
|
|
createDir conf.dataDir.string
|
2020-02-19 08:58:10 +00:00
|
|
|
let pk = PrivateKey.random(Secp256k1)
|
|
|
|
writeFile(result, pk.getBytes)
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
proc getPersistentNetKeys*(conf: BeaconNodeConf): KeyPair =
|
2020-02-05 20:40:14 +00:00
|
|
|
let privKeyPath = conf.dataDir / networkKeyFilename
|
2020-02-19 08:58:10 +00:00
|
|
|
var privKey: PrivateKey
|
2020-02-05 20:40:14 +00:00
|
|
|
if not fileExists(privKeyPath):
|
2019-11-12 19:56:37 +00:00
|
|
|
createDir conf.dataDir.string
|
2020-02-19 08:58:10 +00:00
|
|
|
privKey = PrivateKey.random(Secp256k1)
|
|
|
|
writeFile(privKeyPath, privKey.getBytes())
|
2019-11-12 19:56:37 +00:00
|
|
|
else:
|
2020-02-19 08:58:10 +00:00
|
|
|
let keyBytes = readFile(privKeyPath)
|
|
|
|
privKey = PrivateKey.init(keyBytes.toOpenArrayByte(0, keyBytes.high))
|
2019-11-12 19:56:37 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
KeyPair(seckey: privKey, pubkey: privKey.getKey())
|
2019-08-05 00:00:49 +00:00
|
|
|
|
|
|
|
proc createEth2Node*(conf: BeaconNodeConf,
|
2020-02-05 20:40:14 +00:00
|
|
|
bootstrapNodes: seq[ENode]): Future[Eth2Node] {.async.} =
|
2019-06-12 18:22:05 +00:00
|
|
|
var
|
2019-11-15 22:37:39 +00:00
|
|
|
(extIp, extTcpPort, _) = setupNat(conf)
|
2019-06-12 18:22:05 +00:00
|
|
|
hostAddress = tcpEndPoint(globalListeningAddr, Port conf.tcpPort)
|
2019-11-05 22:56:10 +00:00
|
|
|
announcedAddresses = if extIp == globalListeningAddr: @[]
|
2019-06-12 18:22:05 +00:00
|
|
|
else: @[tcpEndPoint(extIp, extTcpPort)]
|
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
info "Initializing networking", hostAddress,
|
|
|
|
announcedAddresses,
|
|
|
|
bootstrapNodes
|
|
|
|
|
|
|
|
when networkBackend == libp2p:
|
2020-02-05 20:40:14 +00:00
|
|
|
let keys = conf.getPersistentNetKeys
|
2019-11-03 23:02:27 +00:00
|
|
|
# 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).
|
2020-02-19 08:58:10 +00:00
|
|
|
var switch = newStandardSwitch(some keys.seckey, hostAddress,
|
2020-02-05 16:19:52 +00:00
|
|
|
triggerSelf = true, gossip = false)
|
2020-02-22 18:52:08 +00:00
|
|
|
result = Eth2Node.init(conf, switch, extIp, keys.seckey.asEthKey)
|
2019-08-05 00:00:49 +00:00
|
|
|
else:
|
2019-11-03 23:02:27 +00:00
|
|
|
let keyFile = conf.ensureNetworkIdFile
|
2019-08-05 00:00:49 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
var daemonFut = if bootstrapNodes.len == 0:
|
|
|
|
newDaemonApi({PSNoSign, DHTFull, PSFloodSub},
|
|
|
|
id = keyFile,
|
|
|
|
hostAddresses = @[hostAddress],
|
|
|
|
announcedAddresses = announcedAddresses)
|
|
|
|
else:
|
|
|
|
newDaemonApi({PSNoSign, DHTFull, PSFloodSub, WaitBootstrap},
|
|
|
|
id = keyFile,
|
|
|
|
hostAddresses = @[hostAddress],
|
|
|
|
announcedAddresses = announcedAddresses,
|
2020-02-05 20:40:14 +00:00
|
|
|
bootstrapNodes = mapIt(bootstrapNodes, it.toMultiAddressStr),
|
2019-11-03 23:02:27 +00:00
|
|
|
peersRequired = 1)
|
2019-11-12 19:56:37 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
mainDaemon = await daemonFut
|
2019-07-11 02:36:07 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
var identity = await mainDaemon.identity()
|
|
|
|
info "LibP2P daemon started", peer = identity.peer.pretty(),
|
|
|
|
addresses = identity.addresses
|
2019-06-12 18:22:05 +00:00
|
|
|
|
2019-11-03 23:02:27 +00:00
|
|
|
result = await Eth2Node.init(mainDaemon)
|
2019-06-12 12:23:05 +00:00
|
|
|
|
2019-05-22 07:13:15 +00:00
|
|
|
proc getPersistenBootstrapAddr*(conf: BeaconNodeConf,
|
2020-02-05 20:40:14 +00:00
|
|
|
ip: IpAddress, port: Port): ENode =
|
|
|
|
let pair = getPersistentNetKeys(conf)
|
2020-02-19 08:58:10 +00:00
|
|
|
initENode(pair.pubkey.skkey, Address(ip: ip, udpPort: port))
|
2020-02-05 20:40:14 +00:00
|
|
|
|
2020-02-19 08:58:10 +00:00
|
|
|
proc shortForm*(id: KeyPair): string =
|
|
|
|
$PeerID.init(id.pubkey)
|
2020-02-05 20:40:14 +00:00
|
|
|
|
|
|
|
proc toPeerInfo(enode: ENode): PeerInfo =
|
|
|
|
let
|
|
|
|
peerId = PeerID.init enode.pubkey.asLibp2pKey
|
|
|
|
addresses = @[MultiAddress.init enode.toMultiAddressStr]
|
|
|
|
when networkBackend == libp2p:
|
|
|
|
return PeerInfo.init(peerId, addresses)
|
|
|
|
else:
|
|
|
|
return PeerInfo(peer: peerId, addresses: addresses)
|
2019-11-03 23:02:27 +00:00
|
|
|
|
2019-11-12 19:56:37 +00:00
|
|
|
proc connectToNetwork*(node: Eth2Node,
|
2020-02-12 13:41:07 +00:00
|
|
|
bootstrapNodes: seq[ENode],
|
|
|
|
bootstrapEnrs: seq[enr.Record]) {.async.} =
|
2020-02-05 20:40:14 +00:00
|
|
|
when networkBackend == libp2pDaemon:
|
|
|
|
var connected = false
|
|
|
|
for bootstrapNode in bootstrapNodes:
|
|
|
|
try:
|
|
|
|
let peerInfo = toPeerInfo(bootstrapNode)
|
|
|
|
when networkBackend == libp2p:
|
|
|
|
discard await node.switch.dial(peerInfo)
|
|
|
|
else:
|
|
|
|
await node.daemon.connect(peerInfo.peer, peerInfo.addresses)
|
|
|
|
var peer = node.getPeer(peerInfo)
|
|
|
|
peer.wasDialed = true
|
|
|
|
await initializeConnection(peer)
|
|
|
|
connected = true
|
|
|
|
except CatchableError as err:
|
|
|
|
error "Failed to connect to bootstrap node",
|
|
|
|
node = bootstrapNode, err = err.msg
|
|
|
|
|
|
|
|
if bootstrapNodes.len > 0 and connected == false:
|
|
|
|
fatal "Failed to connect to any bootstrap node. Quitting."
|
|
|
|
quit 1
|
|
|
|
elif networkBackend == libp2p:
|
2020-02-12 13:41:07 +00:00
|
|
|
for bootstrapNode in bootstrapEnrs:
|
|
|
|
debug "Adding known peer", peer = bootstrapNode
|
2020-02-05 20:40:14 +00:00
|
|
|
node.addKnownPeer bootstrapNode
|
|
|
|
await node.start()
|
|
|
|
|
2020-02-19 10:45:34 +00:00
|
|
|
proc checkIfConnectedToBootstrapNode {.async.} =
|
2020-02-21 18:03:19 +00:00
|
|
|
await sleepAsync(30.seconds)
|
2020-02-19 10:45:34 +00:00
|
|
|
if bootstrapEnrs.len > 0 and libp2p_successful_dials.value == 0:
|
|
|
|
fatal "Failed to connect to any bootstrap node. Quitting", bootstrapEnrs
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
traceAsyncErrors checkIfConnectedToBootstrapNode()
|
2019-06-24 16:27:19 +00:00
|
|
|
|
2019-03-05 22:54:08 +00:00
|
|
|
proc saveConnectionAddressFile*(node: Eth2Node, filename: string) =
|
2019-11-03 23:02:27 +00:00
|
|
|
when networkBackend == libp2p:
|
|
|
|
writeFile(filename, $node.switch.peerInfo.addrs[0] & "/p2p/" &
|
|
|
|
node.switch.peerInfo.id)
|
|
|
|
else:
|
|
|
|
let id = waitFor node.daemon.identity()
|
|
|
|
writeFile(filename, $id.addresses[0] & "/p2p/" & id.peer.pretty)
|
2019-03-05 22:54:08 +00:00
|
|
|
|
2019-05-22 07:13:15 +00:00
|
|
|
func peersCount*(node: Eth2Node): int =
|
|
|
|
node.peers.len
|
|
|
|
|
2019-06-03 17:07:50 +00:00
|
|
|
proc subscribe*[MsgType](node: Eth2Node,
|
|
|
|
topic: string,
|
2019-09-29 17:42:53 +00:00
|
|
|
msgHandler: proc(msg: MsgType) {.gcsafe.} ) {.async, gcsafe.} =
|
2019-12-13 15:33:20 +00:00
|
|
|
template execMsgHandler(peerExpr, gossipBytes, gossipTopic) =
|
2019-11-03 23:02:27 +00:00
|
|
|
inc gossip_messages_received
|
|
|
|
trace "Incoming gossip bytes",
|
2019-12-13 15:33:20 +00:00
|
|
|
peer = peerExpr, len = gossipBytes.len, topic = gossipTopic
|
2019-11-03 23:02:27 +00:00
|
|
|
msgHandler SSZ.decode(gossipBytes, MsgType)
|
|
|
|
|
|
|
|
when networkBackend == libp2p:
|
|
|
|
let incomingMsgHandler = proc(topic: string,
|
|
|
|
data: seq[byte]) {.async, gcsafe.} =
|
2019-12-13 15:33:20 +00:00
|
|
|
execMsgHandler "unknown", data, topic
|
2019-11-03 23:02:27 +00:00
|
|
|
|
|
|
|
await node.switch.subscribe(topic, incomingMsgHandler)
|
|
|
|
|
|
|
|
else:
|
|
|
|
let incomingMsgHandler = proc(api: DaemonAPI,
|
|
|
|
ticket: PubsubTicket,
|
|
|
|
msg: PubSubMessage): Future[bool] {.async, gcsafe.} =
|
2019-12-13 15:33:20 +00:00
|
|
|
execMsgHandler msg.peer, msg.data, msg.topics[0]
|
2019-11-03 23:02:27 +00:00
|
|
|
return true
|
|
|
|
|
|
|
|
discard await node.daemon.pubsubSubscribe(topic, incomingMsgHandler)
|
2019-06-03 17:07:50 +00:00
|
|
|
|
|
|
|
proc broadcast*(node: Eth2Node, topic: string, msg: auto) =
|
2019-10-25 17:15:12 +00:00
|
|
|
inc gossip_messages_sent
|
2019-11-03 23:02:27 +00:00
|
|
|
let broadcastBytes = SSZ.encode(msg)
|
|
|
|
when networkBackend == libp2p:
|
|
|
|
traceAsyncErrors node.switch.publish(topic, broadcastBytes)
|
|
|
|
else:
|
|
|
|
traceAsyncErrors node.daemon.pubsubPublish(topic, broadcastBytes)
|
2019-06-03 17:07:50 +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
|
2020-01-24 08:32:52 +00:00
|
|
|
else:
|
|
|
|
{.fatal: "Unsupported network backend".}
|