-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
377 lines (324 loc) · 8.83 KB
/
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
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package primitives
import (
"bufio"
"bytes"
"crypto/sha256"
"crypto/sha512"
"encoding"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"reflect"
"runtime/debug"
"time"
"github.com/DCNT-developer/dcnt/common/constants"
"github.com/DCNT-developer/dcnt/common/globals"
"github.com/DCNT-developer/dcnt/common/interfaces"
"github.com/DCNT-developer/dcnt/common/primitives/random"
"github.com/DCNT-developer/dcnt/util/atomic"
)
type Hash [constants.HASH_LENGTH]byte
var _ interfaces.Printable = (*Hash)(nil)
var _ interfaces.IHash = (*Hash)(nil)
var _ interfaces.BinaryMarshallableAndCopyable = (*Hash)(nil)
var _ encoding.TextMarshaler = (*Hash)(nil)
var ZeroHash interfaces.IHash = NewHash(constants.ZERO_HASH)
var noRepeat map[string]int = make(map[string]int)
func LogNilHashBug(msg string) {
whereAmI := atomic.WhereAmIString(2)
noRepeat[whereAmI]++
if noRepeat[whereAmI]%100 == 1 {
fmt.Fprintf(os.Stderr, "%s. Called from %s\n", msg, whereAmI)
}
}
func (h *Hash) IsHashNil() bool {
return h == nil || reflect.ValueOf(h).IsNil()
}
func RandomHash() interfaces.IHash {
h := random.RandByteSliceOfLen(constants.HASH_LENGTH)
answer := new(Hash)
answer.SetBytes(h)
return answer
}
func (c *Hash) Copy() (rval interfaces.IHash) {
defer func() {
if rval != nil && reflect.ValueOf(rval).IsNil() {
rval = nil // convert an interface that is nil to a nil interface
LogNilHashBug("Hash.Copy() saw an interface that was nil")
}
}()
h := new(Hash)
err := h.SetBytes(c.Bytes())
if err != nil {
panic(err)
}
return h
}
func (c *Hash) New() interfaces.BinaryMarshallableAndCopyable {
return new(Hash)
}
func (h *Hash) MarshalText() (rval []byte, err error) {
defer func(pe *error) {
if *pe != nil {
fmt.Fprintf(os.Stderr, "Hash.MarshalText err:%v", *pe)
}
}(&err)
return []byte(hex.EncodeToString(h[:])), nil
}
func (h *Hash) IsZero() bool {
return h.String() == "0000000000000000000000000000000000000000000000000000000000000000"
}
// NewShaHashFromStr creates a ShaHash from a hash string. The string should be
// the hexadecimal string of a byte-reversed hash, but any missing characters
// result in zero padding at the end of the ShaHash.
func NewShaHashFromStr(hash string) (*Hash, error) {
h := new(Hash)
err := h.UnmarshalText([]byte(hash))
if err != nil {
return nil, err
}
return h, nil
}
func (h *Hash) UnmarshalText(b []byte) error {
p, err := hex.DecodeString(string(b))
if err != nil {
return err
}
copy(h[:], p)
return nil
}
func (h *Hash) Fixed() [constants.HASH_LENGTH]byte {
// Might change the error produced by IHash in FD-398
if h == nil {
panic("nil Hash")
}
return *h
}
func (h *Hash) PFixed() *[constants.HASH_LENGTH]byte {
// Might change the error produced by IHash in FD-398
return (*[constants.HASH_LENGTH]byte)(h)
}
func (h *Hash) Bytes() (rval []byte) {
defer func() {
if r := recover(); r != nil {
fmt.Fprintf(os.Stderr, "nil hash")
debug.PrintStack()
rval = constants.ZERO_HASH
}
}()
return h.GetBytes()
}
func (Hash) GetHash() interfaces.IHash {
return nil
}
func CreateHash(entities ...interfaces.BinaryMarshallable) (h interfaces.IHash, err error) {
sha := sha256.New()
h = new(Hash)
for _, entity := range entities {
data, err := entity.MarshalBinary()
if err != nil {
return nil, err
}
sha.Write(data)
}
h.SetBytes(sha.Sum(nil))
return
}
func (h *Hash) MarshalBinary() (rval []byte, err error) {
defer func(pe *error) {
if *pe != nil {
fmt.Fprintf(os.Stderr, "Hash.MarshalBinary err:%v", *pe)
}
}(&err)
return h.Bytes(), nil
}
func (h *Hash) UnmarshalBinaryData(p []byte) (newData []byte, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("Error unmarshalling: %v", r)
}
}()
copy(h[:], p)
newData = p[constants.HASH_LENGTH:]
return
}
func (h *Hash) UnmarshalBinary(p []byte) (err error) {
_, err = h.UnmarshalBinaryData(p)
return
}
// Make a copy of the hash in this hash. Changes to the return value WILL NOT be
// reflected in the source hash. You have to do a SetBytes to change the source
// value.
func (h *Hash) GetBytes() []byte {
newHash := make([]byte, constants.HASH_LENGTH)
copy(newHash, h[:])
return newHash
}
// SetBytes sets the bytes which represent the hash. An error is returned if
// the number of bytes passed in is not constants.HASH_LENGTH.
func (hash *Hash) SetBytes(newHash []byte) error {
nhlen := len(newHash)
if nhlen != constants.HASH_LENGTH {
return fmt.Errorf("invalid sha length of %v, want %v", nhlen, constants.HASH_LENGTH)
}
copy(hash[:], newHash)
return nil
}
// NewShaHash returns a new ShaHash from a byte slice. An error is returned if
// the number of bytes passed in is not constants.HASH_LENGTH.
func NewShaHash(newHash []byte) (*Hash, error) {
var sh Hash
err := sh.SetBytes(newHash)
if err != nil {
return nil, err
}
return &sh, err
}
// Create a Sha512[:256] Hash from a byte array
func Sha512Half(p []byte) (h *Hash) {
sha := sha512.New()
sha.Write(p)
h = new(Hash)
copy(h[:], sha.Sum(nil)[:constants.HASH_LENGTH])
return h
}
// Convert a hash into a string with hex encoding
func (h *Hash) String() string {
if h == nil {
return hex.EncodeToString(nil)
} else {
return hex.EncodeToString(h[:])
}
}
func (h *Hash) ByteString() string {
return string(h[:])
}
func HexToHash(hexStr string) (h interfaces.IHash, err error) {
h = new(Hash)
v, err := hex.DecodeString(hexStr)
err = h.SetBytes(v)
return h, err
}
// Compare two Hashes
func (a *Hash) IsSameAs(b interfaces.IHash) bool {
if a == nil || b == nil {
if a == nil && b == nil {
return true
}
return false
}
if bytes.Compare(a[:], b.Bytes()) == 0 {
return true
}
return false
}
// Is the hash a minute marker (the last byte indicates the minute number)
func (h *Hash) IsMinuteMarker() bool {
if bytes.Equal(h[:constants.HASH_LENGTH-1], constants.ZERO_HASH[:constants.HASH_LENGTH-1]) {
return true
}
return false
}
func (h *Hash) ToMinute() byte {
return h[constants.HASH_LENGTH-1]
}
func (e *Hash) JSONByte() ([]byte, error) {
return EncodeJSON(e)
}
func (e *Hash) JSONString() (string, error) {
return EncodeJSONString(e)
}
/****************************************************************
DEBUG logging to keep full hash. Turned on from command line
****************************************************************/
func Loghashfixed(h [32]byte) {
if !globals.Params.FullHashesLog {
return
}
if globals.Hashlog == nil {
f, err := os.Create("fullhashes.txt")
globals.Hashlog = bufio.NewWriter(f)
f.WriteString(time.Now().String() + "\n")
if err != nil {
panic(err)
}
}
globals.HashMutex.Lock()
defer globals.HashMutex.Unlock()
if globals.Hashes == nil {
globals.Hashes = make(map[[32]byte]bool)
}
_, exists := globals.Hashes[h]
if !exists {
//fmt.Fprintf(globals.Hashlog, "%x\n", h)
var x int
// turns out random is better than LRU because the leader/common chain hashes get used a lot and keep getting
// tossed. Probably better to add special handling for leader and known chains ...
if true {
x = globals.HashNext // Use LRU
} else {
x = random.RandIntBetween(0, len(globals.HashesInOrder)) // use random replacement
}
if globals.HashesInOrder[x] != nil {
fmt.Fprintf(globals.Hashlog, "delete [%4d] %x\n", x, *globals.HashesInOrder[x])
delete(globals.Hashes, *globals.HashesInOrder[x]) // delete the oldest hash
globals.HashesInOrder[x] = nil
}
fmt.Fprintf(globals.Hashlog, "add [%4d] %x\n", x, h)
globals.Hashes[h] = true // add the new hash
globals.HashesInOrder[x] = &h // add it to the ordered list
globals.HashNext = (globals.HashNext + 1) % len(globals.HashesInOrder) // wrap index at end of array
}
}
func Loghash(h interfaces.IHash) {
if h == nil {
return
}
Loghashfixed(h.Fixed())
}
/**********************
* Support functions
**********************/
// Create a Sha256 Hash from a byte array
func Sha(p []byte) interfaces.IHash {
h := new(Hash)
b := sha256.Sum256(p)
h.SetBytes(b[:])
Loghash(h)
return h
}
// Shad Double Sha256 Hash; sha256(sha256(data))
func Shad(data []byte) interfaces.IHash {
h1 := sha256.Sum256(data)
h2 := sha256.Sum256(h1[:])
h := new(Hash)
h.SetBytes(h2[:])
return h
}
func NewZeroHash() interfaces.IHash {
h := new(Hash)
return h
}
func NewHash(b []byte) interfaces.IHash {
h := new(Hash)
h.SetBytes(b)
return h
}
// shad Double Sha256 Hash; sha256(sha256(data))
func DoubleSha(data []byte) []byte {
h1 := sha256.Sum256(data)
h2 := sha256.Sum256(h1[:])
Loghashfixed(h2)
return h2[:]
}
func NewShaHashFromStruct(DataStruct interface{}) (interfaces.IHash, error) {
jsonbytes, err := json.Marshal(DataStruct)
if err != nil {
return nil, err
}
return NewShaHash(DoubleSha(jsonbytes))
}