nim-eth/eth/trie/trie_utils.nim

64 lines
1.7 KiB
Nim
Raw Normal View History

2019-02-05 12:01:10 +00:00
import
2020-04-18 08:17:59 +00:00
stew/byteutils,
2019-07-07 09:55:17 +00:00
stew/ranges/[typedranges, ptr_arith], nimcrypto/[hash, keccak],
2019-02-05 12:01:10 +00:00
trie_defs, binaries
proc toTrieNodeKey*(hash: KeccakHash): TrieNodeKey =
result = newRange[byte](32)
copyMem(result.baseAddr, hash.data.baseAddr, 32)
template checkValidHashZ*(x: untyped) =
when x.type isnot KeccakHash:
2019-03-13 22:15:26 +00:00
doAssert(x.len == 32 or x.len == 0)
2019-02-05 12:01:10 +00:00
template isZeroHash*(x: ByteRange): bool =
x.len == 0
template toRange*(hash: KeccakHash): ByteRange =
toTrieNodeKey(hash)
proc toRange*(str: string): ByteRange =
var s = newSeq[byte](str.len)
if str.len > 0:
copyMem(s[0].addr, str[0].unsafeAddr, str.len)
result = toRange(s)
proc hashFromHex*(bits: static[int], input: string): MDigest[bits] =
2020-04-18 08:17:59 +00:00
MDigest(data: hexToByteArray[bits div 8](input))
2019-02-05 12:01:10 +00:00
template hashFromHex*(s: static[string]): untyped = hashFromHex(s.len * 4, s)
proc keccakHash*(input: openArray[byte]): ByteRange =
var s = newSeq[byte](32)
var ctx: keccak256
ctx.init()
if input.len > 0:
ctx.update(input[0].unsafeAddr, uint(input.len))
ctx.finish s
ctx.clear()
result = toRange(s)
proc keccakHash*(dest: var openArray[byte], a, b: openArray[byte]) =
var ctx: keccak256
ctx.init()
if a.len != 0:
ctx.update(a[0].unsafeAddr, uint(a.len))
if b.len != 0:
ctx.update(b[0].unsafeAddr, uint(b.len))
ctx.finish dest
ctx.clear()
proc keccakHash*(a, b: openArray[byte]): ByteRange =
var s = newSeq[byte](32)
keccakHash(s, a, b)
result = toRange(s)
template keccakHash*(input: ByteRange): ByteRange =
keccakHash(input.toOpenArray)
template keccakHash*(a, b: ByteRange): ByteRange =
keccakHash(a.toOpenArray, b.toOpenArray)
template keccakHash*(dest: var ByteRange, a, b: ByteRange) =
keccakHash(dest.toOpenArray, a.toOpenArray, b.toOpenArray)