2021-04-28 14:20:05 +00:00
|
|
|
# nim-eth - Node Discovery Protocol v5
|
2024-01-24 08:09:11 +00:00
|
|
|
# Copyright (c) 2020-2024 Status Research & Development GmbH
|
2021-04-28 14:20:05 +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.
|
|
|
|
#
|
|
|
|
## ENR implementation according to specification in EIP-778:
|
|
|
|
## https://github.com/ethereum/EIPs/blob/master/EIPS/eip-778.md
|
|
|
|
|
2023-05-10 13:50:04 +00:00
|
|
|
{.push raises: [].}
|
2019-12-18 11:06:45 +00:00
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
import
|
2024-06-24 12:57:39 +00:00
|
|
|
std/[strutils, sequtils, macros, algorithm, net],
|
2024-01-24 08:09:11 +00:00
|
|
|
nimcrypto/[keccak, utils],
|
2024-06-13 10:11:25 +00:00
|
|
|
stew/base64,
|
|
|
|
results,
|
2022-11-10 09:52:24 +00:00
|
|
|
chronicles,
|
2024-01-24 08:09:11 +00:00
|
|
|
".."/../[rlp, keys],
|
|
|
|
../../net/utils
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
export results, rlp, keys
|
2020-04-06 16:24:15 +00:00
|
|
|
|
2019-12-18 11:06:45 +00:00
|
|
|
const
|
2020-07-07 15:19:15 +00:00
|
|
|
maxEnrSize = 300 ## Maximum size of an encoded node record, in bytes.
|
|
|
|
minRlpListLen = 4 ## Minimum node record RLP list has: signature, seqId,
|
|
|
|
## "id" key and value.
|
2024-06-24 12:57:39 +00:00
|
|
|
PreDefinedKeys = ["id", "secp256k1", "ip", "ip6", "tcp", "tcp6", "udp", "udp6"]
|
|
|
|
## Predefined keys in the ENR spec, these have specific constraints on the
|
|
|
|
## type of the associated value.
|
2019-12-18 11:06:45 +00:00
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
type
|
|
|
|
FieldKind = enum
|
|
|
|
kString,
|
|
|
|
kNum,
|
2021-10-19 07:26:14 +00:00
|
|
|
kBytes,
|
|
|
|
kList
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
Field = object
|
|
|
|
case kind: FieldKind
|
|
|
|
of kString:
|
|
|
|
str: string
|
|
|
|
of kNum:
|
2020-02-11 16:25:31 +00:00
|
|
|
num: BiggestUInt
|
2019-12-10 18:34:57 +00:00
|
|
|
of kBytes:
|
|
|
|
bytes: seq[byte]
|
2021-10-19 07:26:14 +00:00
|
|
|
of kList:
|
|
|
|
listRaw: seq[byte] ## Differently from the other kinds, this is is stored
|
|
|
|
## as raw (encoded) RLP data, and thus treated as such further on.
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
FieldPair* = (string, Field)
|
|
|
|
|
|
|
|
Record* = object
|
|
|
|
seqNum*: uint64 ## ENR sequence number
|
|
|
|
pairs*: seq[FieldPair] ## List of all key:value pairs. List must have
|
|
|
|
## at least the id k:v pair and the secp256k1 k:v pair. The list of pairs
|
|
|
|
## must remain sorted and without duplicate keys. Use the insert func to
|
|
|
|
## ensure this.
|
|
|
|
raw*: seq[byte] ## RLP encoded record
|
2024-06-27 13:15:23 +00:00
|
|
|
publicKey: PublicKey ## Public key of the record
|
2024-06-24 12:57:39 +00:00
|
|
|
|
|
|
|
EnrUri* = distinct string
|
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
# TODO: I think it makes more sense to have the directly usable types for the
|
|
|
|
# fields here because in its current for you might as well just access the
|
|
|
|
# pairs in a Record directly. This would break the current API unless the type
|
|
|
|
# gets renamed.
|
2024-06-24 12:57:39 +00:00
|
|
|
TypedRecord* = object
|
|
|
|
id*: string
|
|
|
|
secp256k1*: Opt[array[33, byte]]
|
|
|
|
ip*: Opt[array[4, byte]]
|
|
|
|
ip6*: Opt[array[16, byte]]
|
|
|
|
tcp*: Opt[int]
|
|
|
|
udp*: Opt[int]
|
|
|
|
tcp6*: Opt[int]
|
|
|
|
udp6*: Opt[int]
|
|
|
|
|
2020-04-29 22:11:03 +00:00
|
|
|
EnrResult*[T] = Result[T, cstring]
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
template toField[T](v: T): Field =
|
|
|
|
when T is string:
|
|
|
|
Field(kind: kString, str: v)
|
2020-02-11 16:25:31 +00:00
|
|
|
elif T is array:
|
|
|
|
Field(kind: kBytes, bytes: @v)
|
2019-12-10 18:34:57 +00:00
|
|
|
elif T is seq[byte]:
|
|
|
|
Field(kind: kBytes, bytes: v)
|
2020-02-11 16:25:31 +00:00
|
|
|
elif T is SomeUnsignedInt:
|
|
|
|
Field(kind: kNum, num: BiggestUInt(v))
|
2021-10-19 07:26:14 +00:00
|
|
|
elif T is object|tuple:
|
|
|
|
Field(kind: kList, listRaw: rlp.encode(v))
|
2019-12-10 18:34:57 +00:00
|
|
|
else:
|
|
|
|
{.error: "Unsupported field type".}
|
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func `==`(a, b: Field): bool =
|
2020-07-07 15:19:15 +00:00
|
|
|
if a.kind == b.kind:
|
|
|
|
case a.kind
|
|
|
|
of kString:
|
2022-11-15 09:34:56 +00:00
|
|
|
a.str == b.str
|
2020-07-07 15:19:15 +00:00
|
|
|
of kNum:
|
2022-11-15 09:34:56 +00:00
|
|
|
a.num == b.num
|
2020-07-07 15:19:15 +00:00
|
|
|
of kBytes:
|
2022-11-15 09:34:56 +00:00
|
|
|
a.bytes == b.bytes
|
2021-10-19 07:26:14 +00:00
|
|
|
of kList:
|
2022-11-15 09:34:56 +00:00
|
|
|
a.listRaw == b.listRaw
|
2020-07-07 15:19:15 +00:00
|
|
|
else:
|
2022-11-15 09:34:56 +00:00
|
|
|
false
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
template toFieldPair*(key: string, value: auto): FieldPair =
|
|
|
|
(key, toField(value))
|
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func cmp(a, b: FieldPair): int = cmp(a[0], b[0])
|
2020-07-08 10:14:00 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
func hasPredefinedKey(pair: FieldPair): bool =
|
|
|
|
PreDefinedKeys.contains(pair[0])
|
|
|
|
|
|
|
|
func hasPredefinedKey(pairs: openArray[FieldPair]): bool =
|
|
|
|
for pair in pairs:
|
|
|
|
if hasPredefinedKey(pair):
|
|
|
|
return true
|
|
|
|
false
|
|
|
|
|
|
|
|
func find(pairs: openArray[FieldPair], key: string): Opt[int] =
|
|
|
|
## Search for key in key:value pairs.
|
|
|
|
##
|
|
|
|
## Returns some(index of key) if key is found. Else returns none.
|
|
|
|
for i, (k, v) in pairs:
|
|
|
|
if k == key:
|
|
|
|
return Opt.some(i)
|
|
|
|
Opt.none(int)
|
|
|
|
|
|
|
|
func insert(pairs: var seq[FieldPair], item: FieldPair) =
|
|
|
|
## Insert item in key:value pairs.
|
|
|
|
##
|
|
|
|
## If a FieldPair with key is already present, the value is updated, otherwise
|
|
|
|
## the pair is inserted in the correct position to keep the pairs sorted.
|
|
|
|
let index = find(pairs, item[0])
|
|
|
|
if index.isSome():
|
|
|
|
pairs[index.get()] = item
|
|
|
|
else:
|
|
|
|
pairs.insert(item, pairs.lowerBound(item, cmp))
|
|
|
|
|
|
|
|
func insert(pairs: var seq[FieldPair], b: openArray[FieldPair]) =
|
|
|
|
## Insert all items in key:value pairs.
|
|
|
|
for item in b:
|
|
|
|
pairs.insert(item)
|
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func makeEnrRaw(
|
|
|
|
seqNum: uint64, pk: PrivateKey,
|
2021-12-20 12:14:50 +00:00
|
|
|
pairs: openArray[FieldPair]): EnrResult[seq[byte]] =
|
2022-11-15 09:34:56 +00:00
|
|
|
func append(
|
|
|
|
w: var RlpWriter, seqNum: uint64,
|
2021-12-20 12:14:50 +00:00
|
|
|
pairs: openArray[FieldPair]): seq[byte] =
|
2020-02-11 16:25:31 +00:00
|
|
|
w.append(seqNum)
|
2019-12-10 18:34:57 +00:00
|
|
|
for (k, v) in pairs:
|
|
|
|
w.append(k)
|
|
|
|
case v.kind
|
|
|
|
of kString: w.append(v.str)
|
|
|
|
of kNum: w.append(v.num)
|
|
|
|
of kBytes: w.append(v.bytes)
|
2021-10-19 07:26:14 +00:00
|
|
|
of kList: w.appendRawBytes(v.listRaw) # No encoding needs to happen
|
2019-12-10 18:34:57 +00:00
|
|
|
w.finish()
|
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
let content =
|
|
|
|
block:
|
|
|
|
var w = initRlpList(pairs.len * 2 + 1)
|
|
|
|
w.append(seqNum, pairs)
|
2020-04-29 22:11:03 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
let signature = signNR(pk, content)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
let raw =
|
|
|
|
block:
|
|
|
|
var w = initRlpList(pairs.len * 2 + 2)
|
|
|
|
w.append(signature.toRaw())
|
|
|
|
w.append(seqNum, pairs)
|
2020-07-07 15:19:15 +00:00
|
|
|
|
|
|
|
if raw.len > maxEnrSize:
|
|
|
|
err("Record exceeds maximum size")
|
|
|
|
else:
|
|
|
|
ok(raw)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func makeEnrAux(
|
2024-06-24 12:57:39 +00:00
|
|
|
seqNum: uint64, id: string, pk: PrivateKey,
|
2021-12-20 12:14:50 +00:00
|
|
|
pairs: openArray[FieldPair]): EnrResult[Record] =
|
2020-07-07 15:19:15 +00:00
|
|
|
var record: Record
|
|
|
|
record.pairs = @pairs
|
|
|
|
record.seqNum = seqNum
|
|
|
|
|
|
|
|
let pubkey = pk.toPublicKey()
|
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
record.pairs.insert(("id", Field(kind: kString, str: id)))
|
|
|
|
record.pairs.insert(("secp256k1",
|
2020-07-07 15:19:15 +00:00
|
|
|
Field(kind: kBytes, bytes: @(pubkey.toRawCompressed()))))
|
|
|
|
|
|
|
|
record.raw = ? makeEnrRaw(seqNum, pk, record.pairs)
|
2020-04-29 22:11:03 +00:00
|
|
|
ok(record)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
macro initRecord*(
|
|
|
|
seqNum: uint64, pk: PrivateKey,
|
2024-06-24 12:57:39 +00:00
|
|
|
pairs: untyped{nkTableConstr}): untyped {.deprecated: "Please use Record.init instead".} =
|
2020-07-07 15:19:15 +00:00
|
|
|
## Initialize a `Record` with given sequence number, private key and k:v
|
|
|
|
## pairs.
|
|
|
|
##
|
|
|
|
## Can fail in case the record exceeds the `maxEnrSize`.
|
2024-06-24 12:57:39 +00:00
|
|
|
# Note: Deprecated as it is flawed. It allows for any type to be stored in the
|
|
|
|
# predefined keys. It also allows for duplicate keys (which could be fixed)
|
|
|
|
# and no longer sorts the pairs. It can however be moved and used for testing
|
|
|
|
# purposes.
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
for c in pairs:
|
|
|
|
c.expectKind(nnkExprColonExpr)
|
|
|
|
c[1] = newCall(bindSym"toField", c[1])
|
|
|
|
|
|
|
|
result = quote do:
|
2024-06-24 12:57:39 +00:00
|
|
|
makeEnrAux(`seqNum`, "v4", `pk`, `pairs`)
|
2020-04-15 02:32:52 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
func insertAddress(
|
2022-11-15 09:34:56 +00:00
|
|
|
fields: var seq[FieldPair],
|
2024-06-18 16:09:27 +00:00
|
|
|
ip: Opt[IpAddress],
|
|
|
|
tcpPort, udpPort: Opt[Port]) =
|
2024-06-24 12:57:39 +00:00
|
|
|
## Insert address data.
|
|
|
|
## Incomplete address information is allowed (example: Port but not IP) as
|
|
|
|
## that information might be already in the ENR or added later.
|
2020-03-30 11:21:32 +00:00
|
|
|
if ip.isSome():
|
2024-06-24 12:57:39 +00:00
|
|
|
case ip.value.family
|
|
|
|
of IPv4:
|
|
|
|
fields.insert(("ip", ip.value.address_v4.toField))
|
|
|
|
of IPv6:
|
|
|
|
fields.insert(("ip6", ip.value.address_v6.toField))
|
|
|
|
|
|
|
|
if tcpPort.isSome():
|
|
|
|
fields.insert(("tcp", tcpPort.get().uint16.toField))
|
|
|
|
if udpPort.isSome():
|
|
|
|
fields.insert(("udp", udpPort.get().uint16.toField))
|
2020-04-15 02:32:52 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func init*(
|
|
|
|
T: type Record,
|
|
|
|
seqNum: uint64, pk: PrivateKey,
|
2024-06-24 12:57:39 +00:00
|
|
|
ip: Opt[IpAddress] = Opt.none(IpAddress),
|
|
|
|
tcpPort: Opt[Port] = Opt.none(Port),
|
|
|
|
udpPort: Opt[Port] = Opt.none(Port),
|
2022-11-15 09:34:56 +00:00
|
|
|
extraFields: openArray[FieldPair] = []):
|
|
|
|
EnrResult[T] =
|
2020-07-08 10:14:00 +00:00
|
|
|
## Initialize a `Record` with given sequence number, private key, optional
|
2020-07-08 12:56:56 +00:00
|
|
|
## ip address, tcp port, udp port, and optional custom k:v pairs.
|
2020-07-08 10:14:00 +00:00
|
|
|
##
|
|
|
|
## Can fail in case the record exceeds the `maxEnrSize`.
|
2024-06-24 12:57:39 +00:00
|
|
|
doAssert(not hasPredefinedKey(extraFields), "Predefined key in custom pairs")
|
|
|
|
|
2020-07-08 10:14:00 +00:00
|
|
|
var fields = newSeq[FieldPair]()
|
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
fields.insertAddress(ip, tcpPort, udpPort)
|
|
|
|
fields.insert extraFields
|
|
|
|
makeEnrAux(seqNum, "v4", pk, fields)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func getField(r: Record, name: string, field: var Field): bool =
|
2019-12-10 18:34:57 +00:00
|
|
|
# It might be more correct to do binary search,
|
|
|
|
# as the fields are sorted, but it's unlikely to
|
|
|
|
# make any difference in reality.
|
|
|
|
for (k, v) in r.pairs:
|
|
|
|
if k == name:
|
|
|
|
field = v
|
|
|
|
return true
|
2022-11-15 09:34:56 +00:00
|
|
|
false
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func requireKind(f: Field, kind: FieldKind): EnrResult[void] =
|
2019-12-10 18:34:57 +00:00
|
|
|
if f.kind != kind:
|
2021-12-21 14:09:32 +00:00
|
|
|
err("Wrong field kind")
|
|
|
|
else:
|
|
|
|
ok()
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func get*(r: Record, key: string, T: type): EnrResult[T] =
|
2020-07-12 15:25:18 +00:00
|
|
|
## Get the value from the provided key.
|
2019-12-10 18:34:57 +00:00
|
|
|
var f: Field
|
|
|
|
if r.getField(key, f):
|
2019-12-18 01:10:09 +00:00
|
|
|
when T is SomeInteger:
|
2021-12-21 14:09:32 +00:00
|
|
|
? requireKind(f, kNum)
|
|
|
|
ok(T(f.num))
|
2019-12-18 01:10:09 +00:00
|
|
|
elif T is seq[byte]:
|
2021-12-21 14:09:32 +00:00
|
|
|
? requireKind(f, kBytes)
|
|
|
|
ok(f.bytes)
|
2019-12-18 01:10:09 +00:00
|
|
|
elif T is string:
|
2021-12-21 14:09:32 +00:00
|
|
|
? requireKind(f, kString)
|
|
|
|
ok(f.str)
|
2020-02-17 22:47:13 +00:00
|
|
|
elif T is PublicKey:
|
2021-12-21 14:09:32 +00:00
|
|
|
? requireKind(f, kBytes)
|
2020-04-04 16:44:01 +00:00
|
|
|
let pk = PublicKey.fromRaw(f.bytes)
|
|
|
|
if pk.isErr:
|
2021-12-21 14:09:32 +00:00
|
|
|
err("Invalid public key")
|
|
|
|
else:
|
|
|
|
ok(pk[])
|
2019-12-18 01:10:09 +00:00
|
|
|
elif T is array:
|
2021-12-21 14:09:32 +00:00
|
|
|
when type(default(T)[low(T)]) is byte:
|
|
|
|
? requireKind(f, kBytes)
|
|
|
|
if f.bytes.len != T.len:
|
|
|
|
err("Invalid byte blob length")
|
|
|
|
else:
|
|
|
|
var res: T
|
|
|
|
copyMem(addr res[0], addr f.bytes[0], res.len)
|
|
|
|
ok(res)
|
2019-12-18 01:10:09 +00:00
|
|
|
else:
|
|
|
|
{.fatal: "Unsupported output type in enr.get".}
|
|
|
|
else:
|
|
|
|
{.fatal: "Unsupported output type in enr.get".}
|
2019-12-13 17:29:42 +00:00
|
|
|
else:
|
2021-12-21 14:09:32 +00:00
|
|
|
err("Key not found in ENR")
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-18 16:09:27 +00:00
|
|
|
func get*(r: Record, T: type PublicKey): Opt[T] =
|
2020-07-12 15:25:18 +00:00
|
|
|
## Get the `PublicKey` from provided `Record`. Return `none` when there is
|
|
|
|
## no `PublicKey` in the record.
|
2019-12-10 18:34:57 +00:00
|
|
|
var pubkeyField: Field
|
|
|
|
if r.getField("secp256k1", pubkeyField) and pubkeyField.kind == kBytes:
|
2020-04-04 16:44:01 +00:00
|
|
|
let pk = PublicKey.fromRaw(pubkeyField.bytes)
|
|
|
|
if pk.isOk:
|
2024-06-18 16:09:27 +00:00
|
|
|
return Opt.some(pk[])
|
|
|
|
Opt.none(T)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func update*(
|
2024-06-24 12:57:39 +00:00
|
|
|
record: var Record,
|
|
|
|
pk: PrivateKey,
|
|
|
|
ip: Opt[IpAddress] = Opt.none(IpAddress),
|
|
|
|
tcpPort: Opt[Port] = Opt.none(Port),
|
|
|
|
udpPort: Opt[Port] = Opt.none(Port),
|
|
|
|
extraFields: openArray[FieldPair] = []):
|
|
|
|
EnrResult[void] =
|
|
|
|
## Update a `Record` with given ip address, tcp port, udp port and optional
|
|
|
|
## custom k:v pairs.
|
|
|
|
##
|
|
|
|
## If none of the k:v pairs are changed, the sequence number of the `Record`
|
|
|
|
## will still be incremented and a new signature will be applied.
|
2020-07-08 12:56:56 +00:00
|
|
|
##
|
2024-06-24 12:57:39 +00:00
|
|
|
## Providing an `Opt.none` for `ip`, `tcpPort` or `udpPort` will leave the
|
|
|
|
## corresponding field untouched.
|
2020-07-08 12:56:56 +00:00
|
|
|
##
|
|
|
|
## Can fail in case of wrong `PrivateKey`, if the size of the resulting record
|
|
|
|
## exceeds `maxEnrSize` or if maximum sequence number is reached. The `Record`
|
|
|
|
## will not be altered in these cases.
|
2024-06-24 12:57:39 +00:00
|
|
|
# TODO: deprecate this call and have individual functions for updating?
|
|
|
|
doAssert(not hasPredefinedKey(extraFields), "Predefined key in custom pairs")
|
|
|
|
|
2020-07-07 15:19:15 +00:00
|
|
|
var r = record
|
|
|
|
|
|
|
|
let pubkey = r.get(PublicKey)
|
|
|
|
if pubkey.isNone() or pubkey.get() != pk.toPublicKey():
|
|
|
|
return err("Public key does not correspond with given private key")
|
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
r.pairs.insertAddress(ip, tcpPort, udpPort)
|
|
|
|
r.pairs.insert extraFields
|
2020-07-07 20:48:26 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
if r.seqNum == high(type r.seqNum): # highly unlikely
|
|
|
|
return err("Maximum sequence number reached")
|
|
|
|
r.seqNum.inc()
|
2020-07-07 20:48:26 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
r.raw = ? makeEnrRaw(r.seqNum, pk, r.pairs)
|
|
|
|
record = r
|
2020-07-07 21:39:32 +00:00
|
|
|
|
2024-06-24 12:57:39 +00:00
|
|
|
ok()
|
2020-07-07 15:19:15 +00:00
|
|
|
|
2024-06-18 16:09:27 +00:00
|
|
|
func tryGet*(r: Record, key: string, T: type): Opt[T] =
|
2020-07-12 15:25:18 +00:00
|
|
|
## Get the value from the provided key.
|
|
|
|
## Return `none` if the key does not exist or if the value is invalid
|
|
|
|
## according to type `T`.
|
2024-06-18 16:09:27 +00:00
|
|
|
get(r, key, T).optValue()
|
2019-12-18 01:10:09 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromRecord*(T: type TypedRecord, r: Record): T =
|
|
|
|
TypedRecord(
|
|
|
|
id: r.get("id", string).expect("Record must always have id field"),
|
|
|
|
secp256k1: r.tryGet("secp256k1", array[33, byte]),
|
|
|
|
ip: r.tryGet("ip", array[4, byte]),
|
|
|
|
ip6: r.tryGet("ip6", array[16, byte]),
|
|
|
|
tcp: r.tryGet("tcp", int),
|
|
|
|
tcp6: r.tryGet("tcp6", int),
|
|
|
|
udp: r.tryGet("udp", int),
|
|
|
|
udp6: r.tryGet("udp6", int)
|
|
|
|
)
|
|
|
|
|
|
|
|
func toTypedRecord*(r: Record): EnrResult[TypedRecord] {.deprecated: "Please use TypedRecord.fromRecord instead".} =
|
|
|
|
ok(TypedRecord.fromRecord(r))
|
2019-12-18 01:10:09 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func contains*(r: Record, fp: (string, seq[byte])): bool =
|
2020-06-11 19:24:52 +00:00
|
|
|
# TODO: use FieldPair for this, but that is a bit cumbersome. Perhaps the
|
|
|
|
# `get` call can be improved to make this easier.
|
|
|
|
let field = r.tryGet(fp[0], seq[byte])
|
|
|
|
if field.isSome():
|
|
|
|
if field.get() == fp[1]:
|
|
|
|
return true
|
2022-11-15 09:34:56 +00:00
|
|
|
false
|
2020-06-11 19:24:52 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func verifySignatureV4(
|
2024-06-27 13:15:23 +00:00
|
|
|
publicKey: PublicKey, sigData: openArray[byte], content: openArray[byte]): EnrResult[void] =
|
|
|
|
## Verify the signature for the "v4" identity scheme
|
|
|
|
let signature = ?SignatureNR.fromRaw(sigData)
|
|
|
|
let hash = keccak256.digest(content)
|
|
|
|
if verify(signature, SkMessage(hash.data), publicKey):
|
|
|
|
ok()
|
2022-11-15 09:34:56 +00:00
|
|
|
else:
|
2024-06-27 13:15:23 +00:00
|
|
|
err("Signature verfication failed")
|
|
|
|
|
|
|
|
template rlpResult(body: untyped): auto =
|
|
|
|
try:
|
|
|
|
body
|
|
|
|
except RlpError:
|
|
|
|
return err("Invalid RLP list")
|
|
|
|
|
|
|
|
func buildRlpContent(bytes: openArray[byte]): EnrResult[seq[byte]] =
|
|
|
|
## Rebuild the encoded RLP content without the signature. This is used to
|
|
|
|
## verify the signature.
|
|
|
|
var rlp = rlpFromBytes(bytes)
|
|
|
|
let listLen = rlpResult rlp.listLen
|
|
|
|
doAssert rlp.enterList()
|
|
|
|
|
|
|
|
# skip signature
|
|
|
|
rlpResult rlp.skipElem()
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
let content = block:
|
2024-06-27 13:15:23 +00:00
|
|
|
var writer = initRlpList(listLen - 1)
|
|
|
|
for i in 1 ..< listLen:
|
|
|
|
rlpResult:
|
|
|
|
writer.appendRawBytes(rlp.rawData)
|
|
|
|
rlp.skipElem()
|
2019-12-10 18:34:57 +00:00
|
|
|
writer.finish()
|
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
ok(content)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromBytesAux(T: type Record, s: openArray[byte]): EnrResult[T] =
|
|
|
|
## Creates ENR from rlp-encoded bytes and verifies the signature.
|
|
|
|
if s.len > maxEnrSize:
|
|
|
|
return err("Record exceeds maximum size")
|
2019-12-18 11:06:45 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
var rlp = rlpFromBytes(s)
|
2020-02-27 18:09:05 +00:00
|
|
|
if not rlp.isList:
|
2024-06-27 13:15:23 +00:00
|
|
|
return err("Record does not contain valid RLP list")
|
2020-02-27 18:09:05 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
let sz = rlpResult rlp.listLen
|
2019-12-18 11:06:45 +00:00
|
|
|
if sz < minRlpListLen or sz mod 2 != 0:
|
2024-06-27 13:15:23 +00:00
|
|
|
return err("Wrong RLP list length")
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2020-02-27 18:09:05 +00:00
|
|
|
# We already know we are working with a list
|
2020-02-29 16:35:08 +00:00
|
|
|
doAssert rlp.enterList()
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
let
|
|
|
|
signatureRaw = rlpResult rlp.read(seq[byte])
|
|
|
|
seqNum = rlpResult rlp.read(uint64)
|
|
|
|
numPairs = (sz - 2) div 2
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
var
|
|
|
|
pairs = newSeqOfCap[FieldPair](numPairs)
|
|
|
|
id: string = ""
|
|
|
|
pkRaw = Opt.none(seq[byte])
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
for i in 0 ..< numPairs:
|
2024-06-27 13:15:23 +00:00
|
|
|
let k = rlpResult rlp.read(string)
|
2019-12-10 18:34:57 +00:00
|
|
|
case k
|
|
|
|
of "id":
|
2024-06-27 13:15:23 +00:00
|
|
|
id = rlpResult rlp.read(string)
|
|
|
|
pairs.add((k, Field(kind: kString, str: id)))
|
2019-12-10 18:34:57 +00:00
|
|
|
of "secp256k1":
|
2024-06-27 13:15:23 +00:00
|
|
|
pkRaw = Opt.some rlpResult rlp.read(seq[byte])
|
|
|
|
pairs.add((k, Field(kind: kBytes, bytes: pkRaw.value())))
|
2020-02-11 16:25:31 +00:00
|
|
|
of "tcp", "udp", "tcp6", "udp6":
|
2024-06-27 13:15:23 +00:00
|
|
|
let v = rlpResult rlp.read(uint16)
|
|
|
|
pairs.add((k, Field(kind: kNum, num: v)))
|
2019-12-10 18:34:57 +00:00
|
|
|
else:
|
2021-10-19 07:26:14 +00:00
|
|
|
# Don't know really what this is supposed to represent so drop it in
|
|
|
|
# `kBytes` field pair when a single byte or blob.
|
|
|
|
if rlp.isSingleByte() or rlp.isBlob():
|
2024-06-27 13:15:23 +00:00
|
|
|
let bytes = rlpResult rlp.read(seq[byte])
|
|
|
|
pairs.add((k, Field(kind: kBytes, bytes: bytes)))
|
2021-10-19 07:26:14 +00:00
|
|
|
elif rlp.isList():
|
|
|
|
# Not supporting decoding lists as value (especially unknown ones),
|
|
|
|
# just drop the raw RLP value in there.
|
2024-06-27 13:15:23 +00:00
|
|
|
pairs.add((k, Field(kind: kList, listRaw: @(rlpResult rlp.rawData()))))
|
2021-10-19 07:26:14 +00:00
|
|
|
# Need to skip the element still.
|
2024-06-27 13:15:23 +00:00
|
|
|
rlpResult rlp.skipElem()
|
|
|
|
|
|
|
|
# Storing the PublicKey in the Record as `fromRaw` is relatively expensive.
|
|
|
|
let pk: PublicKey =
|
|
|
|
case id
|
|
|
|
of "":
|
|
|
|
return err("No id k:v pair in the ENR")
|
|
|
|
of "v4":
|
|
|
|
let content = ?buildRlpContent(s)
|
|
|
|
if pkRaw.isNone():
|
|
|
|
return err("No secp256k1 k:v pair in the ENR")
|
|
|
|
let pk = ?PublicKey.fromRaw(pkRaw.value())
|
|
|
|
?verifySignatureV4(pk, signatureRaw, content)
|
|
|
|
pk
|
|
|
|
else:
|
|
|
|
return err("Unknown Identity Scheme")
|
|
|
|
|
|
|
|
ok(Record(
|
|
|
|
seqNum: seqNum,
|
|
|
|
pairs: pairs,
|
|
|
|
raw: @s,
|
|
|
|
publicKey: pk
|
|
|
|
))
|
|
|
|
|
|
|
|
func fromBytes*(T: type Record, s: openArray[byte]): EnrResult[T] =
|
|
|
|
## Creates ENR from rlp-encoded bytes and verifies the signature.
|
|
|
|
Record.fromBytesAux(s)
|
|
|
|
|
|
|
|
func fromBytes*(r: var Record, s: openArray[byte]): bool {.deprecated: "Use the Result[Record] version instead".} =
|
|
|
|
## Loads ENR from rlp-encoded bytes and verifies the signature.
|
|
|
|
r = Record.fromBytes(s).valueOr:
|
|
|
|
return false
|
|
|
|
true
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromBase64*(T: type Record, s: string): EnrResult[T] =
|
|
|
|
## Creates ENR from base64-encoded rlp-encoded bytes and verifies the
|
|
|
|
## signature.
|
|
|
|
let rlpRaw =
|
|
|
|
try:
|
|
|
|
Base64Url.decode(s)
|
|
|
|
except Base64Error:
|
|
|
|
return err("Base64 decoding error")
|
|
|
|
|
|
|
|
Record.fromBytesAux(rlpRaw)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromBase64*(r: var Record, s: string): bool {.deprecated: "Use the Result[Record] version instead".} =
|
|
|
|
## Loads ENR from base64-encoded rlp-encoded bytes and verifies the
|
2020-04-29 22:11:03 +00:00
|
|
|
## signature.
|
2024-06-27 13:15:23 +00:00
|
|
|
r = Record.fromBase64(s).valueOr:
|
|
|
|
return false
|
|
|
|
true
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromURI*(T: type Record, s: string): EnrResult[T] =
|
|
|
|
## Creates ENR from its URI encoding: base64-encoded rlp-encoded bytes,
|
|
|
|
## prefixed with "enr:". Verifies the signature.
|
2019-12-10 18:34:57 +00:00
|
|
|
const prefix = "enr:"
|
|
|
|
if s.startsWith(prefix):
|
2024-06-27 13:15:23 +00:00
|
|
|
Record.fromBase64(s[prefix.len .. ^1])
|
2022-11-15 09:34:56 +00:00
|
|
|
else:
|
2024-06-27 13:15:23 +00:00
|
|
|
err("Invalid URI prefix")
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
func fromURI*(r: var Record, s: string): bool {.deprecated: "Use the Result[Record] version instead".} =
|
|
|
|
## Loads ENR from its URI encoding: base64-encoded rlp-encoded bytes,
|
|
|
|
## prefixed with "enr:". Verifies the signature.
|
|
|
|
r = Record.fromURI(s).valueOr:
|
|
|
|
return false
|
|
|
|
true
|
|
|
|
|
|
|
|
template fromURI*(r: var Record, url: EnrUri): bool {.deprecated: "Use the Result[Record] version instead".} =
|
2019-12-17 21:20:26 +00:00
|
|
|
fromURI(r, string(url))
|
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func toBase64*(r: Record): string =
|
|
|
|
Base64Url.encode(r.raw)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func toURI*(r: Record): string = "enr:" & r.toBase64
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func `$`(f: Field): string =
|
2019-12-10 18:34:57 +00:00
|
|
|
case f.kind
|
|
|
|
of kNum:
|
|
|
|
$f.num
|
|
|
|
of kBytes:
|
|
|
|
"0x" & f.bytes.toHex
|
|
|
|
of kString:
|
|
|
|
"\"" & f.str & "\""
|
2021-10-19 07:26:14 +00:00
|
|
|
of kList:
|
|
|
|
"(Raw RLP list) " & "0x" & f.listRaw.toHex
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2022-11-10 09:52:24 +00:00
|
|
|
func `$`*(fp: FieldPair): string =
|
|
|
|
fp[0] & ":" & $fp[1]
|
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func `$`*(r: Record): string =
|
|
|
|
var res = "("
|
|
|
|
res &= $r.seqNum
|
2019-12-10 18:34:57 +00:00
|
|
|
for (k, v) in r.pairs:
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= ", "
|
|
|
|
res &= k
|
|
|
|
res &= ": "
|
2021-10-19 12:13:09 +00:00
|
|
|
# For IP addresses we print something prettier than the default kinds
|
|
|
|
# Note: Could disallow for invalid IPs in ENR also.
|
|
|
|
if k == "ip":
|
|
|
|
let ip = r.tryGet("ip", array[4, byte])
|
|
|
|
if ip.isSome():
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= $ipv4(ip.get())
|
2021-10-19 12:13:09 +00:00
|
|
|
else:
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= "(Invalid) " & $v
|
2021-10-19 12:13:09 +00:00
|
|
|
elif k == "ip6":
|
|
|
|
let ip = r.tryGet("ip6", array[16, byte])
|
|
|
|
if ip.isSome():
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= $ipv6(ip.get())
|
2021-10-19 12:13:09 +00:00
|
|
|
else:
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= "(Invalid) " & $v
|
2021-10-19 12:13:09 +00:00
|
|
|
else:
|
2022-11-15 09:34:56 +00:00
|
|
|
res &= $v
|
|
|
|
res &= ')'
|
2019-12-16 19:38:45 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
res
|
2020-03-24 09:51:34 +00:00
|
|
|
|
2022-11-15 09:34:56 +00:00
|
|
|
func `==`*(a, b: Record): bool = a.raw == b.raw
|
|
|
|
|
|
|
|
func read*(
|
|
|
|
rlp: var Rlp, T: type Record):
|
2024-06-27 13:15:23 +00:00
|
|
|
T {.raises: [RlpError].} =
|
|
|
|
if not rlp.hasData():
|
|
|
|
raise newException(RlpError, "Empty RLP data")
|
|
|
|
|
|
|
|
let res = T.fromBytes(rlp.rawData())
|
|
|
|
if res.isErr:
|
|
|
|
raise newException(RlpError, $res.error)
|
|
|
|
|
2019-12-16 19:38:45 +00:00
|
|
|
rlp.skipElem()
|
|
|
|
|
2024-06-27 13:15:23 +00:00
|
|
|
res.value
|
2022-11-15 09:34:56 +00:00
|
|
|
|
|
|
|
func append*(rlpWriter: var RlpWriter, value: Record) =
|
2020-07-17 14:18:50 +00:00
|
|
|
rlpWriter.appendRawBytes(value.raw)
|
2022-11-10 09:52:24 +00:00
|
|
|
|
|
|
|
chronicles.formatIt(seq[FieldPair]): $it
|