-
Notifications
You must be signed in to change notification settings - Fork 16
/
hash.go
56 lines (49 loc) · 1022 Bytes
/
hash.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package merkleTree
import (
"crypto/sha512"
)
// Len returns the number of bytes in the hash, but after shifting off
// leading 0s from the length size of the hash
func (h Hash) Len() int {
for idx, x := range h {
if x != 0 {
return len(h) - idx
}
}
return 0
}
func (h Hash) cmp(h2 Hash) int {
if h.Len() < h2.Len() {
return -1
}
if h.Len() > h2.Len() {
return 1
}
for i, b := range h {
b2 := h2[i]
if b < b2 {
return -1
}
if b > b2 {
return 1
}
}
// Equal in this case
return 0
}
// Less determines if the receiver is less than the arg, after shifting off all
// leading 0 bytes and using big-endian byte ordering.
func (h Hash) Less(h2 Hash) bool {
return h.cmp(h2) < 0
}
// Eq determines if the two hashes are equal.
func (h Hash) Eq(h2 Hash) bool {
return h.cmp(h2) == 0
}
// SHA512Hasher is a simple SHA512 hash function application
type SHA512Hasher struct{}
// Hash the data
func (s SHA512Hasher) Hash(b []byte) Hash {
tmp := sha512.Sum512(b)
return Hash(tmp[:])
}