-
Notifications
You must be signed in to change notification settings - Fork 0
/
proof_of_work.go
67 lines (55 loc) · 1.26 KB
/
proof_of_work.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 block_chain
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"fmt"
"math"
"math/big"
)
const targetBits = 24
type ProofOfWork struct {
block *Block
targetBit *big.Int
}
func NewProofOfWork(block *Block) *ProofOfWork {
var intTargit = new(big.Int).SetInt64(100)
intTargit.Lsh(intTargit, uint(256-targetBits))
return &ProofOfWork{block, intTargit}
}
func (pow *ProofOfWork) PrepareRawData(nonce int64) []byte {
block := pow.block
block.Nonce = nonce
block.SetHash()
var network bytes.Buffer
enc := gob.NewEncoder(&network)
err := enc.Encode(block)
CheckErr("newblockchain", err)
//fmt.Println(network)
return network.Bytes()
}
func (pow ProofOfWork) Run() (int64, []byte) {
var nonce int64
var hash [32]byte
var hashInt big.Int
fmt.Println("开始 挖圹了")
for nonce < math.MaxInt64 {
data := pow.PrepareRawData(nonce)
hash = sha256.Sum256(data)
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.targetBit) < 0 {
fmt.Printf("found hash :%x hashInt :%s \n", hash, hashInt)
break
} else {
nonce++
}
}
return nonce, hash[:]
}
func (pow *ProofOfWork) IsValid() bool {
data := pow.PrepareRawData(pow.block.Nonce)
hash := sha256.Sum256(data)
var intHash big.Int
intHash.SetBytes(hash[:])
return intHash.Cmp(pow.targetBit) < 0
}