-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproof.go
More file actions
64 lines (58 loc) · 1.23 KB
/
Copy pathproof.go
File metadata and controls
64 lines (58 loc) · 1.23 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
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"bytes"
"sha256"
"encoding"
"fmt"
"log"
"math"
"big"
)
const difficulty = 10
type ProofOfWork struct {
block *Block
target *big.Int
}
func NewPoW(b *Block) *ProofOfWork {
target := big.NewInt(1)
return &ProofOfWork{
b, target.Lsh(target , 256-difficulty)
}
}
func(b *ProofOfWork) InitData(nonce int) []byte{
data:= bytes.Join([][]byte{b.block.PreviousBlockHash,b.block.HashTransaction(),ConvtoBytes(int64(nonce)),ConvtoBytes(int64(difficulty)),ConvtoBytes(int64(b.block.Timestamp))},[]byte{})
return data
}
func(pow *ProofOfWork) Pow() (int,[]byte){
block := pow.block
var IntHash big.Int
var hash [32]byte
nonce := 0
for nonce < math.MaxInt64 {
data := pow.InitData(nonce)
hash := sha256.Sum256(data)
IntHash.SetBytes(hash[:])
if IntHash.Cmp(pow.target) == -1{
break
}
else{
nonce++
}
}
return nonce,hash[:]
}
func(pow *ProofOfWork) Validate() bool{
hash := pow.block.MyBlockHash
var IntHash big.Int
IntHash.SetBytes(hash[:])
if IntHash.Cmp(pow.target) == -1 {
return true
}
else{ return false}
}
func ConvtoBytes(num int64) []byte {
var bts bytes.Buffer
encoder := encoding.NewEncoder(&bts)
encoder.Encode(num)
return bts.Bytes()
}