-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathminer.go
89 lines (72 loc) · 1.68 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package ozcoin
import (
"log"
"time"
)
type Miner struct {
*Client
}
func NewMiner(miningAddr, walletAddr string, password string) *Miner {
m := &Miner{
Client: NewBlockchain(miningAddr, walletAddr, password),
}
err := m.Client.Wallet.OpenWallet(password)
if err != nil {
log.Println(err)
panic("Could not authenticate wallet")
}
go m.run()
return m
}
func (m *Miner) run() {
log.Println("Running miner...")
addresses, err := m.Wallet.TrackingKeys()
if err != nil {
panic("Could not load addresses from wallet")
}
miningAddress := addresses[0].PublicKey()
gblock := GenesisBlock(miningAddress)
err = m.WriteBlock(gblock)
if err != nil {
panic("Could not add genesis block")
}
updateTime := time.After(30 * time.Second)
recentlyUpdated := false
m.LastHeader = gblock.Header
last := m.LastHeader.Hash()
block := m.NewBlock(m.LastHeader, miningAddress)
for {
select {
case now := <-updateTime:
log.Println("Updating block time")
if !recentlyUpdated {
block.Header.Time = now
block.Header.Difficulty = m.ComputeDifficulty(block)
}
updateTime = time.After(30 * time.Second)
recentlyUpdated = false
// Sign request for testing
_, err = m.Wallet.SignTxn(&miningAddress, 1, 1)
if err != nil {
log.Println(err)
}
default:
if last != m.LastHeader.Hash() {
log.Println("Building new block")
// Create new block
last = m.LastHeader.Hash()
block = m.NewBlock(m.LastHeader, miningAddress)
recentlyUpdated = true
} else {
// Increment nonce
block.Header.Nonce += 1
}
if !block.Header.ValidPoW() {
continue
}
// Inform self
log.Println("Block found")
m.BlockChan <- block
}
}
}