-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_hash.go
67 lines (60 loc) · 1.32 KB
/
util_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
57
58
59
60
61
62
63
64
65
66
67
package hash
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"io"
)
// Hash returns the Hash256 value of the data
func Hash(data []byte) Hash256 {
h := sha256.New()
if _, err := h.Write(data); err != nil {
panic(err)
}
bs := h.Sum(nil)
var hash Hash256
copy(hash[:], bs)
return hash
}
// DoubleHash returns the result of Hash(Hash(data))
func DoubleHash(data []byte) Hash256 {
h1 := Hash(data)
return Hash(h1[:])
}
// TwoHash returns the result of Hash(h1,'h',h2)
func TwoHash(h1 Hash256, h2 Hash256) Hash256 {
data := make([]byte, Hash256Size*2+1)
copy(data, h1[:])
data[Hash256Size] = 'h'
copy(data[Hash256Size+1:], h2[:])
return Hash(data)
}
// ParseHex parses the Hash256 from the hex string
func ParseHex(str string) (Hash256, error) {
bs, err := hex.DecodeString(str)
if err != nil {
return Hash256{}, err
}
if len(bs) != Hash256Size {
return Hash256{}, ErrInvalidHashSize
}
var h Hash256
copy(h[:], bs)
return h, nil
}
// MustParseHex panics when parsing fails.
func MustParseHex(str string) Hash256 {
h, err := ParseHex(str)
if err != nil {
panic(err)
}
return h
}
// DoubleHashByWriterTo returns the result of Hash(io.Writer)
func DoubleHashByWriterTo(w io.WriterTo) Hash256 {
var buffer bytes.Buffer
if _, err := w.WriteTo(&buffer); err != nil {
panic(err)
}
return DoubleHash(buffer.Bytes())
}