-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpow.go
64 lines (54 loc) · 1.06 KB
/
pow.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
package main
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"fmt"
"io"
"math"
"math/big"
)
func (b *Block) PoW() {
var hash []byte
fmt.Println("mining...")
for b.Nonce < math.MaxUint32 {
hash = b.calcHash()
fmt.Printf("\rHash: %x", hash)
if b.validateHash(hash) {
break
}
b.Nonce++
}
b.Hash = hash[:]
fmt.Println("\n")
}
func (b *Block) calcHash() []byte {
headerHex := new(bytes.Buffer)
headerHex.Write(b.PrevBlock)
writeElement(headerHex, b.Transactions)
writeElement(headerHex, b.Timestamp.Unix())
writeElement(headerHex, b.Bits)
writeElement(headerHex, b.Nonce)
hash := sha256.Sum256(headerHex.Bytes())
return hash[:]
}
func writeElement(w io.Writer, e interface{}) error {
err := binary.Write(w, binary.BigEndian, e)
if err != nil {
return err
}
return nil
}
func (b *Block) validateHash(hash []byte) bool {
target := big.NewInt(1)
target.Lsh(target, uint(256-b.Bits))
var hashInt big.Int
hashInt.SetBytes(hash[:])
if hashInt.Cmp(target) == -1 {
return true
}
return false
}
func getTargetBits() uint32 {
return 20
}