nim-eth-p2p/ethp2p/server.nim

53 lines
1.6 KiB
Nim
Raw Normal View History

import peer_pool, discovery, enode, async, asyncnet, auth, rlpx, net
2018-05-02 10:46:33 +03:00
import eth_keys
type Server* = ref object
socket: AsyncSocket
chainDb: AsyncChainDb
keyPair: KeyPair
address: Address
networkId: int
discovery: DiscoveryProtocol
peerPool: PeerPool
proc newServer*(keyPair: KeyPair, address: Address, chainDb: AsyncChainDB,
2018-05-10 15:51:33 +03:00
bootstrapNodes: openarray[ENode], networkId: int): Server =
2018-05-02 10:46:33 +03:00
result.new()
result.chainDb = chainDb
result.keyPair = keyPair
result.address = address
result.networkId = networkId
# TODO: bootstrap_nodes should be looked up by network_id.
result.discovery = newDiscoveryProtocol(keyPair.seckey, address, bootstrapNodes)
result.peerPool = newPeerPool(chainDb, networkId, keyPair, result.discovery)
proc isRunning(s: Server): bool {.inline.} = not s.socket.isNil
proc receiveHandshake(s: Server, address: string, remote: AsyncSocket) {.async.} =
let p = await rlpxConnectIncoming(s.keyPair, s.address.tcpPort, parseIpAddress(address), remote)
2018-05-10 15:51:33 +03:00
if not p.isNil:
echo "TODO: Add peer to the pool..."
2018-05-02 10:46:33 +03:00
else:
2018-05-10 15:51:33 +03:00
echo "Could not establish connection with incoming peer"
2018-05-02 10:46:33 +03:00
proc run(s: Server) {.async.} =
2018-05-11 13:11:57 +03:00
# TODO: Add error handling
2018-05-02 10:46:33 +03:00
s.socket = newAsyncSocket()
s.socket.setSockOpt(OptReuseAddr, true)
s.socket.bindAddr(s.address.tcpPort)
s.socket.listen()
while s.isRunning:
let (address, client) = await s.socket.acceptAddr()
2018-05-11 13:11:57 +03:00
discard s.receiveHandshake(address, client)
2018-05-02 10:46:33 +03:00
proc start*(s: Server) =
2018-05-10 15:51:33 +03:00
if not s.isRunning:
2018-05-11 13:11:57 +03:00
discard s.run()
2018-05-02 10:46:33 +03:00
proc stop*(s: Server) =
if s.isRunning:
s.socket.close()
s.socket = nil
# s.peerPool.stop() # XXX