Add a `sszList` helper for writing tests involving SSZ lists

This commit is contained in:
Zahary Karadjov 2019-08-16 18:50:04 +02:00
parent 7d3d30c576
commit f477eb6877
No known key found for this signature in database
GPG Key ID: C8936F8A3073D609
2 changed files with 21 additions and 2 deletions

View File

@ -48,7 +48,7 @@ type
Chunk = array[bytesPerChunk, byte]
TypeWithMaxLen[T; maxLen: static int64] = distinct T
TypeWithMaxLen*[T; maxLen: static int64] = distinct T
SizePrefixed*[T] = distinct T
SszMaxSizeExceeded* = object of SerializationError
@ -84,13 +84,16 @@ when false:
# TODO: Nim can't handle yet this simpler definition. File an issue.
template valueOf[T; N](x: TypeWithMaxLen[T, N]): auto = T(x)
else:
proc unwrapImpl[T; N](x: ptr TypeWithMaxLen[T, N]): ptr T =
proc unwrapImpl[T; N: static int64](x: ptr TypeWithMaxLen[T, N]): ptr T =
cast[ptr T](x)
template valueOf(x: TypeWithMaxLen): auto =
let xaddr = unsafeAddr x
unwrapImpl(xaddr)[]
template sszList*(x: seq|array, maxLen: static int64): auto =
TypeWithMaxLen[type(x), maxLen](x)
template toSszType*(x: auto): auto =
mixin toSszType

View File

@ -68,6 +68,9 @@ type
Baz = object
i: uint64
proc toDigest[N: static int](x: array[N, byte]): Eth2Digest =
result.data[0 .. N-1] = x
suite "SSZ Navigation":
test "simple object fields":
var foo = Foo(bar: Bar(b: "bar", baz: Baz(i: 10'u64)))
@ -81,3 +84,16 @@ suite "SSZ Navigation":
let mountedBar = mountedFoo.bar
check mountedBar.baz.i == 10'u64
test "lists with max size":
let a = [byte 0x01, 0x02, 0x03].toDigest
let b = [byte 0x04, 0x05, 0x06].toDigest
let c = [byte 0x07, 0x08, 0x09].toDigest
let leaves = sszList(@[a, b, c], int64(1 shl 3))
let root = hashTreeRoot(leaves)
check $root == "5248085B588FAB1DD1E03F3CD62201602B12E6560665935964F46E805977E8C5"
let leaves2 = sszList(@[a, b, c], int64(1 shl 10))
let root2 = hashTreeRoot(leaves2)
check $root2 == "9FB7D518368DC14E8CC588FB3FD2749BEEF9F493FEF70AE34AF5721543C67173"