hash.gno
1.36 Kb · 55 lines
1package qrc
2
3import (
4 "crypto/keccak256"
5 "crypto/sha256"
6)
7
8// HashSize is the output size, in bytes, of both hash functions.
9const HashSize = 32
10
11// Hash names the hash function a commit is built on. A commit uses its
12// function for everything: public keys, message digests and tree nodes.
13type Hash uint8
14
15const (
16 // SHA256 is SHA-256 of FIPS 180-4, the SHA-2 family.
17 SHA256 Hash = 1
18 // Keccak256 is Keccak-256 with the original padding, as used by the
19 // EVM. It is the same sponge and permutation as SHA3-256 of FIPS 202
20 // and differs from it only in the padding byte.
21 Keccak256 Hash = 2
22)
23
24// Valid reports whether h names a supported hash function.
25func (h Hash) Valid() bool {
26 return h == SHA256 || h == Keccak256
27}
28
29// String returns the name of the hash function.
30func (h Hash) String() string {
31 switch h {
32 case SHA256:
33 return "sha256"
34 case Keccak256:
35 return "keccak256"
36 }
37 return "unknown"
38}
39
40// Sum returns the digest of data. It panics if h is not [Valid].
41func (h Hash) Sum(data []byte) [HashSize]byte {
42 return h.function()(data)
43}
44
45// function returns the function h names. Code that hashes in a loop fetches
46// it once instead of calling Sum, which looks it up every time.
47func (h Hash) function() func([]byte) [HashSize]byte {
48 switch h {
49 case SHA256:
50 return sha256.Sum256
51 case Keccak256:
52 return keccak256.Sum256
53 }
54 panic("qrc: unknown hash function")
55}