Add SszError to message decoding result (#1660)

This allows for improved error messages. Required changing the PortalResult from cstring to string for the error.
This commit is contained in:
Kim De Mey 2023-08-23 18:03:09 +02:00 committed by GitHub
parent 849c4bc785
commit 6535b39e47
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 9 deletions

View File

@ -142,16 +142,16 @@ func encodeMessage*[T: SomeMessage](m: T): seq[byte] =
elif T is OfferMessage: SSZ.encode(Message(kind: offer, offer: m))
elif T is AcceptMessage: SSZ.encode(Message(kind: accept, accept: m))
func decodeMessage*(body: openArray[byte]): Result[Message, cstring] =
func decodeMessage*(body: openArray[byte]): Result[Message, string] =
try:
if body.len < 1: # TODO: This check should probably move a layer down
return err("No message data, peer might not support this talk protocol")
ok(SSZ.decode(body, Message))
except SszError:
err("Invalid message encoding")
except SszError as e:
err("Invalid message encoding: " & e.msg)
template innerMessage[T: SomeMessage](
message: Message, expected: MessageKind): Result[T, cstring] =
message: Message, expected: MessageKind): Result[T, string] =
if (message.kind == expected):
ok(message.expected)
else:
@ -160,7 +160,7 @@ template innerMessage[T: SomeMessage](
# Each `Message` variants corresponds to an MessageKind. Therefore, the inner
# message can be extracted when providing the expected message type T.
# If the message does not hold the expacted variant, return error.
func getInnerMessage*[T: SomeMessage](m: Message): Result[T, cstring] =
func getInnerMessage*[T: SomeMessage](m: Message): Result[T, string] =
innerMessage[T](m, messageKind(T))
func getTalkReqOverhead*(protocolIdLen: int): int =

View File

@ -171,7 +171,7 @@ type
offerQueue: AsyncQueue[OfferRequest]
offerWorkers: seq[Future[void]]
PortalResult*[T] = Result[T, cstring]
PortalResult*[T] = Result[T, string]
FoundContentKind* = enum
Nodes,
@ -495,9 +495,10 @@ proc reqResponse[Request: SomeMessage, Response: SomeMessage](
# not supporting the specific talk protocol, as according to specification
# an empty response needs to be send in that case.
# See: https://github.com/ethereum/devp2p/blob/master/discv5/discv5-wire.md#talkreq-request-0x05
let messageResponse = talkresp
.flatMap(proc (x: seq[byte]): Result[Message, cstring] = decodeMessage(x))
.flatMap(proc (m: Message): Result[Response, cstring] =
let messageResponse = talkresp.mapErr(proc (x: cstring): string = $x)
.flatMap(proc (x: seq[byte]): Result[Message, string] = decodeMessage(x))
.flatMap(proc (m: Message): Result[Response, string] =
getInnerMessage[Response](m))
if messageResponse.isOk():