2023-05-09 20:19:44 +00:00
|
|
|
# Copyright (c) 2022-2023 Status Research & Development GmbH
|
2022-09-02 14:57:52 +00:00
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
2023-05-09 20:19:44 +00:00
|
|
|
{.push raises: [].}
|
2022-09-02 14:57:52 +00:00
|
|
|
|
|
|
|
## keccak256 is used across ethereum as the "default" hash function and this
|
|
|
|
## module provides a type and some helpers to produce such hashes
|
|
|
|
|
2024-08-09 05:20:35 +00:00
|
|
|
import
|
|
|
|
nimcrypto/[keccak, hash]
|
2022-09-02 14:57:52 +00:00
|
|
|
|
|
|
|
export
|
2024-08-09 05:20:35 +00:00
|
|
|
keccak.update, keccak.finish, hash
|
2022-09-02 14:57:52 +00:00
|
|
|
|
|
|
|
type
|
|
|
|
KeccakHash* = MDigest[256]
|
|
|
|
## A hash value computed using keccak256
|
2024-08-09 05:20:35 +00:00
|
|
|
## note: this aliases Eth2Digest too, which uses a different hash!
|
2022-09-02 14:57:52 +00:00
|
|
|
|
|
|
|
template withKeccakHash*(body: untyped): KeccakHash =
|
|
|
|
## This little helper will init the hash function and return the sliced
|
|
|
|
## hash:
|
|
|
|
## let hashOfData = withHash: h.update(data)
|
|
|
|
block:
|
|
|
|
var h {.inject.}: keccak256
|
|
|
|
# init(h) # not needed for new instance
|
|
|
|
body
|
|
|
|
finish(h)
|
|
|
|
|
2024-06-07 14:27:38 +00:00
|
|
|
func keccakHash*(input: openArray[byte]): KeccakHash {.noinit.} =
|
|
|
|
# We use the init-update-finish interface to avoid
|
|
|
|
# the expensive burning/clearing memory (20~30% perf)
|
|
|
|
var ctx: keccak256
|
|
|
|
ctx.update(input)
|
|
|
|
ctx.finish()
|
|
|
|
|
|
|
|
func keccakHash*(input: openArray[char]): KeccakHash {.noinit.} =
|
|
|
|
keccakHash(input.toOpenArrayByte(0, input.high()))
|
2022-09-02 14:57:52 +00:00
|
|
|
|
|
|
|
func keccakHash*(a, b: openArray[byte]): KeccakHash =
|
|
|
|
withKeccakHash:
|
|
|
|
h.update a
|
|
|
|
h.update b
|