generated from flashbots/go-template
-
Notifications
You must be signed in to change notification settings - Fork 120
/
service.go
2659 lines (2319 loc) · 92.9 KB
/
service.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 contains the API webserver for the proposer and block-builder APIs
package api
import (
"bytes"
"compress/gzip"
"context"
"database/sql"
"encoding/json"
"fmt"
"io"
"math/big"
"net/http"
_ "net/http/pprof"
"os"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/NYTimes/gziphandler"
builderApi "github.com/attestantio/go-builder-client/api"
builderApiV1 "github.com/attestantio/go-builder-client/api/v1"
"github.com/attestantio/go-eth2-client/spec"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/buger/jsonparser"
"github.com/flashbots/go-boost-utils/bls"
"github.com/flashbots/go-boost-utils/ssz"
"github.com/flashbots/go-boost-utils/utils"
"github.com/flashbots/go-utils/cli"
"github.com/flashbots/go-utils/httplogger"
"github.com/flashbots/mev-boost-relay/beaconclient"
"github.com/flashbots/mev-boost-relay/common"
"github.com/flashbots/mev-boost-relay/database"
"github.com/flashbots/mev-boost-relay/datastore"
"github.com/flashbots/mev-boost-relay/metrics"
"github.com/go-redis/redis/v9"
"github.com/gorilla/mux"
"github.com/holiman/uint256"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/otel/attribute"
otelapi "go.opentelemetry.io/otel/metric"
uberatomic "go.uber.org/atomic"
"golang.org/x/exp/slices"
)
const (
ErrBlockAlreadyKnown = "simulation failed: block already known"
ErrBlockRequiresReorg = "simulation failed: block requires a reorg"
ErrMissingTrieNode = "missing trie node"
)
var (
ErrMissingLogOpt = errors.New("log parameter is nil")
ErrMissingBeaconClientOpt = errors.New("beacon-client is nil")
ErrMissingDatastoreOpt = errors.New("proposer datastore is nil")
ErrRelayPubkeyMismatch = errors.New("relay pubkey does not match existing one")
ErrServerAlreadyStarted = errors.New("server was already started")
ErrBuilderAPIWithoutSecretKey = errors.New("cannot start builder API without secret key")
ErrNegativeTimestamp = errors.New("timestamp cannot be negative")
)
var (
// Proposer API (builder-specs)
pathStatus = "/eth/v1/builder/status"
pathRegisterValidator = "/eth/v1/builder/validators"
pathGetHeader = "/eth/v1/builder/header/{slot:[0-9]+}/{parent_hash:0x[a-fA-F0-9]+}/{pubkey:0x[a-fA-F0-9]+}"
pathGetPayload = "/eth/v1/builder/blinded_blocks"
// Block builder API
pathBuilderGetValidators = "/relay/v1/builder/validators"
pathSubmitNewBlock = "/relay/v1/builder/blocks"
// Data API
pathDataProposerPayloadDelivered = "/relay/v1/data/bidtraces/proposer_payload_delivered"
pathDataBuilderBidsReceived = "/relay/v1/data/bidtraces/builder_blocks_received"
pathDataValidatorRegistration = "/relay/v1/data/validator_registration"
// Internal API
pathInternalBuilderStatus = "/internal/v1/builder/{pubkey:0x[a-fA-F0-9]+}"
pathInternalBuilderCollateral = "/internal/v1/builder/collateral/{pubkey:0x[a-fA-F0-9]+}"
// number of goroutines to save active validator
numValidatorRegProcessors = cli.GetEnvInt("NUM_VALIDATOR_REG_PROCESSORS", 10)
// various timings
timeoutGetPayloadRetryMs = cli.GetEnvInt("GETPAYLOAD_RETRY_TIMEOUT_MS", 100)
getHeaderRequestCutoffMs = cli.GetEnvInt("GETHEADER_REQUEST_CUTOFF_MS", 3000)
getPayloadRequestCutoffMs = cli.GetEnvInt("GETPAYLOAD_REQUEST_CUTOFF_MS", 4000)
getPayloadResponseDelayMs = cli.GetEnvInt("GETPAYLOAD_RESPONSE_DELAY_MS", 1000)
// api settings
apiReadTimeoutMs = cli.GetEnvInt("API_TIMEOUT_READ_MS", 1500)
apiReadHeaderTimeoutMs = cli.GetEnvInt("API_TIMEOUT_READHEADER_MS", 600)
apiIdleTimeoutMs = cli.GetEnvInt("API_TIMEOUT_IDLE_MS", 3_000)
apiWriteTimeoutMs = cli.GetEnvInt("API_TIMEOUT_WRITE_MS", 10_000)
apiMaxHeaderBytes = cli.GetEnvInt("API_MAX_HEADER_BYTES", 60_000)
// api shutdown: wait time (to allow removal from load balancer before stopping http server)
apiShutdownWaitDuration = common.GetEnvDurationSec("API_SHUTDOWN_WAIT_SEC", 30)
// api shutdown: whether to stop sending bids during shutdown phase (only useful if running a single-instance testnet setup)
apiShutdownStopSendingBids = os.Getenv("API_SHUTDOWN_STOP_SENDING_BIDS") == "1"
// maximum payload bytes for a block submission to be fast-tracked (large payloads slow down other fast-tracked requests!)
fastTrackPayloadSizeLimit = cli.GetEnvInt("FAST_TRACK_PAYLOAD_SIZE_LIMIT", 230_000)
// user-agents which shouldn't receive bids
apiNoHeaderUserAgents = common.GetEnvStrSlice("NO_HEADER_USERAGENTS", []string{
"mev-boost/v1.5.0 Go-http-client/1.1", // Prysm v4.0.1 (Shapella signing issue)
})
)
// RelayAPIOpts contains the options for a relay
type RelayAPIOpts struct {
Log *logrus.Entry
ListenAddr string
BlockSimURL string
BeaconClient beaconclient.IMultiBeaconClient
Datastore *datastore.Datastore
Redis *datastore.RedisCache
Memcached *datastore.Memcached
DB database.IDatabaseService
SecretKey *bls.SecretKey // used to sign bids (getHeader responses)
// Network specific variables
EthNetDetails common.EthNetworkDetails
// APIs to enable
ProposerAPI bool
BlockBuilderAPI bool
DataAPI bool
PprofAPI bool
InternalAPI bool
}
type payloadAttributesHelper struct {
slot uint64
parentHash string
withdrawalsRoot phase0.Root
parentBeaconRoot *phase0.Root
payloadAttributes beaconclient.PayloadAttributes
}
// Data needed to issue a block validation request.
type blockSimOptions struct {
isHighPrio bool
fastTrack bool
log *logrus.Entry
builder *blockBuilderCacheEntry
req *common.BuilderBlockValidationRequest
}
type blockBuilderCacheEntry struct {
status common.BuilderStatus
collateral *big.Int
}
type blockSimResult struct {
wasSimulated bool
blockValue *uint256.Int
optimisticSubmission bool
requestErr error
validationErr error
}
// RelayAPI represents a single Relay instance
type RelayAPI struct {
opts RelayAPIOpts
log *logrus.Entry
blsSk *bls.SecretKey
publicKey *phase0.BLSPubKey
srv *http.Server
srvStarted uberatomic.Bool
srvShutdown uberatomic.Bool
beaconClient beaconclient.IMultiBeaconClient
datastore *datastore.Datastore
redis *datastore.RedisCache
memcached *datastore.Memcached
db database.IDatabaseService
headSlot uberatomic.Uint64
genesisInfo *beaconclient.GetGenesisResponse
capellaEpoch int64
denebEpoch int64
proposerDutiesLock sync.RWMutex
proposerDutiesResponse *[]byte // raw http response
proposerDutiesMap map[uint64]*common.BuilderGetValidatorsResponseEntry
proposerDutiesSlot uint64
isUpdatingProposerDuties uberatomic.Bool
blockSimRateLimiter IBlockSimRateLimiter
validatorRegC chan builderApiV1.SignedValidatorRegistration
// used to notify when a new validator has been registered
validatorUpdateCh chan struct{}
// used to wait on any active getPayload calls on shutdown
getPayloadCallsInFlight sync.WaitGroup
// Feature flags
ffForceGetHeader204 bool
ffDisableLowPrioBuilders bool
ffDisablePayloadDBStorage bool // disable storing the execution payloads in the database
ffLogInvalidSignaturePayload bool // log payload if getPayload signature validation fails
ffEnableCancellations bool // whether to enable block builder cancellations
ffRegValContinueOnInvalidSig bool // whether to continue processing further validators if one fails
ffIgnorableValidationErrors bool // whether to enable ignorable validation errors
payloadAttributes map[string]payloadAttributesHelper // key:parentBlockHash
payloadAttributesLock sync.RWMutex
// The slot we are currently optimistically simulating.
optimisticSlot uberatomic.Uint64
// The number of optimistic blocks being processed (only used for logging).
optimisticBlocksInFlight uberatomic.Uint64
// Wait group used to monitor status of per-slot optimistic processing.
optimisticBlocksWG sync.WaitGroup
// Cache for builder statuses and collaterals.
blockBuildersCache map[string]*blockBuilderCacheEntry
}
// NewRelayAPI creates a new service. if builders is nil, allow any builder
func NewRelayAPI(opts RelayAPIOpts) (api *RelayAPI, err error) {
if err := metrics.Setup(context.Background()); err != nil {
return nil, err
}
if opts.Log == nil {
return nil, ErrMissingLogOpt
}
if opts.BeaconClient == nil {
return nil, ErrMissingBeaconClientOpt
}
if opts.Datastore == nil {
return nil, ErrMissingDatastoreOpt
}
// If block-builder API is enabled, then ensure secret key is all set
var publicKey phase0.BLSPubKey
if opts.BlockBuilderAPI {
if opts.SecretKey == nil {
return nil, ErrBuilderAPIWithoutSecretKey
}
// If using a secret key, ensure it's the correct one
blsPubkey, err := bls.PublicKeyFromSecretKey(opts.SecretKey)
if err != nil {
return nil, err
}
publicKey, err = utils.BlsPublicKeyToPublicKey(blsPubkey)
if err != nil {
return nil, err
}
opts.Log.Infof("Using BLS key: %s", publicKey.String())
// ensure pubkey is same across all relay instances
_pubkey, err := opts.Redis.GetRelayConfig(datastore.RedisConfigFieldPubkey)
if err != nil {
return nil, err
} else if _pubkey == "" {
err := opts.Redis.SetRelayConfig(datastore.RedisConfigFieldPubkey, publicKey.String())
if err != nil {
return nil, err
}
} else if _pubkey != publicKey.String() {
return nil, fmt.Errorf("%w: new=%s old=%s", ErrRelayPubkeyMismatch, publicKey.String(), _pubkey)
}
}
api = &RelayAPI{
opts: opts,
log: opts.Log,
blsSk: opts.SecretKey,
publicKey: &publicKey,
datastore: opts.Datastore,
beaconClient: opts.BeaconClient,
redis: opts.Redis,
memcached: opts.Memcached,
db: opts.DB,
payloadAttributes: make(map[string]payloadAttributesHelper),
proposerDutiesResponse: &[]byte{},
blockSimRateLimiter: NewBlockSimulationRateLimiter(opts.BlockSimURL),
validatorRegC: make(chan builderApiV1.SignedValidatorRegistration, 450_000),
validatorUpdateCh: make(chan struct{}),
}
if os.Getenv("FORCE_GET_HEADER_204") == "1" {
api.log.Warn("env: FORCE_GET_HEADER_204 - forcing getHeader to always return 204")
api.ffForceGetHeader204 = true
}
if os.Getenv("DISABLE_LOWPRIO_BUILDERS") == "1" {
api.log.Warn("env: DISABLE_LOWPRIO_BUILDERS - allowing only high-level builders")
api.ffDisableLowPrioBuilders = true
}
if os.Getenv("DISABLE_PAYLOAD_DATABASE_STORAGE") == "1" {
api.log.Warn("env: DISABLE_PAYLOAD_DATABASE_STORAGE - disabling storing payloads in the database")
api.ffDisablePayloadDBStorage = true
}
if os.Getenv("LOG_INVALID_GETPAYLOAD_SIGNATURE") == "1" {
api.log.Warn("env: LOG_INVALID_GETPAYLOAD_SIGNATURE - getPayload payloads with invalid proposer signature will be logged")
api.ffLogInvalidSignaturePayload = true
}
if os.Getenv("ENABLE_BUILDER_CANCELLATIONS") == "1" {
api.log.Warn("env: ENABLE_BUILDER_CANCELLATIONS - builders are allowed to cancel submissions when using ?cancellation=1")
api.ffEnableCancellations = true
}
if os.Getenv("REGISTER_VALIDATOR_CONTINUE_ON_INVALID_SIG") == "1" {
api.log.Warn("env: REGISTER_VALIDATOR_CONTINUE_ON_INVALID_SIG - validator registration will continue processing even if one validator has an invalid signature")
api.ffRegValContinueOnInvalidSig = true
}
if os.Getenv("ENABLE_IGNORABLE_VALIDATION_ERRORS") == "1" {
api.log.Warn("env: ENABLE_IGNORABLE_VALIDATION_ERRORS - some validation errors will be ignored")
api.ffIgnorableValidationErrors = true
}
return api, nil
}
func (api *RelayAPI) getRouter() http.Handler {
r := mux.NewRouter()
r.HandleFunc("/", api.handleRoot).Methods(http.MethodGet)
r.HandleFunc("/livez", api.handleLivez).Methods(http.MethodGet)
r.HandleFunc("/readyz", api.handleReadyz).Methods(http.MethodGet)
r.Handle("/metrics", promhttp.Handler()).Methods(http.MethodGet)
// Proposer API
if api.opts.ProposerAPI {
api.log.Info("proposer API enabled")
r.HandleFunc(pathStatus, api.handleStatus).Methods(http.MethodGet)
r.HandleFunc(pathRegisterValidator, api.handleRegisterValidator).Methods(http.MethodPost)
r.HandleFunc(pathGetHeader, api.handleGetHeader).Methods(http.MethodGet)
r.HandleFunc(pathGetPayload, api.handleGetPayload).Methods(http.MethodPost)
}
// Builder API
if api.opts.BlockBuilderAPI {
api.log.Info("block builder API enabled")
r.HandleFunc(pathBuilderGetValidators, api.handleBuilderGetValidators).Methods(http.MethodGet)
r.HandleFunc(pathSubmitNewBlock, api.handleSubmitNewBlock).Methods(http.MethodPost)
}
// Data API
if api.opts.DataAPI {
api.log.Info("data API enabled")
r.HandleFunc(pathDataProposerPayloadDelivered, api.handleDataProposerPayloadDelivered).Methods(http.MethodGet)
r.HandleFunc(pathDataBuilderBidsReceived, api.handleDataBuilderBidsReceived).Methods(http.MethodGet)
r.HandleFunc(pathDataValidatorRegistration, api.handleDataValidatorRegistration).Methods(http.MethodGet)
}
// Pprof
if api.opts.PprofAPI {
api.log.Info("pprof API enabled")
r.PathPrefix("/debug/pprof/").Handler(http.DefaultServeMux)
}
// /internal/...
if api.opts.InternalAPI {
api.log.Info("internal API enabled")
r.HandleFunc(pathInternalBuilderStatus, api.handleInternalBuilderStatus).Methods(http.MethodGet, http.MethodPost, http.MethodPut)
r.HandleFunc(pathInternalBuilderCollateral, api.handleInternalBuilderCollateral).Methods(http.MethodPost, http.MethodPut)
}
mresp := common.MustB64Gunzip("H4sICAtOkWQAA2EudHh0AKWVPW+DMBCGd36Fe9fIi5Mt8uqqs4dIlZiCEqosKKhVO2Txj699GBtDcEl4JwTnh/t4dS7YWom2FcVaiETSDEmIC+pWLGRVgKrD3UY0iwnSj6THofQJDomiR13BnPgjvJDqNWX+OtzH7inWEGvr76GOCGtg3Kp7Ak+lus3zxLNtmXaMUncjcj1cwbOH3xBZtJCYG6/w+hdpB6ErpnqzFPZxO4FdXB3SAEgpscoDqWeULKmJA4qyfYFg0QV+p7hD8GGDd6C8+mElGDKab1CWeUQMVVvVDTJVj6nngHmNOmSoe6yH1BM3KZIKpuRaHKrOFd/3ksQwzdK+ejdM4VTzSDfjJsY1STeVTWb0T9JWZbJs8DvsNvwaddKdUy4gzVIzWWaWk3IF8D35kyUDf3FfKipwk/DYUee2nYyWQD0xEKDHeprzeXYwVmZD/lXt1OOg8EYhFfitsmQVcwmbUutpdt3PoqWdMyd2DYHKbgcmPlEYMxPjR6HhxOfuNG52xZr7TtzpygJJKNtWS14Uf0T6XSmzBwAA")
r.HandleFunc("/miladyz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK); w.Write(mresp) }).Methods(http.MethodGet) //nolint:errcheck
// r.Use(mux.CORSMethodMiddleware(r))
loggedRouter := httplogger.LoggingMiddlewareLogrus(api.log, r)
withGz := gziphandler.GzipHandler(loggedRouter)
return withGz
}
// StartServer starts up this API instance and HTTP server
// - First it initializes the cache and updates local information
// - Once that is done, the HTTP server is started
func (api *RelayAPI) StartServer() (err error) {
if api.srvStarted.Swap(true) {
return ErrServerAlreadyStarted
}
log := api.log.WithField("method", "StartServer")
// Get best beacon-node status by head slot, process current slot and start slot updates
syncStatus, err := api.beaconClient.BestSyncStatus()
if err != nil {
return err
}
currentSlot := syncStatus.HeadSlot
// Initialize block builder cache.
api.blockBuildersCache = make(map[string]*blockBuilderCacheEntry)
// Get genesis info
api.genesisInfo, err = api.beaconClient.GetGenesis()
if err != nil {
return err
}
log.Infof("genesis info: %d", api.genesisInfo.Data.GenesisTime)
// Get and prepare fork schedule
forkSchedule, err := api.beaconClient.GetForkSchedule()
if err != nil {
return err
}
api.denebEpoch = -1
api.capellaEpoch = -1
for _, fork := range forkSchedule.Data {
log.Infof("forkSchedule: version=%s / epoch=%d", fork.CurrentVersion, fork.Epoch)
switch fork.CurrentVersion {
case api.opts.EthNetDetails.CapellaForkVersionHex:
api.capellaEpoch = int64(fork.Epoch)
case api.opts.EthNetDetails.DenebForkVersionHex:
api.denebEpoch = int64(fork.Epoch)
}
}
if api.denebEpoch == -1 {
// log warning that deneb epoch was not found in CL fork schedule, suggest CL upgrade
log.Info("Deneb epoch not found in fork schedule")
}
// Print fork version information
if hasReachedFork(currentSlot, api.denebEpoch) {
log.Infof("deneb fork detected (currentEpoch: %d / denebEpoch: %d)", common.SlotToEpoch(currentSlot), api.denebEpoch)
} else if hasReachedFork(currentSlot, api.capellaEpoch) {
log.Infof("capella fork detected (currentEpoch: %d / capellaEpoch: %d)", common.SlotToEpoch(currentSlot), api.capellaEpoch)
}
// start proposer API specific things
if api.opts.ProposerAPI {
// Update known validators (which can take 10-30 sec). This is a requirement for service readiness, because without them,
// getPayload() doesn't have the information it needs (known validators), which could lead to missed slots.
go api.datastore.RefreshKnownValidators(api.log, api.beaconClient, currentSlot)
// Start the validator registration db-save processor
api.log.Infof("starting %d validator registration processors", numValidatorRegProcessors)
for range numValidatorRegProcessors {
go api.startValidatorRegistrationDBProcessor()
}
}
// start block-builder API specific things
if api.opts.BlockBuilderAPI {
// Initialize metrics
metrics.BuilderDemotionCount.Add(context.Background(), 0)
// Get current proposer duties blocking before starting, to have them ready
api.updateProposerDuties(syncStatus.HeadSlot)
// Subscribe to payload attributes events (only for builder-api)
go func() {
c := make(chan beaconclient.PayloadAttributesEvent)
api.beaconClient.SubscribeToPayloadAttributesEvents(c)
for {
payloadAttributes := <-c
api.processPayloadAttributes(payloadAttributes)
}
}()
}
// Process current slot
api.processNewSlot(currentSlot)
// Start regular slot updates
go func() {
c := make(chan beaconclient.HeadEventData)
api.beaconClient.SubscribeToHeadEvents(c)
for {
headEvent := <-c
api.processNewSlot(headEvent.Slot)
}
}()
// create and start HTTP server
api.srv = &http.Server{
Addr: api.opts.ListenAddr,
Handler: api.getRouter(),
ReadTimeout: time.Duration(apiReadTimeoutMs) * time.Millisecond,
ReadHeaderTimeout: time.Duration(apiReadHeaderTimeoutMs) * time.Millisecond,
WriteTimeout: time.Duration(apiWriteTimeoutMs) * time.Millisecond,
IdleTimeout: time.Duration(apiIdleTimeoutMs) * time.Millisecond,
MaxHeaderBytes: apiMaxHeaderBytes,
}
err = api.srv.ListenAndServe()
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}
func (api *RelayAPI) IsReady() bool {
// If server is shutting down, return false
if api.srvShutdown.Load() {
return false
}
// Proposer API readiness checks
if api.opts.ProposerAPI {
knownValidatorsUpdated := api.datastore.KnownValidatorsWasUpdated.Load()
return knownValidatorsUpdated
}
// Block-builder API readiness checks
return true
}
// StopServer gracefully shuts down the HTTP server:
// - Stop returning bids
// - Set ready /readyz to negative status
// - Wait a bit to allow removal of service from load balancer and draining of requests
func (api *RelayAPI) StopServer() (err error) {
// avoid running this twice. setting srvShutdown to true makes /readyz switch to negative status
if wasStopping := api.srvShutdown.Swap(true); wasStopping {
return nil
}
// start server shutdown
api.log.Info("Stopping server...")
// stop returning bids on getHeader calls (should only be used when running a single instance)
if api.opts.ProposerAPI && apiShutdownStopSendingBids {
api.ffForceGetHeader204 = true
api.log.Info("Disabled returning bids on getHeader")
}
// wait some time to get service removed from load balancer
api.log.Infof("Waiting %.2f seconds before shutdown...", apiShutdownWaitDuration.Seconds())
time.Sleep(apiShutdownWaitDuration)
// wait for any active getPayload call to finish
api.getPayloadCallsInFlight.Wait()
// shutdown
return api.srv.Shutdown(context.Background())
}
func (api *RelayAPI) ValidatorUpdateCh() chan struct{} {
return api.validatorUpdateCh
}
func (api *RelayAPI) isCapella(slot uint64) bool {
return hasReachedFork(slot, api.capellaEpoch) && !hasReachedFork(slot, api.denebEpoch)
}
func (api *RelayAPI) isDeneb(slot uint64) bool {
return hasReachedFork(slot, api.denebEpoch)
}
func (api *RelayAPI) startValidatorRegistrationDBProcessor() {
for valReg := range api.validatorRegC {
err := api.datastore.SaveValidatorRegistration(valReg)
if err != nil {
api.log.WithError(err).WithFields(logrus.Fields{
"reg_pubkey": valReg.Message.Pubkey,
"reg_feeRecipient": valReg.Message.FeeRecipient,
"reg_gasLimit": valReg.Message.GasLimit,
"reg_timestamp": valReg.Message.Timestamp,
}).Error("error saving validator registration")
}
}
}
// simulateBlock sends a request for a block simulation to blockSimRateLimiter.
func (api *RelayAPI) simulateBlock(ctx context.Context, opts blockSimOptions) (blockValue *uint256.Int, requestErr, validationErr error) {
t := time.Now()
response, requestErr, validationErr := api.blockSimRateLimiter.Send(ctx, opts.req, opts.isHighPrio, opts.fastTrack)
log := opts.log.WithFields(logrus.Fields{
"durationMs": time.Since(t).Milliseconds(),
"numWaiting": api.blockSimRateLimiter.CurrentCounter(),
})
if validationErr != nil {
if api.ffIgnorableValidationErrors {
// Operators chooses to ignore certain validation errors
ignoreError := validationErr.Error() == ErrBlockAlreadyKnown || validationErr.Error() == ErrBlockRequiresReorg || strings.Contains(validationErr.Error(), ErrMissingTrieNode)
if ignoreError {
log.WithError(validationErr).Warn("block validation failed with ignorable error")
return nil, nil, nil
}
}
log.WithError(validationErr).Warn("block validation failed")
return nil, nil, validationErr
}
if requestErr != nil {
log.WithError(requestErr).Warn("block validation failed: request error")
return nil, requestErr, nil
}
log.Info("block validation successful")
if response == nil {
log.Warn("block validation response is nil")
return nil, nil, nil
}
return response.BlockValue, nil, nil
}
func (api *RelayAPI) demoteBuilder(pubkey string, req *common.VersionedSubmitBlockRequest, simError error) {
metrics.BuilderDemotionCount.Add(
context.Background(),
1,
)
builderEntry, ok := api.blockBuildersCache[pubkey]
if !ok {
api.log.Warnf("builder %v not in the builder cache", pubkey)
builderEntry = &blockBuilderCacheEntry{} //nolint:exhaustruct
}
newStatus := common.BuilderStatus{
IsHighPrio: builderEntry.status.IsHighPrio,
IsBlacklisted: builderEntry.status.IsBlacklisted,
IsOptimistic: false,
}
api.log.Infof("demoted builder, new status: %v", newStatus)
if err := api.db.SetBlockBuilderIDStatusIsOptimistic(pubkey, false); err != nil {
api.log.Error(fmt.Errorf("error setting builder: %v status: %w", pubkey, err))
}
// Write to demotions table.
api.log.WithFields(logrus.Fields{
"builderPubkey": pubkey,
"slot": req.Slot,
"blockHash": req.BlockHash,
"demotionErr": simError.Error(),
}).Info("demoting builder")
bidTrace, err := req.BidTrace()
if err != nil {
api.log.WithError(err).Warn("failed to get bid trace from submit block request")
}
if err := api.db.InsertBuilderDemotion(req, simError); err != nil {
api.log.WithError(err).WithFields(logrus.Fields{
"errorWritingDemotionToDB": true,
"bidTrace": bidTrace,
"simError": simError,
}).Error("failed to save demotion to database")
}
}
// processOptimisticBlock is called on a new goroutine when a optimistic block
// needs to be simulated.
func (api *RelayAPI) processOptimisticBlock(opts blockSimOptions, simResultC chan *blockSimResult) {
api.optimisticBlocksInFlight.Add(1)
defer func() { api.optimisticBlocksInFlight.Sub(1) }()
api.optimisticBlocksWG.Add(1)
defer api.optimisticBlocksWG.Done()
ctx := context.Background()
submission, err := common.GetBlockSubmissionInfo(opts.req.VersionedSubmitBlockRequest)
if err != nil {
opts.log.WithError(err).Error("error getting block submission info")
return
}
builderPubkey := submission.BidTrace.BuilderPubkey.String()
opts.log.WithFields(logrus.Fields{
"builderPubkey": builderPubkey,
// NOTE: this value is just an estimate because many goroutines could be
// updating api.optimisticBlocksInFlight concurrently. Since we just use
// it for logging, it is not atomic to avoid the performance impact.
"optBlocksInFlight": api.optimisticBlocksInFlight,
}).Infof("simulating optimistic block with hash: %v", submission.BidTrace.BlockHash.String())
blockValue, reqErr, simErr := api.simulateBlock(ctx, opts)
simResultC <- &blockSimResult{reqErr == nil, blockValue, true, reqErr, simErr}
if reqErr != nil || simErr != nil {
// Mark builder as non-optimistic.
opts.builder.status.IsOptimistic = false
api.log.WithError(simErr).Warn("block simulation failed in processOptimisticBlock, demoting builder")
var demotionErr error
if reqErr != nil {
demotionErr = reqErr
} else {
demotionErr = simErr
}
// Demote the builder.
api.demoteBuilder(builderPubkey, opts.req.VersionedSubmitBlockRequest, demotionErr)
}
}
func (api *RelayAPI) processPayloadAttributes(payloadAttributes beaconclient.PayloadAttributesEvent) {
apiHeadSlot := api.headSlot.Load()
payloadAttrSlot := payloadAttributes.Data.ProposalSlot
// require proposal slot in the future
if payloadAttrSlot <= apiHeadSlot {
return
}
log := api.log.WithFields(logrus.Fields{
"headSlot": apiHeadSlot,
"payloadAttrSlot": payloadAttrSlot,
"payloadAttrParent": payloadAttributes.Data.ParentBlockHash,
})
// discard payload attributes if already known
api.payloadAttributesLock.RLock()
_, ok := api.payloadAttributes[getPayloadAttributesKey(payloadAttributes.Data.ParentBlockHash, payloadAttrSlot)]
api.payloadAttributesLock.RUnlock()
if ok {
return
}
var withdrawalsRoot phase0.Root
var err error
if hasReachedFork(payloadAttrSlot, api.capellaEpoch) {
withdrawalsRoot, err = ComputeWithdrawalsRoot(payloadAttributes.Data.PayloadAttributes.Withdrawals)
log = log.WithField("withdrawalsRoot", withdrawalsRoot.String())
if err != nil {
log.WithError(err).Error("error computing withdrawals root")
return
}
}
var parentBeaconRoot *phase0.Root
if hasReachedFork(payloadAttrSlot, api.denebEpoch) {
if payloadAttributes.Data.PayloadAttributes.ParentBeaconBlockRoot == "" {
log.Error("parent beacon block root in payload attributes is empty")
return
}
// TODO: (deneb) HexToRoot util function
hash, err := utils.HexToHash(payloadAttributes.Data.PayloadAttributes.ParentBeaconBlockRoot)
if err != nil {
log.WithError(err).Error("error parsing parent beacon block root from payload attributes")
return
}
root := phase0.Root(hash)
parentBeaconRoot = &root
}
api.payloadAttributesLock.Lock()
defer api.payloadAttributesLock.Unlock()
// Step 1: clean up old ones
for parentBlockHash, attr := range api.payloadAttributes {
if attr.slot < apiHeadSlot {
delete(api.payloadAttributes, getPayloadAttributesKey(parentBlockHash, attr.slot))
}
}
// Step 2: save new one
api.payloadAttributes[getPayloadAttributesKey(payloadAttributes.Data.ParentBlockHash, payloadAttrSlot)] = payloadAttributesHelper{
slot: payloadAttrSlot,
parentHash: payloadAttributes.Data.ParentBlockHash,
withdrawalsRoot: withdrawalsRoot,
parentBeaconRoot: parentBeaconRoot,
payloadAttributes: payloadAttributes.Data.PayloadAttributes,
}
log.WithFields(logrus.Fields{
"randao": payloadAttributes.Data.PayloadAttributes.PrevRandao,
"timestamp": payloadAttributes.Data.PayloadAttributes.Timestamp,
}).Info("updated payload attributes")
}
func (api *RelayAPI) processNewSlot(headSlot uint64) {
prevHeadSlot := api.headSlot.Load()
if headSlot <= prevHeadSlot {
return
}
// If there's gaps between previous and new headslot, print the missed slots
if prevHeadSlot > 0 {
for s := prevHeadSlot + 1; s < headSlot; s++ {
api.log.WithField("missedSlot", s).Warnf("missed slot: %d", s)
}
}
// store the head slot
api.headSlot.Store(headSlot)
// only for builder-api
if api.opts.BlockBuilderAPI || api.opts.ProposerAPI {
// update proposer duties in the background
go api.updateProposerDuties(headSlot)
// update the optimistic slot
go api.prepareBuildersForSlot(headSlot)
}
if api.opts.ProposerAPI {
go api.datastore.RefreshKnownValidators(api.log, api.beaconClient, headSlot)
}
// log
epoch := headSlot / common.SlotsPerEpoch
api.log.WithFields(logrus.Fields{
"epoch": epoch,
"slotHead": headSlot,
"slotStartNextEpoch": (epoch + 1) * common.SlotsPerEpoch,
}).Infof("updated headSlot to %d", headSlot)
}
func (api *RelayAPI) updateProposerDuties(headSlot uint64) {
// Ensure only one updating is running at a time
if api.isUpdatingProposerDuties.Swap(true) {
return
}
defer api.isUpdatingProposerDuties.Store(false)
// Update once every 8 slots (or more, if a slot was missed)
if headSlot%8 != 0 && headSlot-api.proposerDutiesSlot < 8 {
return
}
api.UpdateProposerDutiesWithoutChecks(headSlot)
}
func (api *RelayAPI) UpdateProposerDutiesWithoutChecks(headSlot uint64) {
// Load upcoming proposer duties from Redis
duties, err := api.redis.GetProposerDuties()
if err != nil {
api.log.WithError(err).Error("failed getting proposer duties from redis")
return
}
// Prepare raw bytes for HTTP response
respBytes, err := json.Marshal(duties)
if err != nil {
api.log.WithError(err).Error("error marshalling duties")
}
// Prepare the map for lookup by slot
dutiesMap := make(map[uint64]*common.BuilderGetValidatorsResponseEntry)
for index, duty := range duties {
dutiesMap[duty.Slot] = &duties[index]
}
// Update
api.proposerDutiesLock.Lock()
if len(respBytes) > 0 {
api.proposerDutiesResponse = &respBytes
}
api.proposerDutiesMap = dutiesMap
api.proposerDutiesSlot = headSlot
api.proposerDutiesLock.Unlock()
// pretty-print
_duties := make([]string, len(duties))
for i, duty := range duties {
_duties[i] = strconv.FormatUint(duty.Slot, 10)
}
sort.Strings(_duties)
api.log.Infof("proposer duties updated: %s", strings.Join(_duties, ", "))
}
func (api *RelayAPI) prepareBuildersForSlot(headSlot uint64) {
// Wait until there are no optimistic blocks being processed. Then we can
// safely update the slot.
api.optimisticBlocksWG.Wait()
api.optimisticSlot.Store(headSlot + 1)
builders, err := api.db.GetBlockBuilders()
if err != nil {
api.log.WithError(err).Error("unable to read block builders from db, not updating builder cache")
return
}
api.log.Debugf("Updating builder cache with %d builders from database", len(builders))
newCache := make(map[string]*blockBuilderCacheEntry)
for _, v := range builders {
entry := &blockBuilderCacheEntry{ //nolint:exhaustruct
status: common.BuilderStatus{
IsHighPrio: v.IsHighPrio,
IsBlacklisted: v.IsBlacklisted,
IsOptimistic: v.IsOptimistic,
},
}
// Try to parse builder collateral string to big int.
builderCollateral, ok := big.NewInt(0).SetString(v.Collateral, 10)
if !ok {
api.log.WithError(err).Errorf("could not parse builder collateral string %s", v.Collateral)
entry.collateral = big.NewInt(0)
} else {
entry.collateral = builderCollateral
}
newCache[v.BuilderPubkey] = entry
}
api.blockBuildersCache = newCache
}
func (api *RelayAPI) RespondError(w http.ResponseWriter, code int, message string) {
api.Respond(w, code, HTTPErrorResp{code, message})
}
func (api *RelayAPI) RespondOK(w http.ResponseWriter, response any) {
api.Respond(w, http.StatusOK, response)
}
func (api *RelayAPI) RespondMsg(w http.ResponseWriter, code int, msg string) {
api.Respond(w, code, HTTPMessageResp{msg})
}
func (api *RelayAPI) Respond(w http.ResponseWriter, code int, response any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if response == nil {
return
}
// write the json response
if err := json.NewEncoder(w).Encode(response); err != nil {
api.log.WithField("response", response).WithError(err).Error("Couldn't write response")
http.Error(w, "", http.StatusInternalServerError)
}
}
func (api *RelayAPI) handleStatus(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}
// ---------------
// PROPOSER APIS
// ---------------
func (api *RelayAPI) handleRoot(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "MEV-Boost Relay API")
}
func (api *RelayAPI) handleRegisterValidator(w http.ResponseWriter, req *http.Request) {
ua := req.UserAgent()
log := api.log.WithFields(logrus.Fields{
"method": "registerValidator",
"ua": ua,
"mevBoostV": common.GetMevBoostVersionFromUserAgent(ua),
"headSlot": api.headSlot.Load(),
"contentLength": req.ContentLength,
})
start := time.Now().UTC()
registrationTimestampUpperBound := start.Unix() + 10 // 10 seconds from now
numRegTotal := 0
numRegProcessed := 0
numRegActive := 0
numRegNew := 0
processingStoppedByError := false
// Setup error handling
handleError := func(_log *logrus.Entry, code int, msg string) {
processingStoppedByError = true
_log.Warnf("error: %s", msg)
api.RespondError(w, code, msg)
}
// Start processing
if req.ContentLength == 0 {
log.Info("empty request")
api.RespondError(w, http.StatusBadRequest, "empty request")
return
}
body, err := io.ReadAll(req.Body)
if err != nil {
log.WithError(err).WithField("contentLength", req.ContentLength).Warn("failed to read request body")
api.RespondError(w, http.StatusBadRequest, "failed to read request body")
return
}
req.Body.Close()
parseRegistration := func(value []byte) (reg *builderApiV1.SignedValidatorRegistration, err error) {
// Pubkey
_pubkey, err := jsonparser.GetUnsafeString(value, "message", "pubkey")
if err != nil {
return nil, fmt.Errorf("registration message error (pubkey): %w", err)
}
pubkey, err := utils.HexToPubkey(_pubkey)
if err != nil {
return nil, fmt.Errorf("registration message error (pubkey): %w", err)
}
// Timestamp
_timestamp, err := jsonparser.GetUnsafeString(value, "message", "timestamp")
if err != nil {
return nil, fmt.Errorf("registration message error (timestamp): %w", err)
}