-
Notifications
You must be signed in to change notification settings - Fork 7
/
miner.go
62 lines (56 loc) · 1.34 KB
/
miner.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
package main
import (
"math/rand"
"time"
"fmt"
"crypto/sha256"
"encoding/base64"
// "math/big"
)
func (node *Node) StartMiner(){
c := make(chan *Block)
go node.Mine(c)
}
func (node *Node) Mine(c chan *Block){
go node.FindSolsHash(c)
for {
select{
case blk := <- c:
node.BroadcastBlock(blk)
}
}
}
func FindSolsTimeout(c chan string){
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for {
rand := r.Intn(10) // Adjusts variance of block speed
fmt.Println("Interval:", rand)
time.Sleep(time.Duration(rand) * time.Second)
c <- "Found a block solution"
}
}
func isWinner(ticket string) bool {
// num := big.NewInt(0).SetBytes(ticket)
winner := "000"
res := false
if ticket[:len(winner)] == winner {
return true
}
return res
}
func (node *Node) FindSolsHash(c chan *Block){
blk := node.CreateNewBlock()
blk.Nonce = make([]byte, 32)
for {
rand.Read(blk.Nonce)
guess := sha256.Sum256(blk.Serialize())
ticket := base64.StdEncoding.EncodeToString(guess[:])
if isWinner(ticket) {
blk.Solution = ticket
// fmt.Println("Ticket:", ticket)
c <- blk
blk = node.CreateNewBlock()
blk.Nonce = make([]byte, 32)
}
}
}