-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproofOfWork.go
More file actions
77 lines (61 loc) · 1.36 KB
/
proofOfWork.go
File metadata and controls
77 lines (61 loc) · 1.36 KB
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
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"math"
"math/big"
)
type ProofOfWork struct {
block *Block
target *big.Int
}
const targetBits = 24
func NewProofOfwork(block *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, uint(256-targetBits))
pow := ProofOfWork{block: block, target: target}
return &pow
}
func (pow *ProofOfWork) PrepareData(nonce int64) []byte {
block := pow.block
tmp := [][]byte{
IntToByte(block.Version),
block.PrevBlockHash,
block.MerKelRoot,
IntToByte(block.TimeStamp),
IntToByte(targetBits),
IntToByte(nonce),
//block.Transaction.TransactionHash()
}
data := bytes.Join(tmp, []byte{})
return data
}
func (pow *ProofOfWork) Run() (int64, []byte) {
var hash [32]byte
var nonce int64 = 0
var hashInt big.Int
fmt.Println("Begin Mining...")
fmt.Printf("target hash: %x\n", pow.target.Bytes())
//寻找nonce
for nonce < math.MaxInt64 {
data := pow.PrepareData(nonce)
hash = sha256.Sum256(data)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
fmt.Printf("found hashs: %x,nonce:%d\n", hash, nonce)
fmt.Println("")
break
} else {
nonce++
}
}
return nonce, hash[:]
}
func (pow *ProofOfWork) IsValid() bool {
var hashInt big.Int
data := pow.PrepareData(pow.block.Nonce)
hash := sha256.Sum256(data)
hashInt.SetBytes(hash[:])
return hashInt.Cmp(pow.target) == -1
}