viem-goviem-go

Hashing Utilities

Cryptographic hashing functions used throughout Ethereum

Cryptographic hashing functions used throughout Ethereum.

keccak256

The primary hash function used in Ethereum:

1import "github.com/ChefBingbong/viem-go/utils/hash"
2
3// Hash bytes
4h := hash.Keccak256([]byte("hello"))
5fmt.Printf("0x%x\n", h)
6// 0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8

sha256

Standard SHA-256 hash:

1h := hash.Sha256([]byte("hello"))
2fmt.Printf("0x%x\n", h)
3// 0x2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

ripemd160

RIPEMD-160 hash (used in Bitcoin addresses):

h := hash.Ripemd160([]byte("hello"))
fmt.Printf("0x%x\n", h)
// 0x108f07b8382412612c048d07d13f814118445acd

hashMessage

Hash a message for EIP-191 personal sign:

1import "github.com/ChefBingbong/viem-go/utils/signature"
2
3// This prepends "\x19Ethereum Signed Message:\n" + length
4messageHash := signature.HashMessage("Hello, Ethereum!")
5fmt.Printf("0x%x\n", messageHash)

The message hash is computed as:

keccak256("\x19Ethereum Signed Message:\n" + len(message) + message)

hashTypedData

Hash EIP-712 typed structured data:

1import "github.com/ChefBingbong/viem-go/utils/signature"
2
3typedData := signature.TypedDataDefinition{
4 Domain: signature.TypedDataDomain{
5 Name: "My App",
6 Version: "1",
7 ChainId: big.NewInt(1),
8 },
9 Types: map[string][]signature.TypedDataField{
10 "Message": {
11 {Name: "content", Type: "string"},
12 },
13 },
14 PrimaryType: "Message",
15 Message: map[string]any{
16 "content": "Hello!",
17 },
18}
19
20hash, err := signature.HashTypedData(typedData)
21fmt.Printf("0x%x\n", hash)

toFunctionSelector

Get the 4-byte function selector:

1selector := hash.ToFunctionSelector("transfer(address,uint256)")
2fmt.Printf("0x%x\n", selector)
3// 0xa9059cbb

toEventSelector

Get the event topic hash:

1topic := hash.ToEventSelector("Transfer(address,address,uint256)")
2fmt.Printf("%s\n", topic.Hex())
3// 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef

isHash

Check if a value is a valid hash:

1valid := hash.IsHash("0x1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8")
2fmt.Println(valid) // true
3
4invalid := hash.IsHash("0x123") // Too short
5fmt.Println(invalid) // false

Common Use Cases

Verify Contract Deployment

// Check if code exists at address
code, _ := client.GetCode(ctx, address)
codeHash := hash.Keccak256(code)
fmt.Printf("Code hash: 0x%x\n", codeHash)

Create Deterministic IDs

// Create unique ID from components
id := hash.Keccak256(append(
    address.Bytes(),
    big.NewInt(timestamp).Bytes()...,
))

Verify Message Signature

// Hash the message the same way it was signed
messageHash := signature.HashMessage(originalMessage)

// Recover the signer
recovered, _ := signature.RecoverAddress(messageHash, sig)

// Verify it matches expected signer
if recovered != expectedSigner {
    return errors.New("invalid signature")
}