-
Notifications
You must be signed in to change notification settings - Fork 435
/
statistics.go
1485 lines (1247 loc) · 55.2 KB
/
statistics.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
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package db
import (
"context"
"database/sql"
"eth2-exporter/cache"
"eth2-exporter/metrics"
"eth2-exporter/price"
"eth2-exporter/types"
"eth2-exporter/utils"
"fmt"
"math/big"
"strings"
"sync"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/stdlib"
"github.com/lib/pq"
"github.com/shopspring/decimal"
"github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"
pgxdecimal "github.com/jackc/pgx-shopspring-decimal"
)
func WriteValidatorStatisticsForDay(day uint64) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
logger.Infof("exporting statistics for day %v (epoch %v to %v)", day, firstEpoch, lastEpoch)
if err := checkIfDayIsFinalized(day); err != nil {
return err
}
logger.Infof("getting exported state for day %v", day)
type Exported struct {
Status bool `db:"status"`
}
exported := Exported{}
err := WriterDb.Get(&exported, `
SELECT
status
FROM validator_stats_status
WHERE day = $1;
`, day)
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("error retrieving exported state: %w", err)
}
previousDayExported := Exported{}
err = WriterDb.Get(&previousDayExported, `
SELECT
status
FROM validator_stats_status
WHERE day = $1;
`, int64(day)-1)
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("error retrieving previous day exported state: %w", err)
}
if day > 0 && !previousDayExported.Status {
return fmt.Errorf("cannot export day %v as day %v has not yet been exported yet", day, int64(day)-1)
}
maxValidatorIndex, err := BigtableClient.GetMaxValidatorindexForEpoch(lastEpoch)
if err != nil {
return err
}
validators := make([]uint64, 0, maxValidatorIndex)
validatorData := make([]*types.ValidatorStatsTableDbRow, 0, maxValidatorIndex)
validatorDataMux := &sync.Mutex{}
logger.Infof("processing statistics for validators 0-%d", maxValidatorIndex)
for i := uint64(0); i <= maxValidatorIndex; i++ {
validators = append(validators, i)
validatorData = append(validatorData, &types.ValidatorStatsTableDbRow{
ValidatorIndex: i,
Day: int64(day),
})
}
// temporarily disabled for debugging
// if exported.Status {
// logger.Infof("Skipping day %v as it is already exported", day)
// return nil
// }
g := &errgroup.Group{}
g.Go(func() error {
if err := gatherValidatorFailedAttestationsStatisticsForDay(validators, day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorFailedAttestationsStatisticsForDay: %w", err)
}
return nil
})
g.Go(func() error {
if err := gatherValidatorSyncDutiesForDay(validators, day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorSyncDutiesForDay: %w", err)
}
return nil
})
g.Go(func() error {
if err := gatherValidatorDepositWithdrawals(day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorDepositWithdrawals: %w", err)
}
return nil
})
g.Go(func() error {
if err := gatherValidatorBlockStats(day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorBlockStats: %w", err)
}
return nil
})
g.Go(func() error {
if err := gatherValidatorBalances(validators, day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorBalances: %w", err)
}
return nil
})
g.Go(func() error {
if err := gatherValidatorElIcome(day, validatorData, validatorDataMux); err != nil {
return fmt.Errorf("error in GatherValidatorElIcome: %w", err)
}
return nil
})
var previousDayStatisticsData []*types.ValidatorStatsTableDbRow
g.Go(func() error {
var err error
previousDayStatisticsData, err = gatherPreviousDayStatisticsData(int64(day)) // convert to int64 to avoid underflows
if err != nil {
return fmt.Errorf("error in GatherPreviousDayStatisticsData: %w", err)
}
return nil
})
err = g.Wait()
if err != nil {
return err
}
// calculate cl income data & update totals
for index, data := range validatorData {
previousDayData := &types.ValidatorStatsTableDbRow{
ValidatorIndex: uint64(index),
EndBalance: data.StartBalance, // special case for handling day 0
}
if index < len(previousDayStatisticsData) && day > 0 {
previousDayData = previousDayStatisticsData[index]
}
if data.ValidatorIndex != previousDayData.ValidatorIndex {
return fmt.Errorf("logic error when retrieving previous day data for validator %v (%v wanted, %v retrieved)", index, index, previousDayData.ValidatorIndex)
}
// update attestation totals
data.MissedAttestationsTotal = previousDayData.MissedAttestationsTotal + data.MissedAttestations
// update sync total
data.ParticipatedSyncTotal = previousDayData.ParticipatedSyncTotal + data.ParticipatedSync
data.MissedSyncTotal = previousDayData.MissedSyncTotal + data.MissedSync
data.OrphanedSyncTotal = previousDayData.OrphanedSyncTotal + data.OrphanedSync
// calculate cl reward & update totals
data.ClRewardsGWei = data.EndBalance - previousDayData.EndBalance + data.WithdrawalsAmount - data.DepositsAmount
data.ClRewardsGWeiTotal = previousDayData.ClRewardsGWeiTotal + data.ClRewardsGWei
// update el reward total
data.ElRewardsWeiTotal = previousDayData.ElRewardsWeiTotal.Add(data.ElRewardsWei)
// update mev reward total
data.MEVRewardsWeiTotal = previousDayData.MEVRewardsWeiTotal.Add(data.MEVRewardsWei)
}
conn, err := WriterDb.Conn(context.Background())
if err != nil {
return fmt.Errorf("error retrieving raw sql connection: %w", err)
}
defer conn.Close()
err = conn.Raw(func(driverConn interface{}) error {
conn := driverConn.(*stdlib.Conn).Conn()
pgxdecimal.Register(conn.TypeMap())
tx, err := conn.Begin(context.Background())
if err != nil {
return err
}
defer tx.Rollback(context.Background())
_, err = tx.Exec(context.Background(), "DELETE FROM validator_stats WHERE day = $1", day)
if err != nil {
return err
}
_, err = tx.CopyFrom(context.Background(), pgx.Identifier{"validator_stats"}, []string{
"validatorindex",
"day",
"start_balance",
"end_balance",
"min_balance",
"max_balance",
"start_effective_balance",
"end_effective_balance",
"min_effective_balance",
"max_effective_balance",
"missed_attestations",
"missed_attestations_total",
"orphaned_attestations",
"participated_sync",
"participated_sync_total",
"missed_sync",
"missed_sync_total",
"orphaned_sync",
"orphaned_sync_total",
"proposed_blocks",
"missed_blocks",
"orphaned_blocks",
"attester_slashings",
"proposer_slashings",
"deposits",
"deposits_amount",
"withdrawals",
"withdrawals_amount",
"cl_rewards_gwei",
"cl_rewards_gwei_total",
"el_rewards_wei",
"el_rewards_wei_total",
"mev_rewards_wei",
"mev_rewards_wei_total",
}, pgx.CopyFromSlice(len(validatorData), func(i int) ([]interface{}, error) {
return []interface{}{
validatorData[i].ValidatorIndex,
validatorData[i].Day,
validatorData[i].StartBalance,
validatorData[i].EndBalance,
validatorData[i].MinBalance,
validatorData[i].MaxBalance,
validatorData[i].StartEffectiveBalance,
validatorData[i].EndEffectiveBalance,
validatorData[i].MinEffectiveBalance,
validatorData[i].MaxEffectiveBalance,
validatorData[i].MissedAttestations,
validatorData[i].MissedAttestationsTotal,
validatorData[i].OrphanedAttestations,
validatorData[i].ParticipatedSync,
validatorData[i].ParticipatedSyncTotal,
validatorData[i].MissedSync,
validatorData[i].MissedSyncTotal,
validatorData[i].OrphanedSync,
validatorData[i].OrphanedSyncTotal,
validatorData[i].ProposedBlocks,
validatorData[i].MissedBlocks,
validatorData[i].OrphanedBlocks,
validatorData[i].AttesterSlashings,
validatorData[i].ProposerSlashing,
validatorData[i].Deposits,
validatorData[i].DepositsAmount,
validatorData[i].Withdrawals,
validatorData[i].WithdrawalsAmount,
validatorData[i].ClRewardsGWei,
validatorData[i].ClRewardsGWeiTotal,
validatorData[i].ElRewardsWei,
validatorData[i].ElRewardsWeiTotal,
validatorData[i].MEVRewardsWei,
validatorData[i].MEVRewardsWeiTotal,
}, nil
}))
if err != nil {
return err
}
logger.Infof("batch insert of statistics data completed")
if err := WriteValidatorTotalPerformance(day, tx); err != nil {
return fmt.Errorf("error in WriteValidatorTotalPerformance: %w", err)
}
if err := WriteValidatorStatsExported(day, tx); err != nil {
return fmt.Errorf("error in WriteValidatorStatsExported: %w", err)
}
err = tx.Commit(context.Background())
if err != nil {
return err
}
return nil
})
if err != nil {
return fmt.Errorf("error during statistics data insert: %w", err)
}
logger.Infof("statistics export of day %v completed, took %v", day, time.Since(exportStart))
return nil
}
func WriteValidatorStatsExported(day uint64, tx pgx.Tx) error {
start := time.Now()
logger.Infof("marking day export as completed in the validator_stats_status table for day %v", day)
_, err := tx.Exec(context.Background(), `
INSERT INTO validator_stats_status (day, status,failed_attestations_exported,sync_duties_exported,withdrawals_deposits_exported,balance_exported,cl_rewards_exported,el_rewards_exported,total_performance_exported,block_stats_exported,total_accumulation_exported)
VALUES ($1, true, true, true, true,true,true,true,true,true,true)
ON CONFLICT (day) DO UPDATE
SET status = true,
failed_attestations_exported = true,
sync_duties_exported = true,
withdrawals_deposits_exported = true,
balance_exported = true,
cl_rewards_exported = true,
el_rewards_exported = true,
total_performance_exported = true,
block_stats_exported = true,
total_accumulation_exported = true;
`, day)
if err != nil {
return fmt.Errorf("error marking day export as completed in the validator_stats_status table for day %v: %w", day, err)
}
logger.Infof("marking completed, took %v", time.Since(start))
return nil
}
func WriteValidatorTotalPerformance(day uint64, tx pgx.Tx) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_total_performance_stats").Observe(time.Since(exportStart).Seconds())
}()
start := time.Now()
logger.Infof("exporting total performance stats")
_, err := tx.Exec(context.Background(), `insert into validator_performance (
validatorindex,
balance,
rank7d,
cl_performance_1d,
cl_performance_7d,
cl_performance_31d,
cl_performance_365d,
cl_performance_total,
el_performance_1d,
el_performance_7d,
el_performance_31d,
el_performance_365d,
el_performance_total,
mev_performance_1d,
mev_performance_7d,
mev_performance_31d,
mev_performance_365d,
mev_performance_total
) (
select
vs_now.validatorindex,
COALESCE(vs_now.end_balance, 0) as balance,
0 as rank7d,
coalesce(vs_now.cl_rewards_gwei_total, 0) - coalesce(vs_1d.cl_rewards_gwei_total, 0) as cl_performance_1d,
coalesce(vs_now.cl_rewards_gwei_total, 0) - coalesce(vs_7d.cl_rewards_gwei_total, 0) as cl_performance_7d,
coalesce(vs_now.cl_rewards_gwei_total, 0) - coalesce(vs_31d.cl_rewards_gwei_total, 0) as cl_performance_31d,
coalesce(vs_now.cl_rewards_gwei_total, 0) - coalesce(vs_365d.cl_rewards_gwei_total, 0) as cl_performance_365d,
coalesce(vs_now.cl_rewards_gwei_total, 0) as cl_performance_total,
coalesce(vs_now.el_rewards_wei_total, 0) - coalesce(vs_1d.el_rewards_wei_total, 0) as el_performance_1d,
coalesce(vs_now.el_rewards_wei_total, 0) - coalesce(vs_7d.el_rewards_wei_total, 0) as el_performance_7d,
coalesce(vs_now.el_rewards_wei_total, 0) - coalesce(vs_31d.el_rewards_wei_total, 0) as el_performance_31d,
coalesce(vs_now.el_rewards_wei_total, 0) - coalesce(vs_365d.el_rewards_wei_total, 0) as el_performance_365d,
coalesce(vs_now.el_rewards_wei_total, 0) as el_performance_total,
coalesce(vs_now.mev_rewards_wei_total, 0) - coalesce(vs_1d.mev_rewards_wei_total, 0) as mev_performance_1d,
coalesce(vs_now.mev_rewards_wei_total, 0) - coalesce(vs_7d.mev_rewards_wei_total, 0) as mev_performance_7d,
coalesce(vs_now.mev_rewards_wei_total, 0) - coalesce(vs_31d.mev_rewards_wei_total, 0) as mev_performance_31d,
coalesce(vs_now.mev_rewards_wei_total, 0) - coalesce(vs_365d.mev_rewards_wei_total, 0) as mev_performance_365d,
coalesce(vs_now.mev_rewards_wei_total, 0) as mev_performance_total
from validator_stats vs_now
left join validator_stats vs_1d on vs_1d.validatorindex = vs_now.validatorindex and vs_1d.day = $2
left join validator_stats vs_7d on vs_7d.validatorindex = vs_now.validatorindex and vs_7d.day = $3
left join validator_stats vs_31d on vs_31d.validatorindex = vs_now.validatorindex and vs_31d.day = $4
left join validator_stats vs_365d on vs_365d.validatorindex = vs_now.validatorindex and vs_365d.day = $5
where vs_now.day = $1
)
on conflict (validatorindex) do update set
balance = excluded.balance,
rank7d=excluded.rank7d,
cl_performance_1d=excluded.cl_performance_1d,
cl_performance_7d=excluded.cl_performance_7d,
cl_performance_31d=excluded.cl_performance_31d,
cl_performance_365d=excluded.cl_performance_365d,
cl_performance_total=excluded.cl_performance_total,
el_performance_1d=excluded.el_performance_1d,
el_performance_7d=excluded.el_performance_7d,
el_performance_31d=excluded.el_performance_31d,
el_performance_365d=excluded.el_performance_365d,
el_performance_total=excluded.el_performance_total,
mev_performance_1d=excluded.mev_performance_1d,
mev_performance_7d=excluded.mev_performance_7d,
mev_performance_31d=excluded.mev_performance_31d,
mev_performance_365d=excluded.mev_performance_365d,
mev_performance_total=excluded.mev_performance_total
;`, day, int64(day)-1, int64(day)-7, int64(day)-31, int64(day)-365)
if err != nil {
return fmt.Errorf("error inserting performance into validator_performance for day [%v]: %w", day, err)
}
logger.Infof("export completed, took %v", time.Since(start))
start = time.Now()
logger.Infof("populate validator_performance rank7d")
_, err = tx.Exec(context.Background(), `
WITH ranked_performance AS (
SELECT
validatorindex,
row_number() OVER (ORDER BY cl_performance_7d DESC) AS rank7d
FROM validator_performance
)
UPDATE validator_performance vp
SET rank7d = rp.rank7d
FROM ranked_performance rp
WHERE vp.validatorindex = rp.validatorindex
`)
if err != nil {
return fmt.Errorf("error updating rank7d while exporting day [%v]: %w", day, err)
}
logger.Infof("export completed, took %v", time.Since(start))
logger.Infof("total performance statistics export of day %v completed, took %v", day, time.Since(exportStart))
return nil
}
func gatherValidatorBlockStats(day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_block_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstEpoch": firstEpoch,
"lastEpoch": lastEpoch,
})
type resRowBlocks struct {
ValidatorIndex uint64 `db:"validatorindex"`
ProposedBlocks uint64 `db:"proposed_blocks"`
MissedBlocks uint64 `db:"missed_blocks"`
OrphanedBlocks uint64 `db:"orphaned_blocks"`
}
resBlocks := make([]*resRowBlocks, 0, 1024)
logger.Infof("gathering proposed_blocks, missed_blocks and orphaned_blocks statistics")
err := WriterDb.Select(&resBlocks, `select proposer AS validatorindex, sum(case when status = '1' then 1 else 0 end) AS proposed_blocks, sum(case when status = '2' then 1 else 0 end) AS missed_blocks, sum(case when status = '3' then 1 else 0 end) AS orphaned_blocks
from blocks
where epoch >= $1 and epoch <= $2 and proposer != $3
group by proposer
;`,
firstEpoch, lastEpoch, MaxSqlInteger)
if err != nil {
return fmt.Errorf("error inserting blocks into validator_stats for day [%v], firstEpoch [%v] and lastEpoch [%v]: %w", day, firstEpoch, lastEpoch, err)
}
mux.Lock()
for _, r := range resBlocks {
data[r.ValidatorIndex].ProposedBlocks = int64(r.ProposedBlocks)
data[r.ValidatorIndex].MissedBlocks = int64(r.MissedBlocks)
data[r.ValidatorIndex].OrphanedBlocks = int64(r.OrphanedBlocks)
}
mux.Unlock()
type resRowSlashings struct {
ValidatorIndex uint64 `db:"validatorindex"`
AttesterSlashings uint64 `db:"attester_slashings"`
ProposerSlashing uint64 `db:"proposer_slashings"`
}
resSlashings := make([]*resRowSlashings, 0, 1024)
logger.Infof("gathering attester_slashings and proposer_slashings statistics")
err = WriterDb.Select(&resSlashings, `
select proposer AS validatorindex, sum(attesterslashingscount) AS attester_slashings, sum(proposerslashingscount) AS proposer_slashings
from blocks
where epoch >= $1 and epoch <= $2 and status = '1' and proposer != $3
group by proposer;
`,
firstEpoch, lastEpoch, MaxSqlInteger)
if err != nil {
return fmt.Errorf("error inserting slashings into validator_stats for day [%v], firstEpoch [%v] and lastEpoch [%v]: %w", day, firstEpoch, lastEpoch, err)
}
mux.Lock()
for _, r := range resSlashings {
data[r.ValidatorIndex].AttesterSlashings = int64(r.AttesterSlashings)
data[r.ValidatorIndex].ProposerSlashing = int64(r.ProposerSlashing)
}
mux.Unlock()
logger.Infof("gathering block statistics completed, took %v", time.Since(exportStart))
return nil
}
func gatherValidatorElIcome(day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_el_income_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstEpoch": firstEpoch,
"lastEpoch": lastEpoch,
})
logger.Infof("gathering mev & el rewards")
type Container struct {
Slot uint64 `db:"slot"`
ExecBlockNumber uint64 `db:"exec_block_number"`
Proposer uint64 `db:"proposer"`
TxFeeReward *big.Int
MevReward *big.Int
}
blocks := make([]*Container, 0)
blocksMap := make(map[uint64]*Container)
err := WriterDb.Select(&blocks, "SELECT slot, exec_block_number, proposer FROM blocks WHERE epoch >= $1 AND epoch <= $2 AND exec_block_number > 0 AND status = '1'", firstEpoch, lastEpoch)
if err != nil {
return fmt.Errorf("error retrieving blocks data for firstEpoch [%v] and lastEpoch [%v]: %w", firstEpoch, lastEpoch, err)
}
numbers := make([]uint64, 0, len(blocks))
for _, b := range blocks {
numbers = append(numbers, b.ExecBlockNumber)
blocksMap[b.ExecBlockNumber] = b
}
blocksData, err := BigtableClient.GetBlocksIndexedMultiple(numbers, uint64(len(numbers)))
if err != nil {
return fmt.Errorf("error in GetBlocksIndexedMultiple: %w", err)
}
relaysData, err := GetRelayDataForIndexedBlocks(blocksData)
if err != nil {
return fmt.Errorf("error in GetRelayDataForIndexedBlocks: %w", err)
}
proposerRewards := make(map[uint64]*Container)
for _, b := range blocksData {
proposer := blocksMap[b.Number].Proposer
if proposerRewards[proposer] == nil {
proposerRewards[proposer] = &Container{
MevReward: big.NewInt(0),
TxFeeReward: big.NewInt(0),
}
}
txFeeReward := new(big.Int).SetBytes(b.TxReward)
proposerRewards[proposer].TxFeeReward = new(big.Int).Add(txFeeReward, proposerRewards[proposer].TxFeeReward)
mevReward, ok := relaysData[common.BytesToHash(b.Hash)]
if ok {
proposerRewards[proposer].MevReward = new(big.Int).Add(mevReward.MevBribe.BigInt(), proposerRewards[proposer].MevReward)
} else {
proposerRewards[proposer].MevReward = new(big.Int).Add(txFeeReward, proposerRewards[proposer].MevReward)
}
}
mux.Lock()
for proposer, r := range proposerRewards {
data[proposer].ElRewardsWei = decimal.NewFromBigInt(r.TxFeeReward, 0)
data[proposer].MEVRewardsWei = decimal.NewFromBigInt(r.MevReward, 0)
}
mux.Unlock()
logger.Infof("gathering el rewards statistics completed, took %v", time.Since(exportStart))
return nil
}
func gatherValidatorBalances(validators []uint64, day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_balances_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstEpoch": firstEpoch,
"lastEpoch": lastEpoch,
})
logger.Infof("gathering balance statistics")
balanceStatistics, err := BigtableClient.GetValidatorBalanceStatistics(validators, firstEpoch, lastEpoch)
if err != nil {
return fmt.Errorf("error in GetValidatorBalanceStatistics for firstEpoch [%v] and lastEpoch [%v]: %w", firstEpoch, lastEpoch, err)
}
mux.Lock()
for _, stat := range balanceStatistics {
data[stat.Index].StartBalance = int64(stat.StartBalance)
data[stat.Index].EndBalance = int64(stat.EndBalance)
data[stat.Index].MinBalance = int64(stat.MinBalance)
data[stat.Index].MaxBalance = int64(stat.MaxBalance)
data[stat.Index].StartEffectiveBalance = int64(stat.StartEffectiveBalance)
data[stat.Index].EndEffectiveBalance = int64(stat.EndEffectiveBalance)
data[stat.Index].MinEffectiveBalance = int64(stat.MinEffectiveBalance)
data[stat.Index].MaxEffectiveBalance = int64(stat.MaxEffectiveBalance)
}
mux.Unlock()
logger.Infof("gathering balance statistics completed, took %v", time.Since(exportStart))
return nil
}
func gatherValidatorDepositWithdrawals(day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_deposit_withdrawal_stats").Observe(time.Since(exportStart).Seconds())
}()
// The end_balance of a day is the balance after the first slot of the last epoch of that day.
// Therefore the last 31 slots of the day are not included in the end_balance of that day.
// Since our income calculation is base on subtracting end_balances the deposits and withdrawals that happen during those slots must be added to the next day instead.
firstSlot := uint64(0)
if day > 0 {
firstSlot = utils.GetLastBalanceInfoSlotForDay(day-1) + 1
}
lastSlot := utils.GetLastBalanceInfoSlotForDay(day)
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstSlot": firstSlot,
"lastSlot": lastSlot,
})
logger.Infof("gathering withdrawals + deposits")
type resRowDeposits struct {
ValidatorIndex uint64 `db:"validatorindex"`
Deposits uint64 `db:"deposits"`
DepositsAmount uint64 `db:"deposits_amount"`
}
resDeposits := make([]*resRowDeposits, 0, 1024)
depositsQry := `
select validators.validatorindex, count(*) AS deposits, sum(amount) AS deposits_amount
from blocks_deposits
inner join validators on blocks_deposits.publickey = validators.pubkey
inner join blocks on blocks_deposits.block_root = blocks.blockroot
where blocks.slot >= $1 and blocks.slot <= $2 and blocks.status = '1' and blocks_deposits.valid_signature
group by validators.validatorindex`
err := WriterDb.Select(&resDeposits, depositsQry, firstSlot, lastSlot)
if err != nil {
return fmt.Errorf("error inserting deposits into validator_stats for day [%v], firstSlot [%v] and lastSlot [%v]: %w", day, firstSlot, lastSlot, err)
}
mux.Lock()
for _, r := range resDeposits {
data[r.ValidatorIndex].Deposits = int64(r.Deposits)
data[r.ValidatorIndex].DepositsAmount = int64(r.DepositsAmount)
}
mux.Unlock()
type resRowWithdrawals struct {
ValidatorIndex uint64 `db:"validatorindex"`
Withdrawals uint64 `db:"withdrawals"`
WithdrawalsAmount uint64 `db:"withdrawals_amount"`
}
resWithdrawals := make([]*resRowWithdrawals, 0, 1024)
withdrawalsQuery := `select validatorindex, count(*) AS withdrawals, sum(amount) AS withdrawals_amount
from blocks_withdrawals
inner join blocks on blocks_withdrawals.block_root = blocks.blockroot
where block_slot >= $1 and block_slot <= $2 and blocks.status = '1'
group by validatorindex;`
err = WriterDb.Select(&resWithdrawals, withdrawalsQuery, firstSlot, lastSlot)
if err != nil {
return fmt.Errorf("error inserting withdrawals into validator_stats for day [%v], firstSlot [%v] and lastSlot [%v]: %w", day, firstSlot, lastSlot, err)
}
mux.Lock()
for _, r := range resWithdrawals {
data[r.ValidatorIndex].Withdrawals = int64(r.Withdrawals)
data[r.ValidatorIndex].WithdrawalsAmount = int64(r.WithdrawalsAmount)
}
mux.Unlock()
logger.Infof("gathering deposits + withdrawals completed, took %v", time.Since(exportStart))
return nil
}
func gatherValidatorSyncDutiesForDay(validators []uint64, day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_sync_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
if firstEpoch < utils.Config.Chain.Config.AltairForkEpoch && lastEpoch > utils.Config.Chain.Config.AltairForkEpoch {
firstEpoch = utils.Config.Chain.Config.AltairForkEpoch
} else if lastEpoch < utils.Config.Chain.Config.AltairForkEpoch {
logger.Infof("day %v is pre-altair, skipping sync committee export")
return nil
}
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstEpoch": firstEpoch,
"lastEpoch": lastEpoch,
})
logger.Infof("gathering sync duties")
syncStats, err := BigtableClient.GetValidatorSyncDutiesStatistics(validators, firstEpoch, lastEpoch)
if err != nil {
return fmt.Errorf("error in GetValidatorSyncDutiesStatistics for firstEpoch [%v] and lastEpoch [%v]: %w", firstEpoch, lastEpoch, err)
}
mux.Lock()
for _, stat := range syncStats {
data[stat.Index].ParticipatedSync = int64(stat.ParticipatedSync)
data[stat.Index].MissedSync = int64(stat.MissedSync)
data[stat.Index].OrphanedSync = int64(stat.OrphanedSync)
}
mux.Unlock()
logger.Infof("gathering sync duties completed, took %v", time.Since(exportStart))
return nil
}
func gatherValidatorFailedAttestationsStatisticsForDay(validators []uint64, day uint64, data []*types.ValidatorStatsTableDbRow, mux *sync.Mutex) error {
exportStart := time.Now()
defer func() {
metrics.TaskDuration.WithLabelValues("db_update_validator_failed_att_stats").Observe(time.Since(exportStart).Seconds())
}()
firstEpoch, lastEpoch := utils.GetFirstAndLastEpochForDay(day)
logger := logger.WithFields(logrus.Fields{
"day": day,
"firstEpoch": firstEpoch,
"lastEpoch": lastEpoch,
})
start := time.Now()
logger.Infof("gathering failed attestations statistics")
batchSize := 10000
for i := 0; i < len(validators); i += batchSize {
upperBound := i + batchSize
if len(validators) < upperBound {
upperBound = len(validators)
}
vals := validators[i:upperBound]
// logrus.Infof("retrieving validator missed attestations stats for validators %v - %v", vals[0], vals[len(vals)-1])
ma, err := BigtableClient.GetValidatorMissedAttestationsCount(vals, firstEpoch, lastEpoch)
if err != nil {
return fmt.Errorf("error in GetValidatorMissedAttestationsCount for fromEpoch [%v] and toEpoch [%v]: %w", firstEpoch, lastEpoch, err)
}
mux.Lock()
for validator, stats := range ma {
data[validator].MissedAttestations = int64(stats.MissedAttestations)
data[validator].OrphanedAttestations = 0
}
mux.Unlock()
}
logrus.Infof("gathering failed attestations completed, took %v", time.Since(start))
return nil
}
func gatherPreviousDayStatisticsData(day int64) ([]*types.ValidatorStatsTableDbRow, error) {
ret := make([]*types.ValidatorStatsTableDbRow, 0)
err := WriterDb.Select(&ret, `SELECT
validatorindex,
day,
COALESCE(start_balance, 0) AS start_balance,
COALESCE(end_balance, 0) AS end_balance,
COALESCE(min_balance, 0) AS min_balance,
COALESCE(max_balance, 0) AS max_balance,
COALESCE(start_effective_balance, 0) AS start_effective_balance,
COALESCE(end_effective_balance, 0) AS end_effective_balance,
COALESCE(min_effective_balance, 0) AS min_effective_balance,
COALESCE(max_effective_balance, 0) AS max_effective_balance,
COALESCE(missed_attestations, 0) AS missed_attestations,
COALESCE(missed_attestations_total, 0) AS missed_attestations_total,
COALESCE(orphaned_attestations, 0) AS orphaned_attestations,
COALESCE(participated_sync, 0) AS participated_sync,
COALESCE(participated_sync_total, 0) AS participated_sync_total,
COALESCE(missed_sync, 0) AS missed_sync,
COALESCE(missed_sync_total, 0) AS missed_sync_total,
COALESCE(orphaned_sync, 0) AS orphaned_sync,
COALESCE(orphaned_sync_total, 0) AS orphaned_sync_total,
COALESCE(proposed_blocks, 0) AS proposed_blocks,
COALESCE(missed_blocks, 0) AS missed_blocks,
COALESCE(orphaned_blocks, 0) AS orphaned_blocks,
COALESCE(attester_slashings, 0) AS attester_slashings,
COALESCE(proposer_slashings, 0) AS proposer_slashings,
COALESCE(deposits, 0) AS deposits,
COALESCE(deposits_amount, 0) AS deposits_amount,
COALESCE(withdrawals, 0) AS withdrawals,
COALESCE(withdrawals_amount, 0) AS withdrawals_amount,
COALESCE(cl_rewards_gwei, 0) AS cl_rewards_gwei,
COALESCE(cl_rewards_gwei_total, 0) AS cl_rewards_gwei_total,
COALESCE(el_rewards_wei, 0) AS el_rewards_wei,
COALESCE(el_rewards_wei_total, 0) AS el_rewards_wei_total,
COALESCE(mev_rewards_wei, 0) AS mev_rewards_wei,
COALESCE(mev_rewards_wei_total, 0) AS mev_rewards_wei_total
from validator_stats WHERE day = $1 ORDER BY validatorindex
`, day-1)
if err != nil {
return nil, fmt.Errorf("error retreiving previous day statistics data: %w", err)
}
return ret, nil
}
func GetValidatorIncomeHistoryChart(validatorIndices []uint64, currency string, lastFinalizedEpoch uint64, lowerBoundDay uint64) ([]*types.ChartDataPoint, error) {
incomeHistory, err := GetValidatorIncomeHistory(validatorIndices, lowerBoundDay, 0, lastFinalizedEpoch)
if err != nil {
return nil, err
}
var clRewardsSeries = make([]*types.ChartDataPoint, len(incomeHistory))
for i := 0; i < len(incomeHistory); i++ {
color := "#7cb5ec"
if incomeHistory[i].ClRewards < 0 {
color = "#f7a35c"
}
balanceTs := utils.DayToTime(incomeHistory[i].Day)
clRewardsSeries[i] = &types.ChartDataPoint{X: float64(balanceTs.Unix() * 1000), Y: utils.ExchangeRateForCurrency(currency) * (float64(incomeHistory[i].ClRewards) / 1e9), Color: color}
}
return clRewardsSeries, err
}
func GetValidatorIncomeHistory(validatorIndices []uint64, lowerBoundDay uint64, upperBoundDay uint64, lastFinalizedEpoch uint64) ([]types.ValidatorIncomeHistory, error) {
if len(validatorIndices) == 0 {
return []types.ValidatorIncomeHistory{}, nil
}
if upperBoundDay == 0 {
upperBoundDay = 65536
}
validatorIndices = utils.SortedUniqueUint64(validatorIndices)
validatorIndicesStr := make([]string, len(validatorIndices))
for i, v := range validatorIndices {
validatorIndicesStr[i] = fmt.Sprintf("%d", v)
}
validatorIndicesPqArr := pq.Array(validatorIndices)
cacheDur := time.Second * time.Duration(utils.Config.Chain.Config.SecondsPerSlot*utils.Config.Chain.Config.SlotsPerEpoch+10) // updates every epoch, keep 10sec longer
cacheKey := fmt.Sprintf("%d:validatorIncomeHistory:%d:%d:%d:%s", utils.Config.Chain.Config.DepositChainID, lowerBoundDay, upperBoundDay, lastFinalizedEpoch, strings.Join(validatorIndicesStr, ","))
cached := []types.ValidatorIncomeHistory{}
if _, err := cache.TieredCache.GetWithLocalTimeout(cacheKey, cacheDur, &cached); err == nil {
return cached, nil
}
var result []types.ValidatorIncomeHistory
err := ReaderDb.Select(&result, `
SELECT
day,
SUM(COALESCE(cl_rewards_gwei, 0)) AS cl_rewards_gwei,
SUM(COALESCE(end_balance, 0)) AS end_balance
FROM validator_stats
WHERE validatorindex = ANY($1) AND day BETWEEN $2 AND $3
GROUP BY day
ORDER BY day
;`, validatorIndicesPqArr, lowerBoundDay, upperBoundDay)
if err != nil {
return nil, err
}
// retrieve rewards for epochs not yet in stats
if upperBoundDay == 65536 {
lastDay := int64(0)
if len(result) > 0 {
lastDay = int64(result[len(result)-1].Day)
} else {
lastDayDb, err := GetLastExportedStatisticDay()
if err == nil {
lastDay = int64(lastDayDb)
} else if err == ErrNoStats {
lastDay = -1
} else {
return nil, err
}
}
currentDay := lastDay + 1
firstSlot := uint64(0)
if lastDay > -1 {
firstSlot = utils.GetLastBalanceInfoSlotForDay(uint64(lastDay)) + 1
}
lastSlot := lastFinalizedEpoch * utils.Config.Chain.Config.SlotsPerEpoch
totalBalance := uint64(0)
g := errgroup.Group{}
g.Go(func() error {
latestBalances, err := BigtableClient.GetValidatorBalanceHistory(validatorIndices, lastFinalizedEpoch, lastFinalizedEpoch)
if err != nil {
logger.Errorf("error getting validator balance data in GetValidatorEarnings: %v", err)
return err
}
for _, balance := range latestBalances {
if len(balance) == 0 {
continue
}
totalBalance += balance[0].Balance
}
return nil
})
var lastBalance uint64
g.Go(func() error {
if lastDay < 0 {
return GetValidatorActivationBalance(validatorIndices, &lastBalance)
} else {
return GetValidatorBalanceForDay(validatorIndices, uint64(lastDay), &lastBalance)
}
})
var lastDeposits uint64
g.Go(func() error {
return GetValidatorDepositsForSlots(validatorIndices, firstSlot, lastSlot, &lastDeposits)
})
var lastWithdrawals uint64
g.Go(func() error {
return GetValidatorWithdrawalsForSlots(validatorIndices, firstSlot, lastSlot, &lastWithdrawals)
})
err = g.Wait()
if err != nil {
return nil, err
}
result = append(result, types.ValidatorIncomeHistory{
Day: int64(currentDay),
ClRewards: int64(totalBalance - lastBalance - lastDeposits + lastWithdrawals),
})
}
go func() {
err := cache.TieredCache.Set(cacheKey, &result, cacheDur)
if err != nil {
utils.LogError(err, fmt.Errorf("error setting tieredCache for GetValidatorIncomeHistory with key %v", cacheKey), 0)
}
}()
return result, nil
}
func WriteChartSeriesForDay(day int64) error {
startTs := time.Now()
ctx, cancel := context.WithTimeout(context.Background(), time.Second*60)
defer cancel()
g, gCtx := errgroup.WithContext(ctx)