From 9a1d35f803d4ae2bda0ede2356cc3213977a3d60 Mon Sep 17 00:00:00 2001 From: Jordan Hrycaj Date: Wed, 19 Apr 2023 13:26:41 +0100 Subject: [PATCH] Fix block body encoding (#598) why: List wrapper was missing in `append()` mixin. --- eth/common/eth_types_rlp.nim | 3 ++- tests/rlp/test_api_usage.nim | 31 ++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/eth/common/eth_types_rlp.nim b/eth/common/eth_types_rlp.nim index d325bcb..48d35c3 100644 --- a/eth/common/eth_types_rlp.nim +++ b/eth/common/eth_types_rlp.nim @@ -358,10 +358,11 @@ proc rlpHash*[T](v: T): Hash256 = func blockHash*(h: BlockHeader): KeccakHash {.inline.} = rlpHash(h) proc append*(w: var RlpWriter, b: BlockBody) = + w.startList 2 + b.withdrawals.isSome.ord w.append(b.transactions) w.append(b.uncles) if b.withdrawals.isSome: - w.append(b.withdrawals.get) + w.append(b.withdrawals.unsafeGet) # Is there a better way of doing this? We have tests that call # rlp.readRecordType(BlockBody, false), so I overrode diff --git a/tests/rlp/test_api_usage.nim b/tests/rlp/test_api_usage.nim index c790968..e9578f2 100644 --- a/tests/rlp/test_api_usage.nim +++ b/tests/rlp/test_api_usage.nim @@ -4,12 +4,38 @@ import std/[math, strutils], unittest2, stew/byteutils, - ../../eth/rlp + ../../eth/[common, rlp] proc q(s: string): string = "\"" & s & "\"" proc i(s: string): string = s.replace(" ").replace("\n") proc inspectMatch(r: Rlp, s: string): bool = r.inspect.i == s.i +proc `==`(a,b: ChainId): bool {.borrow.} + ## helper for ` test_calcBlockBodyTranscode()` + +proc test_blockBodyTranscode() = + ## RLP encode/decode a list of `BlockBody` objects. Note that tere is/was a + ## problem in `eth/common/eth_types_rlp.append()` for `BlockBody` encoding. + let blkSeq = @[ + BlockBody( + transactions: @[ + Transaction(nonce: 1)]), + BlockBody( + uncles: @[ + BlockHeader(nonce: [0x20u8,0,0,0,0,0,0,0])]), + BlockBody(), + BlockBody( + transactions: @[ + Transaction(nonce: 3), + Transaction(nonce: 4)])] + + let trBlkSeq = blkSeq.encode.decode(typeof blkSeq) + + check trBlkSeq.len == blkSeq.len + for n in 0 ..< min(trBlkSeq.len, trBlkSeq.len): + check (n, trBlkSeq[n]) == (n, blkSeq[n]) + + when (NimMajor, NimMinor, NimPatch) < (1, 4, 0): type AssertionDefect = AssertionError @@ -120,6 +146,9 @@ suite "test api usage": check(not list.hasData) expect AssertionDefect: list.skipElem + test "encode and decode block body": + test_blockBodyTranscode() + test "toBytes": let rlp = rlpFromHex("f2cb847f000001827666827666a040ef02798f211da2e8173d37f255be908871ae65060dbb2f77fb29c0421447f4845ab90b50") let tok = rlp.listElem(1).toBytes()