forked from meshplus/bitxhub
-
Notifications
You must be signed in to change notification settings - Fork 3
/
node.go
416 lines (378 loc) · 13.1 KB
/
node.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
package solo
import (
"context"
"fmt"
"sync"
"time"
"github.com/ethereum/go-ethereum/event"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/sirupsen/logrus"
"github.com/axiomesh/axiom-bft/common/consensus"
"github.com/axiomesh/axiom-kit/txpool"
"github.com/axiomesh/axiom-kit/types"
"github.com/axiomesh/axiom-ledger/internal/components/timer"
"github.com/axiomesh/axiom-ledger/internal/consensus/common"
"github.com/axiomesh/axiom-ledger/internal/consensus/precheck"
"github.com/axiomesh/axiom-ledger/internal/network"
"github.com/axiomesh/axiom-ledger/pkg/events"
"github.com/axiomesh/axiom-ledger/pkg/repo"
)
func init() {
repo.Register(repo.ConsensusTypeSolo, false)
}
type Node struct {
config *common.Config
isTimed bool
commitC chan *common.CommitEvent // block channel
logger logrus.FieldLogger // logger
txpool txpool.TxPool[types.Transaction, *types.Transaction] // transaction pool
batchDigestM map[uint64]string // mapping blockHeight to batch digest
poolFull int32 // pool full symbol
recvCh chan consensusEvent // receive message from consensus engine
blockCh chan *txpool.RequestHashBatch[types.Transaction, *types.Transaction] // receive batch from txpool
batchMgr *batchTimerManager
noTxBatchTimeout time.Duration // generate no-tx block period
batchTimeout time.Duration // generate block period
lastExec uint64 // the index of the last-applied block
network network.Network // network manager
checkpoint uint64
txPreCheck precheck.PreCheck
ctx context.Context
cancel context.CancelFunc
sync.RWMutex
txFeed event.Feed
mockBlockFeed event.Feed
}
func NewNode(config *common.Config) (*Node, error) {
currentEpoch, err := config.GetCurrentEpochInfoFromEpochMgrContractFunc()
if err != nil {
return nil, err
}
// init batch timer manager
recvCh := make(chan consensusEvent, maxChanSize)
ctx, cancel := context.WithCancel(context.Background())
soloNode := &Node{
config: config,
isTimed: currentEpoch.ConsensusParams.EnableTimedGenEmptyBlock,
noTxBatchTimeout: config.Config.TimedGenBlock.NoTxBatchTimeout.ToDuration(),
batchTimeout: config.Config.Solo.BatchTimeout.ToDuration(),
blockCh: make(chan *txpool.RequestHashBatch[types.Transaction, *types.Transaction], maxChanSize),
commitC: make(chan *common.CommitEvent, maxChanSize),
batchDigestM: make(map[uint64]string),
checkpoint: config.Config.Solo.CheckpointPeriod,
poolFull: 0,
recvCh: recvCh,
lastExec: config.Applied,
txpool: config.TxPool,
network: config.Network,
ctx: ctx,
cancel: cancel,
txPreCheck: precheck.NewTxPreCheckMgr(ctx, config),
logger: config.Logger,
}
batchTimerMgr := &batchTimerManager{Timer: timer.NewTimerManager(config.Logger)}
err = batchTimerMgr.CreateTimer(timer.Batch, config.Config.Solo.BatchTimeout.ToDuration(), soloNode.handleTimeoutEvent)
if err != nil {
return nil, err
}
err = batchTimerMgr.CreateTimer(timer.NoTxBatch, config.Config.TimedGenBlock.NoTxBatchTimeout.ToDuration(), soloNode.handleTimeoutEvent)
if err != nil {
return nil, err
}
soloNode.batchMgr = batchTimerMgr
soloNode.logger.Infof("SOLO lastExec = %d", soloNode.lastExec)
soloNode.logger.Infof("SOLO epoch period = %d", config.GenesisEpochInfo.EpochPeriod)
soloNode.logger.Infof("SOLO checkpoint period = %d", config.GenesisEpochInfo.ConsensusParams.CheckpointPeriod)
soloNode.logger.Infof("SOLO enable timed gen empty block = %v", config.GenesisEpochInfo.ConsensusParams.EnableTimedGenEmptyBlock)
soloNode.logger.Infof("SOLO no-tx batch timeout = %v", config.Config.TimedGenBlock.NoTxBatchTimeout.ToDuration())
soloNode.logger.Infof("SOLO batch timeout = %v", config.Config.Solo.BatchTimeout.ToDuration())
soloNode.logger.Infof("SOLO batch size = %d", config.GenesisEpochInfo.ConsensusParams.BlockMaxTxNum)
soloNode.logger.Infof("SOLO pool size = %d", config.Config.TxPool.PoolSize)
soloNode.logger.Infof("SOLO tolerance time = %v", config.Config.TxPool.ToleranceTime.ToDuration())
soloNode.logger.Infof("SOLO tolerance remove time = %v", config.Config.TxPool.ToleranceRemoveTime.ToDuration())
soloNode.logger.Infof("SOLO tolerance nonce gap = %d", config.Config.TxPool.ToleranceNonceGap)
return soloNode, nil
}
func (n *Node) GetLowWatermark() uint64 {
req := &getLowWatermarkReq{
Resp: make(chan uint64),
}
n.postMsg(req)
return <-req.Resp
}
func (n *Node) Start() error {
n.txpool.Init(txpool.ConsensusConfig{
NotifyGenerateBatchFn: n.notifyGenerateBatch,
})
err := n.txpool.Start()
if err != nil {
return err
}
err = n.batchMgr.StartTimer(timer.Batch)
if err != nil {
return err
}
if n.isTimed {
err = n.batchMgr.StartTimer(timer.NoTxBatch)
if err != nil {
return err
}
}
n.txPreCheck.Start()
go n.listenEvent()
go n.listenReadyBlock()
n.logger.Info("Consensus started")
return nil
}
func (n *Node) Stop() {
n.cancel()
n.logger.Info("Consensus stopped")
}
func (n *Node) Prepare(tx *types.Transaction) error {
defer n.txFeed.Send([]*types.Transaction{tx})
if err := n.Ready(); err != nil {
return fmt.Errorf("node get ready failed: %w", err)
}
txWithResp := &common.TxWithResp{
Tx: tx,
CheckCh: make(chan *common.TxResp),
PoolCh: make(chan *common.TxResp),
}
n.postMsg(txWithResp)
resp := <-txWithResp.CheckCh
if !resp.Status {
return errors.Wrap(common.ErrorPreCheck, resp.ErrorMsg)
}
resp = <-txWithResp.PoolCh
if !resp.Status {
return errors.Wrap(common.ErrorAddTxPool, resp.ErrorMsg)
}
return nil
}
func (n *Node) Commit() chan *common.CommitEvent {
return n.commitC
}
func (n *Node) Step([]byte) error {
return nil
}
func (n *Node) Ready() error {
if n.txpool.IsPoolFull() {
return fmt.Errorf(ErrPoolFull)
}
return nil
}
func (n *Node) ReportState(height uint64, blockHash *types.Hash, txPointerList []*events.TxPointer, _ *consensus.Checkpoint, _ bool) {
txHashList := make([]*types.Hash, len(txPointerList))
lo.ForEach(txPointerList, func(item *events.TxPointer, i int) {
txHashList[i] = item.Hash
})
state := &chainState{
Height: height,
BlockHash: blockHash,
TxHashList: txHashList,
}
n.postMsg(state)
}
func (n *Node) Quorum() uint64 {
return 1
}
func (n *Node) SubscribeTxEvent(events chan<- []*types.Transaction) event.Subscription {
return n.txFeed.Subscribe(events)
}
func (n *Node) SubscribeMockBlockEvent(ch chan<- events.ExecutedEvent) event.Subscription {
return n.mockBlockFeed.Subscribe(ch)
}
func (n *Node) SubmitTxsFromRemote(_ [][]byte) error {
return nil
}
func (n *Node) listenEvent() {
for {
select {
case <-n.ctx.Done():
n.logger.Info("----- Exit listen event -----")
return
case ev := <-n.recvCh:
switch e := ev.(type) {
// handle report state
case *chainState:
if e.Height%n.checkpoint == 0 {
n.logger.WithFields(logrus.Fields{
"height": e.Height,
"hash": e.BlockHash.String(),
}).Info("Report checkpoint")
digestList := make([]string, 0)
for i := e.Height; i > e.Height-n.checkpoint; i-- {
for h, d := range n.batchDigestM {
if i == h {
digestList = append(digestList, d)
delete(n.batchDigestM, i)
}
}
}
n.txpool.RemoveBatches(digestList)
}
// receive tx from api
case *common.TxWithResp:
unCheckedEv := &common.UncheckedTxEvent{
EventType: common.LocalTxEvent,
Event: e,
}
n.txPreCheck.PostUncheckedTxEvent(unCheckedEv)
// handle timeout event
case timer.TimeoutEvent:
if err := n.processBatchTimeout(e); err != nil {
n.logger.Errorf("Process batch timeout failed: %v", err)
}
if err := n.batchMgr.RestartTimer(timer.Batch); err != nil {
n.logger.Errorf("restart batch timeout failed: %v", err)
}
// check if there is no tx in the txpool, start the no tx batch timer
if n.isTimed && !n.txpool.HasPendingRequestInPool() {
if !n.batchMgr.IsTimerActive(timer.NoTxBatch) {
if err := n.batchMgr.StartTimer(timer.NoTxBatch); err != nil {
n.logger.Errorf("start no-tx batch timeout failed: %v", err)
}
}
}
case *getLowWatermarkReq:
e.Resp <- n.lastExec
case *genBatchReq:
n.batchMgr.StopTimer(timer.Batch)
batch, err := n.txpool.GenerateRequestBatch(e.typ)
if err != nil {
n.logger.Errorf("Generate batch failed: %v", err)
} else if batch != nil {
n.postProposal(batch)
}
// start no-tx batch timer when this node handle the last transaction
if n.isTimed && !n.txpool.HasPendingRequestInPool() {
if err = n.batchMgr.RestartTimer(timer.NoTxBatch); err != nil {
n.logger.Errorf("restart no-tx batch timeout failed: %v", err)
}
}
if err = n.batchMgr.RestartTimer(timer.Batch); err != nil {
n.logger.Errorf("restart batch timeout failed: %v", err)
}
}
}
}
}
func (n *Node) processBatchTimeout(e timer.TimeoutEvent) error {
switch e {
case timer.Batch:
n.batchMgr.StopTimer(timer.Batch)
if n.txpool.HasPendingRequestInPool() {
batch, err := n.txpool.GenerateRequestBatch(txpool.GenBatchTimeoutEvent)
if err != nil {
return err
}
if batch != nil {
now := time.Now().UnixNano()
if n.batchMgr.lastBatchTime != 0 {
interval := time.Duration(now - n.batchMgr.lastBatchTime).Seconds()
batchInterval.WithLabelValues("timeout").Observe(interval)
if n.batchMgr.minTimeoutBatchTime == 0 || interval < n.batchMgr.minTimeoutBatchTime {
n.logger.Debugf("update min timeoutBatch Time[height:%d, interval:%f, lastBatchTime:%v]",
n.lastExec+1, interval, time.Unix(0, n.batchMgr.lastBatchTime))
minBatchIntervalDuration.WithLabelValues("timeout").Set(interval)
n.batchMgr.minTimeoutBatchTime = interval
}
}
n.batchMgr.lastBatchTime = now
n.postProposal(batch)
n.logger.Debugf("batch timeout, post proposal: %v", batch)
}
}
case timer.NoTxBatch:
if n.txpool.HasPendingRequestInPool() {
n.logger.Debugf("TxPool is not empty, skip handle the no-tx batch timer event")
return nil
}
if !n.isTimed {
n.batchMgr.StopTimer(timer.NoTxBatch)
return errors.New("the node is not support the no-tx batch, skip the timer")
}
n.batchMgr.StopTimer(timer.NoTxBatch)
batch, err := n.txpool.GenerateRequestBatch(txpool.GenBatchNoTxTimeoutEvent)
if err != nil {
return err
}
if batch != nil {
n.logger.Debug("Start create empty block")
now := time.Now().UnixNano()
if n.batchMgr.lastBatchTime != 0 {
interval := time.Duration(now - n.batchMgr.lastBatchTime).Seconds()
batchInterval.WithLabelValues("timeout_no_tx").Observe(interval)
if n.batchMgr.minNoTxTimeoutBatchTime == 0 || interval < n.batchMgr.minNoTxTimeoutBatchTime {
n.logger.Debugf("update min noTxTimeoutBatch Time[height:%d, interval:%f, lastBatchTime:%v]",
n.lastExec+1, interval, time.Unix(0, n.batchMgr.lastBatchTime))
minBatchIntervalDuration.WithLabelValues("timeout_no_tx").Set(interval)
n.batchMgr.minNoTxTimeoutBatchTime = interval
}
}
n.batchMgr.lastBatchTime = now
n.postProposal(batch)
if err = n.batchMgr.RestartTimer(timer.NoTxBatch); err != nil {
n.logger.Errorf("restart no-tx batch timeout failed: %v", err)
}
n.logger.Debugf("batch no-tx timeout, post proposal: %v", batch)
}
}
return nil
}
// Schedule to collect txs to the listenReadyBlock channel
func (n *Node) listenReadyBlock() {
for {
select {
case <-n.ctx.Done():
n.logger.Info("----- Exit listen ready block loop -----")
return
case e := <-n.blockCh:
n.logger.WithFields(logrus.Fields{
"batch_hash": e.BatchHash,
"tx_count": len(e.TxList),
}).Debugf("Receive proposal from txcache")
n.logger.Infof("======== Call execute, height=%d", n.lastExec+1)
block := &types.Block{
BlockHeader: &types.BlockHeader{
Epoch: 1,
Number: n.lastExec + 1,
Timestamp: e.Timestamp / int64(time.Second),
ProposerAccount: n.config.SelfAccountAddress,
},
Transactions: e.TxList,
}
localList := make([]bool, len(e.TxList))
for i := 0; i < len(e.TxList); i++ {
localList[i] = true
}
executeEvent := &common.CommitEvent{
Block: block,
}
n.commitC <- executeEvent
n.batchDigestM[block.Height()] = e.BatchHash
n.lastExec++
}
}
}
func (n *Node) postProposal(batch *txpool.RequestHashBatch[types.Transaction, *types.Transaction]) {
n.blockCh <- batch
}
func (n *Node) notifyGenerateBatch(typ int) {
req := &genBatchReq{typ: typ}
n.postMsg(req)
}
func (n *Node) postMsg(ev consensusEvent) {
n.recvCh <- ev
}
func (n *Node) handleTimeoutEvent(typ timer.TimeoutEvent) {
switch typ {
case timer.Batch:
n.postMsg(timer.Batch)
case timer.NoTxBatch:
n.postMsg(timer.NoTxBatch)
default:
n.logger.Errorf("receive wrong timeout event type: %s", typ)
}
}