2020-02-17 16:44:56 +00:00
|
|
|
import
|
2020-03-05 00:25:21 +00:00
|
|
|
std/[net, hashes], nimcrypto, stint, chronicles,
|
2020-02-17 16:44:56 +00:00
|
|
|
types, enr, eth/keys, ../enode
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
Node* = ref object
|
|
|
|
node*: ENode
|
|
|
|
id*: NodeId
|
|
|
|
record*: Record
|
|
|
|
|
|
|
|
proc toNodeId*(pk: PublicKey): NodeId =
|
|
|
|
readUintBE[256](keccak256.digest(pk.getRaw()).data)
|
|
|
|
|
2020-02-21 23:55:37 +00:00
|
|
|
proc newNode*(enode: ENode): Node =
|
|
|
|
Node(node: enode,
|
|
|
|
id: enode.pubkey.toNodeId())
|
|
|
|
|
|
|
|
proc newNode*(enode: ENode, r: Record): Node =
|
|
|
|
Node(node: enode,
|
|
|
|
id: enode.pubkey.toNodeId(),
|
|
|
|
record: r)
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
proc newNode*(uriString: string): Node =
|
2020-02-21 23:55:37 +00:00
|
|
|
newNode initENode(uriString)
|
2019-12-16 19:38:45 +00:00
|
|
|
|
2020-02-21 23:55:37 +00:00
|
|
|
proc newNode*(pk: PublicKey, address: Address): Node =
|
|
|
|
newNode initENode(pk, address)
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
proc newNode*(r: Record): Node =
|
|
|
|
# TODO: Handle IPv6
|
2020-02-12 13:36:39 +00:00
|
|
|
let
|
|
|
|
ipBytes = r.get("ip", array[4, byte])
|
|
|
|
udpPort = r.get("udp", uint16)
|
2019-12-16 19:38:45 +00:00
|
|
|
|
2020-02-12 13:36:39 +00:00
|
|
|
var pk: PublicKey
|
2019-12-16 19:38:45 +00:00
|
|
|
if recoverPublicKey(r.get("secp256k1", seq[byte]), pk) != EthKeysStatus.Success:
|
2020-02-17 16:44:56 +00:00
|
|
|
warn "Could not recover public key"
|
2020-02-12 13:36:39 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
let a = Address(ip: IpAddress(family: IpAddressFamily.IPv4,
|
|
|
|
address_v4: ipBytes),
|
|
|
|
udpPort: Port udpPort)
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
result = newNode(initENode(pk, a))
|
|
|
|
result.record = r
|
|
|
|
|
|
|
|
proc hash*(n: Node): hashes.Hash = hash(n.node.pubkey.data)
|
|
|
|
proc `==`*(a, b: Node): bool = (a.isNil and b.isNil) or (not a.isNil and not b.isNil and a.node.pubkey == b.node.pubkey)
|
|
|
|
|
2019-12-18 10:36:11 +00:00
|
|
|
proc address*(n: Node): Address {.inline.} = n.node.address
|
|
|
|
|
2019-12-16 19:38:45 +00:00
|
|
|
proc `$`*(n: Node): string =
|
|
|
|
if n == nil:
|
|
|
|
"Node[local]"
|
|
|
|
else:
|
|
|
|
"Node[" & $n.node.address.ip & ":" & $n.node.address.udpPort & "]"
|