forked from hacash/miner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
miner.go
86 lines (72 loc) · 2.02 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
package diamondminer
import (
"fmt"
"github.com/hacash/core/actions"
"github.com/hacash/core/genesis"
"github.com/hacash/core/interfaces"
"github.com/hacash/core/interfacev2"
"github.com/hacash/core/stores"
"sync"
"time"
)
type DiamondMiner struct {
Config *DiamondMinerConfig
blockchain interfaces.BlockChain
txpool interfaces.TxPool
stopMarksLocker sync.Mutex
stopMarks map[*byte]*byte
newDiamondBeFoundCh chan *stores.DiamondSmelt
successMiningDiamondCh chan *actions.Action_4_DiamondCreate
// Current successful diamond transactions
currentSuccessMiningDiamondTx interfacev2.Transaction
changeLock sync.Mutex
}
func NewDiamondMiner(cnf *DiamondMinerConfig) *DiamondMiner {
dia := &DiamondMiner{
Config: cnf,
stopMarks: map[*byte]*byte{},
newDiamondBeFoundCh: make(chan *stores.DiamondSmelt, 2),
successMiningDiamondCh: make(chan *actions.Action_4_DiamondCreate, 4),
currentSuccessMiningDiamondTx: nil,
}
return dia
}
func (d *DiamondMiner) Start() error {
if d.blockchain == nil {
return fmt.Errorf("d.blockchain not be set yet.")
}
if d.txpool == nil {
return fmt.Errorf("d.txpool not be set yet.")
}
go d.loop()
go func() {
time.Sleep(time.Second)
prev, e := d.blockchain.GetChainEngineKernel().StateRead().ReadLastestDiamond()
if e != nil {
fmt.Println("[Diamond Miner Error] miner cannot start: ", e)
return
}
// is first
if prev == nil {
genesisblk := genesis.GetGenesisBlock()
prev = &stores.DiamondSmelt{
Number: 0,
ContainBlockHash: genesisblk.Hash(),
}
}
// do mining
d.RunMining(prev, d.successMiningDiamondCh)
}()
return nil
}
func (m *DiamondMiner) SetTxPool(tp interfaces.TxPool) {
m.txpool = tp
}
func (d *DiamondMiner) SetBlockChain(blockchain interfaces.BlockChain) {
if d.blockchain != nil {
panic("d.blockchain already be set.")
}
d.blockchain = blockchain
// feed event
blockchain.GetChainEngineKernel().SubscribeDiamondOnCreate(d.newDiamondBeFoundCh)
}