forked from dreamerjackson/BuildingBlockChain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproofofwork.go
94 lines (73 loc) · 1.67 KB
/
proofofwork.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
package main
import (
"math/big"
"math"
"bytes"
"fmt"
"crypto/sha256"
)
const maxNonce = math.MaxInt64
const targetBits = 16
// ProofOfWork represents a proof-of-work
type ProofOfWork struct {
block *Block
target *big.Int
}
// NewProofOfWork builds and returns a ProofOfWork
func NewProofOfWork(b *Block) *ProofOfWork {
target := big.NewInt(1)
target.Lsh(target, uint(256-targetBits))
pow := &ProofOfWork{b, target}
return pow
}
//serialize the block
func (pow *ProofOfWork) prepareData(nonce int64) []byte {
data := bytes.Join(
[][]byte{
IntToHex64(pow.block.Version),
pow.block.PrevBlockHash,
pow.block.MerkleRoot,
IntToHex64(pow.block.Timestamp),
IntToHex64(pow.block.Nbits),
IntToHex64(nonce),
},
[]byte{},
)
return data
}
// Run performs a proof-of-work
func (pow *ProofOfWork) Run() (int64, []byte) {
var hashInt big.Int
var hash [32]byte
var nonce int64;
nonce = 0
fmt.Printf("Mining a new block")
//continue the nonce until the hash result <= targetBits
for nonce < maxNonce {
data := pow.prepareData(nonce)
firsthash := sha256.Sum256(data)
hash = sha256.Sum256(firsthash[:])
//if nonce==5{
// fmt.Printf("\rnonce:%x,%x\n", nonce,hash)
//}
hashInt.SetBytes(hash[:])
if hashInt.Cmp(pow.target) == -1 {
break
} else {
nonce++
}
}
fmt.Print("\n\n")
return nonce, hash[:]
}
// Validate validates block's PoW
func (pow *ProofOfWork) Validate() bool {
var hashInt big.Int
data := pow.prepareData(pow.block.Nonce)
firsthash := sha256.Sum256(data)
hash := sha256.Sum256(firsthash[:])
fmt.Printf("\r%x\n", pow.block.Nonce)
hashInt.SetBytes(hash[:])
isValid := hashInt.Cmp(pow.target) == -1
return isValid
}