-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProofOfWork.go
More file actions
51 lines (47 loc) · 1.11 KB
/
Copy pathProofOfWork.go
File metadata and controls
51 lines (47 loc) · 1.11 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
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"math/big"
)
type ProofOfWork struct {
block *Block
target *big.Int
}
func NewProofOfWork(block *Block) *ProofOfWork {
pow := ProofOfWork{
block: block,
}
targetStr := "0000100000000000000000000000000000000000000000000000000000000000" // appoint difficulty
tmpInt := big.Int{}
tmpInt.SetString(targetStr, 16)
pow.target = &tmpInt
return &pow
}
func (pow *ProofOfWork) Run() ([]byte, uint64) {
var nonce uint64
var hash [32]byte
block := pow.block
for {
tmp := [][]byte{
Uint64ToByte(block.Version),
block.PrevHash,
block.MerkelRoot,
Uint64ToByte(block.TimeStamp),
Uint64ToByte(block.Difficulty),
Uint64ToByte(nonce),
// only set hash to block header, block body by MerkelRoot
}
blockInfo := bytes.Join(tmp, []byte{})
hash = sha256.Sum256(blockInfo)
tmpInt := big.Int{}
tmpInt.SetBytes(hash[:]) // let hash to big.int
if tmpInt.Cmp(pow.target) == -1 { // compare generative hash and target
fmt.Printf("Mining success! hash: %x, nonce: %d\n", hash, nonce)
return hash[:], nonce
} else {
nonce++
}
}
}