-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhash.go
56 lines (47 loc) · 1.07 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
package bitacoin
import (
"crypto/sha256"
"fmt"
)
// GenerateMask creates a mask based on the number of zeros required in the hash
func GenerateMask(zeros int) []byte {
full, half := zeros/2, zeros%2
var mask []byte
for i := 0; i < full; i++ {
mask = append(mask, 0)
}
if half > 0 {
mask = append(mask, 0xf)
}
return mask
}
// GoodEnough checks if the hash is good for the current mask
func GoodEnough(mask []byte, hash []byte) bool {
for i := range mask {
if hash[i] > mask[i] {
return false
}
}
return true
}
// EasyHash craete hash, the easy way, just a simple sha256 hash
func EasyHash(data ...interface{}) []byte {
hasher := sha256.New()
fmt.Fprint(hasher, data...)
return hasher.Sum(nil)
}
// DifficultHash creates the hash with difficulty mask and conditions,
// return the hash and the nonce used to create the hash
func DifficultHash(mask []byte, data ...interface{}) ([]byte, int32) {
ln := len(data)
data = append(data, nil)
var i int32
for {
data[ln] = i
hash := EasyHash(data...)
if GoodEnough(mask, hash) {
return hash, i
}
i++
}
}