-
Notifications
You must be signed in to change notification settings - Fork 10
/
strongwork.go
99 lines (74 loc) · 1.84 KB
/
strongwork.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
package provingwork
import (
"bytes"
"crypto/sha256"
"math/big"
"encoding/binary"
"encoding/json"
)
type StrongWork struct {
Counter int64 `json:"counter"`
Resource []byte `json:"resource"`
*WorkOptions
}
// An alias type that won't have any of functions (mostly to avoid an infinite
// loop with the overidden MarshalJSON function)
type RawStrongWork StrongWork
// This is a special version of the StrongWork that has the types we want to
// be importing / exporting.
type StrongWorkExt struct {
Timestamp int64 `json:"timestamp"`
*RawStrongWork
}
func (wo StrongWork) MarshalJSON() ([]byte, error) {
woe := StrongWorkExt{RawStrongWork: (*RawStrongWork)(&wo)}
if wo.Timestamp != nil {
woe.Timestamp = wo.Timestamp.Unix()
}
return json.Marshal(woe)
}
func (wo StrongWork) UnmarshalJSON(data []byte) error {
woe := StrongWorkExt{RawStrongWork: (*RawStrongWork)(&wo)}
if err := json.Unmarshal(data, woe); err != nil {
return err
}
return nil
}
func NewStrongWork(resource []byte, opts ...*WorkOptions) *StrongWork {
sw := StrongWork{ Resource: resource }
if len(opts) != 0 {
sw.WorkOptions = opts[0]
} else {
sw.WorkOptions = &WorkOptions{}
}
setDefaultWorkOptions(sw.WorkOptions)
return &sw
}
func (sw StrongWork) Check() bool {
if sw.ZeroCount() >= sw.BitStrength {
return true
}
return false
}
func (sw StrongWork) ContentHash() []byte {
var buf bytes.Buffer
buf.Write(sw.Resource)
buf.Write(sw.Salt)
ts := sw.Timestamp.Unix()
binary.Write(&buf, binary.BigEndian, ts)
binary.Write(&buf, binary.BigEndian, sw.Counter)
return buf.Bytes()
}
func (sw *StrongWork) FindProof() {
for {
if sw.Check() {
return
}
sw.Counter++
}
}
func (sw StrongWork) ZeroCount() int {
digest := sha256.Sum256(sw.ContentHash())
digestHex := new(big.Int).SetBytes(digest[:])
return ((sha256.Size * 8) - digestHex.BitLen())
}