-
Notifications
You must be signed in to change notification settings - Fork 211
/
hashes.go
268 lines (218 loc) · 8.05 KB
/
hashes.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package types
import (
"encoding/hex"
"fmt"
"math/big"
"reflect"
"github.com/spacemeshos/go-scale"
"github.com/spacemeshos/go-spacemesh/codec"
"github.com/spacemeshos/go-spacemesh/common/util"
"github.com/spacemeshos/go-spacemesh/hash"
"github.com/spacemeshos/go-spacemesh/log"
)
const (
// Hash32Length is 32, the expected length of the hash.
Hash32Length = 32
hash20Length = 20
hash12Length = 12
)
// Hash12 represents the first 12 bytes of blake3 hash, mostly used for internal caches.
type Hash12 [hash12Length]byte
// Hash32 represents the 32-byte blake3 hash of arbitrary data.
type Hash32 [Hash32Length]byte
// Hash20 represents the 20-byte blake3 hash of arbitrary data.
type Hash20 [hash20Length]byte
// Field returns a log field. Implements the LoggableField interface.
func (h Hash12) Field() log.Field { return log.String("hash", hex.EncodeToString(h[:])) }
// Bytes gets the byte representation of the underlying hash.
func (h Hash20) Bytes() []byte { return h[:] }
// Big converts a hash to a big integer.
func (h Hash20) Big() *big.Int { return new(big.Int).SetBytes(h[:]) }
// Hex converts a hash to a hex string.
func (h Hash20) Hex() string { return util.Encode(h[:]) }
// String implements the stringer interface and is used also by the logger when
// doing full logging into a file.
func (h Hash20) String() string {
return h.Hex()
}
// ShortString returns a the first 5 characters of the hash, for logging purposes.
func (h Hash20) ShortString() string {
l := len(h.Hex())
return h.Hex()[util.Min(2, l):util.Min(7, l)]
}
// Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
// without going through the stringer interface used for logging.
func (h Hash20) Format(s fmt.State, c rune) {
_, _ = fmt.Fprintf(s, "%"+string(c), h[:])
}
// UnmarshalText parses a hash in hex syntax.
func (h *Hash20) UnmarshalText(input []byte) error {
if err := util.UnmarshalFixedText("Hash", input, h[:]); err != nil {
return fmt.Errorf("unmarshal text: %w", err)
}
return nil
}
// UnmarshalJSON parses a hash in hex syntax.
func (h *Hash20) UnmarshalJSON(input []byte) error {
if err := util.UnmarshalFixedJSON(hashT, input, h[:]); err != nil {
return fmt.Errorf("unmarshal JSON: %w", err)
}
return nil
}
// MarshalText returns the hex representation of h.
func (h Hash20) MarshalText() ([]byte, error) {
return util.Bytes(h[:]).MarshalText()
}
// SetBytes sets the hash to the value of b.
// If b is larger than len(h), b will be cropped from the left.
func (h *Hash20) SetBytes(b []byte) {
if len(b) > len(h) {
b = b[len(b)-32:]
}
copy(h[32-len(b):], b)
}
// ToHash32 returns a Hash32 whose first 20 bytes are the bytes of this Hash20, it is right-padded with zeros.
func (h Hash20) ToHash32() (h32 Hash32) {
copy(h32[:], h[:])
return
}
// Field returns a log field. Implements the LoggableField interface.
func (h Hash20) Field() log.Field { return log.String("hash", hex.EncodeToString(h[:])) }
// CalcHash12 returns the 12-byte prefix of the blake3 sum of the given byte slice.
func CalcHash12(data []byte) (h Hash12) {
h32 := hash.Sum(data)
copy(h[:], h32[:])
return
}
// CalcProposalsHash32 returns the 32-byte blake3 sum of the IDs, sorted in lexicographic order. The pre-image is
// prefixed with additionalBytes.
func CalcProposalsHash32(view []ProposalID, additionalBytes []byte) Hash32 {
sortedView := make([]ProposalID, len(view))
copy(sortedView, view)
SortProposalIDs(sortedView)
return CalcProposalHash32Presorted(sortedView, additionalBytes)
}
// CalcBlocksHash32 returns the 32-byte blake3 sum of the IDs, sorted in lexicographic order. The pre-image is
// prefixed with additionalBytes.
func CalcBlocksHash32(view []BlockID, additionalBytes []byte) Hash32 {
sortedView := make([]BlockID, len(view))
copy(sortedView, view)
SortBlockIDs(sortedView)
return CalcBlockHash32Presorted(sortedView, additionalBytes)
}
// CalcProposalHash32Presorted returns the 32-byte blake3 sum of the IDs, in the order given. The pre-image is
// prefixed with additionalBytes.
func CalcProposalHash32Presorted(sortedView []ProposalID, additionalBytes []byte) Hash32 {
hasher := hash.New()
hasher.Write(additionalBytes)
for _, id := range sortedView {
hasher.Write(id.Bytes()) // this never returns an error: https://golang.org/pkg/hash/#Hash
}
var res Hash32
hasher.Sum(res[:0])
return res
}
// CalcBlockHash32Presorted returns the 32-byte blake3 sum of the IDs, in the order given. The pre-image is
// prefixed with additionalBytes.
func CalcBlockHash32Presorted(sortedView []BlockID, additionalBytes []byte) Hash32 {
hash := hash.New()
hash.Write(additionalBytes)
for _, id := range sortedView {
hash.Write(id.Bytes()) // this never returns an error: https://golang.org/pkg/hash/#Hash
}
var res Hash32
hash.Sum(res[:0])
return res
}
// CalcMessageHash12 returns the 12-byte blake3 sum of the given msg suffixed with protocol.
func CalcMessageHash12(msg []byte, protocol string) Hash12 {
return CalcHash12(append(msg, protocol...))
}
var hashT = reflect.TypeOf(Hash32{})
// CalcHash32 returns the 32-byte blake3 sum of the given data.
func CalcHash32(data []byte) Hash32 {
return hash.Sum(data)
}
// CalcObjectHash32 returns the 32-byte blake3 sum of the scale serialization of the object.
func CalcObjectHash32(obj scale.Encodable) Hash32 {
bytes, err := codec.Encode(obj)
if err != nil {
panic("could not serialize object")
}
return CalcHash32(bytes)
}
// BytesToHash sets b to hash.
// If b is larger than len(h), b will be cropped from the left.
func BytesToHash(b []byte) Hash32 {
var h Hash32
h.SetBytes(b)
return h
}
// HexToHash32 sets byte representation of s to hash.
// If b is larger than len(h), b will be cropped from the left.
func HexToHash32(s string) Hash32 { return BytesToHash(util.FromHex(s)) }
// Bytes gets the byte representation of the underlying hash.
func (h Hash32) Bytes() []byte { return h[:] }
// Hex converts a hash to a hex string.
func (h Hash32) Hex() string { return util.Encode(h[:]) }
// String implements the stringer interface and is used also by the logger when
// doing full logging into a file.
func (h Hash32) String() string {
return h.Hex()
}
// ShortString returns the first 5 characters of the hash, for logging purposes.
func (h Hash32) ShortString() string {
l := len(h.Hex())
return Shorten(h.Hex()[util.Min(2, l):], 10)
}
// Shorten shortens a string to a specified length.
func Shorten(s string, maxlen int) string {
l := len(s)
return s[:util.Min(maxlen, l)]
}
// Format implements fmt.Formatter, forcing the byte slice to be formatted as is,
// without going through the stringer interface used for logging.
func (h Hash32) Format(s fmt.State, c rune) {
_, _ = fmt.Fprintf(s, "%"+string(c), h[:])
}
// UnmarshalText parses a hash in hex syntax.
func (h *Hash32) UnmarshalText(input []byte) error {
if err := util.UnmarshalFixedText("Hash", input, h[:]); err != nil {
return fmt.Errorf("unmarshal text: %w", err)
}
return nil
}
// UnmarshalJSON parses a hash in hex syntax.
func (h *Hash32) UnmarshalJSON(input []byte) error {
if err := util.UnmarshalFixedJSON(hashT, input, h[:]); err != nil {
return fmt.Errorf("unmarshal JSON: %w", err)
}
return nil
}
// MarshalText returns the hex representation of h.
func (h Hash32) MarshalText() ([]byte, error) {
return util.Bytes(h[:]).MarshalText()
}
// SetBytes sets the hash to the value of b.
// If b is larger than len(h), b will be cropped from the left.
func (h *Hash32) SetBytes(b []byte) {
if len(b) > len(h) {
b = b[len(b)-32:]
}
copy(h[32-len(b):], b)
}
// ToHash20 returns a Hash20, whose the 20-byte prefix of this Hash32.
func (h Hash32) ToHash20() (h20 Hash20) {
copy(h20[:], h[:])
return
}
// Field returns a log field. Implements the LoggableField interface.
func (h Hash32) Field() log.Field { return log.String("hash", hex.EncodeToString(h[:])) }
// EncodeScale implements scale codec interface.
func (h *Hash32) EncodeScale(e *scale.Encoder) (int, error) {
return scale.EncodeByteArray(e, h[:])
}
// DecodeScale implements scale codec interface.
func (h *Hash32) DecodeScale(d *scale.Decoder) (int, error) {
return scale.DecodeByteArray(d, h[:])
}