/
node.go
477 lines (418 loc) · 12.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright (c) 2018 The VeChainThor developers
// Distributed under the GNU Lesser General Public License v3.0 software license, see the accompanying
// file LICENSE or <https://www.gnu.org/licenses/lgpl-3.0.html>
package node
import (
"context"
"fmt"
"sort"
"sync"
"time"
"github.com/beevik/ntp"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/mclock"
"github.com/ethereum/go-ethereum/event"
"github.com/inconshreveable/log15"
"github.com/pkg/errors"
"github.com/syndtr/goleveldb/leveldb"
"github.com/vechain/thor/block"
"github.com/vechain/thor/cache"
"github.com/vechain/thor/chain"
"github.com/vechain/thor/cmd/thor/bandwidth"
"github.com/vechain/thor/co"
"github.com/vechain/thor/comm"
"github.com/vechain/thor/consensus"
"github.com/vechain/thor/logdb"
"github.com/vechain/thor/packer"
"github.com/vechain/thor/state"
"github.com/vechain/thor/thor"
"github.com/vechain/thor/tx"
"github.com/vechain/thor/txpool"
)
var log = log15.New("pkg", "node")
var (
// error when the block larger than known max block number + 1
errBlockTemporaryUnprocessable = errors.New("block temporary unprocessable")
errKnownBlock = errors.New("block already in the chain")
)
type Node struct {
packer *packer.Packer
cons *consensus.Consensus
master *Master
repo *chain.Repository
logDB *logdb.LogDB
txPool *txpool.TxPool
txStashPath string
comm *comm.Communicator
targetGasLimit uint64
skipLogs bool
logDBFailed bool
bandwidth bandwidth.Bandwidth
maxBlockNum uint32
processLock sync.Mutex
logWorker *worker
}
func New(
master *Master,
repo *chain.Repository,
stater *state.Stater,
logDB *logdb.LogDB,
txPool *txpool.TxPool,
txStashPath string,
comm *comm.Communicator,
targetGasLimit uint64,
skipLogs bool,
forkConfig thor.ForkConfig,
) *Node {
return &Node{
packer: packer.New(repo, stater, master.Address(), master.Beneficiary, forkConfig),
cons: consensus.New(repo, stater, forkConfig),
master: master,
repo: repo,
logDB: logDB,
txPool: txPool,
txStashPath: txStashPath,
comm: comm,
targetGasLimit: targetGasLimit,
skipLogs: skipLogs,
}
}
func (n *Node) Run(ctx context.Context) error {
logWorker := newWorker()
defer logWorker.Close()
n.logWorker = logWorker
maxBlockNum, err := n.repo.GetMaxBlockNum()
if err != nil {
return err
}
n.maxBlockNum = maxBlockNum
var goes co.Goes
goes.Go(func() { n.comm.Sync(ctx, n.handleBlockStream) })
goes.Go(func() { n.houseKeeping(ctx) })
goes.Go(func() { n.txStashLoop(ctx) })
goes.Go(func() { n.packerLoop(ctx) })
goes.Wait()
return nil
}
func (n *Node) handleBlockStream(ctx context.Context, stream <-chan *block.Block) (err error) {
log.Debug("start to process block stream")
defer log.Debug("process block stream done", "err", err)
var stats blockStats
startTime := mclock.Now()
report := func(block *block.Block) {
log.Info(fmt.Sprintf("imported blocks (%v)", stats.processed), stats.LogContext(block.Header())...)
stats = blockStats{}
startTime = mclock.Now()
}
var blk *block.Block
for blk = range stream {
if blk == nil {
continue
}
if _, err := n.processBlock(blk, &stats); err != nil {
return err
}
if stats.processed > 0 &&
mclock.Now()-startTime > mclock.AbsTime(time.Second*2) {
report(blk)
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
if blk != nil && stats.processed > 0 {
report(blk)
}
return nil
}
func (n *Node) houseKeeping(ctx context.Context) {
log.Debug("enter house keeping")
defer log.Debug("leave house keeping")
var scope event.SubscriptionScope
defer scope.Close()
newBlockCh := make(chan *comm.NewBlockEvent)
scope.Track(n.comm.SubscribeBlock(newBlockCh))
futureTicker := time.NewTicker(time.Duration(thor.BlockInterval) * time.Second)
defer futureTicker.Stop()
connectivityTicker := time.NewTicker(time.Second)
defer connectivityTicker.Stop()
var noPeerTimes int
futureBlocks := cache.NewRandCache(32)
for {
select {
case <-ctx.Done():
return
case newBlock := <-newBlockCh:
var stats blockStats
if isTrunk, err := n.processBlock(newBlock.Block, &stats); err != nil {
if consensus.IsFutureBlock(err) ||
((consensus.IsParentMissing(err) || err == errBlockTemporaryUnprocessable) && futureBlocks.Contains(newBlock.Header().ParentID())) {
log.Debug("future block added", "id", newBlock.Header().ID())
futureBlocks.Set(newBlock.Header().ID(), newBlock.Block)
}
} else if isTrunk {
n.comm.BroadcastBlock(newBlock.Block)
log.Info(fmt.Sprintf("imported blocks (%v)", stats.processed), stats.LogContext(newBlock.Block.Header())...)
}
case <-futureTicker.C:
// process future blocks
var blocks []*block.Block
futureBlocks.ForEach(func(ent *cache.Entry) bool {
blocks = append(blocks, ent.Value.(*block.Block))
return true
})
sort.Slice(blocks, func(i, j int) bool {
return blocks[i].Header().Number() < blocks[j].Header().Number()
})
var stats blockStats
for i, block := range blocks {
if isTrunk, err := n.processBlock(block, &stats); err == nil || err == errKnownBlock {
log.Debug("future block consumed", "id", block.Header().ID())
futureBlocks.Remove(block.Header().ID())
if isTrunk {
n.comm.BroadcastBlock(block)
}
}
if stats.processed > 0 && i == len(blocks)-1 {
log.Info(fmt.Sprintf("imported blocks (%v)", stats.processed), stats.LogContext(block.Header())...)
}
}
case <-connectivityTicker.C:
if n.comm.PeerCount() == 0 {
noPeerTimes++
if noPeerTimes > 30 {
noPeerTimes = 0
go checkClockOffset()
}
} else {
noPeerTimes = 0
}
}
}
}
func (n *Node) txStashLoop(ctx context.Context) {
log.Debug("enter tx stash loop")
defer log.Debug("leave tx stash loop")
db, err := leveldb.OpenFile(n.txStashPath, nil)
if err != nil {
log.Error("create tx stash", "err", err)
return
}
defer db.Close()
stash := newTxStash(db, 1000)
{
txs := stash.LoadAll()
n.txPool.Fill(txs, false)
log.Debug("loaded txs from stash", "count", len(txs))
}
var scope event.SubscriptionScope
defer scope.Close()
txCh := make(chan *txpool.TxEvent)
scope.Track(n.txPool.SubscribeTxEvent(txCh))
for {
select {
case <-ctx.Done():
return
case txEv := <-txCh:
// skip executables
if txEv.Executable != nil && *txEv.Executable {
continue
}
// only stash non-executable txs
if err := stash.Save(txEv.Tx); err != nil {
log.Warn("stash tx", "id", txEv.Tx.ID(), "err", err)
} else {
log.Debug("stashed tx", "id", txEv.Tx.ID())
}
}
}
}
// guardBlockProcessing adds lock on block processing and maintains block conflicts.
func (n *Node) guardBlockProcessing(blockNum uint32, process func(conflicts uint32) error) error {
n.processLock.Lock()
defer n.processLock.Unlock()
if blockNum > n.maxBlockNum {
if blockNum > n.maxBlockNum+1 {
// the block is surely unprocessable now
return errBlockTemporaryUnprocessable
}
n.maxBlockNum = blockNum
return process(0)
}
conflicts, err := n.repo.ScanConflicts(blockNum)
if err != nil {
return err
}
return process(conflicts)
}
func (n *Node) processBlock(newBlock *block.Block, stats *blockStats) (bool, error) {
var isTrunk *bool
if err := n.guardBlockProcessing(newBlock.Header().Number(), func(conflicts uint32) error {
// Check whether the block was already there.
// It can be skipped if no conflicts.
if conflicts > 0 {
if _, err := n.repo.GetBlockSummary(newBlock.Header().ID()); err != nil {
if !n.repo.IsNotFound(err) {
return err
}
} else {
return errKnownBlock
}
}
var (
startTime = mclock.Now()
oldBest = n.repo.BestBlockSummary()
becomeNewBest = newBlock.Header().BetterThan(oldBest.Header)
logEnabled = becomeNewBest && !n.skipLogs && !n.logDBFailed
)
isTrunk = &becomeNewBest
// process the new block
stage, receipts, err := n.cons.Process(newBlock, uint64(time.Now().Unix()), conflicts)
if err != nil {
return err
}
execElapsed := mclock.Now() - startTime
// write logs
if logEnabled {
if err := n.writeLogs(newBlock, receipts, oldBest.Header.ID()); err != nil {
return errors.Wrap(err, "write logs")
}
}
// commit produced states
if _, err := stage.Commit(); err != nil {
return errors.Wrap(err, "commit state")
}
// ad the new block into repository
if err := n.repo.AddBlock(newBlock, receipts, conflicts); err != nil {
return errors.Wrap(err, "add block")
}
realElapsed := mclock.Now() - startTime
// sync the log-writing task
if logEnabled {
if err := n.logWorker.Sync(); err != nil {
log.Warn("failed to write logs", "err", err)
n.logDBFailed = true
}
}
if becomeNewBest {
if err := n.repo.SetBestBlockID(newBlock.Header().ID()); err != nil {
return err
}
n.processFork(newBlock, oldBest.Header.ID())
}
commitElapsed := mclock.Now() - startTime - execElapsed
if v, updated := n.bandwidth.Update(newBlock.Header(), time.Duration(realElapsed)); updated {
log.Debug("bandwidth updated", "gps", v)
}
stats.UpdateProcessed(1, len(receipts), execElapsed, commitElapsed, realElapsed, newBlock.Header().GasUsed())
return nil
}); err != nil {
switch {
case err == errKnownBlock:
stats.UpdateIgnored(1)
return false, nil
case consensus.IsFutureBlock(err) || consensus.IsParentMissing(err) || err == errBlockTemporaryUnprocessable:
stats.UpdateQueued(1)
case consensus.IsCritical(err):
msg := fmt.Sprintf(`failed to process block due to consensus failure \n%v\n`, newBlock.Header())
log.Error(msg, "err", err)
default:
log.Error("failed to process block", "err", err)
}
return false, err
}
return *isTrunk, nil
}
func (n *Node) writeLogs(newBlock *block.Block, newReceipts tx.Receipts, oldBestBlockID thor.Bytes32) (err error) {
var w *logdb.Writer
if int64(newBlock.Header().Timestamp()) < time.Now().Unix()-24*3600 {
// turn off log sync to quickly catch up
w = n.logDB.NewWriterSyncOff()
} else {
w = n.logDB.NewWriter()
}
defer func() {
if err != nil {
n.logWorker.Run(w.Rollback)
}
}()
oldTrunk := n.repo.NewChain(oldBestBlockID)
newTrunk := n.repo.NewChain(newBlock.Header().ParentID())
oldBranch, err := oldTrunk.Exclude(newTrunk)
if err != nil {
return err
}
// to clear logs on the old branch.
if len(oldBranch) > 0 {
n.logWorker.Run(func() error {
return w.Truncate(block.Number(oldBranch[0]))
})
}
newBranch, err := newTrunk.Exclude(oldTrunk)
if err != nil {
return err
}
// write logs on the new branch.
for _, id := range newBranch {
block, err := n.repo.GetBlock(id)
if err != nil {
return err
}
receipts, err := n.repo.GetBlockReceipts(id)
if err != nil {
return err
}
n.logWorker.Run(func() error {
return w.Write(block, receipts)
})
}
n.logWorker.Run(func() error {
if err := w.Write(newBlock, newReceipts); err != nil {
return err
}
return w.Commit()
})
return nil
}
func (n *Node) processFork(newBlock *block.Block, oldBestBlockID thor.Bytes32) {
oldTrunk := n.repo.NewChain(oldBestBlockID)
newTrunk := n.repo.NewChain(newBlock.Header().ParentID())
sideIds, err := oldTrunk.Exclude(newTrunk)
if err != nil {
log.Warn("failed to process fork", "err", err)
return
}
if len(sideIds) == 0 {
return
}
if n := len(sideIds); n >= 2 {
log.Warn(fmt.Sprintf(
`⑂⑂⑂⑂⑂⑂⑂⑂ FORK HAPPENED ⑂⑂⑂⑂⑂⑂⑂⑂
side-chain: %v %v`,
n, sideIds[n-1]))
}
for _, id := range sideIds {
b, err := n.repo.GetBlock(id)
if err != nil {
log.Warn("failed to process fork", "err", err)
return
}
for _, tx := range b.Transactions() {
if err := n.txPool.Add(tx); err != nil {
log.Debug("failed to add tx to tx pool", "err", err, "id", tx.ID())
}
}
}
}
func checkClockOffset() {
resp, err := ntp.Query("pool.ntp.org")
if err != nil {
log.Debug("failed to access NTP", "err", err)
return
}
if resp.ClockOffset > time.Duration(thor.BlockInterval)*time.Second/2 {
log.Warn("clock offset detected", "offset", common.PrettyDuration(resp.ClockOffset))
}
}