2019-12-18 11:06:45 +00:00
|
|
|
# ENR implemetation according to spec:
|
|
|
|
# https://github.com/ethereum/EIPs/blob/master/EIPS/eip-778.md
|
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
import
|
|
|
|
net, strutils, macros, algorithm, options,
|
|
|
|
nimcrypto, stew/base64,
|
|
|
|
eth/[rlp, keys], ../enode
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2019-12-18 11:06:45 +00:00
|
|
|
const
|
|
|
|
maxEnrSize = 300
|
|
|
|
minRlpListLen = 4 # for signature, seqId, "id" key, id
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
type
|
|
|
|
Record* = object
|
2020-02-11 16:25:31 +00:00
|
|
|
seqNum*: uint64
|
2019-12-10 18:34:57 +00:00
|
|
|
# signature: seq[byte]
|
|
|
|
raw*: seq[byte] # RLP encoded record
|
|
|
|
pairs: seq[(string, Field)] # sorted list of all key/value pairs
|
|
|
|
|
2019-12-17 21:20:26 +00:00
|
|
|
EnrUri* = distinct string
|
|
|
|
|
2019-12-18 01:10:09 +00:00
|
|
|
TypedRecord* = object
|
|
|
|
id*: string
|
|
|
|
secp256k1*: Option[array[33, byte]]
|
|
|
|
ip*: Option[array[4, byte]]
|
|
|
|
ip6*: Option[array[16, byte]]
|
|
|
|
tcp*: Option[int]
|
|
|
|
udp*: Option[int]
|
|
|
|
tcp6*: Option[int]
|
|
|
|
udp6*: Option[int]
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
FieldKind = enum
|
|
|
|
kString,
|
|
|
|
kNum,
|
|
|
|
kBytes
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
|
|
|
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))
|
2019-12-10 18:34:57 +00:00
|
|
|
else:
|
|
|
|
{.error: "Unsupported field type".}
|
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
proc makeEnrAux(seqNum: uint64, pk: PrivateKey, pairs: openarray[(string, Field)]): Record =
|
2019-12-10 18:34:57 +00:00
|
|
|
result.pairs = @pairs
|
2020-02-11 16:25:31 +00:00
|
|
|
result.seqNum = seqNum
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
let pubkey = pk.getPublicKey()
|
|
|
|
|
|
|
|
result.pairs.add(("id", Field(kind: kString, str: "v4")))
|
|
|
|
result.pairs.add(("secp256k1", Field(kind: kBytes, bytes: @(pubkey.getRawCompressed()))))
|
|
|
|
|
|
|
|
# Sort by key
|
|
|
|
result.pairs.sort() do(a, b: (string, Field)) -> int:
|
|
|
|
cmp(a[0], b[0])
|
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
proc append(w: var RlpWriter, seqNum: uint64, pairs: openarray[(string, Field)]): seq[byte] =
|
|
|
|
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)
|
|
|
|
w.finish()
|
|
|
|
|
|
|
|
let toSign = block:
|
|
|
|
var w = initRlpList(result.pairs.len * 2 + 1)
|
2020-02-11 16:25:31 +00:00
|
|
|
w.append(seqNum, result.pairs)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
var sig: SignatureNR
|
|
|
|
if signRawMessage(keccak256.digest(toSign).data, pk, sig) != EthKeysStatus.Success:
|
2020-02-17 22:47:13 +00:00
|
|
|
raise newException(EthKeysException, "Could not sign ENR (internal error)")
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
result.raw = block:
|
|
|
|
var w = initRlpList(result.pairs.len * 2 + 2)
|
|
|
|
w.append(sig.getRaw())
|
2020-02-11 16:25:31 +00:00
|
|
|
w.append(seqNum, result.pairs)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
macro initRecord*(seqNum: uint64, pk: PrivateKey, pairs: untyped{nkTableConstr}): untyped =
|
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:
|
2020-02-11 16:25:31 +00:00
|
|
|
makeEnrAux(`seqNum`, `pk`, `pairs`)
|
|
|
|
|
|
|
|
proc init*(T: type Record, seqNum: uint64,
|
|
|
|
pk: PrivateKey,
|
|
|
|
address: enode.Address): T =
|
|
|
|
let
|
|
|
|
isV6 = address.ip.family == IPv6
|
|
|
|
ipField = if isV6: ("ip6", address.ip.address_v6.toField)
|
|
|
|
else: ("ip", address.ip.address_v4.toField)
|
2020-02-11 17:52:07 +00:00
|
|
|
tcpField = ((if isV6: "tcp6" else: "tcp"), address.tcpPort.uint16.toField)
|
|
|
|
udpField = ((if isV6: "udp6" else: "udp"), address.udpPort.uint16.toField)
|
2020-02-11 16:25:31 +00:00
|
|
|
|
|
|
|
makeEnrAux(seqNum, pk, [ipField, tcpField, udpField])
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
proc getField(r: Record, name: string, field: var Field): bool =
|
|
|
|
# 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
|
|
|
|
|
|
|
|
proc requireKind(f: Field, kind: FieldKind) =
|
|
|
|
if f.kind != kind:
|
|
|
|
raise newException(ValueError, "Wrong field kind")
|
|
|
|
|
2019-12-18 01:10:09 +00:00
|
|
|
proc get*(r: Record, key: string, T: type): T =
|
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:
|
2019-12-10 18:34:57 +00:00
|
|
|
requireKind(f, kNum)
|
2019-12-18 01:10:09 +00:00
|
|
|
return T(f.num)
|
|
|
|
elif T is seq[byte]:
|
2019-12-10 18:34:57 +00:00
|
|
|
requireKind(f, kBytes)
|
|
|
|
return f.bytes
|
2019-12-18 01:10:09 +00:00
|
|
|
elif T is string:
|
2019-12-10 18:34:57 +00:00
|
|
|
requireKind(f, kString)
|
|
|
|
return f.str
|
2020-02-17 22:47:13 +00:00
|
|
|
elif T is PublicKey:
|
|
|
|
requireKind(f, kBytes)
|
|
|
|
if recoverPublicKey(f.bytes, result) != EthKeysStatus.Success:
|
|
|
|
raise newException(ValueError, "Invalid public key")
|
2019-12-18 01:10:09 +00:00
|
|
|
elif T is array:
|
|
|
|
when type(result[0]) is byte:
|
|
|
|
requireKind(f, kBytes)
|
|
|
|
if f.bytes.len != result.len:
|
|
|
|
raise newException(ValueError, "Invalid byte blob length")
|
|
|
|
copyMem(addr result[0], addr f.bytes[0], result.len)
|
|
|
|
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:
|
|
|
|
raise newException(KeyError, "Key not found in ENR: " & key)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
proc get*(r: Record, pubKey: var PublicKey): bool =
|
|
|
|
var pubkeyField: Field
|
|
|
|
if r.getField("secp256k1", pubkeyField) and pubkeyField.kind == kBytes:
|
|
|
|
result = recoverPublicKey(pubkeyField.bytes, pubKey) == EthKeysStatus.Success
|
|
|
|
|
2019-12-18 01:10:09 +00:00
|
|
|
proc tryGet*(r: Record, key: string, T: type): Option[T] =
|
|
|
|
try:
|
2020-02-17 22:47:13 +00:00
|
|
|
return some get(r, key, T)
|
2019-12-18 01:10:09 +00:00
|
|
|
except CatchableError:
|
|
|
|
discard
|
|
|
|
|
2020-02-17 22:47:13 +00:00
|
|
|
proc toTypedRecord*(r: Record): Option[TypedRecord] =
|
2019-12-18 01:10:09 +00:00
|
|
|
let id = r.tryGet("id", string)
|
|
|
|
if id.isSome:
|
|
|
|
var tr: TypedRecord
|
|
|
|
tr.id = id.get
|
|
|
|
|
|
|
|
template readField(fieldName: untyped) {.dirty.} =
|
|
|
|
tr.fieldName = tryGet(r, astToStr(fieldName), type(tr.fieldName.get))
|
|
|
|
|
|
|
|
readField secp256k1
|
|
|
|
readField ip
|
|
|
|
readField ip6
|
|
|
|
readField tcp
|
|
|
|
readField tcp6
|
|
|
|
readField udp
|
|
|
|
readField udp6
|
|
|
|
|
|
|
|
return some(tr)
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
proc verifySignatureV4(r: Record, sigData: openarray[byte], content: seq[byte]): bool =
|
|
|
|
var publicKey: PublicKey
|
|
|
|
if r.get(publicKey):
|
|
|
|
var sig: SignatureNR
|
|
|
|
if sig.parseCompact(sigData) == EthKeysStatus.Success:
|
|
|
|
var h = keccak256.digest(content)
|
|
|
|
if verifySignatureRaw(sig, h.data, publicKey) == EthKeysStatus.Success:
|
|
|
|
return true
|
|
|
|
|
|
|
|
proc verifySignature(r: Record): bool =
|
|
|
|
var rlp = rlpFromBytes(r.raw.toRange)
|
|
|
|
let sz = rlp.listLen
|
|
|
|
rlp.enterList()
|
2020-02-11 16:25:31 +00:00
|
|
|
let sigData = rlp.read(Bytes)
|
2019-12-10 18:34:57 +00:00
|
|
|
let content = block:
|
|
|
|
var writer = initRlpList(sz - 1)
|
|
|
|
var reader = rlp
|
|
|
|
for i in 1 ..< sz:
|
|
|
|
writer.appendRawBytes(reader.rawData)
|
|
|
|
reader.skipElem
|
|
|
|
writer.finish()
|
|
|
|
|
|
|
|
var id: Field
|
|
|
|
if r.getField("id", id) and id.kind == kString:
|
|
|
|
case id.str
|
|
|
|
of "v4":
|
|
|
|
result = verifySignatureV4(r, sigData, content)
|
|
|
|
else:
|
|
|
|
# Unknown Identity Scheme
|
|
|
|
discard
|
|
|
|
|
|
|
|
proc fromBytesAux(r: var Record): bool =
|
2020-02-11 16:25:31 +00:00
|
|
|
if r.raw.len > maxEnrSize:
|
|
|
|
return false
|
2019-12-18 11:06:45 +00:00
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
var rlp = rlpFromBytes(r.raw.toRange)
|
|
|
|
let sz = rlp.listLen
|
2019-12-18 11:06:45 +00:00
|
|
|
if sz < minRlpListLen or sz mod 2 != 0:
|
2019-12-10 18:34:57 +00:00
|
|
|
# Wrong rlp object
|
|
|
|
return false
|
|
|
|
|
|
|
|
rlp.enterList()
|
|
|
|
rlp.skipElem() # Skip signature
|
|
|
|
|
2020-02-11 16:25:31 +00:00
|
|
|
r.seqNum = rlp.read(uint64)
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
let numPairs = (sz - 2) div 2
|
|
|
|
|
|
|
|
for i in 0 ..< numPairs:
|
|
|
|
let k = rlp.read(string)
|
|
|
|
case k
|
|
|
|
of "id":
|
2019-12-18 11:06:45 +00:00
|
|
|
let id = rlp.read(string)
|
2019-12-10 18:34:57 +00:00
|
|
|
r.pairs.add((k, Field(kind: kString, str: id)))
|
|
|
|
of "secp256k1":
|
2019-12-18 11:06:45 +00:00
|
|
|
let pubkeyData = rlp.read(seq[byte])
|
2019-12-10 18:34:57 +00:00
|
|
|
r.pairs.add((k, Field(kind: kBytes, bytes: pubkeyData)))
|
2020-02-11 16:25:31 +00:00
|
|
|
of "tcp", "udp", "tcp6", "udp6":
|
|
|
|
let v = rlp.read(uint16)
|
2019-12-10 18:34:57 +00:00
|
|
|
r.pairs.add((k, Field(kind: kNum, num: v)))
|
|
|
|
else:
|
2020-02-11 16:25:31 +00:00
|
|
|
r.pairs.add((k, Field(kind: kBytes, bytes: rlp.read(Bytes))))
|
2019-12-10 18:34:57 +00:00
|
|
|
|
|
|
|
verifySignature(r)
|
|
|
|
|
|
|
|
proc fromBytes*(r: var Record, s: openarray[byte]): bool =
|
|
|
|
# Loads ENR from rlp-encoded bytes, and validated the signature.
|
|
|
|
r.raw = @s
|
|
|
|
try:
|
|
|
|
result = fromBytesAux(r)
|
|
|
|
except CatchableError:
|
|
|
|
discard
|
|
|
|
|
|
|
|
proc fromBase64*(r: var Record, s: string): bool =
|
|
|
|
# Loads ENR from base64-encoded rlp-encoded bytes, and validated the signature.
|
|
|
|
try:
|
|
|
|
r.raw = Base64Url.decode(s)
|
|
|
|
result = fromBytesAux(r)
|
|
|
|
except CatchableError:
|
|
|
|
discard
|
|
|
|
|
|
|
|
proc fromURI*(r: var Record, s: string): bool =
|
|
|
|
# Loads ENR from its text encoding: base64-encoded rlp-encoded bytes, prefixed with "enr:".
|
|
|
|
const prefix = "enr:"
|
|
|
|
if s.startsWith(prefix):
|
|
|
|
result = r.fromBase64(s[prefix.len .. ^1])
|
|
|
|
|
2019-12-17 21:20:26 +00:00
|
|
|
template fromURI*(r: var Record, url: EnrUri): bool =
|
|
|
|
fromURI(r, string(url))
|
|
|
|
|
2019-12-10 18:34:57 +00:00
|
|
|
proc toBase64*(r: Record): string =
|
|
|
|
result = Base64Url.encode(r.raw)
|
|
|
|
|
|
|
|
proc toURI*(r: Record): string = "enr:" & r.toBase64
|
|
|
|
|
|
|
|
proc `$`(f: Field): string =
|
|
|
|
case f.kind
|
|
|
|
of kNum:
|
|
|
|
$f.num
|
|
|
|
of kBytes:
|
|
|
|
"0x" & f.bytes.toHex
|
|
|
|
of kString:
|
|
|
|
"\"" & f.str & "\""
|
|
|
|
|
|
|
|
proc `$`*(r: Record): string =
|
|
|
|
result = "("
|
|
|
|
var first = true
|
|
|
|
for (k, v) in r.pairs:
|
|
|
|
if first:
|
|
|
|
first = false
|
|
|
|
else:
|
|
|
|
result &= ", "
|
|
|
|
result &= k
|
|
|
|
result &= ": "
|
|
|
|
result &= $v
|
|
|
|
result &= ')'
|
2019-12-16 19:38:45 +00:00
|
|
|
|
|
|
|
proc read*(rlp: var Rlp, T: typedesc[Record]): T {.inline.} =
|
|
|
|
if not result.fromBytes(rlp.rawData.toOpenArray):
|
|
|
|
raise newException(ValueError, "Could not deserialize")
|
|
|
|
rlp.skipElem()
|
|
|
|
|
|
|
|
proc append*(rlpWriter: var RlpWriter, value: Record) =
|
|
|
|
rlpWriter.appendRawBytes(value.raw.toRange)
|