-
Notifications
You must be signed in to change notification settings - Fork 0
/
pow.go
67 lines (51 loc) · 1.08 KB
/
pow.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
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"math"
"math/big"
)
const targetBits = 16
type ProofOfWork struct {
block *Block
target *big.Int
}
func NewProofOfWork(b *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, 256-targetBits)
return &ProofOfWork{b, target}
}
func (pow *ProofOfWork) prepareData(nonce int64) []byte {
data := bytes.Join([][]byte{
pow.block.PrevBlockHash,
pow.block.HashTransaction(),
IntToHex(pow.block.Timestamp),
IntToHex(nonce),
IntToHex(targetBits),
}, []byte{})
return data
}
func (pow *ProofOfWork) Run() (int64, []byte) {
var nonce int64
var hashInt big.Int
var hash [32]byte
for nonce < math.MaxInt64 {
data := pow.prepareData(nonce)
hash = sha256.Sum256(data)
fmt.Printf("\r%x", hash)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
break
}
nonce++
}
return nonce, hash[:]
}
func (pow *ProofOfWork) Validate(b *Block) bool {
var hashInt big.Int
data := pow.prepareData(b.Nonce)
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
return hashInt.Cmp(pow.target) == -1
}