Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

faster hash for Address #688

Merged
merged 1 commit into from
Jun 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion eth/common/eth_types.nim
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
## from many places

import
std/[options, strutils],
std/[options, hashes, strutils],
stew/[byteutils, endians2], stint,
./eth_hash, ./eth_times

Expand Down Expand Up @@ -319,3 +319,20 @@ func `==`*(a, b: NetworkId): bool =

func `$`*(x: NetworkId): string =
`$`(uint(x))

func `==`*(a, b: EthAddress): bool {.inline.} =
equalMem(unsafeAddr a[0], unsafeAddr b[0], a.len)

# TODO https://github.com/nim-lang/Nim/issues/23678
func hash*(a: EthAddress): Hash {.inline.} =
static: doAssert sizeof(a) == 20
var a0{.noinit.}, a1 {.noinit.}: uint64
var a2{.noinit.}: uint32

# Addresses are more or less random so we should not need a fancy mixing
# function
copyMem(addr a0, unsafeAddr a[0], sizeof(a0))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These will be more efficient if EthAddress also is required to be aligned, which nim-eth does not require and array[20, byte] might not automatically trigger since its base type has sizeof() == 1. But that'd have to be changed in another repo, and it's cleaner to keep the changes separate. Both can help, but this works and is useful on its own.

copyMem(addr a1, unsafeAddr a[8], sizeof(a1))
copyMem(addr a2, unsafeAddr a[16], sizeof(a2))

cast[Hash](a0 xor a1 xor uint64(a2))