2021-05-11 07:37:33 +00:00
|
|
|
# nim-eth
|
2023-05-10 13:50:04 +00:00
|
|
|
# Copyright (c) 2018-2023 Status Research & Development GmbH
|
2021-05-11 07:37:33 +00:00
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
2019-02-05 15:40:29 +00:00
|
|
|
|
2023-05-10 13:50:04 +00:00
|
|
|
{.push raises: [].}
|
2021-07-16 19:44:30 +00:00
|
|
|
|
2019-02-05 15:40:29 +00:00
|
|
|
import
|
2023-04-20 09:52:42 +00:00
|
|
|
std/[tables, algorithm, random, typetraits, strutils, net],
|
2022-06-17 20:45:37 +00:00
|
|
|
chronos, chronos/timer, chronicles,
|
2024-09-29 08:52:19 +00:00
|
|
|
./common/keys, ./p2p/private/p2p_types,
|
2021-04-06 11:33:24 +00:00
|
|
|
./p2p/[kademlia, discovery, enode, peer_pool, rlpx]
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
export
|
|
|
|
p2p_types, rlpx, enode, kademlia
|
|
|
|
|
2022-12-06 13:54:03 +00:00
|
|
|
logScope:
|
|
|
|
topics = "eth p2p"
|
|
|
|
|
|
|
|
|
2023-09-08 14:45:41 +00:00
|
|
|
proc addCapability*(node: EthereumNode,
|
2022-10-14 10:16:25 +00:00
|
|
|
p: ProtocolInfo,
|
|
|
|
networkState: RootRef = nil) =
|
2019-03-13 22:15:26 +00:00
|
|
|
doAssert node.connectionState == ConnectionState.None
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
let pos = lowerBound(node.protocols, p, rlpx.cmp)
|
|
|
|
node.protocols.insert(p, pos)
|
|
|
|
node.capabilities.insert(p.asCapability, pos)
|
|
|
|
|
2022-10-14 10:16:25 +00:00
|
|
|
if p.networkStateInitializer != nil and networkState.isNil:
|
2019-02-05 15:40:29 +00:00
|
|
|
node.protocolStates[p.index] = p.networkStateInitializer(node)
|
|
|
|
|
2022-10-14 10:16:25 +00:00
|
|
|
if networkState.isNil.not:
|
|
|
|
node.protocolStates[p.index] = networkState
|
|
|
|
|
2023-09-08 14:45:41 +00:00
|
|
|
template addCapability*(node: EthereumNode, Protocol: type) =
|
2019-02-05 15:40:29 +00:00
|
|
|
addCapability(node, Protocol.protocolInfo)
|
2022-10-14 10:16:25 +00:00
|
|
|
|
2023-09-08 14:45:41 +00:00
|
|
|
template addCapability*(node: EthereumNode,
|
2022-10-14 10:16:25 +00:00
|
|
|
Protocol: type,
|
|
|
|
networkState: untyped) =
|
|
|
|
mixin NetworkState
|
|
|
|
type
|
|
|
|
ParamType = type(networkState)
|
|
|
|
|
|
|
|
when ParamType isnot Protocol.NetworkState:
|
|
|
|
const errMsg = "`$1` is not compatible with `$2`" % [
|
|
|
|
name(ParamType), name(Protocol.NetworkState)]
|
|
|
|
{. error: errMsg .}
|
|
|
|
|
2022-10-20 06:49:20 +00:00
|
|
|
addCapability(node, Protocol.protocolInfo,
|
2022-10-14 10:16:25 +00:00
|
|
|
cast[RootRef](networkState))
|
|
|
|
|
2023-09-08 14:45:41 +00:00
|
|
|
proc replaceNetworkState*(node: EthereumNode,
|
2022-10-14 10:16:25 +00:00
|
|
|
p: ProtocolInfo,
|
|
|
|
networkState: RootRef) =
|
|
|
|
node.protocolStates[p.index] = networkState
|
|
|
|
|
2023-09-08 14:45:41 +00:00
|
|
|
template replaceNetworkState*(node: EthereumNode,
|
2022-10-14 10:16:25 +00:00
|
|
|
Protocol: type,
|
|
|
|
networkState: untyped) =
|
|
|
|
mixin NetworkState
|
|
|
|
type
|
|
|
|
ParamType = type(networkState)
|
|
|
|
|
|
|
|
when ParamType isnot Protocol.NetworkState:
|
|
|
|
const errMsg = "`$1` is not compatible with `$2`" % [
|
|
|
|
name(ParamType), name(Protocol.NetworkState)]
|
|
|
|
{. error: errMsg .}
|
|
|
|
|
2022-10-20 06:49:20 +00:00
|
|
|
replaceNetworkState(node, Protocol.protocolInfo,
|
2022-10-14 10:16:25 +00:00
|
|
|
cast[RootRef](networkState))
|
2019-02-05 15:40:29 +00:00
|
|
|
|
2022-03-15 17:08:15 +00:00
|
|
|
proc newEthereumNode*(
|
|
|
|
keys: KeyPair,
|
|
|
|
address: Address,
|
|
|
|
networkId: NetworkId,
|
2022-10-20 06:49:20 +00:00
|
|
|
clientId = "nim-eth-p2p",
|
2022-03-15 17:08:15 +00:00
|
|
|
addAllCapabilities = true,
|
|
|
|
useCompression: bool = false,
|
|
|
|
minPeers = 10,
|
|
|
|
bootstrapNodes: seq[ENode] = @[],
|
|
|
|
bindUdpPort: Port,
|
|
|
|
bindTcpPort: Port,
|
|
|
|
bindIp = IPv4_any(),
|
|
|
|
rng = newRng()): EthereumNode =
|
2020-07-07 08:56:26 +00:00
|
|
|
|
|
|
|
if rng == nil: # newRng could fail
|
2021-05-06 15:20:54 +00:00
|
|
|
raise (ref Defect)(msg: "Cannot initialize RNG")
|
2020-07-07 08:56:26 +00:00
|
|
|
|
2019-02-05 15:40:29 +00:00
|
|
|
new result
|
|
|
|
result.keys = keys
|
|
|
|
result.networkId = networkId
|
|
|
|
result.clientId = clientId
|
|
|
|
result.protocols.newSeq 0
|
|
|
|
result.capabilities.newSeq 0
|
|
|
|
result.address = address
|
|
|
|
result.connectionState = ConnectionState.None
|
2022-03-15 17:08:15 +00:00
|
|
|
result.bindIp = bindIp
|
|
|
|
result.bindPort = bindTcpPort
|
|
|
|
|
|
|
|
result.discovery = newDiscoveryProtocol(
|
|
|
|
keys.seckey, address, bootstrapNodes, bindUdpPort, bindIp, rng)
|
|
|
|
|
2020-07-07 08:56:26 +00:00
|
|
|
result.rng = rng
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
when useSnappy:
|
|
|
|
result.protocolVersion = if useCompression: devp2pSnappyVersion
|
|
|
|
else: devp2pVersion
|
|
|
|
|
2024-01-22 09:47:46 +00:00
|
|
|
result.protocolStates.newSeq protocolCount()
|
2019-02-05 15:40:29 +00:00
|
|
|
|
2022-03-15 17:08:15 +00:00
|
|
|
result.peerPool = newPeerPool(
|
|
|
|
result, networkId, keys, nil, clientId, minPeers = minPeers)
|
|
|
|
|
|
|
|
result.peerPool.discovery = result.discovery
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
if addAllCapabilities:
|
2024-01-22 09:47:46 +00:00
|
|
|
for cap in protocols():
|
|
|
|
result.addCapability(cap)
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
proc processIncoming(server: StreamServer,
|
2024-02-14 08:59:13 +00:00
|
|
|
remote: StreamTransport): Future[void] {.async: (raises: []).} =
|
|
|
|
try:
|
|
|
|
var node = getUserData[EthereumNode](server)
|
|
|
|
let peer = await node.rlpxAccept(remote)
|
|
|
|
if not peer.isNil:
|
|
|
|
trace "Connection established (incoming)", peer
|
|
|
|
if node.peerPool != nil:
|
|
|
|
node.peerPool.connectingNodes.excl(peer.remote)
|
|
|
|
node.peerPool.addPeer(peer)
|
|
|
|
except CatchableError as exc:
|
|
|
|
error "processIncoming", msg=exc.msg
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
proc listeningAddress*(node: EthereumNode): ENode =
|
2020-04-06 16:24:15 +00:00
|
|
|
node.toENode()
|
2019-02-05 15:40:29 +00:00
|
|
|
|
2023-05-10 13:50:04 +00:00
|
|
|
proc startListening*(node: EthereumNode) {.raises: [CatchableError].} =
|
2022-03-15 17:08:15 +00:00
|
|
|
# TODO: allow binding to both IPv4 & IPv6
|
|
|
|
let ta = initTAddress(node.bindIp, node.bindPort)
|
2019-02-05 15:40:29 +00:00
|
|
|
if node.listeningServer == nil:
|
|
|
|
node.listeningServer = createStreamServer(ta, processIncoming,
|
|
|
|
{ReuseAddr},
|
|
|
|
udata = cast[pointer](node))
|
|
|
|
node.listeningServer.start()
|
|
|
|
info "RLPx listener up", self = node.listeningAddress
|
|
|
|
|
2022-03-15 17:08:15 +00:00
|
|
|
proc connectToNetwork*(
|
|
|
|
node: EthereumNode, startListening = true,
|
|
|
|
enableDiscovery = true, waitForPeers = true) {.async.} =
|
2019-03-13 22:15:26 +00:00
|
|
|
doAssert node.connectionState == ConnectionState.None
|
2019-02-05 15:40:29 +00:00
|
|
|
|
|
|
|
node.connectionState = Connecting
|
|
|
|
|
|
|
|
if startListening:
|
|
|
|
p2p.startListening(node)
|
|
|
|
|
|
|
|
if enableDiscovery:
|
|
|
|
node.discovery.open()
|
|
|
|
await node.discovery.bootstrap()
|
2019-11-07 13:14:15 +00:00
|
|
|
node.peerPool.start()
|
2019-02-05 15:40:29 +00:00
|
|
|
else:
|
|
|
|
info "Discovery disabled"
|
|
|
|
|
2021-07-30 02:09:38 +00:00
|
|
|
while node.peerPool.connectedNodes.len == 0 and waitForPeers:
|
2019-02-05 15:40:29 +00:00
|
|
|
trace "Waiting for more peers", peers = node.peerPool.connectedNodes.len
|
2019-06-11 13:31:00 +00:00
|
|
|
await sleepAsync(500.milliseconds)
|
2019-02-05 15:40:29 +00:00
|
|
|
|
2023-05-10 13:50:04 +00:00
|
|
|
proc stopListening*(node: EthereumNode) {.raises: [CatchableError].} =
|
2019-02-05 15:40:29 +00:00
|
|
|
node.listeningServer.stop()
|
|
|
|
|
|
|
|
iterator peers*(node: EthereumNode): Peer =
|
|
|
|
for peer in node.peerPool.peers:
|
|
|
|
yield peer
|
|
|
|
|
|
|
|
iterator peers*(node: EthereumNode, Protocol: type): Peer =
|
|
|
|
for peer in node.peerPool.peers(Protocol):
|
|
|
|
yield peer
|
|
|
|
|
|
|
|
iterator protocolPeers*(node: EthereumNode, Protocol: type): auto =
|
|
|
|
mixin state
|
|
|
|
for peer in node.peerPool.peers(Protocol):
|
|
|
|
yield peer.state(Protocol)
|
|
|
|
|
|
|
|
iterator randomPeers*(node: EthereumNode, maxPeers: int): Peer =
|
|
|
|
# TODO: this can be implemented more efficiently
|
|
|
|
|
|
|
|
# XXX: this doesn't compile, why?
|
|
|
|
# var peer = toSeq node.peers
|
|
|
|
var peers = newSeqOfCap[Peer](node.peerPool.connectedNodes.len)
|
|
|
|
for peer in node.peers: peers.add(peer)
|
|
|
|
|
|
|
|
shuffle(peers)
|
|
|
|
for i in 0 ..< min(maxPeers, peers.len):
|
|
|
|
yield peers[i]
|
|
|
|
|
|
|
|
proc randomPeer*(node: EthereumNode): Peer =
|
2020-06-24 14:31:44 +00:00
|
|
|
let peerIdx = rand(node.peerPool.connectedNodes.len)
|
2019-02-05 15:40:29 +00:00
|
|
|
var i = 0
|
|
|
|
for peer in node.peers:
|
|
|
|
if i == peerIdx: return peer
|
|
|
|
inc i
|
|
|
|
|
2019-05-09 11:05:31 +00:00
|
|
|
iterator randomPeers*(node: EthereumNode, maxPeers: int, Protocol: type): Peer =
|
|
|
|
var peers = newSeqOfCap[Peer](node.peerPool.connectedNodes.len)
|
|
|
|
for peer in node.peers(Protocol):
|
|
|
|
peers.add(peer)
|
|
|
|
shuffle(peers)
|
|
|
|
if peers.len > maxPeers: peers.setLen(maxPeers)
|
|
|
|
for p in peers: yield p
|
|
|
|
|
2019-02-05 15:40:29 +00:00
|
|
|
proc randomPeerWith*(node: EthereumNode, Protocol: type): Peer =
|
|
|
|
var candidates = newSeq[Peer]()
|
|
|
|
for p in node.peers(Protocol):
|
|
|
|
candidates.add(p)
|
|
|
|
if candidates.len > 0:
|
|
|
|
return candidates.rand()
|
|
|
|
|
2019-12-10 20:49:54 +00:00
|
|
|
proc getPeer*(node: EthereumNode, peerId: NodeId, Protocol: type): Option[Peer] =
|
|
|
|
for peer in node.peers(Protocol):
|
|
|
|
if peer.remote.id == peerId:
|
|
|
|
return some(peer)
|
2022-08-23 08:29:34 +00:00
|
|
|
|
|
|
|
proc connectToNode*(node: EthereumNode, n: Node) {.async.} =
|
|
|
|
await node.peerPool.connectToNode(n)
|
|
|
|
|
|
|
|
proc connectToNode*(node: EthereumNode, n: ENode) {.async.} =
|
|
|
|
await node.peerPool.connectToNode(n)
|
|
|
|
|
|
|
|
func numPeers*(node: EthereumNode): int =
|
|
|
|
node.peerPool.numPeers
|
|
|
|
|
|
|
|
func hasPeer*(node: EthereumNode, n: ENode): bool =
|
|
|
|
n in node.peerPool
|
|
|
|
|
|
|
|
func hasPeer*(node: EthereumNode, n: Node): bool =
|
|
|
|
n in node.peerPool
|
|
|
|
|
|
|
|
func hasPeer*(node: EthereumNode, n: Peer): bool =
|
|
|
|
n in node.peerPool
|
2023-09-08 14:45:41 +00:00
|
|
|
|
|
|
|
proc closeWait*(node: EthereumNode) {.async.} =
|
|
|
|
node.stopListening()
|
|
|
|
await node.listeningServer.closeWait()
|