-
Notifications
You must be signed in to change notification settings - Fork 5
/
service.go
306 lines (267 loc) · 10 KB
/
service.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package bft
import (
"fmt"
"github.com/drep-project/DREP-Chain/app"
blockMgrService "github.com/drep-project/DREP-Chain/blockmgr"
chainService "github.com/drep-project/DREP-Chain/chain"
"github.com/drep-project/DREP-Chain/chain/store"
"github.com/drep-project/DREP-Chain/common/event"
"github.com/drep-project/DREP-Chain/crypto"
"github.com/drep-project/DREP-Chain/crypto/secp256k1"
"github.com/drep-project/DREP-Chain/database"
"github.com/drep-project/DREP-Chain/network/p2p"
p2pService "github.com/drep-project/DREP-Chain/network/service"
"github.com/drep-project/DREP-Chain/params"
accountService "github.com/drep-project/DREP-Chain/pkgs/accounts/service"
consensusTypes "github.com/drep-project/DREP-Chain/pkgs/consensus/types"
chainTypes "github.com/drep-project/DREP-Chain/types"
"gopkg.in/urfave/cli.v1"
"io/ioutil"
"time"
)
var (
MinerFlag = cli.BoolFlag{
Name: "miner",
Usage: "is miner",
}
DefaultConfigMainnet = BftConfig{
MyPk: nil,
StartMiner: true,
ProducerNum: params.GenesisProducerNumMainnet,
BlockInterval: params.BlockInterval,
ChangeInterval: params.ChangeInterval,
}
DefaultConfigTestnet = BftConfig{
MyPk: nil,
StartMiner: true,
ProducerNum: params.GenesisProducerNumTestnet,
BlockInterval: params.BlockInterval,
ChangeInterval: params.ChangeInterval,
}
)
type BftConsensusService struct {
P2pServer p2pService.P2P `service:"p2p"`
ChainService chainService.ChainServiceInterface `service:"chain"`
BroadCastor blockMgrService.ISendMessage `service:"blockmgr"`
BlockMgrNotifier blockMgrService.IBlockNotify `service:"blockmgr"`
BlockGenerator blockMgrService.IBlockBlockGenerator `service:"blockmgr"`
DatabaseService *database.DatabaseService `service:"database"`
WalletService *accountService.AccountService `service:"accounts"`
BftConsensus *BftConsensus
NetType params.NetType
apis []app.API
Config *BftConfig
syncBlockEventSub event.Subscription
syncBlockEventChan chan event.SyncBlockEvent
ConsensusEngine consensusTypes.IConsensusEngine
Miner *secp256k1.PrivateKey
//During the process of synchronizing blocks, the miner stopped mining
pauseForSync bool
start bool
quit chan struct{}
}
func (bftConsensusService *BftConsensusService) Name() string {
return "bft"
}
func (bftConsensusService *BftConsensusService) Api() []app.API {
return bftConsensusService.apis
}
func (bftConsensusService *BftConsensusService) CommandFlags() ([]cli.Command, []cli.Flag) {
return nil, []cli.Flag{MinerFlag}
}
func (bftConsensusService *BftConsensusService) Init(executeContext *app.ExecuteContext) error {
if executeContext.Cli.GlobalIsSet(MinerFlag.Name) {
bftConsensusService.Config.StartMiner = executeContext.Cli.GlobalBool(MinerFlag.Name)
}
var addPeerFeed event.Feed
var removePeerFeed event.Feed
bftConsensusService.BftConsensus = NewBftConsensus(
bftConsensusService.ChainService,
bftConsensusService.BlockGenerator,
bftConsensusService.DatabaseService,
bftConsensusService.P2pServer,
bftConsensusService.Config,
&addPeerFeed,
&removePeerFeed,
)
producers, err := bftConsensusService.BftConsensus.GetProducers(bftConsensusService.BftConsensus.ChainService.BestChain().Height(), MAX_PRODUCER)
if err != nil {
log.Trace("bftConsensusService Init get producers err:", err)
return err
}
bftConsensusService.ChainService.AddBlockValidator(&BlockMultiSigValidator{bftConsensusService.BftConsensus.GetProducers, bftConsensusService.ChainService.GetBlockByHash, len(producers)})
bftConsensusService.ChainService.AddGenesisProcess(NewMinerGenesisProcessor())
if bftConsensusService.WalletService.Wallet == nil {
return ErrWalletNotOpen
}
bftConsensusService.P2pServer.AddProtocols([]p2p.Protocol{
p2p.Protocol{
Name: "bftConsensusService",
Length: NumberOfMsg,
Run: func(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
log.WithField("newpeer ip", peer.IP()).Info("consensuse protocol")
pi := consensusTypes.NewPeerInfo(peer, rw)
addPeerFeed.Send(pi)
defer func() {
select {
case <-bftConsensusService.quit:
log.Info("consensuse protocol ,remove peer, ip", peer.IP())
default:
log.WithField("protocol out, remove peer ip", peer.IP()).Info("consensuse protocol")
removePeerFeed.Send(pi)
log.WithField("protocol out , remove peer ip", peer.IP()).Info("consensuse protocol,remove ok")
}
}()
for {
select {
case <-bftConsensusService.quit:
return fmt.Errorf("bft consensus service been stop")
default:
msg, err := rw.ReadMsg()
if err != nil {
log.WithField("Reason", err).WithField("Ip", pi.IP()).Error("consensus receive msg")
return err
}
buf, err := ioutil.ReadAll(msg.Payload)
if err != nil {
return err
}
bftConsensusService.BftConsensus.ReceiveMsg(pi, msg.Code, buf)
}
}
},
},
})
bftConsensusService.syncBlockEventChan = make(chan event.SyncBlockEvent)
bftConsensusService.syncBlockEventSub = bftConsensusService.BlockMgrNotifier.SubscribeSyncBlockEvent(bftConsensusService.syncBlockEventChan)
bftConsensusService.quit = make(chan struct{})
bftConsensusService.apis = []app.API{
app.API{
Namespace: "consensus",
Version: "1.0",
Service: &ConsensusApi{
consensusService: bftConsensusService,
},
Public: true,
},
}
go bftConsensusService.handlerEvent()
return nil
}
func (bftConsensusService *BftConsensusService) handlerEvent() {
for {
select {
case e := <-bftConsensusService.syncBlockEventChan:
if e.EventType == event.StartSyncBlock {
bftConsensusService.pauseForSync = true
//log.Trace("Start Sync Blcok")
} else {
bftConsensusService.pauseForSync = false
//log.Trace("Stop Sync Blcok")
}
case <-bftConsensusService.quit:
return
}
}
}
func (bftConsensusService *BftConsensusService) Start(executeContext *app.ExecuteContext) error {
bftConsensusService.start = true
go bftConsensusService.BftConsensus.processPeers()
go bftConsensusService.BftConsensus.prepareForMining(bftConsensusService.P2pServer)
go bftConsensusService.BftConsensus.bestHeight()
go func() {
for {
select {
case <-bftConsensusService.quit:
return
default:
//consult privkey in wallet
if bftConsensusService.Miner == nil {
if bftConsensusService.Config.MyPk == nil {
time.Sleep(time.Second * time.Duration(bftConsensusService.Config.BlockInterval))
log.Trace("not set pubkey ,the node is listener")
continue
}
accountNode, err := bftConsensusService.WalletService.Wallet.GetAccountByPubkey(bftConsensusService.Config.MyPk)
if err != nil {
log.WithField("err", err).WithField("addr", crypto.PubkeyToAddress(bftConsensusService.Config.MyPk).String()).Warn("privkey of MyPk in Config is not in local wallet or unlock address")
time.Sleep(time.Second * time.Duration(bftConsensusService.Config.BlockInterval))
continue
}
bftConsensusService.Miner = accountNode.PrivateKey
}
if bftConsensusService.pauseForSync {
time.Sleep(time.Millisecond * 500)
continue
}
log.WithField("Height", bftConsensusService.ChainService.BestChain().Height()).Trace("node start")
block, err := bftConsensusService.BftConsensus.Run(bftConsensusService.Miner)
if err != nil {
log.WithField("Reason", err.Error()).Debug("Producer Block Fail")
} else {
_, _, err := bftConsensusService.ChainService.ProcessBlock(block)
if err == nil {
bftConsensusService.BroadCastor.BroadcastBlock(chainTypes.MsgTypeBlock, block, true)
log.WithField("Height", block.Header.Height).WithField("txs:", block.Data.TxCount).Info("Process block successfully and broad case block message")
} else {
log.WithField("Height", block.Header.Height).WithField("txs:", block.Data.TxCount).WithField("err", err).Info("Process Block fail")
}
}
nextBlockTime, waitSpan := bftConsensusService.getWaitTime()
log.WithField("nextBlockTime", nextBlockTime).WithField("waitSpan", waitSpan).Debug("Sleep")
time.Sleep(waitSpan)
}
}
}()
return nil
}
func (bftConsensusService *BftConsensusService) Stop(executeContext *app.ExecuteContext) error {
if bftConsensusService.Config == nil { //|| !bftConsensusService.Config.StartMiner
return nil
}
if bftConsensusService.quit != nil {
close(bftConsensusService.quit)
}
if bftConsensusService.syncBlockEventSub != nil {
bftConsensusService.syncBlockEventSub.Unsubscribe()
}
bftConsensusService.BftConsensus.Close()
return nil
}
func (bftConsensusService *BftConsensusService) getWaitTime() (time.Time, time.Duration) {
lastBlockTime := time.Unix(int64(bftConsensusService.ChainService.BestChain().Tip().TimeStamp), 0)
targetTime := lastBlockTime.Add(time.Duration(int64(time.Second) * int64(bftConsensusService.Config.BlockInterval)))
now := time.Now()
if targetTime.Before(now) {
interval := now.Sub(lastBlockTime)
nextBlockInterval := int64(interval/(time.Second*time.Duration(bftConsensusService.Config.BlockInterval))) + 1
nextBlockTime := lastBlockTime.Add(time.Second * time.Duration(nextBlockInterval*int64(bftConsensusService.Config.BlockInterval)))
if nextBlockTime.Before(now) {
return nextBlockTime, 0
}
return nextBlockTime, nextBlockTime.Sub(now)
} else {
return targetTime, targetTime.Sub(now)
}
}
func (bftConsensusService *BftConsensusService) GetProducers(height uint64, topN int) ([]chainTypes.Producer, error) {
block, err := bftConsensusService.ChainService.GetBlockByHeight(height)
if err != nil {
return nil, err
}
trie, err := store.TrieStoreFromStore(bftConsensusService.DatabaseService.LevelDb(), block.Header.StateRoot)
if err != nil {
return nil, err
}
return GetCandidates(trie, topN), nil
}
func (bftConsensusService *BftConsensusService) DefaultConfig(netType params.NetType) *BftConfig {
switch bftConsensusService.NetType {
case params.MainnetType:
return &DefaultConfigMainnet
case params.TestnetType:
return &DefaultConfigTestnet
default:
return nil
}
}