forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash_image.go
105 lines (86 loc) · 1.74 KB
/
hash_image.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package gno
import (
"crypto/sha256"
"encoding/binary"
"encoding/hex"
)
type ValueHash struct {
Hashlet
}
func (vh ValueHash) MarshalAmino() (string, error) {
return hex.EncodeToString(vh.Hashlet[:]), nil
}
func (vh *ValueHash) UnmarshalAmino(h string) error {
_, err := hex.Decode(vh.Hashlet[:], []byte(h))
return err
}
func (vh ValueHash) Copy() ValueHash {
return ValueHash{vh.Hashlet.Copy()}
}
//----------------------------------------
// Hash*
const HashSize = 20
type Hashlet [HashSize]byte
func NewHashlet(bz []byte) Hashlet {
res := Hashlet{}
if len(bz) != HashSize {
panic("invalid input size")
}
copy(res[:], bz)
return res
}
func (h Hashlet) Copy() Hashlet {
return h
}
func (h Hashlet) Bytes() []byte {
return h[:]
}
func (h Hashlet) IsZero() bool {
return h == Hashlet{}
}
func HashBytes(bz []byte) (res Hashlet) {
hash := sha256.Sum256(bz)
copy(res[:], hash[:HashSize])
return
}
func leafHash(bz []byte) (res Hashlet) {
buf := make([]byte, 1+len(bz))
buf[0] = 0x00
copy(buf[1:], bz)
res = HashBytes(buf)
return
}
func innerHash(h1, h2 Hashlet) (res Hashlet) {
buf := make([]byte, 1+HashSize*2)
buf[0] = 0x01
copy(buf[1:1+HashSize], h1[:])
copy(buf[1+HashSize:], h2[:])
res = HashBytes(buf)
return
}
//----------------------------------------
// misc
func varintBytes(u int64) []byte {
var buf [10]byte
n := binary.PutVarint(buf[:], u)
return buf[0:n]
}
func sizedBytes(bz []byte) []byte {
bz2 := make([]byte, len(bz)+10)
n := binary.PutVarint(bz2[:10], int64(len(bz)))
copy(bz2[n:n+len(bz)], bz)
return bz2[:n+len(bz)]
}
func isASCIIText(bz []byte) bool {
if len(bz) == 0 {
return false
}
for _, b := range bz {
if 32 <= b && b <= 126 {
// good
} else {
return false
}
}
return true
}