-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathmonitor.go
More file actions
793 lines (673 loc) · 23.6 KB
/
monitor.go
File metadata and controls
793 lines (673 loc) · 23.6 KB
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
package monitor
import (
"context"
"errors"
"fmt"
"math/big"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/maticnetwork/polygon-cli/util"
_ "embed"
"github.com/ethereum/go-ethereum/ethclient"
ethrpc "github.com/ethereum/go-ethereum/rpc"
"github.com/cenkalti/backoff/v4"
termui "github.com/gizak/termui/v3"
"github.com/maticnetwork/polygon-cli/cmd/monitor/ui"
"github.com/maticnetwork/polygon-cli/metrics"
"github.com/maticnetwork/polygon-cli/rpctypes"
"github.com/rs/zerolog/log"
)
var errBatchRequestsNotSupported = errors.New("batch requests are not supported")
var (
// windowSize determines the number of blocks to display in the monitor UI at one time.
windowSize int
// batchSize holds the number of blocks to fetch in one batch.
// It can be adjusted dynamically based on network conditions.
batchSize SafeBatchSize
// interval specifies the time duration to wait between each update cycle.
interval time.Duration
// one and zero are big.Int representations of 1 and 0, used for convenience in calculations.
one = big.NewInt(1)
zero = big.NewInt(0)
// observedPendingTxs holds a historical record of the number of pending transactions.
observedPendingTxs historicalRange
// maxDataPoints defines the maximum number of data points to keep in historical records.
maxDataPoints = 1000
// maxConcurrency defines the maximum number of goroutines that can fetch block data concurrently.
maxConcurrency = 10
// semaphore is a channel used to control the concurrency of block data fetch operations.
semaphore = make(chan struct{}, maxConcurrency)
// size of the sub batches to divide and conquer the total batch size with
subBatchSize = 50
)
type (
monitorStatus struct {
TopDisplayedBlock *big.Int
UpperBlock *big.Int
LowerBlock *big.Int
ChainID *big.Int
HeadBlock *big.Int
PeerCount uint64
GasPrice *big.Int
PendingCount uint64
SelectedBlock rpctypes.PolyBlock
SelectedTransaction rpctypes.PolyTransaction
BlockCache *lru.Cache `json:"-"`
BlocksLock sync.RWMutex `json:"-"`
}
chainState struct {
HeadBlock uint64
ChainID *big.Int
PeerCount uint64
GasPrice *big.Int
PendingCount uint64
}
historicalDataPoint struct {
SampleTime time.Time
SampleValue float64
}
historicalRange []historicalDataPoint
monitorMode int
)
const (
monitorModeHelp monitorMode = iota
monitorModeExplorer
monitorModeBlock
monitorModeTransaction
)
func monitor(ctx context.Context) error {
// Dial rpc.
var rpc *ethrpc.Client
var err error
if parsedHttpHeaders == nil {
rpc, err = ethrpc.DialContext(ctx, rpcUrl)
} else {
rpc, err = ethrpc.DialOptions(ctx, rpcUrl, ethrpc.WithHTTPAuth(util.GetHTTPAuth(parsedHttpHeaders)))
}
if err != nil {
log.Error().Err(err).Msg("Unable to dial rpc")
return err
}
ec := ethclient.NewClient(rpc)
if _, err = ec.BlockNumber(ctx); err != nil {
return err
}
// Check if batch requests are supported.
if err = checkBatchRequestsSupport(ctx, ec.Client()); err != nil {
return errBatchRequestsNotSupported
}
ms := new(monitorStatus)
ms.BlocksLock.Lock()
ms.BlockCache, err = lru.New(blockCacheLimit)
if err != nil {
log.Error().Err(err).Msg("Failed to create new LRU cache")
return err
}
ms.BlocksLock.Unlock()
ms.ChainID = big.NewInt(0)
ms.PendingCount = 0
observedPendingTxs = make(historicalRange, 0)
isUiRendered := false
errChan := make(chan error)
go func() {
defer func() {
if r := recover(); r != nil {
log.Error().Msg(fmt.Sprintf("Recovered in f: %v", r))
}
}()
select {
case <-ctx.Done(): // listens for a cancellation signal
return // exit the goroutine when the context is done
default:
for {
err = fetchCurrentBlockData(ctx, ec, ms, isUiRendered)
if err != nil {
continue
}
if ms.TopDisplayedBlock == nil || ms.SelectedBlock == nil {
ms.TopDisplayedBlock = ms.HeadBlock
}
if !isUiRendered {
go func() {
errChan <- renderMonitorUI(ctx, ec, ms, rpc)
}()
isUiRendered = true
}
time.Sleep(interval)
}
}
}()
err = <-errChan
return err
}
func getChainState(ctx context.Context, ec *ethclient.Client) (*chainState, error) {
var err error
cs := new(chainState)
cs.HeadBlock, err = ec.BlockNumber(ctx)
if err != nil {
return nil, fmt.Errorf("couldn't fetch block number: %s", err.Error())
}
cs.ChainID, err = ec.ChainID(ctx)
if err != nil {
return nil, fmt.Errorf("couldn't fetch chain id: %s", err.Error())
}
cs.PeerCount, err = ec.PeerCount(ctx)
if err != nil {
log.Debug().Err(err).Msg("Using fake peer count")
cs.PeerCount = 0
}
cs.GasPrice, err = ec.SuggestGasPrice(ctx)
if err != nil {
return nil, fmt.Errorf("couldn't estimate gas: %s", err.Error())
}
cs.PendingCount, err = util.GetTxPoolSize(ec.Client())
if err != nil {
log.Debug().Err(err).Msg("Unable to get pending transaction count")
cs.PendingCount = 0
}
return cs, nil
}
func (h historicalRange) getValues(limit int) []float64 {
values := make([]float64, len(h))
for idx, v := range h {
values[idx] = v.SampleValue
}
if limit < len(values) {
values = values[len(values)-limit:]
}
return values
}
func fetchCurrentBlockData(ctx context.Context, ec *ethclient.Client, ms *monitorStatus, isUiRendered bool) (err error) {
var cs *chainState
cs, err = getChainState(ctx, ec)
if err != nil {
log.Error().Err(err).Msg("Encountered issue fetching network information")
time.Sleep(interval)
return err
}
observedPendingTxs = append(observedPendingTxs, historicalDataPoint{SampleTime: time.Now(), SampleValue: float64(cs.PendingCount)})
if len(observedPendingTxs) > maxDataPoints {
observedPendingTxs = observedPendingTxs[len(observedPendingTxs)-maxDataPoints:]
}
log.Debug().Uint64("PeerCount", cs.PeerCount).Uint64("ChainID", cs.ChainID.Uint64()).Uint64("HeadBlock", cs.HeadBlock).Uint64("GasPrice", cs.GasPrice.Uint64()).Msg("Fetching blocks")
if batchSize.Get() == 100 && batchSize.Auto() {
newBatchSize := blockCacheLimit
batchSize.Set(newBatchSize, true)
log.Debug().Msgf("Auto-adjusted batchSize to %d based on cache limit", newBatchSize)
}
ms.HeadBlock = new(big.Int).SetUint64(cs.HeadBlock)
ms.ChainID = cs.ChainID
ms.PeerCount = cs.PeerCount
ms.GasPrice = cs.GasPrice
ms.PendingCount = cs.PendingCount
return
}
func (ms *monitorStatus) getBlockRange(ctx context.Context, to *big.Int, rpc *ethrpc.Client) error {
desiredBatchSize := new(big.Int).SetInt64(int64(batchSize.Get()))
halfBatchSize := new(big.Int).Div(desiredBatchSize, big.NewInt(2))
provisionalStartBlock := new(big.Int).Sub(to, halfBatchSize)
provisionalEndBlock := new(big.Int).Add(to, halfBatchSize)
log.Debug().Int64("desiredBatchSize", int64(batchSize.Get()))
startBlock := big.NewInt(0).Set(provisionalStartBlock)
if startBlock.Cmp(zero) < 0 {
startBlock.SetInt64(0)
}
endBlock := big.NewInt(0).Set(provisionalEndBlock)
if endBlock.Cmp(ms.HeadBlock) > 0 {
endBlock.Set(ms.HeadBlock)
}
if new(big.Int).Sub(endBlock, startBlock).Cmp(desiredBatchSize) < 0 {
if startBlock.Cmp(zero) == 0 {
possibleEndBlock := new(big.Int).Add(startBlock, desiredBatchSize)
if possibleEndBlock.Cmp(ms.HeadBlock) <= 0 {
endBlock.Set(possibleEndBlock)
} else {
endBlock.Set(ms.HeadBlock)
}
} else if endBlock.Cmp(ms.HeadBlock) == 0 {
possibleStartBlock := new(big.Int).Sub(endBlock, desiredBatchSize)
if possibleStartBlock.Cmp(zero) >= 0 {
startBlock.Set(possibleStartBlock)
} else {
startBlock.SetInt64(0)
}
}
}
ms.LowerBlock = startBlock
ms.UpperBlock = endBlock
blms := make([]ethrpc.BatchElem, 0)
for i := new(big.Int).Set(startBlock); i.Cmp(endBlock) <= 0; i.Add(i, one) {
ms.BlocksLock.RLock()
_, found := ms.BlockCache.Get(i.String())
ms.BlocksLock.RUnlock()
if found {
continue
}
r := new(rpctypes.RawBlockResponse)
blms = append(blms, ethrpc.BatchElem{
Method: "eth_getBlockByNumber",
Args: []interface{}{"0x" + i.Text(16), true},
Result: r,
Error: nil,
})
}
if len(blms) == 0 {
return nil
}
err := ms.processBatchesConcurrently(ctx, rpc, blms)
if err != nil {
log.Error().Err(err).Msg("Error processing batches concurrently")
return err
}
return nil
}
func (ms *monitorStatus) processBatchesConcurrently(ctx context.Context, rpc *ethrpc.Client, blms []ethrpc.BatchElem) error {
var wg sync.WaitGroup
var errs []error = make([]error, 0)
var errorsMutex sync.Mutex
for i := 0; i < len(blms); i += subBatchSize {
semaphore <- struct{}{}
wg.Add(1)
go func(i int) {
defer func() {
<-semaphore
wg.Done()
}()
end := i + subBatchSize
if end > len(blms) {
end = len(blms)
}
subBatch := blms[i:end]
b := backoff.NewExponentialBackOff()
b.MaxElapsedTime = 3 * time.Minute
retryable := func() error {
return rpc.BatchCallContext(ctx, subBatch)
}
if err := backoff.Retry(retryable, b); err != nil {
log.Error().Err(err).Msg("unable to retry")
errorsMutex.Lock()
errs = append(errs, err)
errorsMutex.Unlock()
return
}
for _, elem := range subBatch {
if elem.Error != nil {
log.Error().Str("Method", elem.Method).Interface("Args", elem.Args).Err(elem.Error).Msg("Failed batch element")
} else {
pb := rpctypes.NewPolyBlock(elem.Result.(*rpctypes.RawBlockResponse))
ms.BlocksLock.Lock()
ms.BlockCache.Add(pb.Number().String(), pb)
ms.BlocksLock.Unlock()
}
}
}(i)
}
wg.Wait()
return errors.Join(errs...)
}
func renderMonitorUI(ctx context.Context, ec *ethclient.Client, ms *monitorStatus, rpc *ethrpc.Client) error {
if err := termui.Init(); err != nil {
log.Error().Err(err).Msg("Failed to initialize UI")
return err
}
defer termui.Close()
currentMode := monitorModeExplorer
blockTable, blockInfo, transactionList, transactionInformationList, transactionInfo, grid, blockGrid, transactionGrid, skeleton := ui.SetUISkeleton()
termWidth, termHeight := termui.TerminalDimensions()
windowSize = termHeight/2 - 4
grid.SetRect(0, 0, termWidth, termHeight)
blockGrid.SetRect(0, 0, termWidth, termHeight)
transactionGrid.SetRect(0, 0, termWidth, termHeight)
// Initial render needed I assume to avoid the first bad redraw
termui.Render(grid)
var setBlock = false
var renderedBlocks rpctypes.SortableBlocks
redraw := func(ms *monitorStatus, force ...bool) {
if currentMode == monitorModeHelp {
// TODO add some help context?
} else if currentMode == monitorModeBlock {
// render a block
skeleton.BlockInfo.Rows = ui.GetSimpleBlockFields(ms.SelectedBlock)
rows, title := ui.GetTransactionsList(ms.SelectedBlock, ms.ChainID)
transactionList.Rows = rows
transactionList.Title = title
baseFee := ms.SelectedBlock.BaseFee()
if transactionList.SelectedRow != 0 {
ms.SelectedTransaction = ms.SelectedBlock.Transactions()[transactionList.SelectedRow-1]
transactionInformationList.Rows = ui.GetSimpleTxFields(ms.SelectedTransaction, ms.ChainID, baseFee)
}
termui.Clear()
termui.Render(blockGrid)
log.Debug().
Int("skeleton.TransactionList.SelectedRow", transactionList.SelectedRow).
Msg("Redrawing block mode")
return
} else if currentMode == monitorModeTransaction {
baseFee := ms.SelectedBlock.BaseFee()
skeleton.TxInfo.Rows = ui.GetSimpleTxFields(ms.SelectedBlock.Transactions()[transactionList.SelectedRow-1], ms.ChainID, baseFee)
skeleton.Receipts.Rows = ui.GetSimpleReceipt(ctx, rpc, ms.SelectedTransaction)
termui.Clear()
termui.Render(transactionGrid)
log.Debug().
Int("skeleton.TransactionList.SelectedRow", transactionList.SelectedRow).
Msg("Redrawing transaction mode")
return
}
log.Debug().
Str("TopDisplayedBlock", ms.TopDisplayedBlock.String()).
Int("BatchSize", batchSize.Get()).
Str("UpperBlock", ms.UpperBlock.String()).
Str("LowerBlock", ms.LowerBlock.String()).
Str("ChainID", ms.ChainID.String()).
Str("HeadBlock", ms.HeadBlock.String()).
Uint64("PeerCount", ms.PeerCount).
Str("GasPrice", ms.GasPrice.String()).
Uint64("PendingCount", ms.PendingCount).
Msg("Redrawing")
if blockTable.SelectedRow == 0 {
bottomBlockNumber := new(big.Int).Sub(ms.HeadBlock, big.NewInt(int64(windowSize-1)))
if bottomBlockNumber.Cmp(zero) < 0 {
bottomBlockNumber.SetInt64(0)
}
// if ms.LowerBlock == nil || ms.LowerBlock.Cmp(bottomBlockNumber) > 0 {
err := ms.getBlockRange(ctx, ms.TopDisplayedBlock, rpc)
if err != nil {
log.Error().Err(err).Msg("There was an issue fetching the block range")
}
// }
}
toBlockNumber := ms.TopDisplayedBlock
fromBlockNumber := new(big.Int).Sub(toBlockNumber, big.NewInt(int64(windowSize-1)))
if fromBlockNumber.Cmp(zero) < 0 {
fromBlockNumber.SetInt64(0) // We cannot have block numbers less than 0.
}
renderedBlocksTemp := make([]rpctypes.PolyBlock, 0, windowSize)
ms.BlocksLock.RLock()
for i := new(big.Int).Set(fromBlockNumber); i.Cmp(toBlockNumber) <= 0; i.Add(i, big.NewInt(1)) {
if block, ok := ms.BlockCache.Get(i.String()); ok {
renderedBlocksTemp = append(renderedBlocksTemp, block.(rpctypes.PolyBlock))
} else {
// If for some reason the block is not in the cache after fetching, handle this case.
log.Warn().Str("blockNumber", i.String()).Msg("Block should be in cache but is not")
}
}
ms.BlocksLock.RUnlock()
renderedBlocks = renderedBlocksTemp
log.Warn().Int("skeleton.Current.Inner.Dy()", skeleton.Current.Inner.Dy()).Int("skeleton.Current.Inner.Dx()", skeleton.Current.Inner.Dx()).Msg("the dimension of the current box")
skeleton.Current.Text = ui.GetCurrentBlockInfo(ms.HeadBlock, ms.GasPrice, ms.PeerCount, ms.PendingCount, ms.ChainID, renderedBlocks, skeleton.Current.Inner.Dx(), skeleton.Current.Inner.Dy())
skeleton.TxPerBlockChart.Data = metrics.GetTxsPerBlock(renderedBlocks)
skeleton.GasPriceChart.Data = metrics.GetMeanGasPricePerBlock(renderedBlocks)
skeleton.BlockSizeChart.Data = metrics.GetSizePerBlock(renderedBlocks)
// skeleton.pendingTxChart.Data = metrics.GetUnclesPerBlock(renderedBlocks)
skeleton.PendingTxChart.Data = observedPendingTxs.getValues(25)
skeleton.GasChart.Data = metrics.GetGasPerBlock(renderedBlocks)
// If a row has not been selected, continue to update the list with new blocks.
rows, title := ui.GetBlocksList(renderedBlocks)
blockTable.Rows = rows
blockTable.Title = title
blockTable.TextStyle = termui.NewStyle(termui.ColorWhite)
blockTable.SelectedRowStyle = termui.NewStyle(termui.ColorWhite, termui.ColorRed, termui.ModifierBold)
transactionColumnRatio := []int{30, 5, 20, 20, 5, 10}
if blockTable.SelectedRow > 0 && blockTable.SelectedRow <= len(blockTable.Rows) {
// Only changed the selected block when the user presses the up down keys.
// Otherwise this will adjust when the table is updated automatically.
if setBlock {
log.Debug().
Int("blockTable.SelectedRow", blockTable.SelectedRow).
Int("renderedBlocks", len(renderedBlocks)).
Msg("setBlock")
ms.SelectedBlock = renderedBlocks[len(renderedBlocks)-blockTable.SelectedRow]
blockInfo.Rows = ui.GetSimpleBlockFields(ms.SelectedBlock)
transactionInfo.ColumnWidths = getColumnWidths(transactionColumnRatio, transactionInfo.Dx())
transactionInfo.Rows = ui.GetBlockTxTable(ms.SelectedBlock, ms.ChainID)
transactionInfo.Title = fmt.Sprintf("Latest Transactions for Block #%s", ms.SelectedBlock.Number().String())
setBlock = false
log.Debug().Uint64("blockNumber", ms.SelectedBlock.Number().Uint64()).Msg("Selected block changed")
}
} else {
ms.SelectedBlock = nil
blockInfo.Rows = []string{}
transactionInfo.ColumnWidths = getColumnWidths(transactionColumnRatio, transactionInfo.Dx())
transactionInfo.Rows = ui.GetBlockTxTable(renderedBlocks[len(renderedBlocks)-1], ms.ChainID)
transactionInfo.Title = fmt.Sprintf("Latest Transactions for Block #%s", renderedBlocks[len(renderedBlocks)-1].Number().String())
}
termui.Render(grid)
}
currentBn := ms.HeadBlock
uiEvents := termui.PollEvents()
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
redraw(ms)
for {
forceRedraw := false
select {
case e := <-uiEvents:
switch e.ID {
case "q", "<C-c>":
return nil
case "<Escape>":
if currentMode == monitorModeExplorer {
ms.TopDisplayedBlock = ms.HeadBlock
blockTable.SelectedRow = 0
toBlockNumber := new(big.Int).Sub(ms.TopDisplayedBlock, big.NewInt(int64(windowSize-1)))
if toBlockNumber.Cmp(zero) < 0 {
toBlockNumber.SetInt64(0)
}
err := ms.getBlockRange(ctx, ms.TopDisplayedBlock, rpc)
if err != nil {
log.Error().Err(err).Msg("There was an issue fetching the block range")
break
}
} else if currentMode == monitorModeBlock {
currentMode = monitorModeExplorer
} else if currentMode == monitorModeTransaction {
currentMode = monitorModeBlock
}
case "<Enter>":
if currentMode == monitorModeExplorer && blockTable.SelectedRow > 0 {
currentMode = monitorModeBlock
} else if transactionList.SelectedRow > 0 {
currentMode = monitorModeTransaction
}
case "<Resize>":
payload := e.Payload.(termui.Resize)
grid.SetRect(0, 0, payload.Width, payload.Height)
blockGrid.SetRect(0, 0, payload.Width, payload.Height)
transactionGrid.SetRect(0, 0, payload.Width, payload.Height)
_, termHeight = termui.TerminalDimensions()
windowSize = termHeight/2 - 4
termui.Clear()
case "<Up>", "<Down>":
if currentMode == monitorModeBlock {
if len(transactionList.Rows) != 0 && e.ID == "<Down>" {
transactionList.ScrollDown()
} else if len(transactionList.Rows) != 0 && e.ID == "<Up>" {
transactionList.ScrollUp()
}
break
}
if blockTable.SelectedRow == 0 {
blockTable.SelectedRow = 1
setBlock = true
break
}
if e.ID == "<Down>" {
log.Debug().
Int("blockTable.SelectedRow", blockTable.SelectedRow).
Int("windowSize", windowSize).
Int("renderedBlocks", len(renderedBlocks)).
Int("dy", blockTable.Dy()).
Msg("Down")
if blockTable.SelectedRow > windowSize-1 {
nextTopBlockNumber := new(big.Int).Sub(ms.TopDisplayedBlock, one)
if nextTopBlockNumber.Cmp(zero) < 0 {
nextTopBlockNumber.SetInt64(0)
}
toBlockNumber := new(big.Int).Sub(nextTopBlockNumber, big.NewInt(int64(windowSize-1)))
if toBlockNumber.Cmp(zero) < 0 {
toBlockNumber.SetInt64(0)
}
if !isBlockInCache(ms.BlockCache, toBlockNumber) {
err := ms.getBlockRange(ctx, toBlockNumber, rpc)
if err != nil {
log.Warn().Err(err).Msg("Failed to fetch blocks on page down")
break
}
}
ms.TopDisplayedBlock = nextTopBlockNumber
blockTable.SelectedRow = len(renderedBlocks)
setBlock = true
forceRedraw = true
redraw(ms, true)
break
}
// blockTable.SelectedRow += 1
blockTable.ScrollDown()
setBlock = true
} else if e.ID == "<Up>" {
log.Debug().Int("blockTable.SelectedRow", blockTable.SelectedRow).Int("windowSize", windowSize).Msg("Up")
// the last row of current window size
if blockTable.SelectedRow == 1 {
// Calculate the range of block numbers we are trying to page down to
nextTopBlockNumber := new(big.Int).Add(ms.TopDisplayedBlock, one)
if nextTopBlockNumber.Cmp(ms.HeadBlock) > 0 {
nextTopBlockNumber.SetInt64(ms.HeadBlock.Int64())
}
// Calculate the 'to' block number based on the next top block number
toBlockNumber := new(big.Int).Sub(nextTopBlockNumber, big.NewInt(int64(windowSize-1)))
if toBlockNumber.Cmp(zero) < 0 {
toBlockNumber.SetInt64(0)
}
// Fetch the blocks in the new range if they are missing
if !isBlockInCache(ms.BlockCache, nextTopBlockNumber) {
err := ms.getBlockRange(ctx, new(big.Int).Add(nextTopBlockNumber, big.NewInt(int64(windowSize))), rpc)
if err != nil {
log.Warn().Err(err).Msg("Failed to fetch blocks on page up")
break
}
}
// Update the top displayed block number
ms.TopDisplayedBlock = nextTopBlockNumber
blockTable.SelectedRow = 1
setBlock = true
// Force redraw to update the UI with the new page of blocks
forceRedraw = true
redraw(ms, true)
break
}
// blockTable.SelectedRow -= 1
blockTable.ScrollUp()
setBlock = true
}
case "<Home>":
ms.TopDisplayedBlock = ms.HeadBlock
blockTable.SelectedRow = 1
setBlock = true
case "g":
blockTable.SelectedRow = 1
setBlock = true
case "G", "<End>":
if len(renderedBlocks) < windowSize {
ms.TopDisplayedBlock = ms.HeadBlock
blockTable.SelectedRow = len(renderedBlocks)
} else {
blockTable.SelectedRow = max(windowSize, len(renderedBlocks))
}
setBlock = true
case "<C-f>", "<PageDown>":
nextTopBlockNumber := new(big.Int).Sub(ms.TopDisplayedBlock, big.NewInt(int64(windowSize)))
if nextTopBlockNumber.Cmp(zero) < 0 {
nextTopBlockNumber.SetInt64(0)
}
bottomBlockNumber := new(big.Int).Sub(nextTopBlockNumber, big.NewInt(int64(windowSize-1)))
if bottomBlockNumber.Cmp(zero) < 0 {
bottomBlockNumber.SetInt64(0)
}
if ms.LowerBlock.Cmp(bottomBlockNumber) > 0 {
log.Debug().Msgf("TEST NOT HERE %d %d", ms.LowerBlock, bottomBlockNumber)
err := ms.getBlockRange(ctx, nextTopBlockNumber, rpc)
if err != nil {
log.Warn().Err(err).Msg("Failed to fetch blocks on page down")
break
}
}
ms.TopDisplayedBlock = nextTopBlockNumber
blockTable.SelectedRow = 1
setBlock = true
log.Debug().
Int("TopDisplayedBlock", int(ms.TopDisplayedBlock.Int64())).
Int("bottomBlockNumber", int(bottomBlockNumber.Int64())).
Msg("PageDown")
forceRedraw = true
redraw(ms, true)
case "<C-b>", "<PageUp>":
nextTopBlockNumber := new(big.Int).Add(ms.TopDisplayedBlock, big.NewInt(int64(windowSize)))
if nextTopBlockNumber.Cmp(ms.HeadBlock) > 0 {
nextTopBlockNumber.SetInt64(ms.HeadBlock.Int64())
}
toBlockNumber := new(big.Int).Sub(nextTopBlockNumber, big.NewInt(int64(windowSize-1)))
if toBlockNumber.Cmp(zero) < 0 {
toBlockNumber.SetInt64(0)
}
err := ms.getBlockRange(ctx, nextTopBlockNumber, rpc)
if err != nil {
log.Warn().Err(err).Msg("Failed to fetch blocks on page up")
break
}
ms.TopDisplayedBlock = nextTopBlockNumber
blockTable.SelectedRow = 1
setBlock = true
log.Debug().
Int("TopDisplayedBlock", int(ms.TopDisplayedBlock.Int64())).
Int("toBlockNumber", int(toBlockNumber.Int64())).
Msg("PageDown")
forceRedraw = true
redraw(ms, true)
default:
log.Trace().Str("id", e.ID).Msg("Unknown ui event")
}
if !forceRedraw {
redraw(ms)
}
case <-ticker.C:
if currentBn != ms.HeadBlock {
currentBn = ms.HeadBlock
redraw(ms)
}
}
}
}
func isBlockInCache(cache *lru.Cache, blockNumber *big.Int) bool {
_, exists := cache.Get(blockNumber.String())
return exists
}
func max(nums ...int) int {
m := nums[0]
for _, n := range nums {
if m < n {
m = n
}
}
return m
}
// checkBatchRequestsSupport checks if batch requests are supported by making a sample batch request.
// https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_blocknumber
func checkBatchRequestsSupport(ctx context.Context, ec *ethrpc.Client) error {
batchRequest := []ethrpc.BatchElem{
{Method: "eth_blockNumber"},
{Method: "eth_blockNumber"},
}
return ec.BatchCallContext(ctx, batchRequest)
}
func getColumnWidths(columnRatio []int, width int) (columnWidths []int) {
totalRatio := 0
for _, ratio := range columnRatio {
totalRatio += ratio
}
columnWidths = make([]int, len(columnRatio))
for i, ratio := range columnRatio {
columnWidths[i] = width * ratio / totalRatio
}
return
}