forked from gobitfly/eth2-beaconchain-explorer
/
slot.go
899 lines (810 loc) · 28.5 KB
/
slot.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
package handlers
import (
"database/sql"
"encoding/hex"
"encoding/json"
"eth2-exporter/db"
"eth2-exporter/templates"
"eth2-exporter/types"
"eth2-exporter/utils"
"fmt"
"html/template"
"math/big"
"net/http"
"strconv"
"strings"
"time"
"github.com/juliangruber/go-intersect"
"github.com/lib/pq"
"github.com/gorilla/mux"
)
// Hacky AF way to ensure intersect module is imported and not optimised away, unsure why its being optimised away
var _ = intersect.Simple
const MaxSlotValue = 137438953503 // we only render a page for blocks up to this slot
// Slot will return the data for a block contained in the slot
func Slot(w http.ResponseWriter, r *http.Request) {
slotTemplateFiles := append(layoutTemplateFiles,
"slot/slot.html",
"slot/transactions.html",
"slot/withdrawals.html",
"slot/attestations.html",
"slot/deposits.html",
"slot/votes.html",
"slot/attesterSlashing.html",
"slot/proposerSlashing.html",
"slot/exits.html",
"slot/overview.html",
"slot/execTransactions.html")
slotFutureTemplateFiles := append(layoutTemplateFiles, "slot/slotFuture.html")
blockNotFoundTemplateFiles := append(layoutTemplateFiles, "slotnotfound.html")
var slotTemplate = templates.GetTemplate(slotTemplateFiles...)
var slotFutureTemplate = templates.GetTemplate(slotFutureTemplateFiles...)
var blockNotFoundTemplate = templates.GetTemplate(blockNotFoundTemplateFiles...)
w.Header().Set("Content-Type", "text/html")
vars := mux.Vars(r)
slotOrHash := strings.Replace(vars["slotOrHash"], "0x", "", -1)
blockSlot := int64(-1)
blockRootHash, err := hex.DecodeString(slotOrHash)
if err != nil || len(slotOrHash) != 64 {
blockRootHash = []byte{}
blockSlot, err = strconv.ParseInt(vars["slotOrHash"], 10, 64)
if err != nil || blockSlot >= 2147483648 { // block slot must be lower then max int4
data := InitPageData(w, r, "blockchain", "/slots", fmt.Sprintf("Slot %v", slotOrHash), blockNotFoundTemplateFiles)
data.Data = "slot"
if handleTemplateError(w, r, "slot.go", "Slot", "blockSlot", blockNotFoundTemplate.ExecuteTemplate(w, "layout", data)) != nil {
return // an error has occurred and was processed
}
return
}
}
if blockSlot == -1 {
err = db.ReaderDb.Get(&blockSlot, `SELECT slot FROM blocks WHERE blockroot = $1 OR stateroot = $1 LIMIT 1`, blockRootHash)
if blockSlot == -1 {
data := InitPageData(w, r, "blockchain", "/slots", fmt.Sprintf("Slot %v", slotOrHash), blockNotFoundTemplateFiles)
data.Data = "slot"
if handleTemplateError(w, r, "slot.go", "Slot", "blockSlot", blockNotFoundTemplate.ExecuteTemplate(w, "layout", data)) != nil {
return // an error has occurred and was processed
}
return
}
if err != nil {
logger.Errorf("error retrieving entry count of given block or state data: %v", err)
http.Error(w, "Internal server error", http.StatusServiceUnavailable)
return
}
}
blockPageData, err := GetSlotPageData(uint64(blockSlot))
if err == sql.ErrNoRows {
slot := uint64(blockSlot)
//Slot not in database -> Show future block
if slot > MaxSlotValue {
logger.Errorf("error retrieving blockPageData: %v", err)
data := InitPageData(w, r, "blockchain", "/slots", fmt.Sprintf("Slot %v", slotOrHash), blockNotFoundTemplateFiles)
if handleTemplateError(w, r, "slot.go", "Slot", "MaxSlotValue", blockNotFoundTemplate.ExecuteTemplate(w, "layout", data)) != nil {
return // an error has occurred and was processed
}
}
data := InitPageData(w, r, "blockchain", "/slots", fmt.Sprintf("Slot %v", slotOrHash), slotFutureTemplateFiles)
data.Meta.Path = "/slot/" + slotOrHash
futurePageData := types.BlockPageData{
Slot: slot,
Epoch: utils.EpochOfSlot(slot),
Ts: utils.SlotToTime(slot),
NextSlot: slot + 1,
PreviousSlot: slot - 1,
}
data.Data = futurePageData
if handleTemplateError(w, r, "slot.go", "Slot", "ErrNoRows", slotFutureTemplate.ExecuteTemplate(w, "layout", data)) != nil {
return // an error has occurred and was processed
}
return
} else if err != nil {
if handleTemplateError(w, r, "slot.go", "Slot", "GetSlotPageData", err) != nil {
return // an error has occurred and was processed
}
return
}
if blockPageData.ExecBlockNumber.Int64 != 0 && blockPageData.Status == 1 {
// slot has corresponding execution block, fetch execution data
eth1BlockPageData, err := GetExecutionBlockPageData(uint64(blockPageData.ExecBlockNumber.Int64), 10)
// if err != nil, simply show slot view without block
if err == nil {
blockPageData.ExecutionData = eth1BlockPageData
blockPageData.ExecutionData.IsValidMev = blockPageData.IsValidMev
}
}
data := InitPageData(w, r, "blockchain", fmt.Sprintf("/slot/%v", blockPageData.Slot), fmt.Sprintf("Slot %v", slotOrHash), slotTemplateFiles)
data.Data = blockPageData
if utils.IsApiRequest(r) {
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(data.Data)
} else {
w.Header().Set("Content-Type", "text/html")
err = slotTemplate.ExecuteTemplate(w, "layout", data)
}
if handleTemplateError(w, r, "slot.go", "Slot", "ApiRequest", err) != nil {
return // an error has occurred and was processed
}
}
func getAttestationsData(slot uint64, onlyFirst bool) ([]*types.BlockPageAttestation, error) {
limit := ";"
if onlyFirst {
limit = " LIMIT 1;"
}
var attestations []*types.BlockPageAttestation
rows, err := db.ReaderDb.Query(`
SELECT
block_slot,
block_index,
aggregationbits,
validators,
signature,
slot,
committeeindex,
beaconblockroot,
source_epoch,
source_root,
target_epoch,
target_root
FROM blocks_attestations
WHERE block_slot = $1
ORDER BY block_index`+limit,
slot)
if err != nil {
return nil, fmt.Errorf("error retrieving block attestation data: %v", err)
}
defer rows.Close()
for rows.Next() {
attestation := &types.BlockPageAttestation{}
err := rows.Scan(
&attestation.BlockSlot,
&attestation.BlockIndex,
&attestation.AggregationBits,
&attestation.Validators,
&attestation.Signature,
&attestation.Slot,
&attestation.CommitteeIndex,
&attestation.BeaconBlockRoot,
&attestation.SourceEpoch,
&attestation.SourceRoot,
&attestation.TargetEpoch,
&attestation.TargetRoot)
if err != nil {
return nil, fmt.Errorf("error scanning block attestation data: %v", err)
}
attestations = append(attestations, attestation)
}
return attestations, nil
}
func GetSlotPageData(blockSlot uint64) (*types.BlockPageData, error) {
blockPageData := types.BlockPageData{}
blockPageData.Mainnet = utils.Config.Chain.Config.ConfigName == "mainnet"
err := db.ReaderDb.Get(&blockPageData, `
SELECT
blocks.epoch,
COALESCE(epochs.finalized, false) AS epoch_finalized,
COALESCE(epochs.globalparticipationrate, 0) AS epoch_participation_rate,
blocks.slot,
blocks.blockroot,
blocks.parentroot,
blocks.stateroot,
blocks.signature,
blocks.randaoreveal,
blocks.graffiti,
blocks.eth1data_depositroot,
blocks.eth1data_depositcount,
blocks.eth1data_blockhash,
blocks.syncaggregate_bits,
blocks.syncaggregate_signature,
blocks.syncaggregate_participation,
blocks.proposerslashingscount,
blocks.attesterslashingscount,
blocks.attestationscount,
blocks.depositscount,
blocks.withdrawalcount,
blocks.voluntaryexitscount,
blocks.proposer,
blocks.status,
exec_block_number,
jsonb_agg(tags.metadata) as tags,
COALESCE(not 'invalid-relay-reward'=ANY(array_agg(tags.id)), true) as is_valid_mev,
COALESCE(validator_names.name, '') AS name,
(SELECT count(*) from blocks_bls_change where block_slot = $1) as bls_change_count
FROM blocks
LEFT JOIN validators ON blocks.proposer = validators.validatorindex
LEFT JOIN validator_names ON validators.pubkey = validator_names.publickey
LEFT JOIN blocks_tags ON blocks.slot = blocks_tags.slot and blocks.blockroot = blocks_tags.blockroot
LEFT JOIN tags ON blocks_tags.tag_id = tags.id
LEFT JOIN epochs ON blocks.epoch = epochs.epoch
WHERE blocks.slot = $1
group by
blocks.epoch,
blocks.slot,
blocks.blockroot,
validator_names."name",
epoch_finalized,
epoch_participation_rate
ORDER BY blocks.blockroot DESC, blocks.status ASC limit 1
`,
blockSlot)
if err != nil {
return nil, err
}
blockPageData.Slot = uint64(blockSlot)
blockPageData.Ts = utils.SlotToTime(blockPageData.Slot)
if blockPageData.ExecTimestamp.Valid {
blockPageData.ExecTime = time.Unix(int64(blockPageData.ExecTimestamp.Int64), 0)
}
blockPageData.SlashingsCount = blockPageData.AttesterSlashingsCount + blockPageData.ProposerSlashingsCount
blockPageData.NextSlot = blockPageData.Slot + 1
blockPageData.PreviousSlot = blockPageData.Slot - 1
blockPageData.Attestations, err = getAttestationsData(blockPageData.Slot, true)
if err != nil {
return nil, err
}
rows, err := db.ReaderDb.Query(`
SELECT validators
FROM blocks_attestations
WHERE beaconblockroot = $1`,
blockPageData.BlockRoot)
if err != nil {
return nil, fmt.Errorf("error retrieving block votes data: %v", err)
}
defer rows.Close()
votesCount := 0
votesPerValidator := map[int64]int{}
for rows.Next() {
validators := pq.Int64Array{}
err := rows.Scan(&validators)
if err != nil {
return nil, fmt.Errorf("error scanning votes validators data: %v", err)
}
for _, validator := range validators {
votesCount++
_, exists := votesPerValidator[validator]
if !exists {
votesPerValidator[validator] = 1
} else {
votesPerValidator[validator]++
}
}
}
blockPageData.VotingValidatorsCount = uint64(len(votesPerValidator))
blockPageData.VotesCount = uint64(votesCount)
err = db.ReaderDb.Select(&blockPageData.VoluntaryExits, "SELECT validatorindex, signature FROM blocks_voluntaryexits WHERE block_slot = $1", blockPageData.Slot)
if err != nil {
return nil, fmt.Errorf("error retrieving block deposit data: %v", err)
}
err = db.ReaderDb.Select(&blockPageData.AttesterSlashings, `
SELECT
block_slot,
block_index,
attestation1_indices,
attestation1_signature,
attestation1_slot,
attestation1_index,
attestation1_beaconblockroot,
attestation1_source_epoch,
attestation1_source_root,
attestation1_target_epoch,
attestation1_target_root,
attestation2_indices,
attestation2_signature,
attestation2_slot,
attestation2_index,
attestation2_beaconblockroot,
attestation2_source_epoch,
attestation2_source_root,
attestation2_target_epoch,
attestation2_target_root
FROM blocks_attesterslashings
WHERE block_slot = $1`, blockPageData.Slot)
if err != nil {
return nil, fmt.Errorf("error retrieving block attester slashings data: %v", err)
}
if len(blockPageData.AttesterSlashings) > 0 {
for _, slashing := range blockPageData.AttesterSlashings {
inter := intersect.Simple(slashing.Attestation1Indices, slashing.Attestation2Indices)
for _, i := range inter {
slashing.SlashedValidators = append(slashing.SlashedValidators, i.(int64))
}
}
}
err = db.ReaderDb.Select(&blockPageData.ProposerSlashings, "SELECT block_slot, block_index, block_root, proposerindex, header1_slot, header1_parentroot, header1_stateroot, header1_bodyroot, header1_signature, header2_slot, header2_parentroot, header2_stateroot, header2_bodyroot, header2_signature FROM blocks_proposerslashings WHERE block_slot = $1", blockPageData.Slot)
if err != nil {
return nil, fmt.Errorf("error retrieving block proposer slashings data: %v", err)
}
// TODO: fix blockPageData data type to include SyncCommittee
err = db.ReaderDb.Select(&blockPageData.SyncCommittee, "SELECT validatorindex FROM sync_committees WHERE period = $1 ORDER BY committeeindex", utils.SyncPeriodOfEpoch(blockPageData.Epoch))
if err != nil {
return nil, fmt.Errorf("error retrieving sync-committee of block %v: %v", blockPageData.Slot, err)
}
// old code retrieving txs from postgres db
/* if retrieveTxsFromDb {
// retrieve transactions from db
var transactions []*types.BlockPageTransaction
rows, err = db.ReaderDb.Query(`
SELECT
block_slot,
block_index,
txhash,
nonce,
gas_price,
gas_limit,
sender,
recipient,
amount,
payload
FROM blocks_transactions
WHERE block_slot = $1
ORDER BY block_index`,
blockPageData.Slot)
if err != nil {
return nil, fmt.Errorf("error retrieving block transaction data: %v", err)
}
defer rows.Close()
for rows.Next() {
tx := &types.BlockPageTransaction{}
err := rows.Scan(
&tx.BlockSlot,
&tx.BlockIndex,
&tx.TxHash,
&tx.AccountNonce,
&tx.Price,
&tx.GasLimit,
&tx.Sender,
&tx.Recipient,
&tx.Amount,
&tx.Payload,
)
if err != nil {
return nil, fmt.Errorf("error scanning block transaction data: %v", err)
}
var amount, price big.Int
amount.SetBytes(tx.Amount)
price.SetBytes(tx.Price)
tx.AmountPretty = ToEth(&amount)
tx.PricePretty = ToGWei(&amount)
transactions = append(transactions, tx)
}
blockPageData.Transactions = transactions
}
*/
return &blockPageData, nil
}
// SlotDepositData returns the deposits for a specific slot
func SlotDepositData(w http.ResponseWriter, r *http.Request) {
currency := GetCurrency(r)
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slotOrHash := strings.Replace(vars["slotOrHash"], "0x", "", -1)
blockSlot := int64(-1)
blockRootHash, err := hex.DecodeString(slotOrHash)
if err != nil || len(slotOrHash) != 64 {
blockSlot, err = strconv.ParseInt(vars["slotOrHash"], 10, 64)
if err != nil {
logger.Errorf("error parsing slotOrHash url parameter %v, err: %v", vars["slotOrHash"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
} else {
err = db.ReaderDb.Get(&blockSlot, `
SELECT
blocks.slot
FROM blocks
WHERE blocks.blockroot = $1
`, blockRootHash)
if err != nil {
logger.Errorf("error querying for block slot with block root hash %v err: %v", blockRootHash, err)
http.Error(w, "Interal server error", http.StatusInternalServerError)
return
}
}
q := r.URL.Query()
draw, err := strconv.ParseUint(q.Get("draw"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables data parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
start, err := strconv.ParseUint(q.Get("start"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables start parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
length, err := strconv.ParseUint(q.Get("length"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables length parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if length > 100 {
length = 100
}
var count uint64
err = db.ReaderDb.Get(&count, `
SELECT
count(*)
FROM
blocks_deposits
WHERE
block_slot = $1
GROUP BY
block_slot
`, blockSlot)
if err != nil {
logger.Errorf("error retrieving deposit count for slot %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
var deposits []*types.BlockPageDeposit
err = db.ReaderDb.Select(&deposits, `
SELECT
publickey,
withdrawalcredentials,
amount,
signature
FROM blocks_deposits
WHERE block_slot = $1
ORDER BY block_index
LIMIT $2
OFFSET $3`,
blockSlot, length, start)
if err != nil {
logger.Errorf("error retrieving block deposit data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
tableData := make([][]interface{}, 0, len(deposits))
for i, deposit := range deposits {
tableData = append(tableData, []interface{}{
i + 1 + int(start),
utils.FormatPublicKey(deposit.PublicKey),
utils.FormatBalance(deposit.Amount, currency),
utils.FormatWithdawalCredentials(deposit.WithdrawalCredentials, true),
deposit.Signature,
})
}
data := &types.DataTableResponse{
Draw: draw,
RecordsTotal: count,
RecordsFiltered: count,
Data: tableData,
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
// SlotVoteData returns the votes for a specific slot
func SlotVoteData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slotOrHash := strings.Replace(vars["slotOrHash"], "0x", "", -1)
blockSlot := int64(-1)
blockRootHash, err := hex.DecodeString(slotOrHash)
if err != nil || len(slotOrHash) != 64 {
blockSlot, err = strconv.ParseInt(vars["slotOrHash"], 10, 64)
if err != nil {
logger.Errorf("error parsing slotOrHash url parameter %v, err: %v", vars["slotOrHash"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
err = db.ReaderDb.Get(&blockRootHash, "select blocks.blockroot from blocks where blocks.slot = $1", blockSlot)
if err != nil {
logger.Errorf("error getting blockRootHash for slot %v: %v", blockSlot, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
} else {
err = db.ReaderDb.Get(&blockSlot, `SELECT blocks.slot FROM blocks WHERE blocks.blockroot = $1 OR blocks.stateroot = $1`, blockRootHash)
if err != nil {
logger.Errorf("error querying for block slot with block root hash %v err: %v", blockRootHash, err)
http.Error(w, "Interal server error", http.StatusInternalServerError)
return
}
}
q := r.URL.Query()
search := q.Get("search[value]")
searchIsUint64 := false
searchUint64, err := strconv.ParseUint(search, 10, 64)
if err == nil {
searchIsUint64 = true
}
draw, err := strconv.ParseUint(q.Get("draw"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables data parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
start, err := strconv.ParseUint(q.Get("start"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables start parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
length, err := strconv.ParseUint(q.Get("length"), 10, 64)
if err != nil {
logger.Errorf("error converting datatables length parameter from string to int: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if length > 100 {
length = 100
}
var count uint64
var votes []struct {
AllocatedSlot uint64 `db:"slot"` // "the slot during which the validators were allocated to vote for a block"
CommitteeIndex uint64 `db:"committeeindex"`
BlockSlot uint64 `db:"block_slot"` // "the block where the attestation was included in"
Validators pq.Int64Array `db:"validators"`
}
if search == "" {
err = db.ReaderDb.Get(&count, `SELECT count(*) FROM blocks_attestations WHERE beaconblockroot = $1`, blockRootHash)
if err != nil {
logger.Errorf("error retrieving deposit count for slot %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
err = db.ReaderDb.Select(&votes, `
SELECT
slot,
committeeindex,
block_slot,
validators
FROM blocks_attestations
WHERE beaconblockroot = $1
ORDER BY committeeindex
LIMIT $2
OFFSET $3`,
blockRootHash, length, start)
if err != nil {
logger.Errorf("error retrieving block vote data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
} else if searchIsUint64 {
err = db.ReaderDb.Get(&count, `SELECT count(*) FROM blocks_attestations WHERE beaconblockroot = $1 AND $2 = ANY(validators)`, blockRootHash, searchUint64)
if err != nil {
logger.Errorf("error retrieving deposit count for slot %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
err = db.ReaderDb.Select(&votes, `
SELECT
slot,
committeeindex,
block_slot,
validators
FROM blocks_attestations
WHERE beaconblockroot = $1 AND $2 = ANY(validators)
ORDER BY committeeindex
LIMIT $3
OFFSET $4`,
blockRootHash, searchUint64, length, start)
if err != nil {
logger.Errorf("error retrieving block vote data: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
tableData := make([][]interface{}, 0, len(votes))
for _, vote := range votes {
formatedValidators := make([]string, len(vote.Validators))
for i, v := range vote.Validators {
formatedValidators[i] = fmt.Sprintf("<a href='/validator/%[1]d'>%[1]d</a>", v)
}
tableData = append(tableData, []interface{}{
vote.AllocatedSlot,
vote.CommitteeIndex,
vote.BlockSlot,
strings.Join(formatedValidators, ", "),
})
}
data := &types.DataTableResponse{
Draw: draw,
RecordsTotal: count,
RecordsFiltered: count,
Data: tableData,
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
type transactionsData struct {
HashFormatted template.HTML `json:"HashFormatted"`
Method string `json:"Method"`
FromFormatted template.HTML `json:"FromFormatted"`
ToFormatted template.HTML `json:"ToFormatted"`
Value template.HTML `json:"Value"`
Fee template.HTML `json:"Fee"`
GasPrice template.HTML `json:"GasPrice"`
}
// BlockTransactionsData returns the transactions for a specific block
func BlockTransactionsData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slot, err := strconv.ParseUint(vars["block"], 10, 64)
if err != nil {
logger.Errorf("error parsing slot url parameter %v, err: %v", vars["slot"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
transactions, err := GetExecutionBlockPageData(slot, 0)
if err != nil || transactions == nil {
logger.Errorf("error retrieving transactions data for slot %v, err: %v", slot, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
data := make([]*transactionsData, len(transactions.Txs))
for i, v := range transactions.Txs {
if len(v.Method) == 0 {
v.Method = "Transfer"
}
data[i] = &transactionsData{
HashFormatted: v.HashFormatted,
Method: `<span class="badge badge-light">` + v.Method + `</span>`,
FromFormatted: v.FromFormatted,
ToFormatted: v.ToFormatted,
Value: utils.FormatAmountFormatted(v.Value, "Ether", 5, 0, true, true, false),
Fee: utils.FormatAmountFormatted(v.Fee, "Ether", 5, 0, true, true, false),
GasPrice: utils.FormatAmountFormatted(v.GasPrice, "GWei", 5, 0, true, true, false),
}
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
type attestationsData struct {
BlockIndex uint64 `json:"BlockIndex"`
Slot uint64 `json:"Slot"`
CommitteeIndex uint64 `json:"CommitteeIndex"`
AggregationBits template.HTML `json:"AggregationBits"`
Validators template.HTML `json:"Validators"`
BeaconBlockRoot string `json:"BeaconBlockRoot"`
SourceEpoch uint64 `json:"SourceEpoch"`
SourceRoot string `json:"SourceRoot"`
TargetEpoch uint64 `json:"TargetEpoch"`
TargetRoot string `json:"TargetRoot"`
Signature string `json:"Signature"`
}
// SlotAttestationsData returns the attestations for a specific slot
func SlotAttestationsData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slot, err := strconv.ParseUint(vars["slot"], 10, 64)
if err != nil {
logger.Errorf("error parsing slot url parameter %v, err: %v", vars["slot"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
attestations, err := getAttestationsData(slot, false)
if err != nil {
logger.Errorf("error retrieving attestations data for slot %v, err: %v", slot, err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
data := make([]*attestationsData, len(attestations))
for i, v := range attestations {
var validators template.HTML
for _, val := range v.Validators {
validators += utils.FormatValidatorInt64(val) + " "
}
data[i] = &attestationsData{
BlockIndex: v.BlockIndex,
Slot: v.Slot,
CommitteeIndex: v.CommitteeIndex,
AggregationBits: utils.FormatBitlist(v.AggregationBits),
Validators: validators,
BeaconBlockRoot: fmt.Sprintf("%x", v.BeaconBlockRoot),
SourceEpoch: v.SourceEpoch,
SourceRoot: fmt.Sprintf("%x", v.SourceRoot),
TargetEpoch: v.TargetEpoch,
TargetRoot: fmt.Sprintf("%x", v.TargetRoot),
Signature: fmt.Sprintf("%x", v.Signature),
}
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
func SlotWithdrawalData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slot, err := strconv.ParseUint(vars["slot"], 10, 64)
if err != nil {
logger.Errorf("error parsing slot url parameter %v, err: %v", vars["slot"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
withdrawals, err := db.GetSlotWithdrawals(slot)
if err != nil {
logger.Errorf("error retrieving withdrawals data for slot %v, err: %v", slot, err)
}
tableData := make([][]interface{}, 0, len(withdrawals))
for _, w := range withdrawals {
// logger.Infof("w: %+v", w)
tableData = append(tableData, []interface{}{
template.HTML(fmt.Sprintf("%v", w.Index)),
template.HTML(fmt.Sprintf("%v", utils.FormatValidator(w.ValidatorIndex))),
template.HTML(fmt.Sprintf("%v", utils.FormatAddress(w.Address, nil, "", false, false, true))),
template.HTML(fmt.Sprintf("%v", utils.FormatAmount(new(big.Int).Mul(new(big.Int).SetUint64(w.Amount), big.NewInt(1e9)), "Ether", 6))),
})
}
data := &types.DataTableResponse{
Draw: 1,
RecordsTotal: uint64(len(withdrawals)),
// RecordsFiltered: uint64(len(withdrawals)),
Data: tableData,
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
func SlotBlsChangeData(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
vars := mux.Vars(r)
slot, err := strconv.ParseUint(vars["slot"], 10, 64)
if err != nil {
logger.Errorf("error parsing slot url parameter %v, err: %v", vars["slot"], err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
blsChange, err := db.GetSlotBLSChange(slot)
if err != nil {
logger.Errorf("error retrieving blsChange data for slot %v, err: %v", slot, err)
}
tableData := make([][]interface{}, 0, len(blsChange))
for _, c := range blsChange {
tableData = append(tableData, []interface{}{
template.HTML(fmt.Sprintf("%v", utils.FormatValidator(c.Validatorindex))),
template.HTML(fmt.Sprintf("%v", utils.FormatHashWithCopy(c.Signature))),
template.HTML(fmt.Sprintf("%v", utils.FormatHashWithCopy(c.BlsPubkey))),
template.HTML(fmt.Sprintf("%v", utils.FormatAddress(c.Address, nil, "", false, false, true))),
})
}
data := &types.DataTableResponse{
Draw: 1,
RecordsTotal: uint64(len(blsChange)),
// RecordsFiltered: uint64(len(withdrawals)),
Data: tableData,
}
err = json.NewEncoder(w).Encode(data)
if err != nil {
logger.Errorf("error encoding json response for %v route: %v", r.URL.String(), err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
// ToWei converts the big.Int wei to its gwei string representation.
func ToWei(wei *big.Int) string {
return wei.String()
}
// ToGWei converts the big.Int wei to its gwei string representation.
func ToGWei(wei *big.Int) string {
return ToEth(new(big.Int).Mul(wei, big.NewInt(1e9)))
}
// ToEth converts the big.Int wei to its ether string representation.
func ToEth(wei *big.Int) string {
z, m := new(big.Int).DivMod(wei, big.NewInt(1e18), new(big.Int))
if m.Cmp(new(big.Int)) == 0 {
return z.String()
}
s := strings.TrimRight(fmt.Sprintf("%018s", m.String()), "0")
return z.String() + "." + s
}