-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
1268 lines (1090 loc) · 44.3 KB
/
api.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 api
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
"time"
builderApiV1 "github.com/attestantio/go-builder-client/api/v1"
eth2 "github.com/attestantio/go-eth2-client/api"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/avast/retry-go/v4"
"github.com/dappnode/mev-sp-oracle/config"
"github.com/dappnode/mev-sp-oracle/constants"
"github.com/dappnode/mev-sp-oracle/metrics"
"github.com/dappnode/mev-sp-oracle/oracle"
"github.com/dappnode/mev-sp-oracle/utils"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"golang.org/x/exp/maps"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
)
// Oracle does not serve some endpoint if not in sync to latest finalized epoch. Some
// slots behind are allowed, since its normal that when a new epoch is finalized, some
// slots are still pending to be processed. This is the max number of slots allowed
var MaxSlotsBehind = uint64(64)
// Note that the api has no paging, so it is not suitable for large queries, but
// it should be able to scale to a few thousand subscribed validators without any problem
// Important: These are the retry options when an api call involves external call to
// the beacon node or execution client. The idea is to try once, and fail fast.
// Use this for all onchain calls, otherwise defaultRetryOpts will be aplied
var apiRetryOpts = []retry.Option{
retry.Attempts(1),
}
const defaultMerkleRoot = "0x0000000000000000000000000000000000000000000000000000000000000000"
// 30 days/month * 24 hours/day * 3600 seconds/day / 12 seconds/slot
var SlotsInOneMonth = uint64(216000)
const (
// Available endpoints
pathStatus = "/status"
pathConfig = "/config"
pathValidatorRelayers = "/registeredrelays/{valpubkey}"
pathState = "/state"
// Memory endpoints: what the oracle knows
pathMemoryValidators = "/memory/validators"
pathMemoryValidatorByIndex = "/memory/validator/{valindex}"
pathMemoryValidatorsByIndex = "/memory/validatorsbyindex/{valindices}"
pathMemoryValidatorsByWithdrawal = "/memory/validators/{withdrawalAddress}"
pathMemoryFeesInfo = "/memory/feesinfo"
pathMemoryAllBlocks = "/memory/allblocks"
pathMemoryProposedBlocks = "/memory/proposedblocks"
pathMemoryMissedBlocks = "/memory/missedblocks"
pathMemoryWrongFeeBlocks = "/memory/wrongfeeblocks"
pathMemoryDonations = "/memory/donations"
pathMemoryPoolStatistics = "/memory/statistics"
// Onchain endpoints: what is submitted to the contract
pathOnchainMerkleProof = "/onchain/proof/{withdrawalAddress}"
)
type ApiService struct {
srv *http.Server
cfg *oracle.Config
cliCfg *config.CliConfig
Onchain *oracle.Onchain
oracle *oracle.Oracle
ApiListenAddr string
Network string
}
func NewApiService(
cfg *oracle.Config,
cliCfg *config.CliConfig,
oracle *oracle.Oracle,
onchain *oracle.Onchain) *ApiService {
return &ApiService{
ApiListenAddr: fmt.Sprintf("0.0.0.0:%d", cliCfg.ApiPort),
cfg: cfg,
cliCfg: cliCfg,
oracle: oracle,
Onchain: onchain,
Network: cfg.Network,
}
}
func (m *ApiService) respondError(w http.ResponseWriter, code int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
resp := httpErrorResp{code, message}
if err := json.NewEncoder(w).Encode(resp); err != nil {
log.WithField("response", resp).WithError(err).Error("Couldn't write error response")
http.Error(w, "", http.StatusInternalServerError)
}
}
func (m *ApiService) respondOK(w http.ResponseWriter, response any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(response); err != nil {
log.WithField("response", response).WithError(err).Error("Couldn't write OK response")
http.Error(w, "", http.StatusInternalServerError)
}
}
type responseWriterDelegator struct {
http.ResponseWriter
status int
written int64
wroteHeader bool
}
func (r *responseWriterDelegator) WriteHeader(code int) {
r.status = code
r.wroteHeader = true
r.ResponseWriter.WriteHeader(code)
}
func (r *responseWriterDelegator) Write(b []byte) (int, error) {
if !r.wroteHeader {
r.WriteHeader(http.StatusOK)
}
n, err := r.ResponseWriter.Write(b)
r.written += int64(n)
return n, err
}
func sanitizeMethod(m string) string {
return strings.ToLower(m)
}
func sanitizeCode(s int) string {
return strconv.Itoa(s)
}
// Prometheus middleware to track http requests count and latency. Inspired by
// https://github.com/albertogviana/prometheus-middleware
func prometheusMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
begin := time.Now()
delegate := &responseWriterDelegator{ResponseWriter: w}
rw := delegate
next.ServeHTTP(rw, r)
route := mux.CurrentRoute(r)
path, _ := route.GetPathTemplate()
code := sanitizeCode(delegate.status)
method := sanitizeMethod(r.Method)
go metrics.HttpRequestsTotal.WithLabelValues(
code,
method,
path,
).Inc()
go metrics.HttpRequestsLatency.WithLabelValues(
code,
method,
path,
).Observe(float64(time.Since(begin)) / float64(time.Second))
})
}
func (m *ApiService) getRouter() http.Handler {
r := mux.NewRouter()
// Map endpoints and their handlers
r.HandleFunc("/", m.handleRoot).Methods(http.MethodGet)
// General endpoints
r.HandleFunc(pathStatus, m.handleStatus).Methods(http.MethodGet)
r.HandleFunc(pathConfig, m.handleConfig).Methods(http.MethodGet)
r.HandleFunc(pathValidatorRelayers, m.handleValidatorRelayers).Methods(http.MethodGet)
r.HandleFunc(pathState, m.handleState).Methods(http.MethodGet)
// Memory endpoints
r.HandleFunc(pathMemoryValidators, m.handleMemoryValidators).Methods(http.MethodGet)
r.HandleFunc(pathMemoryValidatorByIndex, m.handleMemoryValidatorInfo).Methods(http.MethodGet)
r.HandleFunc(pathMemoryValidatorsByIndex, m.handleMemoryValidatorsByIndex).Methods(http.MethodGet)
r.HandleFunc(pathMemoryValidatorsByWithdrawal, m.handleMemoryValidatorsByWithdrawal).Methods(http.MethodGet)
r.HandleFunc(pathMemoryFeesInfo, m.handleMemoryFeesInfo).Methods(http.MethodGet)
r.HandleFunc(pathMemoryPoolStatistics, m.handleMemoryStatistics).Methods(http.MethodGet)
r.HandleFunc(pathMemoryAllBlocks, m.handleMemoryAllBlocks).Methods(http.MethodGet)
r.HandleFunc(pathMemoryProposedBlocks, m.handleMemoryProposedBlocks).Methods(http.MethodGet)
r.HandleFunc(pathMemoryMissedBlocks, m.handleMemoryMissedBlocks).Methods(http.MethodGet)
r.HandleFunc(pathMemoryWrongFeeBlocks, m.handleMemoryWrongFeeBlocks).Methods(http.MethodGet)
r.HandleFunc(pathMemoryDonations, m.handleMemoryDonations).Methods(http.MethodGet)
// Onchain endpoints
r.HandleFunc(pathOnchainMerkleProof, m.handleOnchainMerkleProof).Methods(http.MethodGet)
// Not strictly necessary but good to have
r.Use(mux.CORSMethodMiddleware(r))
r.Use(prometheusMiddleware)
return r
}
func (m *ApiService) StartHTTPServer() {
log.Info("Starting HTTP server on ", m.ApiListenAddr)
if m.srv != nil {
log.Fatal("HTTP server already started")
}
m.srv = &http.Server{
Addr: m.ApiListenAddr,
//wrap handler with corsMiddleware, it passes execution to router handler when finished
Handler: corsMiddleware(m.getRouter()),
//ReadTimeout: time.Duration(config.ServerReadTimeoutMs) * time.Millisecond,
//ReadHeaderTimeout: time.Duration(config.ServerReadHeaderTimeoutMs) * time.Millisecond,
//WriteTimeout: time.Duration(config.ServerWriteTimeoutMs) * time.Millisecond,
//IdleTimeout: time.Duration(config.ServerIdleTimeoutMs) * time.Millisecond,
//MaxHeaderBytes: config.ServerMaxHeaderBytes,
}
err := m.srv.ListenAndServe()
if err != nil {
log.Fatal("could not start http server: ", err)
}
}
// Checks Origin header of the request and only allows from the desired origin or "" origin.
// Also adds CORS headers to the HTTP response so that the server indicates which origins and methods are allowed.
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set the CORS headers for all requests so that the browser allows the request
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// If the request method is OPTIONS, return a response with the allowed methods, headers, and origin
if r.Method == "OPTIONS" {
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
return
}
next.ServeHTTP(w, r)
})
}
func (m *ApiService) handleRoot(w http.ResponseWriter, req *http.Request) {
m.respondOK(w, "see api doc for available endpoints")
}
func (m *ApiService) handleMemoryStatistics(w http.ResponseWriter, req *http.Request) {
// Ensure the oracle is ready
if !m.OracleReady(uint64(64)) {
m.respondError(w, http.StatusServiceUnavailable, "Oracle node is currently syncing and not serving requests")
return
}
totalSubscribed := uint64(0)
totalActive := uint64(0)
totalYellowCard := uint64(0)
totalRedCard := uint64(0)
totalBanned := uint64(0)
totalNotSubscribed := uint64(0)
totalAccumulatedRewards := big.NewInt(0)
totalPendingRewards := big.NewInt(0)
for _, validator := range m.oracle.State().Validators {
if validator.ValidatorStatus == oracle.Active {
totalActive++
} else if validator.ValidatorStatus == oracle.YellowCard {
totalYellowCard++
} else if validator.ValidatorStatus == oracle.RedCard {
totalRedCard++
} else if validator.ValidatorStatus == oracle.Banned {
totalBanned++
} else if validator.ValidatorStatus == oracle.NotSubscribed {
totalNotSubscribed++
}
totalAccumulatedRewards.Add(totalAccumulatedRewards, validator.AccumulatedRewardsWei)
totalPendingRewards.Add(totalPendingRewards, validator.PendingRewardsWei)
}
totalSubscribed = totalActive + totalYellowCard + totalRedCard
totalRewardsSentWei := big.NewInt(0)
totalRewardsSent30DaysWei := big.NewInt(0)
totalDonationsWei := big.NewInt(0)
// Prevent underflow
if uint64(m.oracle.State().LatestProcessedSlot) < 1 {
m.respondError(w, http.StatusInternalServerError, "head slot is lower than 1, this should not happen")
return
}
if uint64(m.oracle.State().LatestProcessedBlock) < 1 {
m.respondError(w, http.StatusInternalServerError, "head block is lower than 1, this should not happen")
return
}
// Only consider blocks in the last 30 days
limitSlot := uint64(m.oracle.State().LatestProcessedSlot) - SlotsInOneMonth
limitBlock := uint64(m.oracle.State().LatestProcessedBlock) - SlotsInOneMonth
// Note that in a month we have SlotsInOneMonth slots, but not exactly that amount of blocks. If blocks
// are missed we can have less. If blocks are missed we will take into account a time window
// slightly higher than 30 days.
totalOkPoolProposalBlocks := uint64(0)
for _, block := range m.oracle.State().ProposedBlocks {
// only consider ok pool proposals, since these are the only type of blocks that are shared
// across all validators
if block.BlockType == oracle.OkPoolProposal {
totalRewardsSentWei.Add(totalRewardsSentWei, block.Reward)
totalOkPoolProposalBlocks++
// Filter blocks in the last 30 days
if block.Slot > limitSlot {
totalRewardsSent30DaysWei.Add(totalRewardsSent30DaysWei, block.Reward)
}
}
}
for _, donation := range m.oracle.State().Donations {
totalDonationsWei.Add(totalDonationsWei, donation.DonationAmount)
// Note that rewards also take donations into account
totalRewardsSentWei.Add(totalRewardsSentWei, donation.DonationAmount)
if donation.Raw.BlockNumber > limitBlock {
totalRewardsSent30DaysWei.Add(totalRewardsSent30DaysWei, donation.DonationAmount)
}
}
rewardsPerValidatorPer30Days := big.NewInt(0)
totalValidatorsEarning := totalActive + totalYellowCard
if totalSubscribed != 0 {
// This metric can be biased if multiple validators exit at once within the month
rewardsPerValidatorPer30Days.Div(totalRewardsSent30DaysWei, big.NewInt(0).SetUint64(totalValidatorsEarning))
}
totalProposedBlocks := uint64(len(m.oracle.State().ProposedBlocks))
avgBlockRewardWei := big.NewInt(0)
// Avoid division by zero
if totalOkPoolProposalBlocks != 0 {
avgBlockRewardWei = big.NewInt(0).Div(totalRewardsSentWei, big.NewInt(0).SetUint64(totalOkPoolProposalBlocks))
}
m.respondOK(w, httpOkMemoryStatistics{
TotalSubscribed: totalSubscribed,
TotalActive: totalActive,
TotalYellowCard: totalYellowCard,
TotalRedCard: totalRedCard,
TotalBanned: totalBanned,
TotalNotSubscribed: totalNotSubscribed,
LatestCheckpointSlot: m.oracle.State().LatestProcessedSlot,
NextCheckpointSlot: m.oracle.State().LatestProcessedSlot + m.cfg.CheckPointSizeInSlots,
TotalAccumulatedRewardsWei: totalAccumulatedRewards.String(),
TotalPendingRewaradsWei: totalPendingRewards.String(),
TotalRewardsSentWei: totalRewardsSentWei.String(),
TotalDonationsWei: totalDonationsWei.String(),
AvgBlockRewardWei: avgBlockRewardWei.String(),
TotalRewardsSent30DaysWei: totalRewardsSent30DaysWei.String(),
RewardsPerValidatorPer30Days: rewardsPerValidatorPer30Days.String(),
TotalProposedBlocks: totalProposedBlocks,
TotalMissedBlocks: uint64(len(m.oracle.State().MissedBlocks)),
TotalWrongFeeBlocks: uint64(len(m.oracle.State().WrongFeeBlocks)),
})
}
func (m *ApiService) handleStatus(w http.ResponseWriter, req *http.Request) {
chainId, err := m.Onchain.ExecutionClient.ChainID(context.Background())
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get exex chainid: "+err.Error())
return
}
depositContract, err := m.Onchain.ConsensusClient.DepositContract(context.Background(), ð2.DepositContractOpts{})
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get deposit contract: "+err.Error())
return
}
execSync, err := m.Onchain.ExecutionClient.SyncProgress(context.Background())
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get exec sync progress: "+err.Error())
return
}
// Seems that if nil means its in sync
execInSync := false
if execSync == nil {
execInSync = true
}
consSync, err := m.Onchain.ConsensusClient.NodeSyncing(context.Background(), ð2.NodeSyncingOpts{})
if consSync == nil || err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get consensus sync progress or result is nil: "+err.Error())
return
}
if consSync.Data == nil {
m.respondError(w, http.StatusInternalServerError, "consensus sync progress data is nil")
return
}
// Allow some slots to avoid jitter
consInSync := false
if uint64(consSync.Data.SyncDistance) < 2 {
consInSync = true
}
finality, err := m.Onchain.FinalizedBeaconBlockHeader(apiRetryOpts...)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get consensus latest finalized slot: "+err.Error())
return
}
finalizedSlot := uint64(finality.Header.Message.Slot)
oracleSync := false
if m.oracle.State().LatestProcessedSlot-finalizedSlot == 0 {
oracleSync = true
}
_, onchainSlot, err := m.Onchain.GetOnchainSlotAndRoot(apiRetryOpts...)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get onchain slot and root: "+err.Error())
return
}
// If the oracle is not in sync, we cant really calculate the slots till the next checkpoint
// because we are behind. So we just set it to 0
nextCheckpointInSlots := uint64(0)
if finalizedSlot < (onchainSlot + m.cfg.CheckPointSizeInSlots) {
nextCheckpointInSlots = onchainSlot + m.cfg.CheckPointSizeInSlots - finalizedSlot
}
status := httpOkStatus{
IsConsensusInSync: consInSync,
IsExecutionInSync: execInSync,
IsOracleInSync: oracleSync,
LatestProcessedSlot: m.oracle.State().LatestProcessedSlot,
LatestProcessedBlock: m.oracle.State().LatestProcessedBlock,
LatestFinalizedEpoch: finalizedSlot / 32,
LatestFinalizedSlot: finalizedSlot,
OracleHeadDistance: finalizedSlot - m.oracle.State().LatestProcessedSlot,
NextCheckpointSlot: onchainSlot + m.cfg.CheckPointSizeInSlots,
NextCheckpointTime: "", // TODO:
NextCheckpointRemaining: utils.SlotsToTime(nextCheckpointInSlots, constants.SecondsInSlot),
NextCheckpointRemainingUnix: nextCheckpointInSlots * constants.SecondsInSlot,
PreviousCheckpointSlot: onchainSlot,
PreviousCheckpointTime: "", // TODO:
PreviousCheckpointAge: utils.SlotsToTime(finalizedSlot-onchainSlot, constants.SecondsInSlot),
PreviousCheckpointAgeUnix: (finalizedSlot - onchainSlot) * constants.SecondsInSlot,
ExecutionChainId: chainId.String(),
ConsensusChainId: strconv.FormatUint(depositContract.Data.ChainID, 10),
DepositContact: hexutil.Encode(depositContract.Data.Address[:]),
}
m.respondOK(w, status)
}
func (m *ApiService) handleConfig(w http.ResponseWriter, req *http.Request) {
if m.cfg == nil {
m.respondError(w, http.StatusInternalServerError, "no config loaded, nil value")
return
}
m.respondOK(w, httpOkConfig{
Network: m.cfg.Network,
PoolAddress: m.cfg.PoolAddress,
DeployedSlot: m.cfg.DeployedSlot,
CheckPointSizeInSlots: m.cfg.CheckPointSizeInSlots,
PoolFeesPercentOver10000: m.cfg.PoolFeesPercentOver10000,
PoolFeesAddress: m.cfg.PoolFeesAddress,
DryRun: m.cfg.DryRun,
CollateralInWei: m.cfg.CollateralInWei.String(),
})
}
func (m *ApiService) handleMemoryValidators(w http.ResponseWriter, req *http.Request) {
if !m.OracleReady(uint64(64)) {
m.respondError(w, http.StatusServiceUnavailable, "Oracle node is currently syncing and not serving requests")
return
}
validators := maps.Values(m.oracle.State().Validators)
// Order by index
sort.Slice(validators, func(i, j int) bool { return validators[i].ValidatorIndex < validators[j].ValidatorIndex })
validatorsResp := make([]httpOkValidatorInfo, 0)
for _, v := range validators {
beaconState, found := m.Onchain.Validators()[phase0.ValidatorIndex(v.ValidatorIndex)]
if !found {
log.Warn("could not find validator in beacon state: ", v.ValidatorIndex)
continue
}
validatorsResp = append(validatorsResp, httpOkValidatorInfo{
ValidatorStatus: v.ValidatorStatus.String(),
BeaconValidatorStatus: beaconState.Status.String(),
AccumulatedRewardsWei: v.AccumulatedRewardsWei.String(),
PendingRewardsWei: v.PendingRewardsWei.String(),
CollateralWei: v.CollateralWei.String(),
WithdrawalAddress: v.WithdrawalAddress,
ValidatorIndex: v.ValidatorIndex,
ValidatorKey: v.ValidatorKey,
SubscriptionType: v.SubscriptionType.String(),
})
}
m.respondOK(w, validatorsResp)
}
func (m *ApiService) handleMemoryValidatorInfo(w http.ResponseWriter, req *http.Request) {
if !m.OracleReady(MaxSlotsBehind) {
m.respondError(w, http.StatusServiceUnavailable, "Oracle node is currently syncing and not serving requests")
return
}
vars := mux.Vars(req)
valIndexStr := vars["valindex"]
valIndex, ok := IsValidIndex(valIndexStr)
if !ok {
m.respondError(w, http.StatusBadRequest, "invalid validator index: "+valIndexStr)
return
}
validator, found := m.oracle.State().Validators[valIndex]
if !found {
m.respondError(w, http.StatusBadRequest, fmt.Sprint("could not find validator with index: ", valIndex))
return
}
// TODO: Temporal, remove in production.
if validator.ValidatorIndex != valIndex {
validator.ValidatorIndex = valIndex
}
m.respondOK(w, validator)
}
func (m *ApiService) handleMemoryValidatorsByIndex(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
valIndicesStr := vars["valindices"]
// Check if the string is empty or ends with a comma
if valIndicesStr == "" || strings.HasSuffix(valIndicesStr, ",") {
m.respondError(w, http.StatusBadRequest, "Invalid format for validator indices")
return
}
// Split the valIndicesStr into a slice of strings
indicesStr := strings.Split(valIndicesStr, ",")
if len(indicesStr) > 100 {
m.respondError(w, http.StatusBadRequest, "Request exceeds maximum limit of 100 validators")
return
}
// Check each index format and convert it to uint64
var indices []uint64
for _, indexStr := range indicesStr {
index, valid := IsValidIndex(indexStr)
if !valid {
m.respondError(w, http.StatusBadRequest, "Invalid format for validator indices")
return
}
indices = append(indices, index)
}
// Initialize both response slices
var foundValidators []httpOkValidatorInfo
var notFoundValidators []uint64
// Check if each validator is in the oracle state. Append to foundValidators or notFoundValidators
for _, index := range indices {
if validator, found := m.oracle.State().Validators[index]; found {
// Convert ValidatorInfo to httpOkValidatorInfo. This is done to return strings instead of bigInts
beaconState, found := m.Onchain.Validators()[phase0.ValidatorIndex(validator.ValidatorIndex)]
if !found {
log.Warn("could not find validator in beacon state: ", validator.ValidatorIndex)
continue
}
foundValidator := httpOkValidatorInfo{
ValidatorStatus: validator.ValidatorStatus.String(),
BeaconValidatorStatus: beaconState.Status.String(),
AccumulatedRewardsWei: validator.AccumulatedRewardsWei.String(),
PendingRewardsWei: validator.PendingRewardsWei.String(),
CollateralWei: validator.CollateralWei.String(),
WithdrawalAddress: validator.WithdrawalAddress,
ValidatorIndex: validator.ValidatorIndex,
ValidatorKey: validator.ValidatorKey,
SubscriptionType: validator.SubscriptionType.String(),
}
foundValidators = append(foundValidators, foundValidator)
} else {
notFoundValidators = append(notFoundValidators, index)
}
}
response := httpOkValidatorsByIndex{
Found: foundValidators,
NotFound: notFoundValidators,
}
m.respondOK(w, response)
}
func (m *ApiService) handleMemoryValidatorsByWithdrawal(w http.ResponseWriter, req *http.Request) {
if !m.OracleReady(MaxSlotsBehind) {
m.respondError(w, http.StatusServiceUnavailable, "Oracle node is currently syncing and not serving requests")
return
}
vars := mux.Vars(req)
withdrawalAddress := vars["withdrawalAddress"]
// Use always lowercase
withdrawalAddress = strings.ToLower(withdrawalAddress)
if !IsValidAddress(withdrawalAddress) {
m.respondError(w, http.StatusBadRequest, "invalid withdrawalAddress: "+withdrawalAddress)
return
}
if m.Onchain.Validators() == nil {
m.respondError(w, http.StatusInternalServerError, "finalized validators not loaded yet, try again later")
return
}
// We return
// 1) validators using this withdrawal address but not tracked by the oracle
// 2) validators using this withdrawal address and tracked by the oracle (eg already subscribed)
requestedValidators := make(map[uint64]*oracle.ValidatorInfo, 0)
// 1) Get all onchain validators for that withdrawal address (untracked)
for valIndex, validator := range m.Onchain.Validators() {
// Check if the withdrawal address matches the requested one
credStr := hex.EncodeToString(validator.Validator.WithdrawalCredentials)
eth1Add, err := utils.GetCompatibleAddress(credStr) // TODO: Use the new function
// Skip validators without non eth withdrawal address (bls address)
if err != nil {
continue
}
// Skip if the address does not match with the requested
if !AreAddressEqual(eth1Add, withdrawalAddress) {
continue
}
// Skip validators that cannot be subscribed
//if !oracle.CanValidatorSubscribeToPool(validator) {
// continue
//}
requestedValidators[uint64(valIndex)] = &oracle.ValidatorInfo{
ValidatorStatus: oracle.Untracked,
AccumulatedRewardsWei: big.NewInt(0),
PendingRewardsWei: big.NewInt(0),
CollateralWei: big.NewInt(0),
WithdrawalAddress: eth1Add,
ValidatorIndex: uint64(validator.Index),
ValidatorKey: hexutil.Encode(validator.Validator.PublicKey[:]),
}
}
// 2) Get all tracked validators for that withdrawal address (tracked)
validatorsCopy := make(map[uint64]*oracle.ValidatorInfo)
// Imporant! This is a deep copy, otherwise we will modify the state
utils.DeepCopy(m.oracle.State().Validators, &validatorsCopy)
for valIndex, validator := range validatorsCopy {
// Just overwrite the untracked validators with oracle state
if AreAddressEqual(validator.WithdrawalAddress, withdrawalAddress) {
requestedValidators[valIndex] = validator
// TODO: Temporal, remove in production.
if validator.ValidatorIndex != valIndex {
validator.ValidatorIndex = valIndex
}
}
}
// If at this point we have no validators, just return empty to avoid more processing
// TODO: Cant i return earlier? after 2)?
if len(requestedValidators) == 0 {
m.respondOK(w, make([]httpOkValidatorInfo, 0))
return
}
// Now we apply the state transition to these validators, based on what we have seen
// onchain since the latest finalized slot util head. This is neccesary because the
// oracle runs all calculations on finalized states, but the api must report to the
// users without this 15 minutes-ish delay.
// This applies a non-finalized state to the validators, creating a virtual state
// only used for the api.
if m.oracle.State().LatestProcessedBlock == 0 {
m.respondError(w, http.StatusInternalServerError, "latest processed block is 0, try again later")
return
}
firstNotProcessedBlock := m.oracle.State().LatestProcessedBlock + 1
// TODO: Cache this, very inneficient to get it every time
allSubsTillHead, err := m.GetSubscriptionsTillHead(firstNotProcessedBlock)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get subscriptions: "+err.Error())
return
}
allUnsubsTillHead, err := m.GetUnsubscriptionsTillHead(firstNotProcessedBlock)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get unsubscriptions: "+err.Error())
return
}
// Apply latest seen events to the existing state. This is a "virtual" state, just for the api
// so that users are aware of the latest events, without waiting for the next finalized state.
m.ApplyNonFinalizedState(
allSubsTillHead,
allUnsubsTillHead,
requestedValidators)
// Sort by index
values := maps.Values(requestedValidators)
sort.Slice(values, func(i, j int) bool { return values[i].ValidatorIndex < values[j].ValidatorIndex })
validatorsResp := make([]httpOkValidatorInfo, 0)
for _, v := range values {
beaconState, found := m.Onchain.Validators()[phase0.ValidatorIndex(v.ValidatorIndex)]
if !found {
log.Warn("could not find validator in beacon state: ", v.ValidatorIndex)
continue
}
validatorsResp = append(validatorsResp, httpOkValidatorInfo{
ValidatorStatus: v.ValidatorStatus.String(),
BeaconValidatorStatus: beaconState.Status.String(),
AccumulatedRewardsWei: v.AccumulatedRewardsWei.String(),
PendingRewardsWei: v.PendingRewardsWei.String(),
CollateralWei: v.CollateralWei.String(),
WithdrawalAddress: v.WithdrawalAddress,
ValidatorIndex: v.ValidatorIndex,
ValidatorKey: v.ValidatorKey,
SubscriptionType: v.SubscriptionType.String(),
})
}
m.respondOK(w, validatorsResp)
}
func (m *ApiService) handleMemoryFeesInfo(w http.ResponseWriter, req *http.Request) {
m.respondOK(w, httpOkMemoryFeesInfo{
PoolFeesPercentOver10000: m.oracle.State().PoolFeesPercentOver10000,
PoolFeesAddress: m.oracle.State().PoolFeesAddress,
PoolAccumulatedFees: m.oracle.State().PoolAccumulatedFees.String(),
})
}
func (m *ApiService) handleMemoryAllBlocks(w http.ResponseWriter, req *http.Request) {
// Concat all the blocks, order is not guaranteed
allBlocks := make([]httpOkBlock, 0)
for _, block := range m.oracle.State().ProposedBlocks {
allBlocks = append(allBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
for _, block := range m.oracle.State().MissedBlocks {
allBlocks = append(allBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
for _, block := range m.oracle.State().WrongFeeBlocks {
allBlocks = append(allBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
m.respondOK(w, allBlocks)
}
func (m *ApiService) handleMemoryProposedBlocks(w http.ResponseWriter, req *http.Request) {
proposedBlocks := make([]httpOkBlock, 0)
for _, block := range m.oracle.State().ProposedBlocks {
proposedBlocks = append(proposedBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
m.respondOK(w, proposedBlocks)
}
func (m *ApiService) handleMemoryMissedBlocks(w http.ResponseWriter, req *http.Request) {
missedBlocks := make([]httpOkBlock, 0)
for _, block := range m.oracle.State().MissedBlocks {
missedBlocks = append(missedBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
m.respondOK(w, missedBlocks)
}
func (m *ApiService) handleMemoryWrongFeeBlocks(w http.ResponseWriter, req *http.Request) {
wrongFeeBlocks := make([]httpOkBlock, 0)
for _, block := range m.oracle.State().WrongFeeBlocks {
wrongFeeBlocks = append(wrongFeeBlocks, httpOkBlock{
Slot: block.Slot,
Block: block.Block,
ValidatorIndex: block.ValidatorIndex,
ValidatorKey: block.ValidatorKey,
BlockType: block.BlockType.String(),
Reward: block.Reward.String(),
RewardType: block.RewardType.String(),
WithdrawalAddress: block.WithdrawalAddress,
})
}
m.respondOK(w, wrongFeeBlocks)
}
func (m *ApiService) handleMemoryDonations(w http.ResponseWriter, req *http.Request) {
donations := make([]httpOkDonation, 0)
for _, donation := range m.oracle.State().Donations {
donations = append(donations, httpOkDonation{
AmountWei: donation.DonationAmount.String(),
Block: donation.Raw.BlockNumber,
TxHash: donation.Raw.TxHash.String(),
Sender: donation.Sender.String(),
})
}
m.respondOK(w, donations)
}
func (m *ApiService) handleOnchainMerkleProof(w http.ResponseWriter, req *http.Request) {
if !m.OracleReady(MaxSlotsBehind) {
m.respondError(w, http.StatusServiceUnavailable, "Oracle node is currently syncing and not serving requests")
return
}
vars := mux.Vars(req)
withdrawalAddress := vars["withdrawalAddress"]
if !IsValidAddress(withdrawalAddress) {
m.respondError(w, http.StatusBadRequest, "invalid WithdrawalAddress: "+withdrawalAddress)
return
}
// Use always lowercase
withdrawalAddress = strings.ToLower(withdrawalAddress)
contractRoot, contractSlot, err := m.Onchain.GetOnchainSlotAndRoot(apiRetryOpts...)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get onchain slot and root: "+err.Error())
return
}
_, found := m.oracle.State().CommitedStates[contractSlot]
if !found {
m.respondError(w, http.StatusInternalServerError, "could not find onchain slot in oracle state: "+strconv.FormatUint(contractSlot, 10))
return
}
// Check if the oracle root matches the one offchain
if contractRoot != m.oracle.State().CommitedStates[contractSlot].MerkleRoot {
m.respondError(w, http.StatusInternalServerError,
"contract merkle root does not match oracle state: "+
contractRoot+" vs "+m.oracle.State().CommitedStates[contractSlot].MerkleRoot)
return
}
// Get the proofs of this withdrawal address (to be used onchain to claim rewards)
proofs, proofFound := m.oracle.State().CommitedStates[contractSlot].Proofs[withdrawalAddress]
if !proofFound {
m.respondError(w, http.StatusBadRequest, "could not find proof for WithdrawalAddress: "+withdrawalAddress)
return
}
// Get the leafs of this withdrawal address (to be used onchain to claim rewards)
leafs, leafsFound := m.oracle.State().CommitedStates[contractSlot].Leafs[withdrawalAddress]
if !leafsFound {
m.respondError(w, http.StatusBadRequest, "could not find leafs for WithdrawalAddress: "+withdrawalAddress)
return
}
// Get validators that are registered to this withdrawal address in the pool
registeredValidators := make([]uint64, 0)
for valIndex, validator := range m.oracle.State().CommitedStates[contractSlot].Validators {
if strings.ToLower(validator.WithdrawalAddress) == strings.ToLower(withdrawalAddress) {
registeredValidators = append(registeredValidators, valIndex)
}
}
claimed, err := m.Onchain.GetContractClaimedBalance(withdrawalAddress, nil, apiRetryOpts...)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not get claimed balance so far from contract: "+err.Error())
return
}
totalPending := big.NewInt(0)
for _, validator := range m.oracle.State().CommitedStates[contractSlot].Validators {
if strings.ToLower(validator.WithdrawalAddress) == strings.ToLower(withdrawalAddress) {
totalPending.Add(totalPending, validator.PendingRewardsWei)
}
}
m.respondOK(w, httpOkProofs{
LeafWithdrawalAddress: leafs.WithdrawalAddress,
LeafAccumulatedBalance: leafs.AccumulatedBalanceWei.String(),
MerkleRoot: m.oracle.State().CommitedStates[contractSlot].MerkleRoot,
CheckpointSlot: m.oracle.State().CommitedStates[contractSlot].Slot,
Proofs: proofs,
RegisteredValidators: registeredValidators,
TotalAccumulatedRewardsWei: leafs.AccumulatedBalanceWei.String(),
ClaimableRewardsWei: new(big.Int).Sub(leafs.AccumulatedBalanceWei, claimed).String(),
AlreadyClaimedRewardsWei: claimed.String(),
PendingRewardsWei: totalPending.String(),
})
}
func (m *ApiService) handleValidatorRelayers(w http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
valPubKey := vars["valpubkey"]
if !IsValidPubkey(valPubKey) {
m.respondError(w, http.StatusInternalServerError, fmt.Sprintf("invalid validator pubkey format"))
return
}
var correctFeeRelays []httpRelay
var wrongFeeRelays []httpRelay
var unregisteredRelays []httpRelay
registeredCorrectFee := false
relayers := m.cliCfg.RelayersEndpoints
for _, relay := range relayers {
url := fmt.Sprintf("%s/relay/v1/data/validator_registration?pubkey=%s", relay, valPubKey)
resp, err := http.Get(url)
if err != nil {
m.respondError(w, http.StatusInternalServerError, "could not call relayer endpoint: "+err.Error())
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
signedRegistration := &builderApiV1.SignedValidatorRegistration{}