2020-02-17 16:44:56 +00:00
|
|
|
import
|
|
|
|
std/net,
|
|
|
|
eth/trie/db, types, ../enode
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
DiscoveryDB* = ref object of Database
|
|
|
|
backend: TrieDatabaseRef
|
|
|
|
|
|
|
|
DbKeyKind = enum
|
|
|
|
kNodeToKeys = 100
|
|
|
|
|
|
|
|
proc init*(T: type DiscoveryDB, backend: TrieDatabaseRef): DiscoveryDB =
|
|
|
|
T(backend: backend)
|
|
|
|
|
2019-12-18 10:36:11 +00:00
|
|
|
const keySize = 1 + # unique triedb prefix (kNodeToKeys)
|
|
|
|
sizeof(NodeId) +
|
|
|
|
16 + # max size of ip address (ipv6)
|
|
|
|
2 # Sizeof port
|
|
|
|
|
|
|
|
proc makeKey(id: NodeId, address: Address): array[keySize, byte] =
|
2019-12-16 19:38:45 +00:00
|
|
|
result[0] = byte(kNodeToKeys)
|
|
|
|
copyMem(addr result[1], unsafeAddr id, sizeof(id))
|
2019-12-18 10:36:11 +00:00
|
|
|
case address.ip.family
|
|
|
|
of IpAddressFamily.IpV4:
|
|
|
|
copyMem(addr result[sizeof(id) + 1], unsafeAddr address.ip.address_v4, sizeof(address.ip.address_v4))
|
|
|
|
of IpAddressFamily.IpV6:
|
|
|
|
copyMem(addr result[sizeof(id) + 1], unsafeAddr address.ip.address_v6, sizeof(address.ip.address_v6))
|
|
|
|
copyMem(addr result[sizeof(id) + 1 + sizeof(address.ip.address_v6)], unsafeAddr address.udpPort, sizeof(address.udpPort))
|
2019-12-16 19:38:45 +00:00
|
|
|
|
2020-02-27 21:36:42 +00:00
|
|
|
method storeKeys*(db: DiscoveryDB, id: NodeId, address: Address, r, w: AesKey):
|
|
|
|
bool {.raises: [Defect].} =
|
2020-02-17 22:47:13 +00:00
|
|
|
try:
|
|
|
|
var value: array[sizeof(r) + sizeof(w), byte]
|
|
|
|
value[0 .. 15] = r
|
|
|
|
value[16 .. ^1] = w
|
|
|
|
db.backend.put(makeKey(id, address), value)
|
|
|
|
return true
|
|
|
|
except CatchableError:
|
|
|
|
return false
|
|
|
|
|
2020-02-27 21:36:42 +00:00
|
|
|
method loadKeys*(db: DiscoveryDB, id: NodeId, address: Address, r, w: var AesKey):
|
|
|
|
bool {.raises: [Defect].} =
|
2020-02-17 22:47:13 +00:00
|
|
|
try:
|
|
|
|
let res = db.backend.get(makeKey(id, address))
|
|
|
|
if res.len != sizeof(r) + sizeof(w):
|
|
|
|
return false
|
2019-12-16 19:38:45 +00:00
|
|
|
copyMem(addr r[0], unsafeAddr res[0], sizeof(r))
|
|
|
|
copyMem(addr w[0], unsafeAddr res[sizeof(r)], sizeof(w))
|
2020-02-17 22:47:13 +00:00
|
|
|
return true
|
|
|
|
except CatchableError:
|
|
|
|
return false
|
|
|
|
|
2020-03-10 15:01:04 +00:00
|
|
|
method deleteKeys*(db: DiscoveryDB, id: NodeId, address: Address):
|
|
|
|
bool {.raises: [Defect].} =
|
|
|
|
try:
|
|
|
|
db.backend.del(makeKey(id, address))
|
|
|
|
return true
|
|
|
|
except CatchableError:
|
|
|
|
return false
|