-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpow.go
75 lines (59 loc) · 1.48 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
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"math/big"
)
const TargetBits = 10
type ProofOfWork struct {
Block *Block
Target *big.Int
}
func NewProofOfWork(Block *Block) *ProofOfWork {
Target := big.NewInt(1)
Target.Lsh(Target, uint(256-TargetBits))
return &ProofOfWork{Block, Target}
}
// / it is metho work on proofOfWork it take nonce and mixe with Block data and give the data in from of []byte
func (pow *ProofOfWork) dataHashed(nonce int) []byte {
data := bytes.Join([][]byte{
[]byte(fmt.Sprintf("%d", pow.Block.Index)),
[]byte(pow.Block.Timestamp),
[]byte(pow.Block.Data),
[]byte(pow.Block.PrevHash),
[]byte(fmt.Sprintf("%d", nonce)),
}, []byte{})
return data
}
func (pow *ProofOfWork) Run() {
var hashInt big.Int
var hash [32]byte
for nonce := 0; ; nonce++ {
data := pow.dataHashed(nonce)
hash = sha256.Sum256([]byte(data))
hashInt.SetBytes(hash[:])
fmt.Printf("Nonce: %d\n", nonce)
fmt.Printf("Data: %s\n", data)
fmt.Printf("Hash: %x\n", hash)
fmt.Printf("HashInt: %d\n", &hashInt)
fmt.Printf("Target: %d\n\n", pow.Target)
if hashInt.Cmp(pow.Target) == -1 {
fmt.Println("Valid hash found!")
pow.Block.Hash = hex.EncodeToString(hash[:])
break
}
}
}
func main() {
Block := &Block{
Index: 1,
Timestamp: "2024-07-02 00:00:00",
Data: "Sample Block Data best in this waorld",
PrevHash: "0000000000000000",
}
pow := NewProofOfWork(Block)
pow.Run()
fmt.Printf("Block Hash: %s\n", Block.Hash)
}