-
Notifications
You must be signed in to change notification settings - Fork 3
/
proofofwork.go
72 lines (62 loc) · 1.73 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
package simpleBlockchain
import (
"math/big"
)
var GenesisBits = []byte{0x1f,0xff,0xff,0xff}
var GenesisTarget = []byte{
0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,
0xff,0xff,
}
type ProofOfWork struct {
block *Block
target *big.Int
}
func SerializeHeaderForMining(blockHeader *BlockHeader) []byte{
return ConcatCopy(
IntToLittleEndianBytes(blockHeader.Version),
ReverseBytes(blockHeader.PrevBlock),
ReverseBytes(blockHeader.MerkleRoot),
IntToLittleEndianBytes(blockHeader.TimeStamp),
IntToLittleEndianBytes(blockHeader.Bits),
IntToLittleEndianBytes(blockHeader.Nonce),
)
}
func NewProofOfWork(block *Block) *ProofOfWork{
//bits := block.BlockHeader.Bits
target := CalculateTarget(GenesisBits)
//target := big.NewInt(0).SetBytes(GenesisTarget)
return &ProofOfWork{
block: block,
target: target,
}
}
func (pow *ProofOfWork) mining(){
var nonce = 0
for {
pow.block.BlockHeader.Nonce = uint32(nonce)
res := big.NewInt(0).SetBytes(ReverseBytes(DoubleSha256(SerializeHeaderForMining(pow.block.BlockHeader))))
if res.Cmp(pow.target) == -1 {
return
}
nonce++
}
}
// a = bits[0]
// b = bits[1]
// coefficient = bits[2:]
// target = coefficient * 2^(8*(a–3))
func CalculateTarget(bits []byte) *big.Int{
//coefficient := big.NewInt(0).SetBytes(bits[2:])
//a := big.NewInt(int64(bits[0]))
//exp := big.NewInt(8).Mul(big.NewInt(8),a.Sub(a,big.NewInt(3)))
//num := exp.Exp(big.NewInt(2), exp,nil)
//target := coefficient.Mul(coefficient,num)
//return target
target := make([]byte, 32)
exp := bits[0]
coefficient := bits[1:]
copy(target[32-exp:32-exp+3], coefficient)
return big.NewInt(0).SetBytes(target)
}