-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProofOfWork.go
50 lines (43 loc) · 906 Bytes
/
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
package main
import (
"bytes"
"crypto/sha256"
"fmt"
"math/big"
)
type ProofOfWork struct {
b *Block
target *big.Int
}
func NewProofOfWork(b *Block) *ProofOfWork {
pow := ProofOfWork{b: b}
temp := big.Int{}
temp.SetString("0000000000000100000001000001000000000000000000000000000000000000000000000", 16)
pow.target = &temp
return &pow
}
func (pow *ProofOfWork) Run() (uint64, []byte) {
b := pow.b
nonce := uint64(00)
for {
tmp := [][]byte{
Uint64ToByte(b.Version),
Uint64ToByte(b.Difficulty),
Uint64ToByte(b.TimeStamp),
Uint64ToByte(nonce),
b.MerkelRoot,
b.Hash,
b.PrvHash,
}
BlockInfo := bytes.Join(tmp, []byte{})
hash := sha256.Sum256(BlockInfo)
tmpBigInt := big.Int{}
tmpBigInt.SetBytes(hash[:])
if tmpBigInt.Cmp(pow.target) == -1 {
fmt.Printf("get hash: %x nonce: %d\n", hash, nonce)
return nonce, hash[:]
} else {
nonce++
}
}
}