HTTP endpoints cleanup (#13251)

* remove validation package

* structs cleanup

* merge with apimiddleware removal

* more validation and Bls capitalization

* builder test fix

* use strconv for uint->str conversions

* use DecodeHexWithLength

* use exact param names

* rename http package to httputil

* change conversions to fmt.Sprintf

* handle query paramsd and route variables

* spans and receiver name

* split structs, move bytes helper

* missing ok check

* fix reference to indexed failure

* errors fixup

* add godoc to helper

* fix BLS casing and chainhead ref

* review

* fix import in tests

* gzl
This commit is contained in:
Radosław Kapka
2023-12-08 21:37:20 +01:00
committed by GitHub
parent 440841d565
commit 4c47756aed
121 changed files with 6048 additions and 6491 deletions

View File

@@ -11,6 +11,7 @@ go_library(
visibility = ["//visibility:public"],
deps = [
"//api/client:go_default_library",
"//api/server:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/rpc/eth/beacon:go_default_library",
"//beacon-chain/rpc/eth/config:go_default_library",

View File

@@ -16,6 +16,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/client"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/config"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
@@ -305,7 +306,7 @@ func (c *Client) SubmitChangeBLStoExecution(ctx context.Context, request []*shar
if resp.StatusCode != http.StatusOK {
decoder := json.NewDecoder(resp.Body)
decoder.DisallowUnknownFields()
errorJson := &shared.IndexedVerificationFailureError{}
errorJson := &server.IndexedVerificationFailureError{}
if err := decoder.Decode(errorJson); err != nil {
return errors.Wrapf(err, "failed to decode error JSON for %s", resp.Request.URL)
}

View File

@@ -268,11 +268,7 @@ func (c *Client) RegisterValidator(ctx context.Context, svr []*ethpb.SignedValid
}
vs := make([]*shared.SignedValidatorRegistration, len(svr))
for i := 0; i < len(svr); i++ {
svrJson, err := shared.SignedValidatorRegistrationFromConsensus(svr[i])
if err != nil {
return errors.Wrap(err, fmt.Sprintf("failed to encode to SignedValidatorRegistration at index %d", i))
}
vs[i] = svrJson
vs[i] = shared.SignedValidatorRegistrationFromConsensus(svr[i])
}
body, err := json.Marshal(vs)
if err != nil {

View File

@@ -705,7 +705,7 @@ func testSignedBlindedBeaconBlockCapella(t *testing.T) *eth.SignedBlindedBeaconB
}
func testSignedBlindedBeaconBlockDeneb(t *testing.T) *eth.SignedBlindedBeaconBlockDeneb {
basebytes, err := shared.Uint256ToSSZBytes("14074904626401341155369551180448584754667373453244490859944217516317499064576")
basebytes, err := bytesutil.Uint256ToSSZBytes("14074904626401341155369551180448584754667373453244490859944217516317499064576")
if err != nil {
log.Error(err)
}

View File

@@ -38,8 +38,7 @@ func TestSignedValidatorRegistration_MarshalJSON(t *testing.T) {
},
Signature: make([]byte, 96),
}
a, err := shared.SignedValidatorRegistrationFromConsensus(svr)
require.NoError(t, err)
a := shared.SignedValidatorRegistrationFromConsensus(svr)
je, err := json.Marshal(a)
require.NoError(t, err)
// decode with a struct w/ plain strings so we can check the string encoding of the hex fields

View File

@@ -3,6 +3,7 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"error.go",
"middleware.go",
"util.go",
],
@@ -17,6 +18,7 @@ go_library(
go_test(
name = "go_default_test",
srcs = [
"error_test.go",
"middleware_test.go",
"util_test.go",
],

45
api/server/error.go Normal file
View File

@@ -0,0 +1,45 @@
package server
import (
"fmt"
"strings"
)
// DecodeError represents an error resulting from trying to decode an HTTP request.
// It tracks the full field name for which decoding failed.
type DecodeError struct {
path []string
err error
}
// NewDecodeError wraps an error (either the initial decoding error or another DecodeError).
// The current field that failed decoding must be passed in.
func NewDecodeError(err error, field string) *DecodeError {
de, ok := err.(*DecodeError)
if ok {
return &DecodeError{path: append([]string{field}, de.path...), err: de.err}
}
return &DecodeError{path: []string{field}, err: err}
}
// Error returns the formatted error message which contains the full field name and the actual decoding error.
func (e *DecodeError) Error() string {
return fmt.Sprintf("could not decode %s: %s", strings.Join(e.path, "."), e.err.Error())
}
// IndexedVerificationFailureError wraps a collection of verification failures.
type IndexedVerificationFailureError struct {
Message string `json:"message"`
Code int `json:"code"`
Failures []*IndexedVerificationFailure `json:"failures"`
}
func (e *IndexedVerificationFailureError) StatusCode() int {
return e.Code
}
// IndexedVerificationFailure represents an issue when verifying a single indexed object e.g. an item in an array.
type IndexedVerificationFailure struct {
Index int `json:"index"`
Message string `json:"message"`
}

16
api/server/error_test.go Normal file
View File

@@ -0,0 +1,16 @@
package server
import (
"errors"
"testing"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
)
func TestDecodeError(t *testing.T) {
e := errors.New("not a number")
de := NewDecodeError(e, "Z")
de = NewDecodeError(de, "Y")
de = NewDecodeError(de, "X")
assert.Equal(t, "could not decode X.Y.Z: not a number", de.Error())
}

View File

@@ -15,6 +15,7 @@ go_library(
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",
"//api/server:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/core/altair:go_default_library",
"//beacon-chain/core/blocks:go_default_library",
@@ -49,7 +50,7 @@ go_library(
"//consensus-types/validator:go_default_library",
"//crypto/bls:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
@@ -73,6 +74,7 @@ go_test(
embed = [":go_default_library"],
deps = [
"//api:go_default_library",
"//api/server:go_default_library",
"//beacon-chain/blockchain/testing:go_default_library",
"//beacon-chain/core/signing:go_default_library",
"//beacon-chain/core/time:go_default_library",
@@ -105,7 +107,7 @@ go_test(
"//crypto/hash:go_default_library",
"//encoding/bytesutil:go_default_library",
"//encoding/ssz:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -26,7 +26,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/time/slots"
@@ -54,7 +54,7 @@ func (s *Server) GetBlock(w http.ResponseWriter, r *http.Request) {
blockId := mux.Vars(r)["block_id"]
if blockId == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -62,7 +62,7 @@ func (s *Server) GetBlock(w http.ResponseWriter, r *http.Request) {
return
}
if http2.SszRequested(r) {
if httputil.SszRequested(r) {
s.getBlockSSZ(ctx, w, blk)
} else {
s.getBlock(ctx, w, blk)
@@ -73,21 +73,21 @@ func (s *Server) GetBlock(w http.ResponseWriter, r *http.Request) {
func (s *Server) getBlock(ctx context.Context, w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
v2Resp, err := s.getBlockPhase0(ctx, blk)
if err != nil {
http2.HandleError(w, "Could not get block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block: "+err.Error(), http.StatusInternalServerError)
return
}
resp := &GetBlockResponse{Data: v2Resp.Data}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// getBlockSSZ returns the SSZ-serialized version of the becaon block for given block ID.
func (s *Server) getBlockSSZ(ctx context.Context, w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
resp, err := s.getBlockPhase0SSZ(ctx, blk)
if err != nil {
http2.HandleError(w, "Could not get block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block: "+err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, resp, "beacon_block.ssz")
httputil.WriteSsz(w, resp, "beacon_block.ssz")
}
// GetBlockV2 retrieves block details for given block ID.
@@ -97,7 +97,7 @@ func (s *Server) GetBlockV2(w http.ResponseWriter, r *http.Request) {
blockId := mux.Vars(r)["block_id"]
if blockId == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -105,7 +105,7 @@ func (s *Server) GetBlockV2(w http.ResponseWriter, r *http.Request) {
return
}
if http2.SszRequested(r) {
if httputil.SszRequested(r) {
s.getBlockSSZV2(ctx, w, blk)
} else {
s.getBlockV2(ctx, w, blk)
@@ -116,7 +116,7 @@ func (s *Server) GetBlockV2(w http.ResponseWriter, r *http.Request) {
func (s *Server) getBlockV2(ctx context.Context, w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root "+err.Error(), http.StatusInternalServerError)
return
}
finalized := s.FinalizationFetcher.IsFinalized(ctx, blkRoot)
@@ -126,12 +126,12 @@ func (s *Server) getBlockV2(ctx context.Context, w http.ResponseWriter, blk inte
if result != nil {
result.Finalized = finalized
w.Header().Set(api.VersionHeader, result.Version)
http2.WriteJson(w, result)
httputil.WriteJson(w, result)
return true
}
// ErrUnsupportedField means that we have another block type
if !errors.Is(err, consensus_types.ErrUnsupportedField) {
http2.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
return true
}
return false
@@ -152,7 +152,7 @@ func (s *Server) getBlockV2(ctx context.Context, w http.ResponseWriter, blk inte
if getBlockHandler(s.getBlockPhase0) {
return
}
http2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
}
// getBlockSSZV2 returns the SSZ-serialized version of the beacon block for given block ID.
@@ -161,12 +161,12 @@ func (s *Server) getBlockSSZV2(ctx context.Context, w http.ResponseWriter, blk i
result, err := get(ctx, blk)
if result != nil {
w.Header().Set(api.VersionHeader, ver)
http2.WriteSsz(w, result, "beacon_block.ssz")
httputil.WriteSsz(w, result, "beacon_block.ssz")
return true
}
// ErrUnsupportedField means that we have another block type
if !errors.Is(err, consensus_types.ErrUnsupportedField) {
http2.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
return true
}
return false
@@ -187,7 +187,7 @@ func (s *Server) getBlockSSZV2(ctx context.Context, w http.ResponseWriter, blk i
if getBlockHandler(s.getBlockPhase0SSZ, version.String(version.Phase0)) {
return
}
http2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
}
// GetBlindedBlock retrieves blinded block for given block id.
@@ -197,7 +197,7 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
blockId := mux.Vars(r)["block_id"]
if blockId == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -205,7 +205,7 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
return
}
if http2.SszRequested(r) {
if httputil.SszRequested(r) {
s.getBlindedBlockSSZ(ctx, w, blk)
} else {
s.getBlindedBlock(ctx, w, blk)
@@ -216,7 +216,7 @@ func (s *Server) GetBlindedBlock(w http.ResponseWriter, r *http.Request) {
func (s *Server) getBlindedBlock(ctx context.Context, w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock) {
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root "+err.Error(), http.StatusInternalServerError)
return
}
finalized := s.FinalizationFetcher.IsFinalized(ctx, blkRoot)
@@ -226,12 +226,12 @@ func (s *Server) getBlindedBlock(ctx context.Context, w http.ResponseWriter, blk
if result != nil {
result.Finalized = finalized
w.Header().Set(api.VersionHeader, result.Version)
http2.WriteJson(w, result)
httputil.WriteJson(w, result)
return true
}
// ErrUnsupportedField means that we have another block type
if !errors.Is(err, consensus_types.ErrUnsupportedField) {
http2.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
return true
}
return false
@@ -252,7 +252,7 @@ func (s *Server) getBlindedBlock(ctx context.Context, w http.ResponseWriter, blk
if getBlockHandler(s.getBlindedBlockDeneb) {
return
}
http2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
}
// getBlindedBlockSSZ returns the SSZ-serialized version of the blinded beacon block for given block id.
@@ -261,12 +261,12 @@ func (s *Server) getBlindedBlockSSZ(ctx context.Context, w http.ResponseWriter,
result, err := get(ctx, blk)
if result != nil {
w.Header().Set(api.VersionHeader, ver)
http2.WriteSsz(w, result, "beacon_block.ssz")
httputil.WriteSsz(w, result, "beacon_block.ssz")
return true
}
// ErrUnsupportedField means that we have another block type
if !errors.Is(err, consensus_types.ErrUnsupportedField) {
http2.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get signed beacon block: "+err.Error(), http.StatusInternalServerError)
return true
}
return false
@@ -287,7 +287,7 @@ func (s *Server) getBlindedBlockSSZ(ctx context.Context, w http.ResponseWriter,
if getBlockHandler(s.getBlindedBlockDenebSSZ, version.String(version.Deneb)) {
return
}
http2.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Unknown block type %T", blk), http.StatusInternalServerError)
}
func (*Server) getBlockPhase0(_ context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*GetBlockV2Response, error) {
@@ -298,10 +298,7 @@ func (*Server) getBlockPhase0(_ context.Context, blk interfaces.ReadOnlySignedBe
if consensusBlk == nil {
return nil, errNilBlock
}
respBlk, err := shared.SignedBeaconBlockFromConsensus(consensusBlk)
if err != nil {
return nil, err
}
respBlk := shared.SignedBeaconBlockFromConsensus(consensusBlk)
jsonBytes, err := json.Marshal(respBlk.Message)
if err != nil {
return nil, err
@@ -324,10 +321,7 @@ func (*Server) getBlockAltair(_ context.Context, blk interfaces.ReadOnlySignedBe
if consensusBlk == nil {
return nil, errNilBlock
}
respBlk, err := shared.SignedBeaconBlockAltairFromConsensus(consensusBlk)
if err != nil {
return nil, err
}
respBlk := shared.SignedBeaconBlockAltairFromConsensus(consensusBlk)
jsonBytes, err := json.Marshal(respBlk.Message)
if err != nil {
return nil, err
@@ -913,7 +907,7 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
blockId := mux.Vars(r)["block_id"]
if blockId == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
blk, err := s.Blocker.Block(ctx, []byte(blockId))
@@ -924,16 +918,16 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
consensusAtts := blk.Block().Body().Attestations()
atts := make([]*shared.Attestation, len(consensusAtts))
for i, att := range consensusAtts {
atts[i] = shared.AttestationFromConsensus(att)
atts[i] = shared.AttFromConsensus(att)
}
root, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, root)
if err != nil {
http2.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -942,7 +936,7 @@ func (s *Server) GetBlockAttestations(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, root),
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// PublishBlindedBlock instructs the beacon node to use the components of the `SignedBlindedBeaconBlock` to construct
@@ -959,7 +953,7 @@ func (s *Server) PublishBlindedBlock(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
isSSZ := http2.SszRequested(r)
isSSZ := httputil.SszRequested(r)
if isSSZ {
s.publishBlindedBlockSSZ(ctx, w, r)
} else {
@@ -984,7 +978,7 @@ func (s *Server) PublishBlindedBlockV2(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
isSSZ := http2.SszRequested(r)
isSSZ := httputil.SszRequested(r)
if isSSZ {
s.publishBlindedBlockSSZ(ctx, w, r)
} else {
@@ -995,7 +989,7 @@ func (s *Server) PublishBlindedBlockV2(w http.ResponseWriter, r *http.Request) {
func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http2.HandleError(w, "Could not read request body: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not read request body: "+err.Error(), http.StatusInternalServerError)
return
}
denebBlock := &eth.SignedBlindedBeaconBlockDeneb{}
@@ -1006,7 +1000,7 @@ func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWrit
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1020,7 +1014,7 @@ func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWrit
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1034,7 +1028,7 @@ func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWrit
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1050,7 +1044,7 @@ func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWrit
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1064,19 +1058,19 @@ func (s *Server) publishBlindedBlockSSZ(ctx context.Context, w http.ResponseWrit
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
return
}
http2.HandleError(w, "Body does not represent a valid block type", http.StatusBadRequest)
httputil.HandleError(w, "Body does not represent a valid block type", http.StatusBadRequest)
}
func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
versionHeader := r.Header.Get(api.VersionHeader)
@@ -1086,7 +1080,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
consensusBlock, err := denebBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1102,7 +1096,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
consensusBlock, err := capellaBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1118,7 +1112,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
consensusBlock, err := bellatrixBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1133,7 +1127,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
consensusBlock, err := altairBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1148,7 +1142,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
consensusBlock, err := phase0Block.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1161,7 +1155,7 @@ func (s *Server) publishBlindedBlock(ctx context.Context, w http.ResponseWriter,
if versionHeader == "" {
blockVersionError = fmt.Sprintf("please add the api header %s to see specific type errors", api.VersionHeader)
}
http2.HandleError(w, "Body does not represent a valid block type: "+blockVersionError, http.StatusBadRequest)
httputil.HandleError(w, "Body does not represent a valid block type: "+blockVersionError, http.StatusBadRequest)
}
// PublishBlock instructs the beacon node to broadcast a newly signed beacon block to the beacon network,
@@ -1178,7 +1172,7 @@ func (s *Server) PublishBlock(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
isSSZ := http2.SszRequested(r)
isSSZ := httputil.SszRequested(r)
if isSSZ {
s.publishBlockSSZ(ctx, w, r)
} else {
@@ -1201,7 +1195,7 @@ func (s *Server) PublishBlockV2(w http.ResponseWriter, r *http.Request) {
if shared.IsSyncing(r.Context(), w, s.SyncChecker, s.HeadFetcher, s.TimeFetcher, s.OptimisticModeFetcher) {
return
}
isSSZ := http2.SszRequested(r)
isSSZ := httputil.SszRequested(r)
if isSSZ {
s.publishBlockSSZ(ctx, w, r)
} else {
@@ -1212,7 +1206,7 @@ func (s *Server) PublishBlockV2(w http.ResponseWriter, r *http.Request) {
func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
denebBlock := &eth.SignedBeaconBlockContentsDeneb{}
@@ -1223,7 +1217,7 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1237,7 +1231,7 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1251,7 +1245,7 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1265,7 +1259,7 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
@@ -1279,19 +1273,19 @@ func (s *Server) publishBlockSSZ(ctx context.Context, w http.ResponseWriter, r *
},
}
if err = s.validateBroadcast(ctx, r, genericBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, genericBlock)
return
}
http2.HandleError(w, "Body does not represent a valid block type", http.StatusBadRequest)
httputil.HandleError(w, "Body does not represent a valid block type", http.StatusBadRequest)
}
func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http2.HandleError(w, "Could not read request body", http.StatusInternalServerError)
httputil.HandleError(w, "Could not read request body", http.StatusInternalServerError)
return
}
versionHeader := r.Header.Get(api.VersionHeader)
@@ -1301,7 +1295,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
consensusBlock, err := denebBlockContents.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1316,7 +1310,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
consensusBlock, err := capellaBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1331,7 +1325,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
consensusBlock, err := bellatrixBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1346,7 +1340,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
consensusBlock, err := altairBlock.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1361,7 +1355,7 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
consensusBlock, err := phase0Block.ToGeneric()
if err == nil {
if err = s.validateBroadcast(ctx, r, consensusBlock); err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
s.proposeBlock(ctx, w, consensusBlock)
@@ -1374,13 +1368,13 @@ func (s *Server) publishBlock(ctx context.Context, w http.ResponseWriter, r *htt
if versionHeader == "" {
blockVersionError = fmt.Sprintf(": please add the api header %s to see specific type errors", api.VersionHeader)
}
http2.HandleError(w, "Body does not represent a valid block type"+blockVersionError, http.StatusBadRequest)
httputil.HandleError(w, "Body does not represent a valid block type"+blockVersionError, http.StatusBadRequest)
}
func (bs *Server) proposeBlock(ctx context.Context, w http.ResponseWriter, blk *eth.GenericSignedBeaconBlock) {
_, err := bs.V1Alpha1ValidatorServer.ProposeBeaconBlock(ctx, blk)
func (s *Server) proposeBlock(ctx context.Context, w http.ResponseWriter, blk *eth.GenericSignedBeaconBlock) {
_, err := s.V1Alpha1ValidatorServer.ProposeBeaconBlock(ctx, blk)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
}
@@ -1452,18 +1446,18 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
var root []byte
blockID := mux.Vars(r)["block_id"]
if blockID == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
switch blockID {
case "head":
root, err = s.ChainInfoFetcher.HeadRoot(ctx)
if err != nil {
http2.HandleError(w, "Could not retrieve head root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not retrieve head root: "+err.Error(), http.StatusInternalServerError)
return
}
if root == nil {
http2.HandleError(w, "No head root was found", http.StatusNotFound)
httputil.HandleError(w, "No head root was found", http.StatusNotFound)
return
}
case "finalized":
@@ -1472,16 +1466,16 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
case "genesis":
blk, err := s.BeaconDB.GenesisBlock(ctx)
if err != nil {
http2.HandleError(w, "Could not retrieve genesis block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not retrieve genesis block: "+err.Error(), http.StatusInternalServerError)
return
}
if err := blocks.BeaconBlockIsNil(blk); err != nil {
http2.HandleError(w, "Could not find genesis block: "+err.Error(), http.StatusNotFound)
httputil.HandleError(w, "Could not find genesis block: "+err.Error(), http.StatusNotFound)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not hash genesis block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not hash genesis block: "+err.Error(), http.StatusInternalServerError)
return
}
root = blkRoot[:]
@@ -1490,38 +1484,38 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
if isHex {
blockIDBytes, err := hexutil.Decode(blockID)
if err != nil {
http2.HandleError(w, "Could not decode block ID into bytes: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode block ID into bytes: "+err.Error(), http.StatusBadRequest)
return
}
if len(blockIDBytes) != fieldparams.RootLength {
http2.HandleError(w, fmt.Sprintf("Block ID has length %d instead of %d", len(blockIDBytes), fieldparams.RootLength), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Block ID has length %d instead of %d", len(blockIDBytes), fieldparams.RootLength), http.StatusBadRequest)
return
}
blockID32 := bytesutil.ToBytes32(blockIDBytes)
blk, err := s.BeaconDB.Block(ctx, blockID32)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not retrieve block for block root %#x: %v", blockID, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not retrieve block for block root %#x: %v", blockID, err), http.StatusInternalServerError)
return
}
if err := blocks.BeaconBlockIsNil(blk); err != nil {
http2.HandleError(w, "Could not find block: "+err.Error(), http.StatusNotFound)
httputil.HandleError(w, "Could not find block: "+err.Error(), http.StatusNotFound)
return
}
root = blockIDBytes
} else {
slot, err := strconv.ParseUint(blockID, 10, 64)
if err != nil {
http2.HandleError(w, "Could not parse block ID: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not parse block ID: "+err.Error(), http.StatusBadRequest)
return
}
hasRoots, roots, err := s.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot))
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not retrieve blocks for slot %d: %v", slot, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not retrieve blocks for slot %d: %v", slot, err), http.StatusInternalServerError)
return
}
if !hasRoots {
http2.HandleError(w, "Could not find any blocks with given slot", http.StatusNotFound)
httputil.HandleError(w, "Could not find any blocks with given slot", http.StatusNotFound)
return
}
root = roots[0][:]
@@ -1531,7 +1525,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
for _, blockRoot := range roots {
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blockRoot)
if err != nil {
http2.HandleError(w, "Could not determine if block root is canonical: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not determine if block root is canonical: "+err.Error(), http.StatusInternalServerError)
return
}
if canonical {
@@ -1545,7 +1539,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
b32Root := bytesutil.ToBytes32(root)
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, b32Root)
if err != nil {
http2.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check if block is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
response := &BlockRootResponse{
@@ -1555,7 +1549,7 @@ func (s *Server) GetBlockRoot(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, b32Root),
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetStateFork returns Fork object for state with given 'stateId'.
@@ -1564,7 +1558,7 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
defer span.End()
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -1575,12 +1569,12 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
fork := st.Fork()
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status"+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Could not calculate root of latest block header: ").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrap(err, "Could not calculate root of latest block header: ").Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1593,7 +1587,7 @@ func (s *Server) GetStateFork(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetCommittees retrieves the committees for the given state at the given epoch.
@@ -1604,19 +1598,19 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
ok, rawEpoch, e := shared.UintFromQuery(w, r, "epoch")
rawEpoch, e, ok := shared.UintFromQuery(w, r, "epoch", false)
if !ok {
return
}
ok, rawIndex, i := shared.UintFromQuery(w, r, "index")
rawIndex, i, ok := shared.UintFromQuery(w, r, "index", false)
if !ok {
return
}
ok, rawSlot, sl := shared.UintFromQuery(w, r, "slot")
rawSlot, sl, ok := shared.UintFromQuery(w, r, "slot", false)
if !ok {
return
}
@@ -1633,18 +1627,18 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
}
activeCount, err := corehelpers.ActiveValidatorCount(ctx, st, epoch)
if err != nil {
http2.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
return
}
startSlot, err := slots.EpochStart(epoch)
if err != nil {
http2.HandleError(w, "Could not get epoch start slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get epoch start slot: "+err.Error(), http.StatusInternalServerError)
return
}
endSlot, err := slots.EpochEnd(epoch)
if err != nil {
http2.HandleError(w, "Could not get epoch end slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get epoch end slot: "+err.Error(), http.StatusInternalServerError)
return
}
committeesPerSlot := corehelpers.SlotCommitteeCount(activeCount)
@@ -1659,7 +1653,7 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
}
committee, err := corehelpers.BeaconCommitteeFromState(ctx, st, slot, index)
if err != nil {
http2.HandleError(w, "Could not get committee: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get committee: "+err.Error(), http.StatusInternalServerError)
return
}
var validators []string
@@ -1677,17 +1671,17 @@ func (s *Server) GetCommittees(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
http2.WriteJson(w, &GetCommitteesResponse{Data: committees, ExecutionOptimistic: isOptimistic, Finalized: isFinalized})
httputil.WriteJson(w, &GetCommitteesResponse{Data: committees, ExecutionOptimistic: isOptimistic, Finalized: isFinalized})
}
// GetBlockHeaders retrieves block headers matching given query. By default it will fetch current head slot blocks.
@@ -1695,46 +1689,43 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.GetBlockHeaders")
defer span.End()
rawSlot := r.URL.Query().Get("slot")
rawParentRoot := r.URL.Query().Get("parent_root")
rawSlot, slot, ok := shared.UintFromQuery(w, r, "slot", false)
if !ok {
return
}
rawParentRoot, parentRoot, ok := shared.HexFromQuery(w, r, "parent_root", fieldparams.RootLength, false)
if !ok {
return
}
var err error
var blks []interfaces.ReadOnlySignedBeaconBlock
var blkRoots [][32]byte
if rawParentRoot != "" {
parentRoot, valid := shared.ValidateHex(w, "Parent Root", rawParentRoot, fieldparams.RootLength)
if !valid {
return
}
blks, blkRoots, err = s.BeaconDB.Blocks(ctx, filters.NewFilter().SetParentRoot(parentRoot))
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for parent root %s", parentRoot).Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for parent root %s", parentRoot).Error(), http.StatusInternalServerError)
return
}
} else {
slot := uint64(s.ChainInfoFetcher.HeadSlot())
if rawSlot != "" {
var valid bool
slot, valid = shared.ValidateUint(w, "Slot", rawSlot)
if !valid {
return
}
if rawSlot == "" {
slot = uint64(s.ChainInfoFetcher.HeadSlot())
}
blks, err = s.BeaconDB.BlocksBySlot(ctx, primitives.Slot(slot))
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
return
}
_, blkRoots, err = s.BeaconDB.BlockRootsBySlot(ctx, primitives.Slot(slot))
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not retrieve blocks for slot %d", slot).Error(), http.StatusInternalServerError)
return
}
}
if len(blks) == 0 {
http2.HandleError(w, "No blocks found", http.StatusNotFound)
httputil.HandleError(w, "No blocks found", http.StatusNotFound)
return
}
@@ -1744,23 +1735,23 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
for i, bl := range blks {
v1alpha1Header, err := bl.Header()
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not get block header from block").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not get block header from block").Error(), http.StatusInternalServerError)
return
}
headerRoot, err := v1alpha1Header.Header.HashTreeRoot()
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not hash block header").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not hash block header").Error(), http.StatusInternalServerError)
return
}
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blkRoots[i])
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not determine if block root is canonical").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not determine if block root is canonical").Error(), http.StatusInternalServerError)
return
}
if !isOptimistic {
isOptimistic, err = s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, blkRoots[i])
if err != nil {
http2.HandleError(w, errors.Wrapf(err, "Could not check if block is optimistic").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrapf(err, "Could not check if block is optimistic").Error(), http.StatusInternalServerError)
return
}
}
@@ -1782,7 +1773,7 @@ func (s *Server) GetBlockHeaders(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetBlockHeader retrieves block header for given block id.
@@ -1792,7 +1783,7 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
blockID := mux.Vars(r)["block_id"]
if blockID == "" {
http2.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "block_id is required in URL params", http.StatusBadRequest)
return
}
@@ -1803,27 +1794,27 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
}
blockHeader, err := blk.Header()
if err != nil {
http2.HandleError(w, "Could not get block header: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block header: %s"+err.Error(), http.StatusInternalServerError)
return
}
headerRoot, err := blockHeader.Header.HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not hash block header: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not hash block header: %s"+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not hash block: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not hash block: %s"+err.Error(), http.StatusInternalServerError)
return
}
canonical, err := s.ChainInfoFetcher.IsCanonical(ctx, blkRoot)
if err != nil {
http2.HandleError(w, "Could not determine if block root is canonical: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not determine if block root is canonical: %s"+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, blkRoot)
if err != nil {
http2.HandleError(w, "Could not check if block is optimistic: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check if block is optimistic: %s"+err.Error(), http.StatusInternalServerError)
return
}
@@ -1839,7 +1830,7 @@ func (s *Server) GetBlockHeader(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetFinalityCheckpoints returns finality checkpoints for state with given 'stateId'. In case finality is
@@ -1850,7 +1841,7 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
@@ -1861,12 +1852,12 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -1892,7 +1883,7 @@ func (s *Server) GetFinalityCheckpoints(w http.ResponseWriter, r *http.Request)
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetGenesis retrieves details of the chain's genesis which can be used to identify chain.
@@ -1902,12 +1893,12 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
genesisTime := s.GenesisTimeFetcher.GenesisTime()
if genesisTime.IsZero() {
http2.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
httputil.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
return
}
validatorsRoot := s.ChainInfoFetcher.GenesisValidatorsRoot()
if bytes.Equal(validatorsRoot[:], params.BeaconConfig().ZeroHash[:]) {
http2.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
httputil.HandleError(w, "Chain genesis info is not yet known", http.StatusNotFound)
return
}
forkVersion := params.BeaconConfig().GenesisForkVersion
@@ -1919,5 +1910,5 @@ func (s *Server) GetGenesis(w http.ResponseWriter, r *http.Request) {
GenesisForkVersion: hexutil.Encode(forkVersion),
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}

View File

@@ -10,6 +10,7 @@ import (
"strings"
"time"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/blocks"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/feed/operation"
@@ -21,7 +22,7 @@ import (
consensus_types "github.com/prysmaticlabs/prysm/v4/consensus-types"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/crypto/bls"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/time/slots"
@@ -36,11 +37,11 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "beacon.ListAttestations")
defer span.End()
ok, rawSlot, slot := shared.UintFromQuery(w, r, "slot")
rawSlot, slot, ok := shared.UintFromQuery(w, r, "slot", false)
if !ok {
return
}
ok, rawCommitteeIndex, committeeIndex := shared.UintFromQuery(w, r, "committee_index")
rawCommitteeIndex, committeeIndex, ok := shared.UintFromQuery(w, r, "committee_index", false)
if !ok {
return
}
@@ -48,7 +49,7 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
attestations := s.AttestationsPool.AggregatedAttestations()
unaggAtts, err := s.AttestationsPool.UnaggregatedAttestations()
if err != nil {
http2.HandleError(w, "Could not get unaggregated attestations: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get unaggregated attestations: "+err.Error(), http.StatusInternalServerError)
return
}
attestations = append(attestations, unaggAtts...)
@@ -56,9 +57,9 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
if isEmptyReq {
allAtts := make([]*shared.Attestation, len(attestations))
for i, att := range attestations {
allAtts[i] = shared.AttestationFromConsensus(att)
allAtts[i] = shared.AttFromConsensus(att)
}
http2.WriteJson(w, &ListAttestationsResponse{Data: allAtts})
httputil.WriteJson(w, &ListAttestationsResponse{Data: allAtts})
return
}
@@ -69,10 +70,10 @@ func (s *Server) ListAttestations(w http.ResponseWriter, r *http.Request) {
slotMatch := rawSlot != "" && att.Data.Slot == primitives.Slot(slot)
shouldAppend := (bothDefined && committeeIndexMatch && slotMatch) || (!bothDefined && (committeeIndexMatch || slotMatch))
if shouldAppend {
filteredAtts = append(filteredAtts, shared.AttestationFromConsensus(att))
filteredAtts = append(filteredAtts, shared.AttFromConsensus(att))
}
}
http2.WriteJson(w, &ListAttestationsResponse{Data: filteredAtts})
httputil.WriteJson(w, &ListAttestationsResponse{Data: filteredAtts})
}
// SubmitAttestations submits an attestation object to node. If the attestation passes all validation
@@ -85,30 +86,30 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
var validAttestations []*eth.Attestation
var attFailures []*shared.IndexedVerificationFailure
var attFailures []*server.IndexedVerificationFailure
for i, sourceAtt := range req.Data {
att, err := sourceAtt.ToConsensus()
if err != nil {
attFailures = append(attFailures, &shared.IndexedVerificationFailure{
attFailures = append(attFailures, &server.IndexedVerificationFailure{
Index: i,
Message: "Could not convert request attestation to consensus attestation: " + err.Error(),
})
continue
}
if _, err = bls.SignatureFromBytes(att.Signature); err != nil {
attFailures = append(attFailures, &shared.IndexedVerificationFailure{
attFailures = append(attFailures, &server.IndexedVerificationFailure{
Index: i,
Message: "Incorrect attestation signature: " + err.Error(),
})
@@ -136,7 +137,7 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
wantedEpoch := slots.ToEpoch(att.Data.Slot)
vals, err := s.HeadFetcher.HeadValidatorsIndices(ctx, wantedEpoch)
if err != nil {
http2.HandleError(w, "Could not get head validator indices: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head validator indices: "+err.Error(), http.StatusInternalServerError)
return
}
subnet := corehelpers.ComputeSubnetFromCommitteeAndSlot(uint64(len(vals)), att.Data.CommitteeIndex, att.Data.Slot)
@@ -156,7 +157,7 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
}
}
if len(failedBroadcasts) > 0 {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Attestations at index %s could not be broadcasted", strings.Join(failedBroadcasts, ", ")),
http.StatusInternalServerError,
@@ -165,12 +166,12 @@ func (s *Server) SubmitAttestations(w http.ResponseWriter, r *http.Request) {
}
if len(attFailures) > 0 {
failuresErr := &shared.IndexedVerificationFailureError{
failuresErr := &server.IndexedVerificationFailureError{
Code: http.StatusBadRequest,
Message: "One or more attestations failed validation",
Failures: attFailures,
}
http2.WriteError(w, failuresErr)
httputil.WriteError(w, failuresErr)
}
}
@@ -182,15 +183,15 @@ func (s *Server) ListVoluntaryExits(w http.ResponseWriter, r *http.Request) {
sourceExits, err := s.VoluntaryExitsPool.PendingExits()
if err != nil {
http2.HandleError(w, "Could not get exits from the pool: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get exits from the pool: "+err.Error(), http.StatusInternalServerError)
return
}
exits := make([]*shared.SignedVoluntaryExit, len(sourceExits))
for i, e := range sourceExits {
exits[i] = shared.SignedVoluntaryExitFromConsensus(e)
exits[i] = shared.SignedExitFromConsensus(e)
}
http2.WriteJson(w, &ListVoluntaryExitsResponse{Data: exits})
httputil.WriteJson(w, &ListVoluntaryExitsResponse{Data: exits})
}
// SubmitVoluntaryExit submits a SignedVoluntaryExit object to node's pool
@@ -203,51 +204,51 @@ func (s *Server) SubmitVoluntaryExit(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
exit, err := req.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request exit to consensus exit: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request exit to consensus exit: "+err.Error(), http.StatusBadRequest)
return
}
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
epochStart, err := slots.EpochStart(exit.Exit.Epoch)
if err != nil {
http2.HandleError(w, "Could not get epoch start: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get epoch start: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, epochStart)
if err != nil {
http2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
val, err := headState.ValidatorAtIndexReadOnly(exit.Exit.ValidatorIndex)
if err != nil {
if errors.Is(err, consensus_types.ErrOutOfBounds) {
http2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
return
}
http2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
return
}
if err = blocks.VerifyExitAndSignature(val, headState, exit); err != nil {
http2.HandleError(w, "Invalid exit: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid exit: "+err.Error(), http.StatusBadRequest)
return
}
s.VoluntaryExitsPool.InsertVoluntaryExit(exit)
if err = s.Broadcaster.Broadcast(ctx, exit); err != nil {
http2.HandleError(w, "Could not broadcast exit: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not broadcast exit: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -261,23 +262,23 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
var validMessages []*eth.SyncCommitteeMessage
var msgFailures []*shared.IndexedVerificationFailure
var msgFailures []*server.IndexedVerificationFailure
for i, sourceMsg := range req.Data {
msg, err := sourceMsg.ToConsensus()
if err != nil {
msgFailures = append(msgFailures, &shared.IndexedVerificationFailure{
msgFailures = append(msgFailures, &server.IndexedVerificationFailure{
Index: i,
Message: "Could not convert request message to consensus message: " + err.Error(),
})
@@ -288,18 +289,18 @@ func (s *Server) SubmitSyncCommitteeSignatures(w http.ResponseWriter, r *http.Re
for _, msg := range validMessages {
if rpcerr := s.CoreService.SubmitSyncMessage(ctx, msg); rpcerr != nil {
http2.HandleError(w, "Could not submit message: "+rpcerr.Err.Error(), core.ErrorReasonToHTTP(rpcerr.Reason))
httputil.HandleError(w, "Could not submit message: "+rpcerr.Err.Error(), core.ErrorReasonToHTTP(rpcerr.Reason))
return
}
}
if len(msgFailures) > 0 {
failuresErr := &shared.IndexedVerificationFailureError{
failuresErr := &server.IndexedVerificationFailureError{
Code: http.StatusBadRequest,
Message: "One or more messages failed validation",
Failures: msgFailures,
}
http2.WriteError(w, failuresErr)
httputil.WriteError(w, failuresErr)
}
}
@@ -310,31 +311,31 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
defer span.End()
st, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get head state: %v", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get head state: %v", err), http.StatusInternalServerError)
return
}
var failures []*shared.IndexedVerificationFailure
var failures []*server.IndexedVerificationFailure
var toBroadcast []*eth.SignedBLSToExecutionChange
var req []*shared.SignedBLSToExecutionChange
err = json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
for i, change := range req {
sbls, err := change.ToConsensus()
if err != nil {
failures = append(failures, &shared.IndexedVerificationFailure{
failures = append(failures, &server.IndexedVerificationFailure{
Index: i,
Message: "Unable to decode SignedBLSToExecutionChange: " + err.Error(),
})
@@ -342,14 +343,14 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
}
_, err = blocks.ValidateBLSToExecutionChange(st, sbls)
if err != nil {
failures = append(failures, &shared.IndexedVerificationFailure{
failures = append(failures, &server.IndexedVerificationFailure{
Index: i,
Message: "Could not validate SignedBLSToExecutionChange: " + err.Error(),
})
continue
}
if err := blocks.VerifyBLSChangeSignature(st, sbls); err != nil {
failures = append(failures, &shared.IndexedVerificationFailure{
failures = append(failures, &server.IndexedVerificationFailure{
Index: i,
Message: "Could not validate signature: " + err.Error(),
})
@@ -368,12 +369,12 @@ func (s *Server) SubmitBLSToExecutionChanges(w http.ResponseWriter, r *http.Requ
}
go s.broadcastBLSChanges(ctx, toBroadcast)
if len(failures) > 0 {
failuresErr := &shared.IndexedVerificationFailureError{
failuresErr := &server.IndexedVerificationFailureError{
Code: http.StatusBadRequest,
Message: "One or more BLSToExecutionChange failed validation",
Failures: failures,
}
http2.WriteError(w, failuresErr)
httputil.WriteError(w, failuresErr)
}
}
@@ -432,18 +433,12 @@ func (s *Server) ListBLSToExecutionChanges(w http.ResponseWriter, r *http.Reques
sourceChanges, err := s.BLSChangesPool.PendingBLSToExecChanges()
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get BLS to execution changes: %v", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get BLS to execution changes: %v", err), http.StatusInternalServerError)
return
}
changes, err := shared.SignedBlsToExecutionChangesFromConsensus(sourceChanges)
if err != nil {
http2.HandleError(w, "failed to decode SignedBlsToExecutionChanges: "+err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &BLSToExecutionChangesPoolResponse{
Data: changes,
httputil.WriteJson(w, &BLSToExecutionChangesPoolResponse{
Data: shared.SignedBLSChangesFromConsensus(sourceChanges),
})
}
@@ -455,13 +450,13 @@ func (s *Server) GetAttesterSlashings(w http.ResponseWriter, r *http.Request) {
headState, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
sourceSlashings := s.SlashingsPool.PendingAttesterSlashings(ctx, headState, true /* return unlimited slashings */)
slashings := shared.AttesterSlashingsFromConsensus(sourceSlashings)
http2.WriteJson(w, &GetAttesterSlashingsResponse{Data: slashings})
httputil.WriteJson(w, &GetAttesterSlashingsResponse{Data: slashings})
}
// SubmitAttesterSlashing submits an attester slashing object to node's pool and
@@ -474,41 +469,41 @@ func (s *Server) SubmitAttesterSlashing(w http.ResponseWriter, r *http.Request)
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, slashing.Attestation_1.Data.Slot)
if err != nil {
http2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
err = blocks.VerifyAttesterSlashing(ctx, headState, slashing)
if err != nil {
http2.HandleError(w, "Invalid attester slashing: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid attester slashing: "+err.Error(), http.StatusBadRequest)
return
}
err = s.SlashingsPool.InsertAttesterSlashing(ctx, headState, slashing)
if err != nil {
http2.HandleError(w, "Could not insert attester slashing into pool: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not insert attester slashing into pool: "+err.Error(), http.StatusInternalServerError)
return
}
if !features.Get().DisableBroadcastSlashings {
if err = s.Broadcaster.Broadcast(ctx, slashing); err != nil {
http2.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -522,13 +517,13 @@ func (s *Server) GetProposerSlashings(w http.ResponseWriter, r *http.Request) {
headState, err := s.ChainInfoFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
sourceSlashings := s.SlashingsPool.PendingProposerSlashings(ctx, headState, true /* return unlimited slashings */)
slashings := shared.ProposerSlashingsFromConsensus(sourceSlashings)
http2.WriteJson(w, &GetProposerSlashingsResponse{Data: slashings})
httputil.WriteJson(w, &GetProposerSlashingsResponse{Data: slashings})
}
// SubmitProposerSlashing submits a proposer slashing object to node's pool and if
@@ -541,42 +536,42 @@ func (s *Server) SubmitProposerSlashing(w http.ResponseWriter, r *http.Request)
err := json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
slashing, err := req.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request slashing to consensus slashing: "+err.Error(), http.StatusBadRequest)
return
}
headState, err := s.ChainInfoFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
headState, err = transition.ProcessSlotsIfPossible(ctx, headState, slashing.Header_1.Header.Slot)
if err != nil {
http2.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not process slots: "+err.Error(), http.StatusInternalServerError)
return
}
err = blocks.VerifyProposerSlashing(headState, slashing)
if err != nil {
http2.HandleError(w, "Invalid proposer slashing: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid proposer slashing: "+err.Error(), http.StatusBadRequest)
return
}
err = s.SlashingsPool.InsertProposerSlashing(ctx, headState, slashing)
if err != nil {
http2.HandleError(w, "Could not insert proposer slashing into pool: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not insert proposer slashing into pool: "+err.Error(), http.StatusInternalServerError)
return
}
if !features.Get().DisableBroadcastSlashings {
if err = s.Broadcaster.Broadcast(ctx, slashing); err != nil {
http2.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not broadcast slashing object: "+err.Error(), http.StatusInternalServerError)
return
}
}

View File

@@ -13,6 +13,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/go-bitfield"
"github.com/prysmaticlabs/prysm/v4/api/server"
blockchainmock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/signing"
prysmtime "github.com/prysmaticlabs/prysm/v4/beacon-chain/core/time"
@@ -34,7 +35,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/crypto/hash"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v4/encoding/ssz"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpbv1alpha1 "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -275,7 +276,7 @@ func TestSubmitAttestations(t *testing.T) {
s.SubmitAttestations(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -290,7 +291,7 @@ func TestSubmitAttestations(t *testing.T) {
s.SubmitAttestations(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -305,7 +306,7 @@ func TestSubmitAttestations(t *testing.T) {
s.SubmitAttestations(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &shared.IndexedVerificationFailureError{}
e := &server.IndexedVerificationFailureError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.Equal(t, 1, len(e.Failures))
@@ -433,7 +434,7 @@ func TestSubmitVoluntaryExit(t *testing.T) {
s := &Server{}
s.SubmitVoluntaryExit(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -449,7 +450,7 @@ func TestSubmitVoluntaryExit(t *testing.T) {
s := &Server{}
s.SubmitVoluntaryExit(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -466,7 +467,7 @@ func TestSubmitVoluntaryExit(t *testing.T) {
s.SubmitVoluntaryExit(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Invalid exit"))
@@ -495,7 +496,7 @@ func TestSubmitVoluntaryExit(t *testing.T) {
s.SubmitVoluntaryExit(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Could not get validator"))
@@ -590,7 +591,7 @@ func TestSubmitSyncCommitteeSignatures(t *testing.T) {
s.SubmitSyncCommitteeSignatures(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
require.NoError(t, err)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
msgsInPool, err := s.CoreService.SyncCommitteePool.SyncCommitteeMessages(1)
@@ -610,7 +611,7 @@ func TestSubmitSyncCommitteeSignatures(t *testing.T) {
s.SubmitSyncCommitteeSignatures(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -624,7 +625,7 @@ func TestSubmitSyncCommitteeSignatures(t *testing.T) {
s.SubmitSyncCommitteeSignatures(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -659,15 +660,11 @@ func TestListBLSToExecutionChanges(t *testing.T) {
s.ListBLSToExecutionChanges(writer, request)
assert.Equal(t, http.StatusOK, writer.Code)
json1, err := shared.SignedBlsToExecutionChangeFromConsensus(change1)
require.NoError(t, err)
json2, err := shared.SignedBlsToExecutionChangeFromConsensus(change2)
require.NoError(t, err)
resp := &BLSToExecutionChangesPoolResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.Equal(t, 2, len(resp.Data))
assert.DeepEqual(t, json1, resp.Data[0])
assert.DeepEqual(t, json2, resp.Data[1])
assert.DeepEqual(t, shared.SignedBLSChangeFromConsensus(change1), resp.Data[0])
assert.DeepEqual(t, shared.SignedBLSChangeFromConsensus(change2), resp.Data[1])
}
func TestSubmitSignedBLSToExecutionChanges_Ok(t *testing.T) {
@@ -729,10 +726,8 @@ func TestSubmitSignedBLSToExecutionChanges_Ok(t *testing.T) {
for i, message := range blsChanges {
signature, err := signing.ComputeDomainAndSign(st, prysmtime.CurrentEpoch(st), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
m, err := shared.BlsToExecutionChangeFromConsensus(message)
require.NoError(t, err)
signed := &shared.SignedBLSToExecutionChange{
Message: m,
Message: shared.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
signedChanges[i] = signed
@@ -844,11 +839,8 @@ func TestSubmitSignedBLSToExecutionChanges_Bellatrix(t *testing.T) {
signature, err := signing.ComputeDomainAndSign(stc, prysmtime.CurrentEpoch(stc), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
bl, err := shared.BlsToExecutionChangeFromConsensus(message)
require.NoError(t, err)
signedChanges[i] = &shared.SignedBLSToExecutionChange{
Message: bl,
Message: shared.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
}
@@ -946,14 +938,11 @@ func TestSubmitSignedBLSToExecutionChanges_Failures(t *testing.T) {
for i, message := range blsChanges {
signature, err := signing.ComputeDomainAndSign(st, prysmtime.CurrentEpoch(st), message, params.BeaconConfig().DomainBLSToExecutionChange, privKeys[i])
require.NoError(t, err)
bl, err := shared.BlsToExecutionChangeFromConsensus(message)
require.NoError(t, err)
if i == 1 {
signature[0] = 0x00
}
signedChanges[i] = &shared.SignedBLSToExecutionChange{
Message: bl,
Message: shared.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
}
}
@@ -986,15 +975,10 @@ func TestSubmitSignedBLSToExecutionChanges_Failures(t *testing.T) {
poolChanges, err := s.BLSChangesPool.PendingBLSToExecChanges()
require.Equal(t, len(poolChanges)+1, len(signedChanges))
require.NoError(t, err)
v2Change, err := shared.SignedBlsToExecutionChangeFromConsensus(poolChanges[0])
require.NoError(t, err)
require.DeepEqual(t, v2Change, signedChanges[0])
require.DeepEqual(t, shared.SignedBLSChangeFromConsensus(poolChanges[0]), signedChanges[0])
for i := 2; i < numValidators; i++ {
v2Change, err := shared.SignedBlsToExecutionChangeFromConsensus(poolChanges[i-1])
require.NoError(t, err)
require.DeepEqual(t, v2Change, signedChanges[i])
require.DeepEqual(t, shared.SignedBLSChangeFromConsensus(poolChanges[i-1]), signedChanges[i])
}
}
@@ -1358,7 +1342,7 @@ func TestSubmitAttesterSlashing_InvalidSlashing(t *testing.T) {
s.SubmitAttesterSlashing(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Invalid attester slashing", e.Message)
@@ -1549,7 +1533,7 @@ func TestSubmitProposerSlashing_InvalidSlashing(t *testing.T) {
s.SubmitProposerSlashing(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Invalid proposer slashing", e.Message)

View File

@@ -16,7 +16,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/time/slots"
"go.opencensus.io/trace"
@@ -34,20 +34,20 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
stateRoot, err := s.Stater.StateRoot(ctx, []byte(stateId))
if err != nil {
if rootNotFoundErr, ok := err.(*lookup.StateRootNotFoundError); ok {
http2.HandleError(w, "State root not found: "+rootNotFoundErr.Error(), http.StatusNotFound)
httputil.HandleError(w, "State root not found: "+rootNotFoundErr.Error(), http.StatusNotFound)
return
} else if parseErr, ok := err.(*lookup.StateIdParseError); ok {
http2.HandleError(w, "Invalid state ID: "+parseErr.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid state ID: "+parseErr.Error(), http.StatusBadRequest)
return
}
http2.HandleError(w, "Could not get state root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get state root: "+err.Error(), http.StatusInternalServerError)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -57,12 +57,12 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -74,7 +74,7 @@ func (s *Server) GetStateRoot(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetRandao fetches the RANDAO mix for the requested epoch from the state identified by state_id.
@@ -87,10 +87,10 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
ok, rawEpoch, e := shared.UintFromQuery(w, r, "epoch")
rawEpoch, e, ok := shared.UintFromQuery(w, r, "epoch", false)
if !ok {
return
}
@@ -114,25 +114,25 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
randaoEpochLowerBound = uint64(stEpoch) - uint64(st.RandaoMixesLength())
}
if epoch > stEpoch || uint64(epoch) < randaoEpochLowerBound+1 {
http2.HandleError(w, "Epoch is out of range for the randao mixes of the state", http.StatusBadRequest)
httputil.HandleError(w, "Epoch is out of range for the randao mixes of the state", http.StatusBadRequest)
return
}
idx := epoch % params.BeaconConfig().EpochsPerHistoricalVector
randao, err := st.RandaoMixAtIndex(uint64(idx))
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get randao mix at index %d: %v", idx, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get randao mix at index %d: %v", idx, err), http.StatusInternalServerError)
return
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -142,7 +142,7 @@ func (s *Server) GetRandao(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetSyncCommittees retrieves the sync committees for the given epoch.
@@ -153,10 +153,10 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
ok, rawEpoch, e := shared.UintFromQuery(w, r, "epoch")
rawEpoch, e, ok := shared.UintFromQuery(w, r, "epoch", false)
if !ok {
return
}
@@ -166,7 +166,7 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
currentEpoch := slots.ToEpoch(currentSlot)
currentPeriodStartEpoch, err := slots.SyncCommitteePeriodStartEpoch(currentEpoch)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not calculate start period for slot %d: %v", currentSlot, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not calculate start period for slot %d: %v", currentSlot, err), http.StatusInternalServerError)
return
}
@@ -174,11 +174,11 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
if rawEpoch != "" {
reqPeriodStartEpoch, err := slots.SyncCommitteePeriodStartEpoch(epoch)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not calculate start period for epoch %d: %v", e, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not calculate start period for epoch %d: %v", e, err), http.StatusInternalServerError)
return
}
if reqPeriodStartEpoch > currentPeriodStartEpoch+params.BeaconConfig().EpochsPerSyncCommitteePeriod {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Could not fetch sync committee too far in the future (requested epoch %d, current epoch %d)", e, currentEpoch),
http.StatusBadRequest,
@@ -209,32 +209,32 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
// Get the next sync committee and sync committee indices from the state.
committeeIndices, committee, err = nextCommitteeIndicesFromState(st)
if err != nil {
http2.HandleError(w, "Could not get next sync committee indices: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get next sync committee indices: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
// Get the current sync committee and sync committee indices from the state.
committeeIndices, committee, err = currentCommitteeIndicesFromState(st)
if err != nil {
http2.HandleError(w, "Could not get current sync committee indices: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get current sync committee indices: "+err.Error(), http.StatusInternalServerError)
return
}
}
subcommittees, err := extractSyncSubcommittees(st, committee)
if err != nil {
http2.HandleError(w, "Could not extract sync subcommittees: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not extract sync subcommittees: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -247,7 +247,7 @@ func (s *Server) GetSyncCommittees(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
func committeeIndicesFromState(st state.BeaconState, committee *ethpbalpha.SyncCommittee) ([]string, *ethpbalpha.SyncCommittee, error) {
@@ -317,7 +317,7 @@ func (s *Server) stateForSyncCommittee(ctx context.Context, w http.ResponseWrite
if req.epoch != nil {
slot, err := slots.EpochStart(*req.epoch)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not calculate start slot for epoch %d: %v", *req.epoch, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not calculate start slot for epoch %d: %v", *req.epoch, err), http.StatusInternalServerError)
return nil, false
}
st, err := s.Stater.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10)))

View File

@@ -20,7 +20,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -216,7 +216,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.StringContains(t, "Epoch is out of range for the randao mixes of the state", e.Message)
@@ -230,7 +230,7 @@ func TestGetRandao(t *testing.T) {
s.GetRandao(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.StringContains(t, "Epoch is out of range for the randao mixes of the state", e.Message)
@@ -617,7 +617,7 @@ func TestGetSyncCommittees_Future(t *testing.T) {
writer.Body = &bytes.Buffer{}
s.GetSyncCommittees(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Could not fetch sync committee too far in the future", e.Message)

View File

@@ -34,7 +34,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
@@ -990,12 +990,10 @@ func TestPublishBlock(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Phase0)
converted, err := shared.BeaconBlockFromConsensus(block.Phase0.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockFromConsensus(block.Phase0.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1013,12 +1011,10 @@ func TestPublishBlock(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Altair)
converted, err := shared.BeaconBlockAltairFromConsensus(block.Altair.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockAltairFromConsensus(block.Altair.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1243,12 +1239,10 @@ func TestPublishBlindedBlock(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Phase0)
converted, err := shared.BeaconBlockFromConsensus(block.Phase0.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockFromConsensus(block.Phase0.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1266,12 +1260,10 @@ func TestPublishBlindedBlock(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Altair)
converted, err := shared.BeaconBlockAltairFromConsensus(block.Altair.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockAltairFromConsensus(block.Altair.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1498,12 +1490,10 @@ func TestPublishBlockV2(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Phase0)
converted, err := shared.BeaconBlockFromConsensus(block.Phase0.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockFromConsensus(block.Phase0.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1521,12 +1511,10 @@ func TestPublishBlockV2(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Altair)
converted, err := shared.BeaconBlockAltairFromConsensus(block.Altair.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockAltairFromConsensus(block.Altair.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1751,12 +1739,10 @@ func TestPublishBlindedBlockV2(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Phase0)
converted, err := shared.BeaconBlockFromConsensus(block.Phase0.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlock
err = json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
err := json.Unmarshal([]byte(rpctesting.Phase0Block), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockFromConsensus(block.Phase0.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -1774,12 +1760,10 @@ func TestPublishBlindedBlockV2(t *testing.T) {
v1alpha1Server := mock2.NewMockBeaconNodeValidatorServer(ctrl)
v1alpha1Server.EXPECT().ProposeBeaconBlock(gomock.Any(), mock.MatchedBy(func(req *eth.GenericSignedBeaconBlock) bool {
block, ok := req.Block.(*eth.GenericSignedBeaconBlock_Altair)
converted, err := shared.BeaconBlockAltairFromConsensus(block.Altair.Block)
require.NoError(t, err)
var signedblock *shared.SignedBeaconBlockAltair
err = json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
err := json.Unmarshal([]byte(rpctesting.AltairBlock), &signedblock)
require.NoError(t, err)
require.DeepEqual(t, converted, signedblock.Message)
require.DeepEqual(t, shared.BeaconBlockAltairFromConsensus(block.Altair.Block), signedblock.Message)
return ok
}))
server := &Server{
@@ -2610,12 +2594,16 @@ func TestGetBlockHeaders(t *testing.T) {
t.Run("list headers", func(t *testing.T) {
wsb, err := blocks.NewSignedBeaconBlock(headBlock.Block.(*eth.BeaconBlockContainer_Phase0Block).Phase0Block)
require.NoError(t, err)
st, err := util.NewBeaconState()
require.NoError(t, err)
require.NoError(t, st.SetSlot(30))
mockChainFetcher := &chainMock.ChainService{
DB: beaconDB,
Block: wsb,
Root: headBlock.BlockRoot,
FinalizedCheckPoint: &eth.Checkpoint{Root: blkContainers[64].BlockRoot},
FinalizedRoots: map[[32]byte]bool{},
State: st,
}
bs := &Server{
BeaconDB: beaconDB,
@@ -2626,15 +2614,22 @@ func TestGetBlockHeaders(t *testing.T) {
tests := []struct {
name string
slot primitives.Slot
slot string
parentRoot string
want []*eth.SignedBeaconBlock
wantErr bool
}{
{
name: "slot",
slot: primitives.Slot(30),
parentRoot: "",
name: "none",
want: []*eth.SignedBeaconBlock{
blkContainers[30].Block.(*eth.BeaconBlockContainer_Phase0Block).Phase0Block,
b1,
b2,
},
},
{
name: "slot",
slot: "30",
want: []*eth.SignedBeaconBlock{
blkContainers[30].Block.(*eth.BeaconBlockContainer_Phase0Block).Phase0Block,
b1,
@@ -2654,7 +2649,7 @@ func TestGetBlockHeaders(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
urlWithParams := fmt.Sprintf("%s?slot=%d&parent_root=%s", url, tt.slot, tt.parentRoot)
urlWithParams := fmt.Sprintf("%s?slot=%s&parent_root=%s", url, tt.slot, tt.parentRoot)
request := httptest.NewRequest(http.MethodGet, urlWithParams, nil)
writer := httptest.NewRecorder()
@@ -2798,7 +2793,7 @@ func TestGetBlockHeaders(t *testing.T) {
bs.GetBlockHeaders(writer, request)
require.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.StringContains(t, "No blocks found", e.Message)
@@ -2854,7 +2849,7 @@ func TestServer_GetBlockHeader(t *testing.T) {
s.GetBlockHeader(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "block_id is required in URL params", e.Message)
@@ -2993,7 +2988,7 @@ func TestGetFinalityCheckpoints(t *testing.T) {
s.GetFinalityCheckpoints(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "state_id is required in URL params", e.Message)
@@ -3006,7 +3001,7 @@ func TestGetFinalityCheckpoints(t *testing.T) {
s.GetFinalityCheckpoints(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.StringContains(t, "State not found", e.Message)
@@ -3111,7 +3106,7 @@ func TestGetGenesis(t *testing.T) {
s.GetGenesis(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.StringContains(t, "Chain genesis info is not yet known", e.Message)
@@ -3132,7 +3127,7 @@ func TestGetGenesis(t *testing.T) {
s.GetGenesis(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.StringContains(t, "Chain genesis info is not yet known", e.Message)

View File

@@ -18,7 +18,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/consensus-types/validator"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/time/slots"
"go.opencensus.io/trace"
)
@@ -30,7 +30,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -41,12 +41,12 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -56,10 +56,10 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
err = json.NewDecoder(r.Body).Decode(&req)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
}
@@ -88,7 +88,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
return
}
@@ -105,7 +105,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorSubStatus(val, epoch)
if err != nil {
http2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
if len(ids) == 0 {
@@ -119,7 +119,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
return
}
@@ -127,7 +127,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for _, ss := range statuses {
ok, vs := validator.StatusFromString(ss)
if !ok {
http2.HandleError(w, "Invalid status "+ss, http.StatusBadRequest)
httputil.HandleError(w, "Invalid status "+ss, http.StatusBadRequest)
return
}
filteredStatuses[vs] = true
@@ -136,12 +136,12 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
for i, val := range readOnlyVals {
valStatus, err := helpers.ValidatorStatus(val, epoch)
if err != nil {
http2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
valSubStatus, err := helpers.ValidatorSubStatus(val, epoch)
if err != nil {
http2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
if filteredStatuses[valStatus] || filteredStatuses[valSubStatus] {
@@ -160,7 +160,7 @@ func (s *Server) GetValidators(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetValidator returns a validator specified by state and id or public key along with status and balance.
@@ -170,12 +170,12 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
valId := mux.Vars(r)["validator_id"]
if valId == "" {
http2.HandleError(w, "validator_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "validator_id is required in URL params", http.StatusBadRequest)
return
}
@@ -193,29 +193,29 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
return
}
if len(ids) == 0 || len(readOnlyVals) == 0 {
http2.HandleError(w, "No validator returned for the given ID", http.StatusInternalServerError)
httputil.HandleError(w, "No validator returned for the given ID", http.StatusInternalServerError)
return
}
valSubStatus, err := helpers.ValidatorSubStatus(readOnlyVals[0], slots.ToEpoch(st.Slot()))
if err != nil {
http2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
bal, err := st.BalanceAtIndex(ids[0])
if err != nil {
http2.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator balance: "+err.Error(), http.StatusInternalServerError)
return
}
container := valContainerFromReadOnlyVal(readOnlyVals[0], ids[0], bal, valSubStatus)
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -225,36 +225,36 @@ func (s *Server) GetValidator(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetValidatorBalances returns a filterable list of validator balances.
func (bs *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
func (s *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.GetValidatorBalances")
defer span.End()
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := bs.Stater.State(ctx, []byte(stateId))
st, err := s.Stater.State(ctx, []byte(stateId))
if err != nil {
shared.WriteStateFetchError(w, err)
return
}
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), bs.OptimisticModeFetcher, bs.Stater, bs.ChainInfoFetcher, bs.BeaconDB)
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateId), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := bs.FinalizationFetcher.IsFinalized(ctx, blockRoot)
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
var rawIds []string
if r.Method == http.MethodGet {
@@ -263,10 +263,10 @@ func (bs *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
err = json.NewDecoder(r.Body).Decode(&rawIds)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
}
@@ -282,7 +282,7 @@ func (bs *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
return
}
@@ -311,7 +311,7 @@ func (bs *Server) GetValidatorBalances(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// decodeIds takes in a list of validator ID strings (as either a pubkey or a validator index)
@@ -323,7 +323,7 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
pubkey, err := hexutil.Decode(rawId)
if err == nil {
if len(pubkey) != fieldparams.BLSPubkeyLength {
http2.HandleError(w, fmt.Sprintf("Pubkey length is %d instead of %d", len(pubkey), fieldparams.BLSPubkeyLength), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Pubkey length is %d instead of %d", len(pubkey), fieldparams.BLSPubkeyLength), http.StatusBadRequest)
return nil, false
}
valIndex, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubkey))
@@ -331,7 +331,7 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
if ignoreUnknown {
continue
}
http2.HandleError(w, fmt.Sprintf("Unknown pubkey %s", pubkey), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Unknown pubkey %s", pubkey), http.StatusBadRequest)
return nil, false
}
ids = append(ids, valIndex)
@@ -340,14 +340,14 @@ func decodeIds(w http.ResponseWriter, st state.BeaconState, rawIds []string, ign
index, err := strconv.ParseUint(rawId, 10, 64)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Invalid validator index %s", rawId), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Invalid validator index %s", rawId), http.StatusBadRequest)
return nil, false
}
if index >= numVals {
if ignoreUnknown {
continue
}
http2.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
return nil, false
}
ids = append(ids, primitives.ValidatorIndex(index))
@@ -364,7 +364,7 @@ func valsFromIds(w http.ResponseWriter, st state.BeaconState, ids []primitives.V
for i, val := range allVals {
readOnlyVal, err := statenative.NewValidator(val)
if err != nil {
http2.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
vals[i] = readOnlyVal
@@ -374,13 +374,13 @@ func valsFromIds(w http.ResponseWriter, st state.BeaconState, ids []primitives.V
for _, id := range ids {
val, err := st.ValidatorAtIndex(id)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %s", id, err.Error()), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %s", id, err.Error()), http.StatusInternalServerError)
return nil, false
}
readOnlyVal, err := statenative.NewValidator(val)
if err != nil {
http2.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not convert validator: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
vals = append(vals, readOnlyVal)

View File

@@ -19,7 +19,7 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -173,7 +173,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "state_id is required in URL params", e.Message)
@@ -373,7 +373,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -403,7 +403,7 @@ func TestGetValidators(t *testing.T) {
s.GetValidators(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Could not decode request body", e.Message)
@@ -713,7 +713,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "state_id is required in URL params", e.Message)
@@ -733,7 +733,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "validator_id is required in URL params", e.Message)
@@ -753,7 +753,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Invalid validator index", e.Message)
@@ -773,7 +773,7 @@ func TestGetValidator(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Unknown pubkey", e.Message)
@@ -1021,7 +1021,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidator(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "state_id is required in URL params", e.Message)
@@ -1141,7 +1141,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -1171,7 +1171,7 @@ func TestGetValidatorBalances(t *testing.T) {
s.GetValidatorBalances(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Could not decode request body", e.Message)

View File

@@ -14,7 +14,7 @@ go_library(
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//config/fieldparams:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@io_opencensus_go//trace:go_default_library",
@@ -32,7 +32,7 @@ go_test(
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/verification:go_default_library",
"//config/params:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",

View File

@@ -10,7 +10,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
field_params "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
httputil "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"go.opencensus.io/trace"
)

View File

@@ -17,7 +17,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/verification"
"github.com/prysmaticlabs/prysm/v4/config/params"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -58,7 +58,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "blobs are not supported for Phase 0 fork", e.Message)
@@ -250,7 +250,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "blobs are not supported before Deneb fork", e.Message)
@@ -268,7 +268,7 @@ func TestBlobs(t *testing.T) {
s.Blobs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Invalid block ID"))

View File

@@ -16,7 +16,7 @@ go_library(
"//beacon-chain/rpc/lookup:go_default_library",
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
@@ -36,7 +36,7 @@ go_test(
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//crypto/bls:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",

View File

@@ -12,7 +12,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
"github.com/prysmaticlabs/prysm/v4/time/slots"
)
@@ -22,7 +22,7 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
// Retrieve beacon state
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: "state_id is required in URL params",
Code: http.StatusBadRequest,
})
@@ -30,7 +30,7 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
}
st, err := s.Stater.State(r.Context(), []byte(stateId))
if err != nil {
http2.WriteError(w, handleWrapError(err, "could not retrieve state", http.StatusNotFound))
httputil.WriteError(w, handleWrapError(err, "could not retrieve state", http.StatusNotFound))
return
}
queryParam := r.URL.Query().Get("proposal_slot")
@@ -38,7 +38,7 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
if queryParam != "" {
pSlot, err := strconv.ParseUint(queryParam, 10, 64)
if err != nil {
http2.WriteError(w, handleWrapError(err, "invalid proposal slot value", http.StatusBadRequest))
httputil.WriteError(w, handleWrapError(err, "invalid proposal slot value", http.StatusBadRequest))
return
}
proposalSlot = primitives.Slot(pSlot)
@@ -48,18 +48,18 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
// Perform sanity checks on proposal slot before computing state
capellaStart, err := slots.EpochStart(params.BeaconConfig().CapellaForkEpoch)
if err != nil {
http2.WriteError(w, handleWrapError(err, "could not calculate Capella start slot", http.StatusInternalServerError))
httputil.WriteError(w, handleWrapError(err, "could not calculate Capella start slot", http.StatusInternalServerError))
return
}
if proposalSlot < capellaStart {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: "expected withdrawals are not supported before Capella fork",
Code: http.StatusBadRequest,
})
return
}
if proposalSlot <= st.Slot() {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: fmt.Sprintf("proposal slot must be bigger than state slot. proposal slot: %d, state slot: %d", proposalSlot, st.Slot()),
Code: http.StatusBadRequest,
})
@@ -67,7 +67,7 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
}
lookAheadLimit := uint64(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().MaxSeedLookahead)))
if st.Slot().Add(lookAheadLimit) <= proposalSlot {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: fmt.Sprintf("proposal slot cannot be >= %d slots ahead of state slot", lookAheadLimit),
Code: http.StatusBadRequest,
})
@@ -76,12 +76,12 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
// Get metadata for response
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
http2.WriteError(w, handleWrapError(err, "could not get optimistic mode info", http.StatusInternalServerError))
httputil.WriteError(w, handleWrapError(err, "could not get optimistic mode info", http.StatusInternalServerError))
return
}
root, err := helpers.BlockRootAtSlot(st, st.Slot()-1)
if err != nil {
http2.WriteError(w, handleWrapError(err, "could not get block root", http.StatusInternalServerError))
httputil.WriteError(w, handleWrapError(err, "could not get block root", http.StatusInternalServerError))
return
}
var blockRoot = [32]byte(root)
@@ -89,7 +89,7 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
// Advance state forward to proposal slot
st, err = transition.ProcessSlots(r.Context(), st, proposalSlot)
if err != nil {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: "could not process slots",
Code: http.StatusInternalServerError,
})
@@ -97,13 +97,13 @@ func (s *Server) ExpectedWithdrawals(w http.ResponseWriter, r *http.Request) {
}
withdrawals, err := st.ExpectedWithdrawals()
if err != nil {
http2.WriteError(w, &http2.DefaultErrorJson{
httputil.WriteError(w, &httputil.DefaultErrorJson{
Message: "could not get expected withdrawals",
Code: http.StatusInternalServerError,
})
return
}
http2.WriteJson(w, &ExpectedWithdrawalsResponse{
httputil.WriteJson(w, &ExpectedWithdrawalsResponse{
ExecutionOptimistic: isOptimistic,
Finalized: isFinalized,
Data: buildExpectedWithdrawalsData(withdrawals),
@@ -123,8 +123,8 @@ func buildExpectedWithdrawalsData(withdrawals []*enginev1.Withdrawal) []*Expecte
return data
}
func handleWrapError(err error, message string, code int) *http2.DefaultErrorJson {
return &http2.DefaultErrorJson{
func handleWrapError(err error, message string, code int) *httputil.DefaultErrorJson {
return &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, message).Error(),
Code: code,
}

View File

@@ -16,7 +16,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/crypto/bls"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -96,7 +96,7 @@ func TestExpectedWithdrawals_BadRequest(t *testing.T) {
s.ExpectedWithdrawals(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, testCase.errorMessage, e.Message)

View File

@@ -12,7 +12,7 @@ go_library(
"//beacon-chain/rpc/eth/shared:go_default_library",
"//config/params:go_default_library",
"//network/forks:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@io_opencensus_go//trace:go_default_library",
],

View File

@@ -11,7 +11,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/network/forks"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"go.opencensus.io/trace"
)
@@ -20,7 +20,7 @@ func GetDepositContract(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "config.GetDepositContract")
defer span.End()
http2.WriteJson(w, &GetDepositContractResponse{
httputil.WriteJson(w, &GetDepositContractResponse{
Data: &DepositContractData{
ChainId: strconv.FormatUint(params.BeaconConfig().DepositChainID, 10),
Address: params.BeaconConfig().DepositContractAddress,
@@ -35,7 +35,7 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
schedule := params.BeaconConfig().ForkVersionSchedule
if len(schedule) == 0 {
http2.WriteJson(w, &GetForkScheduleResponse{
httputil.WriteJson(w, &GetForkScheduleResponse{
Data: make([]*shared.Fork, 0),
})
return
@@ -59,7 +59,7 @@ func GetForkSchedule(w http.ResponseWriter, r *http.Request) {
}
}
http2.WriteJson(w, &GetForkScheduleResponse{
httputil.WriteJson(w, &GetForkScheduleResponse{
Data: chainForks,
})
}
@@ -74,10 +74,10 @@ func GetSpec(w http.ResponseWriter, r *http.Request) {
data, err := prepareConfigSpec()
if err != nil {
http2.HandleError(w, "Could not prepare config spec: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not prepare config spec: "+err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &GetSpecResponse{Data: data})
httputil.WriteJson(w, &GetSpecResponse{Data: data})
}
func prepareConfigSpec() (map[string]string, error) {

View File

@@ -16,14 +16,10 @@ go_library(
"//beacon-chain/rpc/eth/helpers:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/state:go_default_library",
"//network/http:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//network/httputil:go_default_library",
"//runtime/version:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_gorilla_mux//:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@io_opencensus_go//trace:go_default_library",
],
)
@@ -38,6 +34,7 @@ go_test(
"//beacon-chain/db/testing:go_default_library",
"//beacon-chain/forkchoice/doubly-linked-tree:go_default_library",
"//beacon-chain/forkchoice/types:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/testutil:go_default_library",
"//encoding/bytesutil:go_default_library",
"//runtime/version:go_default_library",

View File

@@ -11,7 +11,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"go.opencensus.io/trace"
)
@@ -27,7 +27,7 @@ func (s *Server) GetBeaconStateSSZ(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
st, err := s.Stater.State(ctx, []byte(stateId))
@@ -37,10 +37,10 @@ func (s *Server) GetBeaconStateSSZ(w http.ResponseWriter, r *http.Request) {
}
sszState, err := st.MarshalSSZ()
if err != nil {
http2.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszState, "beacon_state.ssz")
httputil.WriteSsz(w, sszState, "beacon_state.ssz")
}
// GetBeaconStateV2 returns the full beacon state for a given state ID.
@@ -50,11 +50,11 @@ func (s *Server) GetBeaconStateV2(w http.ResponseWriter, r *http.Request) {
stateId := mux.Vars(r)["state_id"]
if stateId == "" {
http2.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "state_id is required in URL params", http.StatusBadRequest)
return
}
if http2.SszRequested(r) {
if httputil.SszRequested(r) {
s.getBeaconStateSSZV2(ctx, w, []byte(stateId))
} else {
s.getBeaconStateV2(ctx, w, []byte(stateId))
@@ -71,12 +71,12 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
isOptimistic, err := helpers.IsOptimistic(ctx, id, s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
http2.HandleError(w, "Could not check if state is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check if state is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not calculate root of latest block header: "+err.Error(), http.StatusInternalServerError)
return
}
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
@@ -84,43 +84,43 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
switch st.Version() {
case version.Phase0:
respSt, err = BeaconStateFromConsensus(st)
respSt, err = shared.BeaconStateFromConsensus(st)
if err != nil {
http2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Altair:
respSt, err = BeaconStateAltairFromConsensus(st)
respSt, err = shared.BeaconStateAltairFromConsensus(st)
if err != nil {
http2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Bellatrix:
respSt, err = BeaconStateBellatrixFromConsensus(st)
respSt, err = shared.BeaconStateBellatrixFromConsensus(st)
if err != nil {
http2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Capella:
respSt, err = BeaconStateCapellaFromConsensus(st)
respSt, err = shared.BeaconStateCapellaFromConsensus(st)
if err != nil {
http2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
case version.Deneb:
respSt, err = BeaconStateDenebFromConsensus(st)
respSt, err = shared.BeaconStateDenebFromConsensus(st)
if err != nil {
http2.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, errMsgStateFromConsensus+": "+err.Error(), http.StatusInternalServerError)
return
}
default:
http2.HandleError(w, "Unsupported state version", http.StatusInternalServerError)
httputil.HandleError(w, "Unsupported state version", http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(respSt)
if err != nil {
http2.HandleError(w, "Could not marshal state into JSON: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not marshal state into JSON: "+err.Error(), http.StatusInternalServerError)
return
}
ver := version.String(st.Version())
@@ -131,7 +131,7 @@ func (s *Server) getBeaconStateV2(ctx context.Context, w http.ResponseWriter, id
Data: jsonBytes,
}
w.Header().Set(api.VersionHeader, ver)
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// getBeaconStateSSZV2 returns the SSZ-serialized version of the full beacon state object for given state ID.
@@ -143,11 +143,11 @@ func (s *Server) getBeaconStateSSZV2(ctx context.Context, w http.ResponseWriter,
}
sszState, err := st.MarshalSSZ()
if err != nil {
http2.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not marshal state into SSZ: "+err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set(api.VersionHeader, version.String(st.Version()))
http2.WriteSsz(w, sszState, "beacon_state.ssz")
httputil.WriteSsz(w, sszState, "beacon_state.ssz")
}
// GetForkChoiceHeadsV2 retrieves the leaves of the current fork choice tree.
@@ -162,7 +162,7 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
for i := range headRoots {
isOptimistic, err := s.OptimisticModeFetcher.IsOptimisticForRoot(ctx, headRoots[i])
if err != nil {
http2.HandleError(w, "Could not check if head is optimistic: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check if head is optimistic: "+err.Error(), http.StatusInternalServerError)
return
}
resp.Data[i] = &ForkChoiceHead{
@@ -172,7 +172,7 @@ func (s *Server) GetForkChoiceHeadsV2(w http.ResponseWriter, r *http.Request) {
}
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetForkChoice returns a dump fork choice store.
@@ -182,7 +182,7 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
dump, err := s.ForkchoiceFetcher.ForkChoiceDump(ctx)
if err != nil {
http2.HandleError(w, "Could not get forkchoice dump: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get forkchoice dump: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -218,5 +218,5 @@ func (s *Server) GetForkChoice(w http.ResponseWriter, r *http.Request) {
HeadRoot: hexutil.Encode(dump.HeadRoot),
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}

View File

@@ -15,6 +15,7 @@ import (
dbtest "github.com/prysmaticlabs/prysm/v4/beacon-chain/db/testing"
doublylinkedtree "github.com/prysmaticlabs/prysm/v4/beacon-chain/forkchoice/doubly-linked-tree"
forkchoicetypes "github.com/prysmaticlabs/prysm/v4/beacon-chain/forkchoice/types"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/testutil"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
@@ -73,7 +74,7 @@ func TestGetBeaconStateV2(t *testing.T) {
resp := &GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Phase0), resp.Version)
st := &BeaconState{}
st := &shared.BeaconState{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -101,7 +102,7 @@ func TestGetBeaconStateV2(t *testing.T) {
resp := &GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Altair), resp.Version)
st := &BeaconStateAltair{}
st := &shared.BeaconStateAltair{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -129,7 +130,7 @@ func TestGetBeaconStateV2(t *testing.T) {
resp := &GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Bellatrix), resp.Version)
st := &BeaconStateBellatrix{}
st := &shared.BeaconStateBellatrix{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -157,7 +158,7 @@ func TestGetBeaconStateV2(t *testing.T) {
resp := &GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Capella), resp.Version)
st := &BeaconStateCapella{}
st := &shared.BeaconStateCapella{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})
@@ -185,7 +186,7 @@ func TestGetBeaconStateV2(t *testing.T) {
resp := &GetBeaconStateV2Response{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
assert.Equal(t, version.String(version.Deneb), resp.Version)
st := &BeaconStateDeneb{}
st := &shared.BeaconStateDeneb{}
require.NoError(t, json.Unmarshal(resp.Data, st))
assert.Equal(t, "123", st.Slot)
})

View File

@@ -2,19 +2,10 @@ package debug
import (
"encoding/json"
"fmt"
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
beaconState "github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
var errPayloadHeaderNotFound = errors.New("expected payload header not found")
type GetBeaconStateV2Response struct {
Version string `json:"version"`
ExecutionOptimistic bool `json:"execution_optimistic"`
@@ -22,948 +13,6 @@ type GetBeaconStateV2Response struct {
Data json.RawMessage `json:"data"` // represents the state values based on the version
}
type BeaconState struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *shared.Fork `json:"fork"`
LatestBlockHeader *shared.BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *shared.Eth1Data `json:"eth1_data"`
Eth1DataVotes []*shared.Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochAttestations []*PendingAttestation `json:"previous_epoch_attestations"`
CurrentEpochAttestations []*PendingAttestation `json:"current_epoch_attestations"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *shared.Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *shared.Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
}
func BeaconStateFromConsensus(st beaconState.BeaconState) (*BeaconState, error) {
if st == nil {
return nil, errors.New("state is empty")
}
f, err := shared.ForkFromConsensus(st.Fork())
if err != nil {
return nil, err
}
srcbr := st.BlockRoots()
br := make([]string, len(srcbr))
for i, r := range srcbr {
br[i] = hexutil.Encode(r)
}
srcsr := st.StateRoots()
sr := make([]string, len(srcsr))
for i, r := range srcsr {
sr[i] = hexutil.Encode(r)
}
srchr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srchr))
for i, r := range srchr {
hr[i] = hexutil.Encode(r)
}
e1d, err := shared.Eth1DataFromConsensus(st.Eth1Data())
if err != nil {
return nil, err
}
srcvotes := st.Eth1DataVotes()
votes := make([]*shared.Eth1Data, len(srcvotes))
for i, e := range srcvotes {
votes[i], err = shared.Eth1DataFromConsensus(e)
if err != nil {
return nil, err
}
}
srcvals := st.Validators()
vals := make([]*Validator, len(srcvals))
for i, v := range srcvals {
vals[i], err = ValidatorFromConsensus(v)
if err != nil {
return nil, err
}
}
srcbals := st.Balances()
bals := make([]string, len(srcbals))
for i, b := range srcbals {
bals[i] = fmt.Sprintf("%d", b)
}
srcrm := st.RandaoMixes()
rm := make([]string, len(srcrm))
for i, m := range srcrm {
rm[i] = hexutil.Encode(m)
}
srcslashings := st.Slashings()
slashings := make([]string, len(srcslashings))
for i, s := range srcslashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevAtts, err := st.PreviousEpochAttestations()
if err != nil {
return nil, err
}
prevAtts := make([]*PendingAttestation, len(srcPrevAtts))
for i, a := range srcPrevAtts {
prevAtts[i], err = PendingAttestationFromConsensus(a)
if err != nil {
return nil, err
}
}
srcCurrAtts, err := st.CurrentEpochAttestations()
if err != nil {
return nil, err
}
currAtts := make([]*PendingAttestation, len(srcCurrAtts))
for i, a := range srcCurrAtts {
currAtts[i], err = PendingAttestationFromConsensus(a)
if err != nil {
return nil, err
}
}
return &BeaconState{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: f,
LatestBlockHeader: shared.BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: e1d,
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochAttestations: prevAtts,
CurrentEpochAttestations: currAtts,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: shared.CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: shared.CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: shared.CheckpointFromConsensus(st.FinalizedCheckpoint()),
}, nil
}
type BeaconStateAltair struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *shared.Fork `json:"fork"`
LatestBlockHeader *shared.BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *shared.Eth1Data `json:"eth1_data"`
Eth1DataVotes []*shared.Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *shared.Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *shared.Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
}
func BeaconStateAltairFromConsensus(st beaconState.BeaconState) (*BeaconStateAltair, error) {
if st == nil {
return nil, errors.New("state is empty")
}
f, err := shared.ForkFromConsensus(st.Fork())
if err != nil {
return nil, err
}
srcbr := st.BlockRoots()
br := make([]string, len(srcbr))
for i, r := range srcbr {
br[i] = hexutil.Encode(r)
}
srcsr := st.StateRoots()
sr := make([]string, len(srcsr))
for i, r := range srcsr {
sr[i] = hexutil.Encode(r)
}
srchr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srchr))
for i, r := range srchr {
hr[i] = hexutil.Encode(r)
}
e1d, err := shared.Eth1DataFromConsensus(st.Eth1Data())
if err != nil {
return nil, err
}
srcvotes := st.Eth1DataVotes()
votes := make([]*shared.Eth1Data, len(srcvotes))
for i, e := range srcvotes {
votes[i], err = shared.Eth1DataFromConsensus(e)
if err != nil {
return nil, err
}
}
srcvals := st.Validators()
vals := make([]*Validator, len(srcvals))
for i, v := range srcvals {
vals[i], err = ValidatorFromConsensus(v)
if err != nil {
return nil, err
}
}
srcbals := st.Balances()
bals := make([]string, len(srcbals))
for i, b := range srcbals {
bals[i] = fmt.Sprintf("%d", b)
}
srcrm := st.RandaoMixes()
rm := make([]string, len(srcrm))
for i, m := range srcrm {
rm[i] = hexutil.Encode(m)
}
srcslashings := st.Slashings()
slashings := make([]string, len(srcslashings))
for i, s := range srcslashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcis, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcis))
for i, s := range srcis {
is[i] = fmt.Sprintf("%d", s)
}
srcCurrSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
currSc, err := SyncCommitteeFromConsensus(srcCurrSc)
if err != nil {
return nil, err
}
srcNextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := SyncCommitteeFromConsensus(srcNextSc)
if err != nil {
return nil, err
}
return &BeaconStateAltair{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: f,
LatestBlockHeader: shared.BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: e1d,
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: shared.CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: shared.CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: shared.CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: currSc,
NextSyncCommittee: nextSc,
}, nil
}
type BeaconStateBellatrix struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *shared.Fork `json:"fork"`
LatestBlockHeader *shared.BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *shared.Eth1Data `json:"eth1_data"`
Eth1DataVotes []*shared.Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *shared.Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *shared.Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *shared.ExecutionPayloadHeader `json:"latest_execution_payload_header"`
}
func BeaconStateBellatrixFromConsensus(st beaconState.BeaconState) (*BeaconStateBellatrix, error) {
if st == nil {
return nil, errors.New("state is empty")
}
f, err := shared.ForkFromConsensus(st.Fork())
if err != nil {
return nil, err
}
srcbr := st.BlockRoots()
br := make([]string, len(srcbr))
for i, r := range srcbr {
br[i] = hexutil.Encode(r)
}
srcsr := st.StateRoots()
sr := make([]string, len(srcsr))
for i, r := range srcsr {
sr[i] = hexutil.Encode(r)
}
srchr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srchr))
for i, r := range srchr {
hr[i] = hexutil.Encode(r)
}
e1d, err := shared.Eth1DataFromConsensus(st.Eth1Data())
if err != nil {
return nil, err
}
srcvotes := st.Eth1DataVotes()
votes := make([]*shared.Eth1Data, len(srcvotes))
for i, e := range srcvotes {
votes[i], err = shared.Eth1DataFromConsensus(e)
if err != nil {
return nil, err
}
}
srcvals := st.Validators()
vals := make([]*Validator, len(srcvals))
for i, v := range srcvals {
vals[i], err = ValidatorFromConsensus(v)
if err != nil {
return nil, err
}
}
srcbals := st.Balances()
bals := make([]string, len(srcbals))
for i, b := range srcbals {
bals[i] = fmt.Sprintf("%d", b)
}
srcrm := st.RandaoMixes()
rm := make([]string, len(srcrm))
for i, m := range srcrm {
rm[i] = hexutil.Encode(m)
}
srcslashings := st.Slashings()
slashings := make([]string, len(srcslashings))
for i, s := range srcslashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcis, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcis))
for i, s := range srcis {
is[i] = fmt.Sprintf("%d", s)
}
srcCurrSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
currSc, err := SyncCommitteeFromConsensus(srcCurrSc)
if err != nil {
return nil, err
}
srcNextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := SyncCommitteeFromConsensus(srcNextSc)
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeader)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := shared.ExecutionPayloadHeaderFromConsensus(srcPayload)
if err != nil {
return nil, err
}
return &BeaconStateBellatrix{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: f,
LatestBlockHeader: shared.BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: e1d,
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: shared.CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: shared.CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: shared.CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: currSc,
NextSyncCommittee: nextSc,
LatestExecutionPayloadHeader: payload,
}, nil
}
type BeaconStateCapella struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *shared.Fork `json:"fork"`
LatestBlockHeader *shared.BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *shared.Eth1Data `json:"eth1_data"`
Eth1DataVotes []*shared.Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *shared.Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *shared.Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *shared.ExecutionPayloadHeaderCapella `json:"latest_execution_payload_header"`
NextWithdrawalIndex string `json:"next_withdrawal_index"`
NextWithdrawalValidatorIndex string `json:"next_withdrawal_validator_index"`
HistoricalSummaries []*HistoricalSummary `json:"historical_summaries"`
}
func BeaconStateCapellaFromConsensus(st beaconState.BeaconState) (*BeaconStateCapella, error) {
if st == nil {
return nil, errors.New("state is empty")
}
f, err := shared.ForkFromConsensus(st.Fork())
if err != nil {
return nil, err
}
srcbr := st.BlockRoots()
br := make([]string, len(srcbr))
for i, r := range srcbr {
br[i] = hexutil.Encode(r)
}
srcsr := st.StateRoots()
sr := make([]string, len(srcsr))
for i, r := range srcsr {
sr[i] = hexutil.Encode(r)
}
srchr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srchr))
for i, r := range srchr {
hr[i] = hexutil.Encode(r)
}
e1d, err := shared.Eth1DataFromConsensus(st.Eth1Data())
if err != nil {
return nil, err
}
srcvotes := st.Eth1DataVotes()
votes := make([]*shared.Eth1Data, len(srcvotes))
for i, e := range srcvotes {
votes[i], err = shared.Eth1DataFromConsensus(e)
if err != nil {
return nil, err
}
}
srcvals := st.Validators()
vals := make([]*Validator, len(srcvals))
for i, v := range srcvals {
vals[i], err = ValidatorFromConsensus(v)
if err != nil {
return nil, err
}
}
srcbals := st.Balances()
bals := make([]string, len(srcbals))
for i, b := range srcbals {
bals[i] = fmt.Sprintf("%d", b)
}
srcrm := st.RandaoMixes()
rm := make([]string, len(srcrm))
for i, m := range srcrm {
rm[i] = hexutil.Encode(m)
}
srcslashings := st.Slashings()
slashings := make([]string, len(srcslashings))
for i, s := range srcslashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcis, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcis))
for i, s := range srcis {
is[i] = fmt.Sprintf("%d", s)
}
srcCurrSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
currSc, err := SyncCommitteeFromConsensus(srcCurrSc)
if err != nil {
return nil, err
}
srcNextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := SyncCommitteeFromConsensus(srcNextSc)
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeaderCapella)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := shared.ExecutionPayloadHeaderCapellaFromConsensus(srcPayload)
if err != nil {
return nil, err
}
srchs, err := st.HistoricalSummaries()
if err != nil {
return nil, err
}
hs := make([]*HistoricalSummary, len(srchs))
for i, s := range srchs {
hs[i], err = HistoricalSummaryFromConsensus(s)
if err != nil {
return nil, err
}
}
nwi, err := st.NextWithdrawalIndex()
if err != nil {
return nil, err
}
nwvi, err := st.NextWithdrawalValidatorIndex()
if err != nil {
return nil, err
}
return &BeaconStateCapella{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: f,
LatestBlockHeader: shared.BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: e1d,
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: shared.CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: shared.CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: shared.CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: currSc,
NextSyncCommittee: nextSc,
LatestExecutionPayloadHeader: payload,
NextWithdrawalIndex: fmt.Sprintf("%d", nwi),
NextWithdrawalValidatorIndex: fmt.Sprintf("%d", nwvi),
HistoricalSummaries: hs,
}, nil
}
type BeaconStateDeneb struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *shared.Fork `json:"fork"`
LatestBlockHeader *shared.BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *shared.Eth1Data `json:"eth1_data"`
Eth1DataVotes []*shared.Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *shared.Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *shared.Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *shared.Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *shared.ExecutionPayloadHeaderDeneb `json:"latest_execution_payload_header"`
NextWithdrawalIndex string `json:"next_withdrawal_index"`
NextWithdrawalValidatorIndex string `json:"next_withdrawal_validator_index"`
HistoricalSummaries []*HistoricalSummary `json:"historical_summaries"`
}
func BeaconStateDenebFromConsensus(st beaconState.BeaconState) (*BeaconStateDeneb, error) {
if st == nil {
return nil, errors.New("state is empty")
}
f, err := shared.ForkFromConsensus(st.Fork())
if err != nil {
return nil, err
}
srcbr := st.BlockRoots()
br := make([]string, len(srcbr))
for i, r := range srcbr {
br[i] = hexutil.Encode(r)
}
srcsr := st.StateRoots()
sr := make([]string, len(srcsr))
for i, r := range srcsr {
sr[i] = hexutil.Encode(r)
}
srchr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srchr))
for i, r := range srchr {
hr[i] = hexutil.Encode(r)
}
e1d, err := shared.Eth1DataFromConsensus(st.Eth1Data())
if err != nil {
return nil, err
}
srcvotes := st.Eth1DataVotes()
votes := make([]*shared.Eth1Data, len(srcvotes))
for i, e := range srcvotes {
votes[i], err = shared.Eth1DataFromConsensus(e)
if err != nil {
return nil, err
}
}
srcvals := st.Validators()
vals := make([]*Validator, len(srcvals))
for i, v := range srcvals {
vals[i], err = ValidatorFromConsensus(v)
if err != nil {
return nil, err
}
}
srcbals := st.Balances()
bals := make([]string, len(srcbals))
for i, b := range srcbals {
bals[i] = fmt.Sprintf("%d", b)
}
srcrm := st.RandaoMixes()
rm := make([]string, len(srcrm))
for i, m := range srcrm {
rm[i] = hexutil.Encode(m)
}
srcslashings := st.Slashings()
slashings := make([]string, len(srcslashings))
for i, s := range srcslashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = strconv.FormatUint(uint64(p), 10)
}
srcis, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcis))
for i, s := range srcis {
is[i] = fmt.Sprintf("%d", s)
}
srcCurrSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
currSc, err := SyncCommitteeFromConsensus(srcCurrSc)
if err != nil {
return nil, err
}
srcNextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := SyncCommitteeFromConsensus(srcNextSc)
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeaderDeneb)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := shared.ExecutionPayloadHeaderDenebFromConsensus(srcPayload)
if err != nil {
return nil, err
}
srchs, err := st.HistoricalSummaries()
if err != nil {
return nil, err
}
hs := make([]*HistoricalSummary, len(srchs))
for i, s := range srchs {
hs[i], err = HistoricalSummaryFromConsensus(s)
if err != nil {
return nil, err
}
}
nwi, err := st.NextWithdrawalIndex()
if err != nil {
return nil, err
}
nwvi, err := st.NextWithdrawalValidatorIndex()
if err != nil {
return nil, err
}
return &BeaconStateDeneb{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: f,
LatestBlockHeader: shared.BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: e1d,
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: shared.CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: shared.CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: shared.CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: currSc,
NextSyncCommittee: nextSc,
LatestExecutionPayloadHeader: payload,
NextWithdrawalIndex: fmt.Sprintf("%d", nwi),
NextWithdrawalValidatorIndex: fmt.Sprintf("%d", nwvi),
HistoricalSummaries: hs,
}, nil
}
type Validator struct {
PublicKey string `json:"pubkey"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
EffectiveBalance string `json:"effective_balance"`
Slashed bool `json:"slashed"`
ActivationEligibilityEpoch string `json:"activation_eligibility_epoch"`
ActivationEpoch string `json:"activation_epoch"`
ExitEpoch string `json:"exit_epoch"`
WithdrawableEpoch string `json:"withdrawable_epoch"`
}
func ValidatorFromConsensus(v *eth.Validator) (*Validator, error) {
if v == nil {
return nil, errors.New("validator is empty")
}
return &Validator{
PublicKey: hexutil.Encode(v.PublicKey),
WithdrawalCredentials: hexutil.Encode(v.WithdrawalCredentials),
EffectiveBalance: fmt.Sprintf("%d", v.EffectiveBalance),
Slashed: v.Slashed,
ActivationEligibilityEpoch: fmt.Sprintf("%d", v.ActivationEligibilityEpoch),
ActivationEpoch: fmt.Sprintf("%d", v.ActivationEpoch),
ExitEpoch: fmt.Sprintf("%d", v.ExitEpoch),
WithdrawableEpoch: fmt.Sprintf("%d", v.WithdrawableEpoch),
}, nil
}
type PendingAttestation struct {
AggregationBits string `json:"aggregation_bits"`
Data *shared.AttestationData `json:"data"`
InclusionDelay string `json:"inclusion_delay"`
ProposerIndex string `json:"proposer_index"`
}
func PendingAttestationFromConsensus(a *eth.PendingAttestation) (*PendingAttestation, error) {
if a == nil {
return nil, errors.New("pending attestation is empty")
}
return &PendingAttestation{
AggregationBits: hexutil.Encode(a.AggregationBits),
Data: shared.AttestationDataFromConsensus(a.Data),
InclusionDelay: fmt.Sprintf("%d", a.InclusionDelay),
ProposerIndex: fmt.Sprintf("%d", a.ProposerIndex),
}, nil
}
type SyncCommittee struct {
Pubkeys []string `json:"pubkeys"`
AggregatePubkey string `json:"aggregate_pubkey"`
}
func SyncCommitteeFromConsensus(sc *eth.SyncCommittee) (*SyncCommittee, error) {
if sc == nil {
return nil, errors.New("sync committee is empty")
}
pubkeys := make([]string, len(sc.Pubkeys))
for i, p := range sc.Pubkeys {
pubkeys[i] = hexutil.Encode(p)
}
return &SyncCommittee{
Pubkeys: pubkeys,
AggregatePubkey: hexutil.Encode(sc.AggregatePubkey),
}, nil
}
type HistoricalSummary struct {
BlockSummaryRoot string `json:"block_summary_root"`
StateSummaryRoot string `json:"state_summary_root"`
}
func HistoricalSummaryFromConsensus(summary *eth.HistoricalSummary) (*HistoricalSummary, error) {
if summary == nil {
return nil, errors.New("historical summary is empty")
}
return &HistoricalSummary{
BlockSummaryRoot: hexutil.Encode(summary.BlockSummaryRoot),
StateSummaryRoot: hexutil.Encode(summary.StateSummaryRoot),
}, nil
}
type GetForkChoiceHeadsV2Response struct {
Data []*ForkChoiceHead `json:"data"`
}

View File

@@ -18,7 +18,7 @@ go_library(
"//beacon-chain/core/time:go_default_library",
"//beacon-chain/core/transition:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",

View File

@@ -14,7 +14,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/time"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/transition"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/eth/v1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/time/slots"
@@ -70,19 +70,19 @@ func (s *Server) StreamEvents(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http2.HandleError(w, "Streaming unsupported!", http.StatusInternalServerError)
httputil.HandleError(w, "Streaming unsupported!", http.StatusInternalServerError)
return
}
topics := r.URL.Query()["topics"]
if len(topics) == 0 {
http2.HandleError(w, "No topics specified to subscribe to", http.StatusBadRequest)
httputil.HandleError(w, "No topics specified to subscribe to", http.StatusBadRequest)
return
}
topicsMap := make(map[string]bool)
for _, topic := range topics {
if _, ok := casesHandled[topic]; !ok {
http2.HandleError(w, fmt.Sprintf("Invalid topic: %s", topic), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Invalid topic: %s", topic), http.StatusBadRequest)
return
}
topicsMap[topic] = true
@@ -124,7 +124,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, AttestationTopic)
return
}
att := shared.AttestationFromConsensus(attData.Attestation.Aggregate)
att := shared.AttFromConsensus(attData.Attestation.Aggregate)
send(w, flusher, AttestationTopic, att)
case operation.UnaggregatedAttReceived:
if _, ok := requestedTopics[AttestationTopic]; !ok {
@@ -135,7 +135,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, AttestationTopic)
return
}
att := shared.AttestationFromConsensus(attData.Attestation)
att := shared.AttFromConsensus(attData.Attestation)
send(w, flusher, AttestationTopic, att)
case operation.ExitReceived:
if _, ok := requestedTopics[VoluntaryExitTopic]; !ok {
@@ -146,7 +146,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, VoluntaryExitTopic)
return
}
exit := shared.SignedVoluntaryExitFromConsensus(exitData.Exit)
exit := shared.SignedExitFromConsensus(exitData.Exit)
send(w, flusher, VoluntaryExitTopic, exit)
case operation.SyncCommitteeContributionReceived:
if _, ok := requestedTopics[SyncCommitteeContributionTopic]; !ok {
@@ -168,12 +168,7 @@ func handleBlockOperationEvents(w http.ResponseWriter, flusher http.Flusher, req
write(w, flusher, topicDataMismatch, event.Data, BLSToExecutionChangeTopic)
return
}
change, err := shared.SignedBlsToExecutionChangeFromConsensus(changeData.Change)
if err != nil {
write(w, flusher, err.Error())
return
}
send(w, flusher, BLSToExecutionChangeTopic, change)
send(w, flusher, BLSToExecutionChangeTopic, shared.SignedBLSChangeFromConsensus(changeData.Change))
case operation.BlobSidecarReceived:
if _, ok := requestedTopics[BlobSidecarTopic]; !ok {
return

View File

@@ -19,7 +19,7 @@ go_library(
"//config/params:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",
"//proto/eth/v2:go_default_library",
"//proto/migration:go_default_library",

View File

@@ -16,7 +16,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
types "github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
)
@@ -29,7 +29,7 @@ func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Reques
// Get the block
blockRootParam, err := hexutil.Decode(mux.Vars(req)["block_root"])
if err != nil {
http2.HandleError(w, "invalid block root: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "invalid block root: "+err.Error(), http.StatusBadRequest)
return
}
@@ -42,13 +42,13 @@ func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Reques
// Get the state
state, err := s.Stater.StateBySlot(ctx, blk.Block().Slot())
if err != nil {
http2.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
bootstrap, err := createLightClientBootstrap(ctx, state)
if err != nil {
http2.HandleError(w, "could not get light client bootstrap: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get light client bootstrap: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -57,7 +57,7 @@ func (s *Server) GetLightClientBootstrap(w http.ResponseWriter, req *http.Reques
Data: bootstrap,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetLightClientUpdatesByRange - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/updates.yaml
@@ -71,16 +71,16 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
slotsPerPeriod := uint64(config.EpochsPerSyncCommitteePeriod) * uint64(config.SlotsPerEpoch)
// Adjust count based on configuration
gotCount, _, count := shared.UintFromQuery(w, req, "count")
_, count, gotCount := shared.UintFromQuery(w, req, "count", true)
if !gotCount {
return
} else if count == 0 {
http2.HandleError(w, fmt.Sprintf("got invalid 'count' query variable '%d': count must be greater than 0", count), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("got invalid 'count' query variable '%d': count must be greater than 0", count), http.StatusInternalServerError)
return
}
// Determine the start and end periods
gotStartPeriod, _, startPeriod := shared.UintFromQuery(w, req, "start_period")
_, startPeriod, gotStartPeriod := shared.UintFromQuery(w, req, "start_period", true)
if !gotStartPeriod {
return
}
@@ -92,7 +92,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
// max possible slot is current head
headState, err := s.HeadFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, "could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -215,7 +215,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
}
if len(updates) == 0 {
http2.HandleError(w, "no updates found", http.StatusNotFound)
httputil.HandleError(w, "no updates found", http.StatusNotFound)
return
}
@@ -223,7 +223,7 @@ func (s *Server) GetLightClientUpdatesByRange(w http.ResponseWriter, req *http.R
Updates: updates,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetLightClientFinalityUpdate - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/finality_update.yaml
@@ -243,7 +243,7 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
state, err := s.Stater.StateBySlot(ctx, block.Block().Slot())
if err != nil {
http2.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -251,14 +251,14 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
attestedRoot := block.Block().ParentRoot()
attestedBlock, err := s.Blocker.Block(ctx, attestedRoot[:])
if err != nil || attestedBlock == nil {
http2.HandleError(w, "could not get attested block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get attested block: "+err.Error(), http.StatusInternalServerError)
return
}
attestedSlot := attestedBlock.Block().Slot()
attestedState, err := s.Stater.StateBySlot(ctx, attestedSlot)
if err != nil {
http2.HandleError(w, "could not get attested state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get attested state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -281,7 +281,7 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
finalizedBlock,
)
if err != nil {
http2.HandleError(w, "could not get light client finality update: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get light client finality update: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -290,7 +290,7 @@ func (s *Server) GetLightClientFinalityUpdate(w http.ResponseWriter, req *http.R
Data: update,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetLightClientOptimisticUpdate - implements https://github.com/ethereum/beacon-APIs/blob/263f4ed6c263c967f13279c7a9f5629b51c5fc55/apis/beacon/light_client/optimistic_update.yaml
@@ -308,7 +308,7 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
state, err := s.Stater.StateBySlot(ctx, block.Block().Slot())
if err != nil {
http2.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -316,18 +316,18 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
attestedRoot := block.Block().ParentRoot()
attestedBlock, err := s.Blocker.Block(ctx, attestedRoot[:])
if err != nil {
http2.HandleError(w, "could not get attested block: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get attested block: "+err.Error(), http.StatusInternalServerError)
return
}
if attestedBlock == nil {
http2.HandleError(w, "attested block is nil", http.StatusInternalServerError)
httputil.HandleError(w, "attested block is nil", http.StatusInternalServerError)
return
}
attestedSlot := attestedBlock.Block().Slot()
attestedState, err := s.Stater.StateBySlot(ctx, attestedSlot)
if err != nil {
http2.HandleError(w, "could not get attested state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get attested state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -338,7 +338,7 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
attestedState,
)
if err != nil {
http2.HandleError(w, "could not get light client optimistic update: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "could not get light client optimistic update: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -347,7 +347,7 @@ func (s *Server) GetLightClientOptimisticUpdate(w http.ResponseWriter, req *http
Data: update,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// getLightClientEventBlock - returns the block that should be used for light client events, which satisfies the minimum number of signatures from sync committee

View File

@@ -6,7 +6,6 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"

View File

@@ -19,7 +19,7 @@ go_library(
"//beacon-chain/p2p/peers/peerdata:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/sync:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",
"//proto/migration:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
@@ -49,7 +49,7 @@ go_test(
"//beacon-chain/sync/initial-sync/testing:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/wrapper:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -9,7 +9,7 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/eth/v1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"go.opencensus.io/trace"
@@ -32,7 +32,7 @@ func (s *Server) GetSyncStatus(w http.ResponseWriter, r *http.Request) {
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -46,7 +46,7 @@ func (s *Server) GetSyncStatus(w http.ResponseWriter, r *http.Request) {
ElOffline: !s.ExecutionChainInfoFetcher.ExecutionClientConnected(),
},
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetIdentity retrieves data about the node's network presence.
@@ -62,7 +62,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
}
sourceDisc, err := s.PeerManager.DiscoveryAddresses()
if err != nil {
http2.HandleError(w, "Could not obtain discovery address: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain discovery address: "+err.Error(), http.StatusInternalServerError)
return
}
discoveryAddresses := make([]string, len(sourceDisc))
@@ -71,7 +71,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
}
serializedEnr, err := p2p.SerializeENR(s.PeerManager.ENR())
if err != nil {
http2.HandleError(w, "Could not obtain enr: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain enr: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -87,7 +87,7 @@ func (s *Server) GetIdentity(w http.ResponseWriter, r *http.Request) {
},
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetVersion requests that the beacon node identify information about its implementation in a
@@ -102,7 +102,7 @@ func (*Server) GetVersion(w http.ResponseWriter, r *http.Request) {
Version: v,
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetHealth returns node health status in http status codes. Useful for load balancers.
@@ -110,11 +110,11 @@ func (s *Server) GetHealth(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "node.GetHealth")
defer span.End()
ok, rawSyncingStatus, syncingStatus := shared.UintFromQuery(w, r, "syncing_status")
rawSyncingStatus, syncingStatus, ok := shared.UintFromQuery(w, r, "syncing_status", false)
// lint:ignore uintcast -- custom syncing status being outside of range is harmless
intSyncingStatus := int(syncingStatus)
if !ok || (rawSyncingStatus != "" && http.StatusText(intSyncingStatus) == "") {
http2.HandleError(w, "syncing_status is not a valid HTTP status code", http.StatusBadRequest)
httputil.HandleError(w, "syncing_status is not a valid HTTP status code", http.StatusBadRequest)
return
}

View File

@@ -11,7 +11,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers/peerdata"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/proto/migration"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"go.opencensus.io/trace"
@@ -24,54 +24,54 @@ func (s *Server) GetPeer(w http.ResponseWriter, r *http.Request) {
rawId := mux.Vars(r)["peer_id"]
if rawId == "" {
http2.HandleError(w, "peer_id is required in URL params", http.StatusBadRequest)
httputil.HandleError(w, "peer_id is required in URL params", http.StatusBadRequest)
return
}
peerStatus := s.PeersFetcher.Peers()
id, err := peer.Decode(rawId)
if err != nil {
http2.HandleError(w, "Invalid peer ID: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid peer ID: "+err.Error(), http.StatusBadRequest)
return
}
enr, err := peerStatus.ENR(id)
if err != nil {
if errors.Is(err, peerdata.ErrPeerUnknown) {
http2.HandleError(w, "Peer not found: "+err.Error(), http.StatusNotFound)
httputil.HandleError(w, "Peer not found: "+err.Error(), http.StatusNotFound)
return
}
http2.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
return
}
serializedEnr, err := p2p.SerializeENR(enr)
if err != nil {
http2.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain ENR: "+err.Error(), http.StatusInternalServerError)
return
}
p2pAddress, err := peerStatus.Address(id)
if err != nil {
http2.HandleError(w, "Could not obtain address: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain address: "+err.Error(), http.StatusInternalServerError)
return
}
state, err := peerStatus.ConnectionState(id)
if err != nil {
http2.HandleError(w, "Could not obtain connection state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain connection state: "+err.Error(), http.StatusInternalServerError)
return
}
direction, err := peerStatus.Direction(id)
if err != nil {
http2.HandleError(w, "Could not obtain direction: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not obtain direction: "+err.Error(), http.StatusInternalServerError)
return
}
if eth.PeerDirection(direction) == eth.PeerDirection_UNKNOWN {
http2.HandleError(w, "Peer not found", http.StatusNotFound)
httputil.HandleError(w, "Peer not found", http.StatusNotFound)
return
}
v1ConnState := migration.V1Alpha1ConnectionStateToV1(eth.ConnectionState(state))
v1PeerDirection, err := migration.V1Alpha1PeerDirectionToV1(eth.PeerDirection(direction))
if err != nil {
http2.HandleError(w, "Could not handle peer direction: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not handle peer direction: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -84,7 +84,7 @@ func (s *Server) GetPeer(w http.ResponseWriter, r *http.Request) {
Direction: strings.ToLower(v1PeerDirection.String()),
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetPeers retrieves data about the node's network peers.
@@ -104,7 +104,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
for _, id := range allIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
http2.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
return
}
if p == nil {
@@ -113,7 +113,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
allPeers = append(allPeers, p)
}
resp := &GetPeersResponse{Data: allPeers}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
return
}
@@ -168,7 +168,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
for _, id := range filteredIds {
p, err := peerInfo(peerStatus, id)
if err != nil {
http2.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get peer info: "+err.Error(), http.StatusInternalServerError)
return
}
if p == nil {
@@ -178,7 +178,7 @@ func (s *Server) GetPeers(w http.ResponseWriter, r *http.Request) {
}
resp := &GetPeersResponse{Data: filteredPeers}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetPeerCount retrieves number of known peers.
@@ -196,7 +196,7 @@ func (s *Server) GetPeerCount(w http.ResponseWriter, r *http.Request) {
Disconnecting: strconv.FormatInt(int64(len(peerStatus.Disconnecting())), 10),
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
func handleEmptyFilters(states []string, directions []string) (emptyState, emptyDirection bool) {

View File

@@ -18,7 +18,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
@@ -65,7 +65,7 @@ func TestGetPeer(t *testing.T) {
s.GetPeer(writer, request)
require.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Invalid peer ID", e.Message)
@@ -79,7 +79,7 @@ func TestGetPeer(t *testing.T) {
s.GetPeer(writer, request)
require.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.StringContains(t, "Peer not found", e.Message)

View File

@@ -21,7 +21,7 @@ import (
syncmock "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync/initial-sync/testing"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/consensus-types/wrapper"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
pb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
@@ -198,7 +198,7 @@ func TestGetIdentity(t *testing.T) {
s.GetIdentity(writer, request)
require.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Could not obtain enr", e.Message)
@@ -223,7 +223,7 @@ func TestGetIdentity(t *testing.T) {
s.GetIdentity(writer, request)
require.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Could not obtain discovery address", e.Message)

View File

@@ -24,7 +24,7 @@ go_library(
"//config/params:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_wealdtech_go_bytesutil//:go_default_library",
@@ -52,7 +52,7 @@ go_test(
"//crypto/bls:go_default_library",
"//crypto/bls/blst:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",

View File

@@ -14,7 +14,7 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/time/slots"
"github.com/wealdtech/go-bytesutil"
@@ -33,23 +33,23 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) {
return
}
if blk.Version() == version.Phase0 {
http2.HandleError(w, "Block rewards are not supported for Phase 0 blocks", http.StatusBadRequest)
httputil.HandleError(w, "Block rewards are not supported for Phase 0 blocks", http.StatusBadRequest)
return
}
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
http2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
blockRewards, httpError := s.BlockRewardFetcher.GetBlockRewardsData(ctx, blk)
if httpError != nil {
http2.WriteError(w, httpError)
httputil.WriteError(w, httpError)
return
}
response := &BlockRewardsResponse{
@@ -57,7 +57,7 @@ func (s *Server) BlockRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(ctx, blkRoot),
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// AttestationRewards retrieves attestation reward info for validators specified by array of public keys or validator index.
@@ -83,12 +83,12 @@ func (s *Server) AttestationRewards(w http.ResponseWriter, r *http.Request) {
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
http2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -100,7 +100,7 @@ func (s *Server) AttestationRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot),
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// SyncCommitteeRewards retrieves rewards info for sync committee members specified by array of public keys or validator index.
@@ -116,18 +116,18 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
return
}
if blk.Version() == version.Phase0 {
http2.HandleError(w, "Sync committee rewards are not supported for Phase 0", http.StatusBadRequest)
httputil.HandleError(w, "Sync committee rewards are not supported for Phase 0", http.StatusBadRequest)
return
}
st, httpErr := s.BlockRewardFetcher.GetStateForRewards(ctx, blk)
if httpErr != nil {
http2.WriteError(w, httpErr)
httputil.WriteError(w, httpErr)
return
}
sa, err := blk.Block().Body().SyncAggregate()
if err != nil {
http2.HandleError(w, "Could not get sync aggregate: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync aggregate: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -139,14 +139,14 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
for i, valIdx := range valIndices {
preProcessBals[i], err = st.BalanceAtIndex(valIdx)
if err != nil {
http2.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
return
}
}
_, proposerReward, err := altair.ProcessSyncAggregate(r.Context(), st, sa)
if err != nil {
http2.HandleError(w, "Could not get sync aggregate rewards: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync aggregate rewards: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -155,7 +155,7 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
for i, valIdx := range valIndices {
bal, err := st.BalanceAtIndex(valIdx)
if err != nil {
http2.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator's balance: "+err.Error(), http.StatusInternalServerError)
return
}
rewards[i] = int(bal - preProcessBals[i]) // lint:ignore uintcast
@@ -166,12 +166,12 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(r.Context())
if err != nil {
http2.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get optimistic mode info: "+err.Error(), http.StatusInternalServerError)
return
}
blkRoot, err := blk.Block().HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block root: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -187,35 +187,35 @@ func (s *Server) SyncCommitteeRewards(w http.ResponseWriter, r *http.Request) {
ExecutionOptimistic: optimistic,
Finalized: s.FinalizationFetcher.IsFinalized(r.Context(), blkRoot),
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
func (s *Server) attRewardsState(w http.ResponseWriter, r *http.Request) (state.BeaconState, bool) {
segments := strings.Split(r.URL.Path, "/")
requestedEpoch, err := strconv.ParseUint(segments[len(segments)-1], 10, 64)
if err != nil {
http2.HandleError(w, "Could not decode epoch: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode epoch: "+err.Error(), http.StatusBadRequest)
return nil, false
}
if primitives.Epoch(requestedEpoch) < params.BeaconConfig().AltairForkEpoch {
http2.HandleError(w, "Attestation rewards are not supported for Phase 0", http.StatusNotFound)
httputil.HandleError(w, "Attestation rewards are not supported for Phase 0", http.StatusNotFound)
return nil, false
}
currentEpoch := uint64(slots.ToEpoch(s.TimeFetcher.CurrentSlot()))
if requestedEpoch+1 >= currentEpoch {
http2.HandleError(w,
httputil.HandleError(w,
"Attestation rewards are available after two epoch transitions to ensure all attestations have a chance of inclusion",
http.StatusNotFound)
return nil, false
}
nextEpochEnd, err := slots.EpochEnd(primitives.Epoch(requestedEpoch + 1))
if err != nil {
http2.HandleError(w, "Could not get next epoch's ending slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get next epoch's ending slot: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
st, err := s.Stater.StateBySlot(r.Context(), nextEpochEnd)
if err != nil {
http2.HandleError(w, "Could not get state for epoch's starting slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get state for epoch's starting slot: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
return st, true
@@ -228,12 +228,12 @@ func attRewardsBalancesAndVals(
) (*precompute.Balance, []*precompute.Validator, []primitives.ValidatorIndex, bool) {
allVals, bal, err := altair.InitializePrecomputeValidators(r.Context(), st)
if err != nil {
http2.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
return nil, nil, nil, false
}
allVals, bal, err = altair.ProcessEpochParticipation(r.Context(), st, bal, allVals)
if err != nil {
http2.HandleError(w, "Could not process epoch participation: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not process epoch participation: "+err.Error(), http.StatusBadRequest)
return nil, nil, nil, false
}
valIndices, ok := requestedValIndices(w, r, st, allVals)
@@ -284,7 +284,7 @@ func idealAttRewards(
}
deltas, err := altair.AttestationsDelta(st, bal, idealVals)
if err != nil {
http2.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
for i, d := range deltas {
@@ -316,7 +316,7 @@ func totalAttRewards(
}
deltas, err := altair.AttestationsDelta(st, bal, vals)
if err != nil {
http2.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get attestations delta: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
for i, d := range deltas {
@@ -342,7 +342,7 @@ func syncRewardsVals(
) ([]*precompute.Validator, []primitives.ValidatorIndex, bool) {
allVals, _, err := altair.InitializePrecomputeValidators(r.Context(), st)
if err != nil {
http2.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not initialize precompute validators: "+err.Error(), http.StatusBadRequest)
return nil, nil, false
}
valIndices, ok := requestedValIndices(w, r, st, allVals)
@@ -352,14 +352,14 @@ func syncRewardsVals(
sc, err := st.CurrentSyncCommittee()
if err != nil {
http2.HandleError(w, "Could not get current sync committee: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not get current sync committee: "+err.Error(), http.StatusBadRequest)
return nil, nil, false
}
allScIndices := make([]primitives.ValidatorIndex, len(sc.Pubkeys))
for i, pk := range sc.Pubkeys {
valIdx, ok := st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pk))
if !ok {
http2.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pk), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pk), http.StatusBadRequest)
return nil, nil, false
}
allScIndices[i] = valIdx
@@ -384,7 +384,7 @@ func requestedValIndices(w http.ResponseWriter, r *http.Request, st state.Beacon
var rawValIds []string
if r.Body != http.NoBody {
if err := json.NewDecoder(r.Body).Decode(&rawValIds); err != nil {
http2.HandleError(w, "Could not decode validators: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode validators: "+err.Error(), http.StatusBadRequest)
return nil, false
}
}
@@ -394,18 +394,18 @@ func requestedValIndices(w http.ResponseWriter, r *http.Request, st state.Beacon
if err != nil {
pubkey, err := bytesutil.FromHexString(v)
if err != nil || len(pubkey) != fieldparams.BLSPubkeyLength {
http2.HandleError(w, fmt.Sprintf("%s is not a validator index or pubkey", v), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("%s is not a validator index or pubkey", v), http.StatusBadRequest)
return nil, false
}
var ok bool
valIndices[i], ok = st.ValidatorIndexByPubkey(bytesutil.ToBytes48(pubkey))
if !ok {
http2.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pubkey), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("No validator index found for pubkey %#x", pubkey), http.StatusBadRequest)
return nil, false
}
} else {
if index >= uint64(st.NumValidators()) {
http2.HandleError(w, fmt.Sprintf("Validator index %d is too large. Maximum allowed index is %d", index, st.NumValidators()-1), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Validator index %d is too large. Maximum allowed index is %d", index, st.NumValidators()-1), http.StatusBadRequest)
return nil, false
}
valIndices[i] = primitives.ValidatorIndex(index)

View File

@@ -28,7 +28,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/crypto/bls"
"github.com/prysmaticlabs/prysm/v4/crypto/bls/blst"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -209,7 +209,7 @@ func TestBlockRewards(t *testing.T) {
s.BlockRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "Block rewards are not supported for Phase 0 blocks", e.Message)
@@ -541,7 +541,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "foo is not a validator index or pubkey", e.Message)
@@ -562,7 +562,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "No validator index found for pubkey "+pubkey, e.Message)
@@ -580,7 +580,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "Validator index 999 is too large. Maximum allowed index is 63", e.Message)
@@ -593,7 +593,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.Equal(t, "Attestation rewards are not supported for Phase 0", e.Message)
@@ -606,7 +606,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Could not decode epoch"))
@@ -619,7 +619,7 @@ func TestAttestationRewards(t *testing.T) {
s.AttestationRewards(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.Equal(t, "Attestation rewards are available after two epoch transitions to ensure all attestations have a chance of inclusion", e.Message)
@@ -844,7 +844,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "foo is not a validator index or pubkey", e.Message)
@@ -871,7 +871,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "No validator index found for pubkey "+pubkey, e.Message)
@@ -895,7 +895,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "Validator index 9999 is too large. Maximum allowed index is 1023", e.Message)
@@ -914,7 +914,7 @@ func TestSyncCommiteeRewards(t *testing.T) {
s.SyncCommitteeRewards(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, "Sync committee rewards are not supported for Phase 0", e.Message)

View File

@@ -11,13 +11,13 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state/stategen"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
// BlockRewardsFetcher is a interface that provides access to reward related responses
type BlockRewardsFetcher interface {
GetBlockRewardsData(context.Context, interfaces.ReadOnlySignedBeaconBlock) (*BlockRewards, *http2.DefaultErrorJson)
GetStateForRewards(context.Context, interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *http2.DefaultErrorJson)
GetBlockRewardsData(context.Context, interfaces.ReadOnlySignedBeaconBlock) (*BlockRewards, *httputil.DefaultErrorJson)
GetStateForRewards(context.Context, interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *httputil.DefaultErrorJson)
}
// BlockRewardService implements BlockRewardsFetcher and can be declared to access the underlying functions
@@ -26,7 +26,7 @@ type BlockRewardService struct {
}
// GetBlockRewardsData returns the BlockRewards Object which is used for the BlockRewardsResponse and ProduceBlockV3
func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*BlockRewards, *http2.DefaultErrorJson) {
func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (*BlockRewards, *httputil.DefaultErrorJson) {
st, httpErr := rs.GetStateForRewards(ctx, blk)
if httpErr != nil {
return nil, httpErr
@@ -35,56 +35,56 @@ func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk inter
proposerIndex := blk.Block().ProposerIndex()
initBalance, err := st.BalanceAtIndex(proposerIndex)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get proposer's balance: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
st, err = altair.ProcessAttestationsNoVerifySignature(ctx, st, blk)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get attestation rewards: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
attBalance, err := st.BalanceAtIndex(proposerIndex)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get proposer's balance: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
st, err = coreblocks.ProcessAttesterSlashings(ctx, st, blk.Block().Body().AttesterSlashings(), validators.SlashValidator)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get attester slashing rewards: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
attSlashingsBalance, err := st.BalanceAtIndex(proposerIndex)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get proposer's balance: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
st, err = coreblocks.ProcessProposerSlashings(ctx, st, blk.Block().Body().ProposerSlashings(), validators.SlashValidator)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get proposer slashing rewards: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
proposerSlashingsBalance, err := st.BalanceAtIndex(proposerIndex)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get proposer's balance: " + err.Error(),
Code: http.StatusInternalServerError,
}
}
sa, err := blk.Block().Body().SyncAggregate()
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get sync aggregate: " + err.Error(),
Code: http.StatusInternalServerError,
}
@@ -92,7 +92,7 @@ func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk inter
var syncCommitteeReward uint64
_, syncCommitteeReward, err = altair.ProcessSyncAggregate(ctx, st, sa)
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get sync aggregate rewards: " + err.Error(),
Code: http.StatusInternalServerError,
}
@@ -109,13 +109,13 @@ func (rs *BlockRewardService) GetBlockRewardsData(ctx context.Context, blk inter
}
// GetStateForRewards returns the state replayed up to the block's slot
func (rs *BlockRewardService) GetStateForRewards(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *http2.DefaultErrorJson) {
func (rs *BlockRewardService) GetStateForRewards(ctx context.Context, blk interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *httputil.DefaultErrorJson) {
// We want to run several block processing functions that update the proposer's balance.
// This will allow us to calculate proposer rewards for each operation (atts, slashings etc).
// To do this, we replay the state up to the block's slot, but before processing the block.
st, err := rs.Replayer.ReplayerForSlot(blk.Block().Slot()-1).ReplayToSlot(ctx, blk.Block().Slot())
if err != nil {
return nil, &http2.DefaultErrorJson{
return nil, &httputil.DefaultErrorJson{
Message: "Could not get state: " + err.Error(),
Code: http.StatusInternalServerError,
}

View File

@@ -9,6 +9,6 @@ go_library(
"//beacon-chain/rpc/eth/rewards:go_default_library",
"//beacon-chain/state:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
],
)

View File

@@ -6,23 +6,23 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/rewards"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
type MockBlockRewardFetcher struct {
Rewards *rewards.BlockRewards
Error *http2.DefaultErrorJson
Error *httputil.DefaultErrorJson
State state.BeaconState
}
func (m *MockBlockRewardFetcher) GetBlockRewardsData(_ context.Context, _ interfaces.ReadOnlySignedBeaconBlock) (*rewards.BlockRewards, *http2.DefaultErrorJson) {
func (m *MockBlockRewardFetcher) GetBlockRewardsData(_ context.Context, _ interfaces.ReadOnlySignedBeaconBlock) (*rewards.BlockRewards, *httputil.DefaultErrorJson) {
if m.Error != nil {
return nil, m.Error
}
return m.Rewards, nil
}
func (m *MockBlockRewardFetcher) GetStateForRewards(_ context.Context, _ interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *http2.DefaultErrorJson) {
func (m *MockBlockRewardFetcher) GetStateForRewards(_ context.Context, _ interfaces.ReadOnlySignedBeaconBlock) (state.BeaconState, *httputil.DefaultErrorJson) {
if m.Error != nil {
return nil, m.Error
}

View File

@@ -3,31 +3,37 @@ load("@prysm//tools/go:def.bzl", "go_library", "go_test")
go_library(
name = "go_default_library",
srcs = [
"conversions.go",
"conversions_block.go",
"conversions_state.go",
"errors.go",
"request.go",
"structs.go",
"structs_blocks.go",
"structs_blocks_conversions.go",
"structs_validator.go",
"structs_block.go",
"structs_state.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared",
visibility = ["//visibility:public"],
deps = [
"//api/server:go_default_library",
"//beacon-chain/blockchain:go_default_library",
"//beacon-chain/rpc/lookup:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/sync:go_default_library",
"//config/fieldparams:go_default_library",
"//consensus-types/blocks:go_default_library",
"//consensus-types/interfaces:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//container/slice:go_default_library",
"//encoding/bytesutil:go_default_library",
"//math:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_gorilla_mux//:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],
)
@@ -38,7 +44,7 @@ go_test(
embed = [":go_default_library"],
deps = [
"//beacon-chain/rpc/lookup:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//testing/assert:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,595 @@
package shared
import (
"errors"
"fmt"
"github.com/ethereum/go-ethereum/common/hexutil"
beaconState "github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
)
var errPayloadHeaderNotFound = errors.New("expected payload header not found")
func BeaconStateFromConsensus(st beaconState.BeaconState) (*BeaconState, error) {
srcBr := st.BlockRoots()
br := make([]string, len(srcBr))
for i, r := range srcBr {
br[i] = hexutil.Encode(r)
}
srcSr := st.StateRoots()
sr := make([]string, len(srcSr))
for i, r := range srcSr {
sr[i] = hexutil.Encode(r)
}
srcHr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srcHr))
for i, r := range srcHr {
hr[i] = hexutil.Encode(r)
}
srcVotes := st.Eth1DataVotes()
votes := make([]*Eth1Data, len(srcVotes))
for i, e := range srcVotes {
votes[i] = Eth1DataFromConsensus(e)
}
srcVals := st.Validators()
vals := make([]*Validator, len(srcVals))
for i, v := range srcVals {
vals[i] = ValidatorFromConsensus(v)
}
srcBals := st.Balances()
bals := make([]string, len(srcBals))
for i, b := range srcBals {
bals[i] = fmt.Sprintf("%d", b)
}
srcRm := st.RandaoMixes()
rm := make([]string, len(srcRm))
for i, m := range srcRm {
rm[i] = hexutil.Encode(m)
}
srcSlashings := st.Slashings()
slashings := make([]string, len(srcSlashings))
for i, s := range srcSlashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevAtts, err := st.PreviousEpochAttestations()
if err != nil {
return nil, err
}
prevAtts := make([]*PendingAttestation, len(srcPrevAtts))
for i, a := range srcPrevAtts {
prevAtts[i] = PendingAttestationFromConsensus(a)
}
srcCurrAtts, err := st.CurrentEpochAttestations()
if err != nil {
return nil, err
}
currAtts := make([]*PendingAttestation, len(srcCurrAtts))
for i, a := range srcCurrAtts {
currAtts[i] = PendingAttestationFromConsensus(a)
}
return &BeaconState{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: ForkFromConsensus(st.Fork()),
LatestBlockHeader: BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: Eth1DataFromConsensus(st.Eth1Data()),
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochAttestations: prevAtts,
CurrentEpochAttestations: currAtts,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: CheckpointFromConsensus(st.FinalizedCheckpoint()),
}, nil
}
func BeaconStateAltairFromConsensus(st beaconState.BeaconState) (*BeaconStateAltair, error) {
srcBr := st.BlockRoots()
br := make([]string, len(srcBr))
for i, r := range srcBr {
br[i] = hexutil.Encode(r)
}
srcSr := st.StateRoots()
sr := make([]string, len(srcSr))
for i, r := range srcSr {
sr[i] = hexutil.Encode(r)
}
srcHr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srcHr))
for i, r := range srcHr {
hr[i] = hexutil.Encode(r)
}
srcVotes := st.Eth1DataVotes()
votes := make([]*Eth1Data, len(srcVotes))
for i, e := range srcVotes {
votes[i] = Eth1DataFromConsensus(e)
}
srcVals := st.Validators()
vals := make([]*Validator, len(srcVals))
for i, v := range srcVals {
vals[i] = ValidatorFromConsensus(v)
}
srcBals := st.Balances()
bals := make([]string, len(srcBals))
for i, b := range srcBals {
bals[i] = fmt.Sprintf("%d", b)
}
srcRm := st.RandaoMixes()
rm := make([]string, len(srcRm))
for i, m := range srcRm {
rm[i] = hexutil.Encode(m)
}
srcSlashings := st.Slashings()
slashings := make([]string, len(srcSlashings))
for i, s := range srcSlashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = fmt.Sprintf("%d", p)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = fmt.Sprintf("%d", p)
}
srcIs, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcIs))
for i, s := range srcIs {
is[i] = fmt.Sprintf("%d", s)
}
currSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
return &BeaconStateAltair{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: ForkFromConsensus(st.Fork()),
LatestBlockHeader: BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: Eth1DataFromConsensus(st.Eth1Data()),
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: SyncCommitteeFromConsensus(currSc),
NextSyncCommittee: SyncCommitteeFromConsensus(nextSc),
}, nil
}
func BeaconStateBellatrixFromConsensus(st beaconState.BeaconState) (*BeaconStateBellatrix, error) {
srcBr := st.BlockRoots()
br := make([]string, len(srcBr))
for i, r := range srcBr {
br[i] = hexutil.Encode(r)
}
srcSr := st.StateRoots()
sr := make([]string, len(srcSr))
for i, r := range srcSr {
sr[i] = hexutil.Encode(r)
}
srcHr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srcHr))
for i, r := range srcHr {
hr[i] = hexutil.Encode(r)
}
srcVotes := st.Eth1DataVotes()
votes := make([]*Eth1Data, len(srcVotes))
for i, e := range srcVotes {
votes[i] = Eth1DataFromConsensus(e)
}
srcVals := st.Validators()
vals := make([]*Validator, len(srcVals))
for i, v := range srcVals {
vals[i] = ValidatorFromConsensus(v)
}
srcBals := st.Balances()
bals := make([]string, len(srcBals))
for i, b := range srcBals {
bals[i] = fmt.Sprintf("%d", b)
}
srcRm := st.RandaoMixes()
rm := make([]string, len(srcRm))
for i, m := range srcRm {
rm[i] = hexutil.Encode(m)
}
srcSlashings := st.Slashings()
slashings := make([]string, len(srcSlashings))
for i, s := range srcSlashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = fmt.Sprintf("%d", p)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = fmt.Sprintf("%d", p)
}
srcIs, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcIs))
for i, s := range srcIs {
is[i] = fmt.Sprintf("%d", s)
}
currSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeader)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := ExecutionPayloadHeaderFromConsensus(srcPayload)
if err != nil {
return nil, err
}
return &BeaconStateBellatrix{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: ForkFromConsensus(st.Fork()),
LatestBlockHeader: BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: Eth1DataFromConsensus(st.Eth1Data()),
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: SyncCommitteeFromConsensus(currSc),
NextSyncCommittee: SyncCommitteeFromConsensus(nextSc),
LatestExecutionPayloadHeader: payload,
}, nil
}
func BeaconStateCapellaFromConsensus(st beaconState.BeaconState) (*BeaconStateCapella, error) {
srcBr := st.BlockRoots()
br := make([]string, len(srcBr))
for i, r := range srcBr {
br[i] = hexutil.Encode(r)
}
srcSr := st.StateRoots()
sr := make([]string, len(srcSr))
for i, r := range srcSr {
sr[i] = hexutil.Encode(r)
}
srcHr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srcHr))
for i, r := range srcHr {
hr[i] = hexutil.Encode(r)
}
srcVotes := st.Eth1DataVotes()
votes := make([]*Eth1Data, len(srcVotes))
for i, e := range srcVotes {
votes[i] = Eth1DataFromConsensus(e)
}
srcVals := st.Validators()
vals := make([]*Validator, len(srcVals))
for i, v := range srcVals {
vals[i] = ValidatorFromConsensus(v)
}
srcBals := st.Balances()
bals := make([]string, len(srcBals))
for i, b := range srcBals {
bals[i] = fmt.Sprintf("%d", b)
}
srcRm := st.RandaoMixes()
rm := make([]string, len(srcRm))
for i, m := range srcRm {
rm[i] = hexutil.Encode(m)
}
srcSlashings := st.Slashings()
slashings := make([]string, len(srcSlashings))
for i, s := range srcSlashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = fmt.Sprintf("%d", p)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = fmt.Sprintf("%d", p)
}
srcIs, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcIs))
for i, s := range srcIs {
is[i] = fmt.Sprintf("%d", s)
}
currSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeaderCapella)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := ExecutionPayloadHeaderCapellaFromConsensus(srcPayload)
if err != nil {
return nil, err
}
srcHs, err := st.HistoricalSummaries()
if err != nil {
return nil, err
}
hs := make([]*HistoricalSummary, len(srcHs))
for i, s := range srcHs {
hs[i] = HistoricalSummaryFromConsensus(s)
}
nwi, err := st.NextWithdrawalIndex()
if err != nil {
return nil, err
}
nwvi, err := st.NextWithdrawalValidatorIndex()
if err != nil {
return nil, err
}
return &BeaconStateCapella{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: ForkFromConsensus(st.Fork()),
LatestBlockHeader: BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: Eth1DataFromConsensus(st.Eth1Data()),
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: SyncCommitteeFromConsensus(currSc),
NextSyncCommittee: SyncCommitteeFromConsensus(nextSc),
LatestExecutionPayloadHeader: payload,
NextWithdrawalIndex: fmt.Sprintf("%d", nwi),
NextWithdrawalValidatorIndex: fmt.Sprintf("%d", nwvi),
HistoricalSummaries: hs,
}, nil
}
func BeaconStateDenebFromConsensus(st beaconState.BeaconState) (*BeaconStateDeneb, error) {
srcBr := st.BlockRoots()
br := make([]string, len(srcBr))
for i, r := range srcBr {
br[i] = hexutil.Encode(r)
}
srcSr := st.StateRoots()
sr := make([]string, len(srcSr))
for i, r := range srcSr {
sr[i] = hexutil.Encode(r)
}
srcHr, err := st.HistoricalRoots()
if err != nil {
return nil, err
}
hr := make([]string, len(srcHr))
for i, r := range srcHr {
hr[i] = hexutil.Encode(r)
}
srcVotes := st.Eth1DataVotes()
votes := make([]*Eth1Data, len(srcVotes))
for i, e := range srcVotes {
votes[i] = Eth1DataFromConsensus(e)
}
srcVals := st.Validators()
vals := make([]*Validator, len(srcVals))
for i, v := range srcVals {
vals[i] = ValidatorFromConsensus(v)
}
srcBals := st.Balances()
bals := make([]string, len(srcBals))
for i, b := range srcBals {
bals[i] = fmt.Sprintf("%d", b)
}
srcRm := st.RandaoMixes()
rm := make([]string, len(srcRm))
for i, m := range srcRm {
rm[i] = hexutil.Encode(m)
}
srcSlashings := st.Slashings()
slashings := make([]string, len(srcSlashings))
for i, s := range srcSlashings {
slashings[i] = fmt.Sprintf("%d", s)
}
srcPrevPart, err := st.PreviousEpochParticipation()
if err != nil {
return nil, err
}
prevPart := make([]string, len(srcPrevPart))
for i, p := range srcPrevPart {
prevPart[i] = fmt.Sprintf("%d", p)
}
srcCurrPart, err := st.CurrentEpochParticipation()
if err != nil {
return nil, err
}
currPart := make([]string, len(srcCurrPart))
for i, p := range srcCurrPart {
currPart[i] = fmt.Sprintf("%d", p)
}
srcIs, err := st.InactivityScores()
if err != nil {
return nil, err
}
is := make([]string, len(srcIs))
for i, s := range srcIs {
is[i] = fmt.Sprintf("%d", s)
}
currSc, err := st.CurrentSyncCommittee()
if err != nil {
return nil, err
}
nextSc, err := st.NextSyncCommittee()
if err != nil {
return nil, err
}
execData, err := st.LatestExecutionPayloadHeader()
if err != nil {
return nil, err
}
srcPayload, ok := execData.Proto().(*enginev1.ExecutionPayloadHeaderDeneb)
if !ok {
return nil, errPayloadHeaderNotFound
}
payload, err := ExecutionPayloadHeaderDenebFromConsensus(srcPayload)
if err != nil {
return nil, err
}
srcHs, err := st.HistoricalSummaries()
if err != nil {
return nil, err
}
hs := make([]*HistoricalSummary, len(srcHs))
for i, s := range srcHs {
hs[i] = HistoricalSummaryFromConsensus(s)
}
nwi, err := st.NextWithdrawalIndex()
if err != nil {
return nil, err
}
nwvi, err := st.NextWithdrawalValidatorIndex()
if err != nil {
return nil, err
}
return &BeaconStateDeneb{
GenesisTime: fmt.Sprintf("%d", st.GenesisTime()),
GenesisValidatorsRoot: hexutil.Encode(st.GenesisValidatorsRoot()),
Slot: fmt.Sprintf("%d", st.Slot()),
Fork: ForkFromConsensus(st.Fork()),
LatestBlockHeader: BeaconBlockHeaderFromConsensus(st.LatestBlockHeader()),
BlockRoots: br,
StateRoots: sr,
HistoricalRoots: hr,
Eth1Data: Eth1DataFromConsensus(st.Eth1Data()),
Eth1DataVotes: votes,
Eth1DepositIndex: fmt.Sprintf("%d", st.Eth1DepositIndex()),
Validators: vals,
Balances: bals,
RandaoMixes: rm,
Slashings: slashings,
PreviousEpochParticipation: prevPart,
CurrentEpochParticipation: currPart,
JustificationBits: hexutil.Encode(st.JustificationBits()),
PreviousJustifiedCheckpoint: CheckpointFromConsensus(st.PreviousJustifiedCheckpoint()),
CurrentJustifiedCheckpoint: CheckpointFromConsensus(st.CurrentJustifiedCheckpoint()),
FinalizedCheckpoint: CheckpointFromConsensus(st.FinalizedCheckpoint()),
InactivityScores: is,
CurrentSyncCommittee: SyncCommitteeFromConsensus(currSc),
NextSyncCommittee: SyncCommitteeFromConsensus(nextSc),
LatestExecutionPayloadHeader: payload,
NextWithdrawalIndex: fmt.Sprintf("%d", nwi),
NextWithdrawalValidatorIndex: fmt.Sprintf("%d", nwvi),
HistoricalSummaries: hs,
}, nil
}

View File

@@ -1,82 +1,41 @@
package shared
import (
"fmt"
"net/http"
"strings"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
"github.com/prysmaticlabs/prysm/v4/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
// DecodeError represents an error resulting from trying to decode an HTTP request.
// It tracks the full field name for which decoding failed.
type DecodeError struct {
path []string
err error
}
// NewDecodeError wraps an error (either the initial decoding error or another DecodeError).
// The current field that failed decoding must be passed in.
func NewDecodeError(err error, field string) *DecodeError {
de, ok := err.(*DecodeError)
if ok {
return &DecodeError{path: append([]string{field}, de.path...), err: de.err}
}
return &DecodeError{path: []string{field}, err: err}
}
// Error returns the formatted error message which contains the full field name and the actual decoding error.
func (e *DecodeError) Error() string {
return fmt.Sprintf("could not decode %s: %s", strings.Join(e.path, "."), e.err.Error())
}
// IndexedVerificationFailureError wraps a collection of verification failures.
type IndexedVerificationFailureError struct {
Message string `json:"message"`
Code int `json:"code"`
Failures []*IndexedVerificationFailure `json:"failures"`
}
func (e *IndexedVerificationFailureError) StatusCode() int {
return e.Code
}
// IndexedVerificationFailure represents an issue when verifying a single indexed object e.g. an item in an array.
type IndexedVerificationFailure struct {
Index int `json:"index"`
Message string `json:"message"`
}
// WriteStateFetchError writes an appropriate error based on the supplied argument.
// The argument error should be a result of fetching state.
func WriteStateFetchError(w http.ResponseWriter, err error) {
if _, ok := err.(*lookup.StateNotFoundError); ok {
http2.HandleError(w, "State not found", http.StatusNotFound)
httputil.HandleError(w, "State not found", http.StatusNotFound)
return
}
if parseErr, ok := err.(*lookup.StateIdParseError); ok {
http2.HandleError(w, "Invalid state ID: "+parseErr.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid state ID: "+parseErr.Error(), http.StatusBadRequest)
return
}
http2.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
}
// WriteBlockFetchError writes an appropriate error based on the supplied argument.
// The argument error should be a result of fetching block.
func WriteBlockFetchError(w http.ResponseWriter, blk interfaces.ReadOnlySignedBeaconBlock, err error) bool {
if invalidBlockIdErr, ok := err.(*lookup.BlockIdParseError); ok {
http2.HandleError(w, "Invalid block ID: "+invalidBlockIdErr.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid block ID: "+invalidBlockIdErr.Error(), http.StatusBadRequest)
return false
}
if err != nil {
http2.HandleError(w, "Could not get block from block ID: %s"+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get block from block ID: %s"+err.Error(), http.StatusInternalServerError)
return false
}
if err = blocks.BeaconBlockIsNil(blk); err != nil {
http2.HandleError(w, "Could not find requested block: %s"+err.Error(), http.StatusNotFound)
httputil.HandleError(w, "Could not find requested block: %s"+err.Error(), http.StatusNotFound)
return false
}
return true

View File

@@ -8,18 +8,10 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
)
func TestDecodeError(t *testing.T) {
e := errors.New("not a number")
de := NewDecodeError(e, "Z")
de = NewDecodeError(de, "Y")
de = NewDecodeError(de, "X")
assert.Equal(t, "could not decode X.Y.Z: not a number", de.Error())
}
// TestWriteStateFetchError tests the WriteStateFetchError function
// to ensure that the correct error message and code are written to the response
// as an expected JSON format.
@@ -53,7 +45,7 @@ func TestWriteStateFetchError(t *testing.T) {
assert.Equal(t, c.expectedCode, writer.Code, "incorrect status code")
assert.StringContains(t, c.expectedMessage, writer.Body.String(), "incorrect error message")
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
assert.NoError(t, json.Unmarshal(writer.Body.Bytes(), e), "failed to unmarshal response")
}
}

View File

@@ -8,66 +8,95 @@ import (
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/gorilla/mux"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/sync"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
func UintFromQuery(w http.ResponseWriter, r *http.Request, name string) (bool, string, uint64) {
func UintFromQuery(w http.ResponseWriter, r *http.Request, name string, required bool) (string, uint64, bool) {
raw := r.URL.Query().Get(name)
if raw != "" {
v, valid := ValidateUint(w, name, raw)
if !valid {
return false, "", 0
}
return true, raw, v
if raw == "" && !required {
return "", 0, true
}
return true, "", 0
v, valid := ValidateUint(w, name, raw)
if !valid {
return "", 0, false
}
return raw, v, true
}
func ValidateHex(w http.ResponseWriter, name string, s string, length int) ([]byte, bool) {
func UintFromRoute(w http.ResponseWriter, r *http.Request, name string) (string, uint64, bool) {
raw := mux.Vars(r)[name]
v, valid := ValidateUint(w, name, raw)
if !valid {
return "", 0, false
}
return raw, v, true
}
func HexFromQuery(w http.ResponseWriter, r *http.Request, name string, length int, required bool) (string, []byte, bool) {
raw := r.URL.Query().Get(name)
if raw == "" && !required {
return "", nil, true
}
v, valid := ValidateHex(w, name, raw, length)
if !valid {
return "", nil, false
}
return raw, v, true
}
func HexFromRoute(w http.ResponseWriter, r *http.Request, name string, length int) (string, []byte, bool) {
raw := mux.Vars(r)[name]
v, valid := ValidateHex(w, name, raw, length)
if !valid {
return "", nil, false
}
return raw, v, true
}
func ValidateHex(w http.ResponseWriter, name, s string, length int) ([]byte, bool) {
if s == "" {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: name + " is required",
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return nil, false
}
hexBytes, err := hexutil.Decode(s)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: name + " is invalid: " + err.Error(),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return nil, false
}
if len(hexBytes) != length {
http2.HandleError(w, fmt.Sprintf("Invalid %s: %s is not length %d", name, s, length), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Invalid %s: %s is not length %d", name, s, length), http.StatusBadRequest)
return nil, false
}
return hexBytes, true
}
func ValidateUint(w http.ResponseWriter, name string, s string) (uint64, bool) {
func ValidateUint(w http.ResponseWriter, name, s string) (uint64, bool) {
if s == "" {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: name + " is required",
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return 0, false
}
v, err := strconv.ParseUint(s, 10, 64)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: name + " is invalid: " + err.Error(),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return 0, false
}
return v, true
@@ -89,11 +118,11 @@ func IsSyncing(
headSlot := headFetcher.HeadSlot()
isOptimistic, err := optimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: "Could not check optimistic status: " + err.Error(),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return true
}
syncDetails := &SyncDetailsContainer{
@@ -110,10 +139,10 @@ func IsSyncing(
if err == nil {
msg += " Details: " + string(details)
}
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: msg,
Code: http.StatusServiceUnavailable}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return true
}
@@ -125,56 +154,20 @@ func IsOptimistic(
) (bool, error) {
isOptimistic, err := optimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: "Could not check optimistic status: " + err.Error(),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return true, err
}
if !isOptimistic {
return false, nil
}
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Code: http.StatusServiceUnavailable,
Message: "Beacon node is currently optimistic and not serving validators",
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return true, nil
}
// DecodeHexWithLength takes a string and a length in bytes,
// and validates whether the string is a hex and has the correct length.
func DecodeHexWithLength(s string, length int) ([]byte, error) {
bytes, err := hexutil.Decode(s)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%s is not a valid hex", s))
}
if len(bytes) != length {
return nil, fmt.Errorf("%s is not length %d bytes", s, length)
}
return bytes, nil
}
// DecodeHexWithMaxLength takes a string and a length in bytes,
// and validates whether the string is a hex and has the correct length.
func DecodeHexWithMaxLength(s string, maxLength int) ([]byte, error) {
bytes, err := hexutil.Decode(s)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%s is not a valid hex", s))
}
err = VerifyMaxLength(bytes, maxLength)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("length of %s exceeds max of %d bytes", s, maxLength))
}
return bytes, nil
}
// VerifyMaxLength takes a slice and a maximum length and validates the length.
func VerifyMaxLength[T any](v []T, max int) error {
l := len(v)
if l > max {
return fmt.Errorf("length of %d exceeds max of %d", l, max)
}
return nil
}

View File

@@ -1,18 +1,27 @@
package shared
import (
"fmt"
"strconv"
type Validator struct {
PublicKey string `json:"pubkey"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
EffectiveBalance string `json:"effective_balance"`
Slashed bool `json:"slashed"`
ActivationEligibilityEpoch string `json:"activation_eligibility_epoch"`
ActivationEpoch string `json:"activation_epoch"`
ExitEpoch string `json:"exit_epoch"`
WithdrawableEpoch string `json:"withdrawable_epoch"`
}
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
type PendingAttestation struct {
AggregationBits string `json:"aggregation_bits"`
Data *AttestationData `json:"data"`
InclusionDelay string `json:"inclusion_delay"`
ProposerIndex string `json:"proposer_index"`
}
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/consensus-types/validator"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
type HistoricalSummary struct {
BlockSummaryRoot string `json:"block_summary_root"`
StateSummaryRoot string `json:"state_summary_root"`
}
type Attestation struct {
AggregationBits string `json:"aggregation_bits"`
@@ -121,117 +130,12 @@ type SignedBLSToExecutionChange struct {
Signature string `json:"signature"`
}
func (s *SignedBLSToExecutionChange) ToConsensus() (*eth.SignedBLSToExecutionChange, error) {
change, err := s.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
sig, err := DecodeHexWithLength(s.Signature, fieldparams.BLSSignatureLength)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SignedBLSToExecutionChange{
Message: change,
Signature: sig,
}, nil
}
type BLSToExecutionChange struct {
ValidatorIndex string `json:"validator_index"`
FromBLSPubkey string `json:"from_bls_pubkey"`
ToExecutionAddress string `json:"to_execution_address"`
}
func (b *BLSToExecutionChange) ToConsensus() (*eth.BLSToExecutionChange, error) {
index, err := strconv.ParseUint(b.ValidatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ValidatorIndex")
}
pubkey, err := DecodeHexWithLength(b.FromBLSPubkey, fieldparams.BLSPubkeyLength)
if err != nil {
return nil, NewDecodeError(err, "FromBLSPubkey")
}
executionAddress, err := DecodeHexWithLength(b.ToExecutionAddress, common.AddressLength)
if err != nil {
return nil, NewDecodeError(err, "ToExecutionAddress")
}
return &eth.BLSToExecutionChange{
ValidatorIndex: primitives.ValidatorIndex(index),
FromBlsPubkey: pubkey,
ToExecutionAddress: executionAddress,
}, nil
}
func BlsToExecutionChangeFromConsensus(blsToExecutionChange *eth.BLSToExecutionChange) (*BLSToExecutionChange, error) {
if blsToExecutionChange == nil {
return nil, errors.New("BLSToExecutionChange is empty")
}
return &BLSToExecutionChange{
ValidatorIndex: strconv.FormatUint(uint64(blsToExecutionChange.ValidatorIndex), 10),
FromBLSPubkey: hexutil.Encode(blsToExecutionChange.FromBlsPubkey),
ToExecutionAddress: hexutil.Encode(blsToExecutionChange.ToExecutionAddress),
}, nil
}
func SignedBlsToExecutionChangeFromConsensus(signedBlsToExecutionChange *eth.SignedBLSToExecutionChange) (*SignedBLSToExecutionChange, error) {
if signedBlsToExecutionChange == nil {
return nil, errors.New("SignedBLSToExecutionChange is empty")
}
bls, err := BlsToExecutionChangeFromConsensus(signedBlsToExecutionChange.Message)
if err != nil {
return nil, err
}
return &SignedBLSToExecutionChange{
Message: bls,
Signature: hexutil.Encode(signedBlsToExecutionChange.Signature),
}, nil
}
func SignedBlsToExecutionChangesFromConsensus(blsToExecutionChanges []*eth.SignedBLSToExecutionChange) ([]*SignedBLSToExecutionChange, error) {
jsonBlsToExecutionChanges := make([]*SignedBLSToExecutionChange, len(blsToExecutionChanges))
for index, signedBlsToExecutionChange := range blsToExecutionChanges {
sbls, err := SignedBlsToExecutionChangeFromConsensus(signedBlsToExecutionChange)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("blsExecutionChange message failed to encode at index %d", index))
}
jsonBlsToExecutionChanges[index] = sbls
}
return jsonBlsToExecutionChanges, nil
}
func (s *Fork) ToConsensus() (*eth.Fork, error) {
previousVersion, err := hexutil.Decode(s.PreviousVersion)
if err != nil {
return nil, NewDecodeError(err, "PreviousVersion")
}
currentVersion, err := hexutil.Decode(s.CurrentVersion)
if err != nil {
return nil, NewDecodeError(err, "CurrentVersion")
}
epoch, err := strconv.ParseUint(s.Epoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Epoch")
}
return &eth.Fork{
PreviousVersion: previousVersion,
CurrentVersion: currentVersion,
Epoch: primitives.Epoch(epoch),
}, nil
}
func ForkFromConsensus(f *eth.Fork) (*Fork, error) {
if f == nil {
return nil, errors.New("fork is empty")
}
return &Fork{
PreviousVersion: hexutil.Encode(f.PreviousVersion),
CurrentVersion: hexutil.Encode(f.CurrentVersion),
Epoch: strconv.FormatUint(uint64(f.Epoch), 10),
}, nil
}
type SyncCommitteeMessage struct {
Slot string `json:"slot"`
BeaconBlockRoot string `json:"beacon_block_root"`
@@ -244,450 +148,6 @@ type SyncCommittee struct {
AggregatePubkey string `json:"aggregate_pubkey"`
}
func (s *SignedValidatorRegistration) ToConsensus() (*eth.SignedValidatorRegistrationV1, error) {
msg, err := s.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
sig, err := DecodeHexWithLength(s.Signature, fieldparams.BLSSignatureLength)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SignedValidatorRegistrationV1{
Message: msg,
Signature: sig,
}, nil
}
func (s *ValidatorRegistration) ToConsensus() (*eth.ValidatorRegistrationV1, error) {
feeRecipient, err := DecodeHexWithLength(s.FeeRecipient, fieldparams.FeeRecipientLength)
if err != nil {
return nil, NewDecodeError(err, "FeeRecipient")
}
pubKey, err := DecodeHexWithLength(s.Pubkey, fieldparams.BLSPubkeyLength)
if err != nil {
return nil, NewDecodeError(err, "Pubkey")
}
gasLimit, err := strconv.ParseUint(s.GasLimit, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "GasLimit")
}
timestamp, err := strconv.ParseUint(s.Timestamp, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Timestamp")
}
return &eth.ValidatorRegistrationV1{
FeeRecipient: feeRecipient,
GasLimit: gasLimit,
Timestamp: timestamp,
Pubkey: pubKey,
}, nil
}
func ValidatorRegistrationFromConsensus(vr *eth.ValidatorRegistrationV1) (*ValidatorRegistration, error) {
if vr == nil {
return nil, errors.New("ValidatorRegistrationV1 is empty")
}
return &ValidatorRegistration{
FeeRecipient: hexutil.Encode(vr.FeeRecipient),
GasLimit: strconv.FormatUint(vr.GasLimit, 10),
Timestamp: strconv.FormatUint(vr.Timestamp, 10),
Pubkey: hexutil.Encode(vr.Pubkey),
}, nil
}
func SignedValidatorRegistrationFromConsensus(vr *eth.SignedValidatorRegistrationV1) (*SignedValidatorRegistration, error) {
if vr == nil {
return nil, errors.New("SignedValidatorRegistrationV1 is empty")
}
v, err := ValidatorRegistrationFromConsensus(vr.Message)
if err != nil {
return nil, err
}
return &SignedValidatorRegistration{
Message: v,
Signature: hexutil.Encode(vr.Signature),
}, nil
}
func (s *SignedContributionAndProof) ToConsensus() (*eth.SignedContributionAndProof, error) {
msg, err := s.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
sig, err := hexutil.Decode(s.Signature)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SignedContributionAndProof{
Message: msg,
Signature: sig,
}, nil
}
func SignedContributionAndProofFromConsensus(c *eth.SignedContributionAndProof) *SignedContributionAndProof {
contribution := ContributionAndProofFromConsensus(c.Message)
return &SignedContributionAndProof{
Message: contribution,
Signature: hexutil.Encode(c.Signature),
}
}
func (c *ContributionAndProof) ToConsensus() (*eth.ContributionAndProof, error) {
contribution, err := c.Contribution.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Contribution")
}
aggregatorIndex, err := strconv.ParseUint(c.AggregatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "AggregatorIndex")
}
selectionProof, err := hexutil.Decode(c.SelectionProof)
if err != nil {
return nil, NewDecodeError(err, "SelectionProof")
}
return &eth.ContributionAndProof{
AggregatorIndex: primitives.ValidatorIndex(aggregatorIndex),
Contribution: contribution,
SelectionProof: selectionProof,
}, nil
}
func ContributionAndProofFromConsensus(c *eth.ContributionAndProof) *ContributionAndProof {
contribution := SyncCommitteeContributionFromConsensus(c.Contribution)
return &ContributionAndProof{
AggregatorIndex: fmt.Sprintf("%d", c.AggregatorIndex),
Contribution: contribution,
SelectionProof: hexutil.Encode(c.SelectionProof),
}
}
func (s *SyncCommitteeContribution) ToConsensus() (*eth.SyncCommitteeContribution, error) {
slot, err := strconv.ParseUint(s.Slot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Slot")
}
bbRoot, err := hexutil.Decode(s.BeaconBlockRoot)
if err != nil {
return nil, NewDecodeError(err, "BeaconBlockRoot")
}
subcommitteeIndex, err := strconv.ParseUint(s.SubcommitteeIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "SubcommitteeIndex")
}
aggBits, err := hexutil.Decode(s.AggregationBits)
if err != nil {
return nil, NewDecodeError(err, "AggregationBits")
}
sig, err := hexutil.Decode(s.Signature)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SyncCommitteeContribution{
Slot: primitives.Slot(slot),
BlockRoot: bbRoot,
SubcommitteeIndex: subcommitteeIndex,
AggregationBits: aggBits,
Signature: sig,
}, nil
}
func SyncCommitteeContributionFromConsensus(c *eth.SyncCommitteeContribution) *SyncCommitteeContribution {
return &SyncCommitteeContribution{
Slot: fmt.Sprintf("%d", c.Slot),
BeaconBlockRoot: hexutil.Encode(c.BlockRoot),
SubcommitteeIndex: fmt.Sprintf("%d", c.SubcommitteeIndex),
AggregationBits: hexutil.Encode(c.AggregationBits),
Signature: hexutil.Encode(c.Signature),
}
}
func (s *SignedAggregateAttestationAndProof) ToConsensus() (*eth.SignedAggregateAttestationAndProof, error) {
msg, err := s.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
sig, err := hexutil.Decode(s.Signature)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SignedAggregateAttestationAndProof{
Message: msg,
Signature: sig,
}, nil
}
func (a *AggregateAttestationAndProof) ToConsensus() (*eth.AggregateAttestationAndProof, error) {
aggIndex, err := strconv.ParseUint(a.AggregatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "AggregatorIndex")
}
agg, err := a.Aggregate.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Aggregate")
}
proof, err := hexutil.Decode(a.SelectionProof)
if err != nil {
return nil, NewDecodeError(err, "SelectionProof")
}
return &eth.AggregateAttestationAndProof{
AggregatorIndex: primitives.ValidatorIndex(aggIndex),
Aggregate: agg,
SelectionProof: proof,
}, nil
}
func (a *Attestation) ToConsensus() (*eth.Attestation, error) {
aggBits, err := hexutil.Decode(a.AggregationBits)
if err != nil {
return nil, NewDecodeError(err, "AggregationBits")
}
data, err := a.Data.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Data")
}
sig, err := hexutil.Decode(a.Signature)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.Attestation{
AggregationBits: aggBits,
Data: data,
Signature: sig,
}, nil
}
func AttestationFromConsensus(a *eth.Attestation) *Attestation {
return &Attestation{
AggregationBits: hexutil.Encode(a.AggregationBits),
Data: AttestationDataFromConsensus(a.Data),
Signature: hexutil.Encode(a.Signature),
}
}
func (a *AttestationData) ToConsensus() (*eth.AttestationData, error) {
slot, err := strconv.ParseUint(a.Slot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Slot")
}
committeeIndex, err := strconv.ParseUint(a.CommitteeIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "CommitteeIndex")
}
bbRoot, err := hexutil.Decode(a.BeaconBlockRoot)
if err != nil {
return nil, NewDecodeError(err, "BeaconBlockRoot")
}
source, err := a.Source.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Source")
}
target, err := a.Target.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Target")
}
return &eth.AttestationData{
Slot: primitives.Slot(slot),
CommitteeIndex: primitives.CommitteeIndex(committeeIndex),
BeaconBlockRoot: bbRoot,
Source: source,
Target: target,
}, nil
}
func AttestationDataFromConsensus(a *eth.AttestationData) *AttestationData {
return &AttestationData{
Slot: strconv.FormatUint(uint64(a.Slot), 10),
CommitteeIndex: strconv.FormatUint(uint64(a.CommitteeIndex), 10),
BeaconBlockRoot: hexutil.Encode(a.BeaconBlockRoot),
Source: CheckpointFromConsensus(a.Source),
Target: CheckpointFromConsensus(a.Target),
}
}
func (c *Checkpoint) ToConsensus() (*eth.Checkpoint, error) {
epoch, err := strconv.ParseUint(c.Epoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Epoch")
}
root, err := hexutil.Decode(c.Root)
if err != nil {
return nil, NewDecodeError(err, "Root")
}
return &eth.Checkpoint{
Epoch: primitives.Epoch(epoch),
Root: root,
}, nil
}
func CheckpointFromConsensus(c *eth.Checkpoint) *Checkpoint {
return &Checkpoint{
Epoch: strconv.FormatUint(uint64(c.Epoch), 10),
Root: hexutil.Encode(c.Root),
}
}
func (s *SyncCommitteeSubscription) ToConsensus() (*validator.SyncCommitteeSubscription, error) {
index, err := strconv.ParseUint(s.ValidatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ValidatorIndex")
}
scIndices := make([]uint64, len(s.SyncCommitteeIndices))
for i, ix := range s.SyncCommitteeIndices {
scIndices[i], err = strconv.ParseUint(ix, 10, 64)
if err != nil {
return nil, NewDecodeError(err, fmt.Sprintf("SyncCommitteeIndices[%d]", i))
}
}
epoch, err := strconv.ParseUint(s.UntilEpoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "UntilEpoch")
}
return &validator.SyncCommitteeSubscription{
ValidatorIndex: primitives.ValidatorIndex(index),
SyncCommitteeIndices: scIndices,
UntilEpoch: primitives.Epoch(epoch),
}, nil
}
func (b *BeaconCommitteeSubscription) ToConsensus() (*validator.BeaconCommitteeSubscription, error) {
valIndex, err := strconv.ParseUint(b.ValidatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ValidatorIndex")
}
committeeIndex, err := strconv.ParseUint(b.CommitteeIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "CommitteeIndex")
}
committeesAtSlot, err := strconv.ParseUint(b.CommitteesAtSlot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "CommitteesAtSlot")
}
slot, err := strconv.ParseUint(b.Slot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Slot")
}
return &validator.BeaconCommitteeSubscription{
ValidatorIndex: primitives.ValidatorIndex(valIndex),
CommitteeIndex: primitives.CommitteeIndex(committeeIndex),
CommitteesAtSlot: committeesAtSlot,
Slot: primitives.Slot(slot),
IsAggregator: b.IsAggregator,
}, nil
}
func (e *SignedVoluntaryExit) ToConsensus() (*eth.SignedVoluntaryExit, error) {
sig, err := hexutil.Decode(e.Signature)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
exit, err := e.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
return &eth.SignedVoluntaryExit{
Exit: exit,
Signature: sig,
}, nil
}
func SignedVoluntaryExitFromConsensus(e *eth.SignedVoluntaryExit) *SignedVoluntaryExit {
return &SignedVoluntaryExit{
Message: VoluntaryExitFromConsensus(e.Exit),
Signature: hexutil.Encode(e.Signature),
}
}
func (e *VoluntaryExit) ToConsensus() (*eth.VoluntaryExit, error) {
epoch, err := strconv.ParseUint(e.Epoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Epoch")
}
valIndex, err := strconv.ParseUint(e.ValidatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ValidatorIndex")
}
return &eth.VoluntaryExit{
Epoch: primitives.Epoch(epoch),
ValidatorIndex: primitives.ValidatorIndex(valIndex),
}, nil
}
func VoluntaryExitFromConsensus(e *eth.VoluntaryExit) *VoluntaryExit {
return &VoluntaryExit{
Epoch: strconv.FormatUint(uint64(e.Epoch), 10),
ValidatorIndex: strconv.FormatUint(uint64(e.ValidatorIndex), 10),
}
}
func (m *SyncCommitteeMessage) ToConsensus() (*eth.SyncCommitteeMessage, error) {
slot, err := strconv.ParseUint(m.Slot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Slot")
}
root, err := DecodeHexWithLength(m.BeaconBlockRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "BeaconBlockRoot")
}
valIndex, err := strconv.ParseUint(m.ValidatorIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ValidatorIndex")
}
sig, err := DecodeHexWithLength(m.Signature, fieldparams.BLSSignatureLength)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SyncCommitteeMessage{
Slot: primitives.Slot(slot),
BlockRoot: root,
ValidatorIndex: primitives.ValidatorIndex(valIndex),
Signature: sig,
}, nil
}
func SyncCommitteeFromConsensus(sc *eth.SyncCommittee) *SyncCommittee {
var sPubKeys []string
for _, p := range sc.Pubkeys {
sPubKeys = append(sPubKeys, hexutil.Encode(p))
}
return &SyncCommittee{
Pubkeys: sPubKeys,
AggregatePubkey: hexutil.Encode(sc.AggregatePubkey),
}
}
func (sc *SyncCommittee) ToConsensus() (*eth.SyncCommittee, error) {
var pubKeys [][]byte
for _, p := range sc.Pubkeys {
pubKey, err := hexutil.Decode(p)
if err != nil {
return nil, NewDecodeError(err, "Pubkeys")
}
pubKeys = append(pubKeys, pubKey)
}
aggPubKey, err := hexutil.Decode(sc.AggregatePubkey)
if err != nil {
return nil, NewDecodeError(err, "AggregatePubkey")
}
return &eth.SyncCommittee{
Pubkeys: pubKeys,
AggregatePubkey: aggPubKey,
}, nil
}
// SyncDetails contains information about node sync status.
type SyncDetails struct {
HeadSlot string `json:"head_slot"`
@@ -702,103 +162,48 @@ type SyncDetailsContainer struct {
Data *SyncDetails `json:"data"`
}
// ChainHead is the response for api endpoint /beacon/chainhead
type ChainHead struct {
HeadSlot string `json:"head_slot"`
HeadEpoch string `json:"head_epoch"`
HeadBlockRoot string `json:"head_block_root"`
FinalizedSlot string `json:"finalized_slot"`
FinalizedEpoch string `json:"finalized_epoch"`
FinalizedBlockRoot string `json:"finalized_block_root"`
JustifiedSlot string `json:"justified_slot"`
JustifiedEpoch string `json:"justified_epoch"`
JustifiedBlockRoot string `json:"justified_block_root"`
PreviousJustifiedSlot string `json:"previous_justified_slot"`
PreviousJustifiedEpoch string `json:"previous_justified_epoch"`
PreviousJustifiedBlockRoot string `json:"previous_justified_block_root"`
OptimisticStatus bool `json:"optimistic_status"`
type Eth1Data struct {
DepositRoot string `json:"deposit_root"`
DepositCount string `json:"deposit_count"`
BlockHash string `json:"block_hash"`
}
func ChainHeadResponseFromConsensus(e *eth.ChainHead) *ChainHead {
return &ChainHead{
HeadSlot: fmt.Sprintf("%d", e.HeadSlot),
HeadEpoch: fmt.Sprintf("%d", e.HeadEpoch),
HeadBlockRoot: hexutil.Encode(e.HeadBlockRoot),
FinalizedSlot: fmt.Sprintf("%d", e.FinalizedSlot),
FinalizedEpoch: fmt.Sprintf("%d", e.FinalizedEpoch),
FinalizedBlockRoot: hexutil.Encode(e.FinalizedBlockRoot),
JustifiedSlot: fmt.Sprintf("%d", e.JustifiedSlot),
JustifiedEpoch: fmt.Sprintf("%d", e.JustifiedEpoch),
JustifiedBlockRoot: hexutil.Encode(e.JustifiedBlockRoot),
PreviousJustifiedSlot: fmt.Sprintf("%d", e.PreviousJustifiedSlot),
PreviousJustifiedEpoch: fmt.Sprintf("%d", e.PreviousJustifiedEpoch),
PreviousJustifiedBlockRoot: hexutil.Encode(e.PreviousJustifiedBlockRoot),
OptimisticStatus: e.OptimisticStatus,
}
type ProposerSlashing struct {
SignedHeader1 *SignedBeaconBlockHeader `json:"signed_header_1"`
SignedHeader2 *SignedBeaconBlockHeader `json:"signed_header_2"`
}
func (m *ChainHead) ToConsensus() (*eth.ChainHead, error) {
headSlot, err := strconv.ParseUint(m.HeadSlot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "HeadSlot")
}
headEpoch, err := strconv.ParseUint(m.HeadEpoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "HeadEpoch")
}
headBlockRoot, err := DecodeHexWithLength(m.HeadBlockRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "HeadBlockRoot")
}
finalizedSlot, err := strconv.ParseUint(m.FinalizedSlot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "FinalizedSlot")
}
finalizedEpoch, err := strconv.ParseUint(m.FinalizedEpoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "FinalizedEpoch")
}
finalizedBlockRoot, err := DecodeHexWithLength(m.FinalizedBlockRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "FinalizedBlockRoot")
}
justifiedSlot, err := strconv.ParseUint(m.JustifiedSlot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "JustifiedSlot")
}
justifiedEpoch, err := strconv.ParseUint(m.JustifiedEpoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "JustifiedEpoch")
}
justifiedBlockRoot, err := DecodeHexWithLength(m.JustifiedBlockRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "JustifiedBlockRoot")
}
previousjustifiedSlot, err := strconv.ParseUint(m.PreviousJustifiedSlot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "PreviousJustifiedSlot")
}
previousjustifiedEpoch, err := strconv.ParseUint(m.PreviousJustifiedEpoch, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "PreviousJustifiedEpoch")
}
previousjustifiedBlockRoot, err := DecodeHexWithLength(m.PreviousJustifiedBlockRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "PreviousJustifiedBlockRoot")
}
return &eth.ChainHead{
HeadSlot: primitives.Slot(headSlot),
HeadEpoch: primitives.Epoch(headEpoch),
HeadBlockRoot: headBlockRoot,
FinalizedSlot: primitives.Slot(finalizedSlot),
FinalizedEpoch: primitives.Epoch(finalizedEpoch),
FinalizedBlockRoot: finalizedBlockRoot,
JustifiedSlot: primitives.Slot(justifiedSlot),
JustifiedEpoch: primitives.Epoch(justifiedEpoch),
JustifiedBlockRoot: justifiedBlockRoot,
PreviousJustifiedSlot: primitives.Slot(previousjustifiedSlot),
PreviousJustifiedEpoch: primitives.Epoch(previousjustifiedEpoch),
PreviousJustifiedBlockRoot: previousjustifiedBlockRoot,
OptimisticStatus: m.OptimisticStatus,
}, nil
type AttesterSlashing struct {
Attestation1 *IndexedAttestation `json:"attestation_1"`
Attestation2 *IndexedAttestation `json:"attestation_2"`
}
type Deposit struct {
Proof []string `json:"proof"`
Data *DepositData `json:"data"`
}
type DepositData struct {
Pubkey string `json:"pubkey"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
Amount string `json:"amount"`
Signature string `json:"signature"`
}
type IndexedAttestation struct {
AttestingIndices []string `json:"attesting_indices"`
Data *AttestationData `json:"data"`
Signature string `json:"signature"`
}
type SyncAggregate struct {
SyncCommitteeBits string `json:"sync_committee_bits"`
SyncCommitteeSignature string `json:"sync_committee_signature"`
}
type Withdrawal struct {
WithdrawalIndex string `json:"index"`
ValidatorIndex string `json:"validator_index"`
ExecutionAddress string `json:"address"`
Amount string `json:"amount"`
}

View File

@@ -0,0 +1,353 @@
package shared
type SignedBeaconBlock struct {
Message *BeaconBlock `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlock struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BeaconBlockBody `json:"body"`
}
type BeaconBlockBody struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
}
type SignedBeaconBlockAltair struct {
Message *BeaconBlockAltair `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlockAltair struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BeaconBlockBodyAltair `json:"body"`
}
type BeaconBlockBodyAltair struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
}
type SignedBeaconBlockBellatrix struct {
Message *BeaconBlockBellatrix `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlockBellatrix struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BeaconBlockBodyBellatrix `json:"body"`
}
type BeaconBlockBodyBellatrix struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayload *ExecutionPayload `json:"execution_payload"`
}
type SignedBlindedBeaconBlockBellatrix struct {
Message *BlindedBeaconBlockBellatrix `json:"message"`
Signature string `json:"signature"`
}
type BlindedBeaconBlockBellatrix struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BlindedBeaconBlockBodyBellatrix `json:"body"`
}
type BlindedBeaconBlockBodyBellatrix struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayloadHeader *ExecutionPayloadHeader `json:"execution_payload_header"`
}
type SignedBeaconBlockCapella struct {
Message *BeaconBlockCapella `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlockCapella struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BeaconBlockBodyCapella `json:"body"`
}
type BeaconBlockBodyCapella struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayload *ExecutionPayloadCapella `json:"execution_payload"`
BLSToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes"`
}
type SignedBlindedBeaconBlockCapella struct {
Message *BlindedBeaconBlockCapella `json:"message"`
Signature string `json:"signature"`
}
type BlindedBeaconBlockCapella struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BlindedBeaconBlockBodyCapella `json:"body"`
}
type BlindedBeaconBlockBodyCapella struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayloadHeader *ExecutionPayloadHeaderCapella `json:"execution_payload_header"`
BLSToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes"`
}
type SignedBeaconBlockContentsDeneb struct {
SignedBlock *SignedBeaconBlockDeneb `json:"signed_block"`
KzgProofs []string `json:"kzg_proofs"`
Blobs []string `json:"blobs"`
}
type BeaconBlockContentsDeneb struct {
Block *BeaconBlockDeneb `json:"block"`
KzgProofs []string `json:"kzg_proofs"`
Blobs []string `json:"blobs"`
}
type SignedBeaconBlockDeneb struct {
Message *BeaconBlockDeneb `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlockDeneb struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BeaconBlockBodyDeneb `json:"body"`
}
type BeaconBlockBodyDeneb struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayload *ExecutionPayloadDeneb `json:"execution_payload"`
BLSToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes"`
BlobKzgCommitments []string `json:"blob_kzg_commitments"`
}
type BlindedBeaconBlockDeneb struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
Body *BlindedBeaconBlockBodyDeneb `json:"body"`
}
type SignedBlindedBeaconBlockDeneb struct {
Message *BlindedBeaconBlockDeneb `json:"message"`
Signature string `json:"signature"`
}
type BlindedBeaconBlockBodyDeneb struct {
RandaoReveal string `json:"randao_reveal"`
Eth1Data *Eth1Data `json:"eth1_data"`
Graffiti string `json:"graffiti"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings"`
Attestations []*Attestation `json:"attestations"`
Deposits []*Deposit `json:"deposits"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits"`
SyncAggregate *SyncAggregate `json:"sync_aggregate"`
ExecutionPayloadHeader *ExecutionPayloadHeaderDeneb `json:"execution_payload_header"`
BLSToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes"`
BlobKzgCommitments []string `json:"blob_kzg_commitments"`
}
type SignedBeaconBlockHeaderContainer struct {
Header *SignedBeaconBlockHeader `json:"header"`
Root string `json:"root"`
Canonical bool `json:"canonical"`
}
type SignedBeaconBlockHeader struct {
Message *BeaconBlockHeader `json:"message"`
Signature string `json:"signature"`
}
type BeaconBlockHeader struct {
Slot string `json:"slot"`
ProposerIndex string `json:"proposer_index"`
ParentRoot string `json:"parent_root"`
StateRoot string `json:"state_root"`
BodyRoot string `json:"body_root"`
}
type ExecutionPayload struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlockHash string `json:"block_hash"`
Transactions []string `json:"transactions"`
}
type ExecutionPayloadHeader struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlockHash string `json:"block_hash"`
TransactionsRoot string `json:"transactions_root"`
}
type ExecutionPayloadCapella struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlockHash string `json:"block_hash"`
Transactions []string `json:"transactions"`
Withdrawals []*Withdrawal `json:"withdrawals"`
}
type ExecutionPayloadHeaderCapella struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlockHash string `json:"block_hash"`
TransactionsRoot string `json:"transactions_root"`
WithdrawalsRoot string `json:"withdrawals_root"`
}
type ExecutionPayloadDeneb struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlobGasUsed string `json:"blob_gas_used"`
ExcessBlobGas string `json:"excess_blob_gas"`
BlockHash string `json:"block_hash"`
Transactions []string `json:"transactions"`
Withdrawals []*Withdrawal `json:"withdrawals"`
}
type ExecutionPayloadHeaderDeneb struct {
ParentHash string `json:"parent_hash"`
FeeRecipient string `json:"fee_recipient"`
StateRoot string `json:"state_root"`
ReceiptsRoot string `json:"receipts_root"`
LogsBloom string `json:"logs_bloom"`
PrevRandao string `json:"prev_randao"`
BlockNumber string `json:"block_number"`
GasLimit string `json:"gas_limit"`
GasUsed string `json:"gas_used"`
Timestamp string `json:"timestamp"`
ExtraData string `json:"extra_data"`
BaseFeePerGas string `json:"base_fee_per_gas"`
BlobGasUsed string `json:"blob_gas_used"`
ExcessBlobGas string `json:"excess_blob_gas"`
BlockHash string `json:"block_hash"`
TransactionsRoot string `json:"transactions_root"`
WithdrawalsRoot string `json:"withdrawals_root"`
}

View File

@@ -1,540 +0,0 @@
package shared
import (
"fmt"
"strconv"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
fieldparams "github.com/prysmaticlabs/prysm/v4/config/fieldparams"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
type SignedBeaconBlock struct {
Message *BeaconBlock `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BeaconBlock struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BeaconBlockBody `json:"body" validate:"required"`
}
type BeaconBlockBody struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required"`
Attestations []*Attestation `json:"attestations" validate:"required"`
Deposits []*Deposit `json:"deposits" validate:"required"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required"`
}
type SignedBeaconBlockAltair struct {
Message *BeaconBlockAltair `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BeaconBlockAltair struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BeaconBlockBodyAltair `json:"body" validate:"required"`
}
type BeaconBlockBodyAltair struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
}
type SignedBeaconBlockBellatrix struct {
Message *BeaconBlockBellatrix `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BeaconBlockBellatrix struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BeaconBlockBodyBellatrix `json:"body" validate:"required"`
}
type BeaconBlockBodyBellatrix struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayload *ExecutionPayload `json:"execution_payload" validate:"required"`
}
type SignedBlindedBeaconBlockBellatrix struct {
Message *BlindedBeaconBlockBellatrix `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BlindedBeaconBlockBellatrix struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BlindedBeaconBlockBodyBellatrix `json:"body" validate:"required"`
}
type BlindedBeaconBlockBodyBellatrix struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayloadHeader *ExecutionPayloadHeader `json:"execution_payload_header" validate:"required"`
}
type SignedBeaconBlockCapella struct {
Message *BeaconBlockCapella `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BeaconBlockCapella struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BeaconBlockBodyCapella `json:"body" validate:"required"`
}
type BeaconBlockBodyCapella struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayload *ExecutionPayloadCapella `json:"execution_payload" validate:"required"`
BlsToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes" validate:"required,dive"`
}
type SignedBlindedBeaconBlockCapella struct {
Message *BlindedBeaconBlockCapella `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BlindedBeaconBlockCapella struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BlindedBeaconBlockBodyCapella `json:"body" validate:"required"`
}
type BlindedBeaconBlockBodyCapella struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayloadHeader *ExecutionPayloadHeaderCapella `json:"execution_payload_header" validate:"required"`
BlsToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes" validate:"required,dive"`
}
type SignedBeaconBlockContentsDeneb struct {
SignedBlock *SignedBeaconBlockDeneb `json:"signed_block" `
KzgProofs []string `json:"kzg_proofs"`
Blobs []string `json:"blobs"`
}
type BeaconBlockContentsDeneb struct {
Block *BeaconBlockDeneb `json:"block" `
KzgProofs []string `json:"kzg_proofs"`
Blobs []string `json:"blobs"`
}
type SignedBeaconBlockDeneb struct {
Message *BeaconBlockDeneb `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BeaconBlockDeneb struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BeaconBlockBodyDeneb `json:"body" validate:"required"`
}
type BeaconBlockBodyDeneb struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayload *ExecutionPayloadDeneb `json:"execution_payload" validate:"required"`
BlsToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes" validate:"required,dive"`
BlobKzgCommitments []string `json:"blob_kzg_commitments" validate:"required,dive"`
}
type ExecutionPayloadDeneb struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlobGasUsed string `json:"blob_gas_used" validate:"required"` // new in deneb
ExcessBlobGas string `json:"excess_blob_gas" validate:"required"` // new in deneb
BlockHash string `json:"block_hash" validate:"required"`
Transactions []string `json:"transactions" validate:"required,dive,hexadecimal"`
Withdrawals []*Withdrawal `json:"withdrawals" validate:"required,dive"`
}
type BlindedBeaconBlockDeneb struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
Body *BlindedBeaconBlockBodyDeneb `json:"body" validate:"required"`
}
type SignedBlindedBeaconBlockDeneb struct {
Message *BlindedBeaconBlockDeneb `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type BlindedBeaconBlockBodyDeneb struct {
RandaoReveal string `json:"randao_reveal" validate:"required"`
Eth1Data *Eth1Data `json:"eth1_data" validate:"required"`
Graffiti string `json:"graffiti" validate:"required"`
ProposerSlashings []*ProposerSlashing `json:"proposer_slashings" validate:"required,dive"`
AttesterSlashings []*AttesterSlashing `json:"attester_slashings" validate:"required,dive"`
Attestations []*Attestation `json:"attestations" validate:"required,dive"`
Deposits []*Deposit `json:"deposits" validate:"required,dive"`
VoluntaryExits []*SignedVoluntaryExit `json:"voluntary_exits" validate:"required,dive"`
SyncAggregate *SyncAggregate `json:"sync_aggregate" validate:"required"`
ExecutionPayloadHeader *ExecutionPayloadHeaderDeneb `json:"execution_payload_header" validate:"required"`
BlsToExecutionChanges []*SignedBLSToExecutionChange `json:"bls_to_execution_changes" validate:"required,dive"`
BlobKzgCommitments []string `json:"blob_kzg_commitments" validate:"required,dive,hexadecimal"`
}
type Eth1Data struct {
DepositRoot string `json:"deposit_root" validate:"required"`
DepositCount string `json:"deposit_count" validate:"required"`
BlockHash string `json:"block_hash" validate:"required"`
}
func Eth1DataFromConsensus(e1d *eth.Eth1Data) (*Eth1Data, error) {
if e1d == nil {
return nil, errors.New("eth1data is nil")
}
return &Eth1Data{
DepositRoot: hexutil.Encode(e1d.DepositRoot),
DepositCount: fmt.Sprintf("%d", e1d.DepositCount),
BlockHash: hexutil.Encode(e1d.BlockHash),
}, nil
}
type ProposerSlashing struct {
SignedHeader1 *SignedBeaconBlockHeader `json:"signed_header_1" validate:"required"`
SignedHeader2 *SignedBeaconBlockHeader `json:"signed_header_2" validate:"required"`
}
func (s *ProposerSlashing) ToConsensus() (*eth.ProposerSlashing, error) {
h1, err := s.SignedHeader1.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "SignedHeader1")
}
h2, err := s.SignedHeader2.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "SignedHeader2")
}
return &eth.ProposerSlashing{
Header_1: h1,
Header_2: h2,
}, nil
}
type AttesterSlashing struct {
Attestation1 *IndexedAttestation `json:"attestation_1" validate:"required"`
Attestation2 *IndexedAttestation `json:"attestation_2" validate:"required"`
}
func (s *AttesterSlashing) ToConsensus() (*eth.AttesterSlashing, error) {
att1, err := s.Attestation1.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Attestation1")
}
att2, err := s.Attestation2.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Attestation2")
}
return &eth.AttesterSlashing{Attestation_1: att1, Attestation_2: att2}, nil
}
type Deposit struct {
Proof []string `json:"proof" validate:"required,dive,hexadecimal"`
Data *DepositData `json:"data" validate:"required"`
}
type DepositData struct {
Pubkey string `json:"pubkey" validate:"required"`
WithdrawalCredentials string `json:"withdrawal_credentials" validate:"required"`
Amount string `json:"amount" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
type SignedBeaconBlockHeaderContainer struct {
Header *SignedBeaconBlockHeader `json:"header"`
Root string `json:"root"`
Canonical bool `json:"canonical"`
}
type SignedBeaconBlockHeader struct {
Message *BeaconBlockHeader `json:"message" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
func (h *SignedBeaconBlockHeader) ToConsensus() (*eth.SignedBeaconBlockHeader, error) {
msg, err := h.Message.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Message")
}
sig, err := DecodeHexWithLength(h.Signature, fieldparams.BLSSignatureLength)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.SignedBeaconBlockHeader{
Header: msg,
Signature: sig,
}, nil
}
type BeaconBlockHeader struct {
Slot string `json:"slot" validate:"required"`
ProposerIndex string `json:"proposer_index" validate:"required"`
ParentRoot string `json:"parent_root" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
BodyRoot string `json:"body_root" validate:"required"`
}
func (h *BeaconBlockHeader) ToConsensus() (*eth.BeaconBlockHeader, error) {
s, err := strconv.ParseUint(h.Slot, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "Slot")
}
pi, err := strconv.ParseUint(h.ProposerIndex, 10, 64)
if err != nil {
return nil, NewDecodeError(err, "ProposerIndex")
}
pr, err := DecodeHexWithLength(h.ParentRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "ParentRoot")
}
sr, err := DecodeHexWithLength(h.StateRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "StateRoot")
}
br, err := DecodeHexWithLength(h.BodyRoot, fieldparams.RootLength)
if err != nil {
return nil, NewDecodeError(err, "BodyRoot")
}
return &eth.BeaconBlockHeader{
Slot: primitives.Slot(s),
ProposerIndex: primitives.ValidatorIndex(pi),
ParentRoot: pr,
StateRoot: sr,
BodyRoot: br,
}, nil
}
type IndexedAttestation struct {
AttestingIndices []string `json:"attesting_indices" validate:"required,dive"`
Data *AttestationData `json:"data" validate:"required"`
Signature string `json:"signature" validate:"required"`
}
func (a *IndexedAttestation) ToConsensus() (*eth.IndexedAttestation, error) {
indices := make([]uint64, len(a.AttestingIndices))
var err error
for i, ix := range a.AttestingIndices {
indices[i], err = strconv.ParseUint(ix, 10, 64)
if err != nil {
return nil, NewDecodeError(err, fmt.Sprintf("AttestingIndices[%d]", i))
}
}
data, err := a.Data.ToConsensus()
if err != nil {
return nil, NewDecodeError(err, "Data")
}
sig, err := DecodeHexWithLength(a.Signature, fieldparams.BLSSignatureLength)
if err != nil {
return nil, NewDecodeError(err, "Signature")
}
return &eth.IndexedAttestation{
AttestingIndices: indices,
Data: data,
Signature: sig,
}, nil
}
type SyncAggregate struct {
SyncCommitteeBits string `json:"sync_committee_bits" validate:"required"`
SyncCommitteeSignature string `json:"sync_committee_signature" validate:"required"`
}
type ExecutionPayload struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlockHash string `json:"block_hash" validate:"required"`
Transactions []string `json:"transactions" validate:"required,dive,hexadecimal"`
}
type ExecutionPayloadHeader struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlockHash string `json:"block_hash" validate:"required"`
TransactionsRoot string `json:"transactions_root" validate:"required"`
}
type ExecutionPayloadCapella struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlockHash string `json:"block_hash" validate:"required"`
Transactions []string `json:"transactions" validate:"required,dive"`
Withdrawals []*Withdrawal `json:"withdrawals" validate:"required,dive"`
}
type ExecutionPayloadHeaderCapella struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlockHash string `json:"block_hash" validate:"required"`
TransactionsRoot string `json:"transactions_root" validate:"required"`
WithdrawalsRoot string `json:"withdrawals_root" validate:"required"`
}
type ExecutionPayloadHeaderDeneb struct {
ParentHash string `json:"parent_hash" validate:"required"`
FeeRecipient string `json:"fee_recipient" validate:"required"`
StateRoot string `json:"state_root" validate:"required"`
ReceiptsRoot string `json:"receipts_root" validate:"required"`
LogsBloom string `json:"logs_bloom" validate:"required"`
PrevRandao string `json:"prev_randao" validate:"required"`
BlockNumber string `json:"block_number" validate:"required"`
GasLimit string `json:"gas_limit" validate:"required"`
GasUsed string `json:"gas_used" validate:"required"`
Timestamp string `json:"timestamp" validate:"required"`
ExtraData string `json:"extra_data" validate:"required"`
BaseFeePerGas string `json:"base_fee_per_gas" validate:"required"`
BlobGasUsed string `json:"blob_gas_used" validate:"required"` // new in deneb
ExcessBlobGas string `json:"excess_blob_gas" validate:"required"` // new in deneb
BlockHash string `json:"block_hash" validate:"required"`
TransactionsRoot string `json:"transactions_root" validate:"required"`
WithdrawalsRoot string `json:"withdrawals_root" validate:"required"`
}
type Withdrawal struct {
WithdrawalIndex string `json:"index" validate:"required"`
ValidatorIndex string `json:"validator_index" validate:"required"`
ExecutionAddress string `json:"address" validate:"required"`
Amount string `json:"amount" validate:"required"`
}
func WithdrawalsFromConsensus(ws []*enginev1.Withdrawal) []*Withdrawal {
result := make([]*Withdrawal, len(ws))
for i, w := range ws {
result[i] = WithdrawalFromConsensus(w)
}
return result
}
func WithdrawalFromConsensus(w *enginev1.Withdrawal) *Withdrawal {
return &Withdrawal{
WithdrawalIndex: fmt.Sprintf("%d", w.Index),
ValidatorIndex: fmt.Sprintf("%d", w.ValidatorIndex),
ExecutionAddress: hexutil.Encode(w.Address),
Amount: fmt.Sprintf("%d", w.Amount),
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,142 @@
package shared
type BeaconState struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *Fork `json:"fork"`
LatestBlockHeader *BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *Eth1Data `json:"eth1_data"`
Eth1DataVotes []*Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochAttestations []*PendingAttestation `json:"previous_epoch_attestations"`
CurrentEpochAttestations []*PendingAttestation `json:"current_epoch_attestations"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
}
type BeaconStateAltair struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *Fork `json:"fork"`
LatestBlockHeader *BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *Eth1Data `json:"eth1_data"`
Eth1DataVotes []*Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
}
type BeaconStateBellatrix struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *Fork `json:"fork"`
LatestBlockHeader *BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *Eth1Data `json:"eth1_data"`
Eth1DataVotes []*Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *ExecutionPayloadHeader `json:"latest_execution_payload_header"`
}
type BeaconStateCapella struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *Fork `json:"fork"`
LatestBlockHeader *BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *Eth1Data `json:"eth1_data"`
Eth1DataVotes []*Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *ExecutionPayloadHeaderCapella `json:"latest_execution_payload_header"`
NextWithdrawalIndex string `json:"next_withdrawal_index"`
NextWithdrawalValidatorIndex string `json:"next_withdrawal_validator_index"`
HistoricalSummaries []*HistoricalSummary `json:"historical_summaries"`
}
type BeaconStateDeneb struct {
GenesisTime string `json:"genesis_time"`
GenesisValidatorsRoot string `json:"genesis_validators_root"`
Slot string `json:"slot"`
Fork *Fork `json:"fork"`
LatestBlockHeader *BeaconBlockHeader `json:"latest_block_header"`
BlockRoots []string `json:"block_roots"`
StateRoots []string `json:"state_roots"`
HistoricalRoots []string `json:"historical_roots"`
Eth1Data *Eth1Data `json:"eth1_data"`
Eth1DataVotes []*Eth1Data `json:"eth1_data_votes"`
Eth1DepositIndex string `json:"eth1_deposit_index"`
Validators []*Validator `json:"validators"`
Balances []string `json:"balances"`
RandaoMixes []string `json:"randao_mixes"`
Slashings []string `json:"slashings"`
PreviousEpochParticipation []string `json:"previous_epoch_participation"`
CurrentEpochParticipation []string `json:"current_epoch_participation"`
JustificationBits string `json:"justification_bits"`
PreviousJustifiedCheckpoint *Checkpoint `json:"previous_justified_checkpoint"`
CurrentJustifiedCheckpoint *Checkpoint `json:"current_justified_checkpoint"`
FinalizedCheckpoint *Checkpoint `json:"finalized_checkpoint"`
InactivityScores []string `json:"inactivity_scores"`
CurrentSyncCommittee *SyncCommittee `json:"current_sync_committee"`
NextSyncCommittee *SyncCommittee `json:"next_sync_committee"`
LatestExecutionPayloadHeader *ExecutionPayloadHeaderDeneb `json:"latest_execution_payload_header"`
NextWithdrawalIndex string `json:"next_withdrawal_index"`
NextWithdrawalValidatorIndex string `json:"next_withdrawal_validator_index"`
HistoricalSummaries []*HistoricalSummary `json:"historical_summaries"`
}

View File

@@ -1,156 +0,0 @@
package shared
import (
"github.com/ethereum/go-ethereum/common/hexutil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
type ValidatorPerformanceResponse struct {
CurrentEffectiveBalances []uint64 `json:"current_effective_balances"`
InclusionSlots []uint64 `json:"inclusion_slots"`
InclusionDistances []uint64 `json:"inclusion_distances"`
CorrectlyVotedSource []bool `json:"correctly_voted_source"`
CorrectlyVotedTarget []bool `json:"correctly_voted_target"`
CorrectlyVotedHead []bool `json:"correctly_voted_head"`
BalancesBeforeEpochTransition []uint64 `json:"balances_before_epoch_transition"`
BalancesAfterEpochTransition []uint64 `json:"balances_after_epoch_transition"`
MissingValidators []string `json:"missing_validators"`
AverageActiveValidatorBalance float32 `json:"average_active_validator_balance"`
PublicKeys []string `json:"public_keys"`
InactivityScores []uint64 `json:"inactivity_scores"`
}
func ValidatorPerformanceResponseFromConsensus(e *eth.ValidatorPerformanceResponse) *ValidatorPerformanceResponse {
inclusionSlots := make([]uint64, len(e.InclusionSlots))
for i, index := range e.InclusionSlots {
inclusionSlots[i] = uint64(index)
}
inclusionDistances := make([]uint64, len(e.InclusionDistances))
for i, index := range e.InclusionDistances {
inclusionDistances[i] = uint64(index)
}
missingValidators := make([]string, len(e.MissingValidators))
for i, key := range e.MissingValidators {
missingValidators[i] = hexutil.Encode(key)
}
publicKeys := make([]string, len(e.PublicKeys))
for i, key := range e.PublicKeys {
publicKeys[i] = hexutil.Encode(key)
}
if len(e.CurrentEffectiveBalances) == 0 {
e.CurrentEffectiveBalances = make([]uint64, 0)
}
if len(e.BalancesBeforeEpochTransition) == 0 {
e.BalancesBeforeEpochTransition = make([]uint64, 0)
}
if len(e.BalancesAfterEpochTransition) == 0 {
e.BalancesAfterEpochTransition = make([]uint64, 0)
}
if len(e.CorrectlyVotedSource) == 0 {
e.CorrectlyVotedSource = make([]bool, 0)
}
if len(e.CorrectlyVotedTarget) == 0 {
e.CorrectlyVotedTarget = make([]bool, 0)
}
if len(e.CorrectlyVotedHead) == 0 {
e.CorrectlyVotedHead = make([]bool, 0)
}
if len(e.InactivityScores) == 0 {
e.InactivityScores = make([]uint64, 0)
}
return &ValidatorPerformanceResponse{
CurrentEffectiveBalances: e.CurrentEffectiveBalances,
InclusionSlots: inclusionSlots,
InclusionDistances: inclusionDistances,
CorrectlyVotedSource: e.CorrectlyVotedSource,
CorrectlyVotedTarget: e.CorrectlyVotedTarget,
CorrectlyVotedHead: e.CorrectlyVotedHead,
BalancesBeforeEpochTransition: e.BalancesBeforeEpochTransition,
BalancesAfterEpochTransition: e.BalancesAfterEpochTransition,
MissingValidators: missingValidators,
AverageActiveValidatorBalance: e.AverageActiveValidatorBalance,
PublicKeys: publicKeys,
InactivityScores: e.InactivityScores,
}
}
type ValidatorBalancesResponse struct {
Epoch uint64 `json:"epoch"`
Balances []*ValidatorBalance `json:"balances"`
NextPageToken string `json:"next_page_token"`
TotalSize int32 `json:"total_size,omitempty"`
}
type ValidatorBalance struct {
PublicKey string `json:"public_key"`
Index uint64 `json:"index"`
Balance uint64 `json:"balance"`
Status string `json:"status"`
}
func ValidatorBalancesResponseFromConsensus(e *eth.ValidatorBalances) (*ValidatorBalancesResponse, error) {
balances := make([]*ValidatorBalance, len(e.Balances))
for i, balance := range e.Balances {
balances[i] = &ValidatorBalance{
PublicKey: hexutil.Encode(balance.PublicKey),
Index: uint64(balance.Index),
Balance: balance.Balance,
Status: balance.Status,
}
}
return &ValidatorBalancesResponse{
Epoch: uint64(e.Epoch),
Balances: balances,
NextPageToken: e.NextPageToken,
TotalSize: e.TotalSize,
}, nil
}
type ValidatorsResponse struct {
Epoch uint64 `json:"epoch"`
ValidatorList []*ValidatorContainer `json:"validator_list"`
NextPageToken string `json:"next_page_token"`
TotalSize int32 `json:"total_size"`
}
type ValidatorContainer struct {
Index uint64 `json:"index"`
Validator *Validator `json:"validator"`
}
type Validator struct {
PublicKey string `json:"public_key,omitempty"`
WithdrawalCredentials string `json:"withdrawal_credentials"`
EffectiveBalance uint64 `json:"effective_balance"`
Slashed bool `json:"slashed"`
ActivationEligibilityEpoch uint64 `json:"activation_eligibility_epoch"`
ActivationEpoch uint64 `json:"activation_epoch"`
ExitEpoch uint64 `json:"exit_epoch"`
WithdrawableEpoch uint64 `json:"withdrawable_epoch"`
}
func ValidatorsResponseFromConsensus(e *eth.Validators) (*ValidatorsResponse, error) {
validatorList := make([]*ValidatorContainer, len(e.ValidatorList))
for i, validatorContainer := range e.ValidatorList {
val := validatorContainer.Validator
validatorList[i] = &ValidatorContainer{
Index: uint64(validatorContainer.Index),
Validator: &Validator{
PublicKey: hexutil.Encode(val.PublicKey),
WithdrawalCredentials: hexutil.Encode(val.WithdrawalCredentials),
EffectiveBalance: val.EffectiveBalance,
Slashed: val.Slashed,
ActivationEligibilityEpoch: uint64(val.ActivationEligibilityEpoch),
ActivationEpoch: uint64(val.ActivationEpoch),
ExitEpoch: uint64(val.ExitEpoch),
WithdrawableEpoch: uint64(val.WithdrawableEpoch),
},
}
}
return &ValidatorsResponse{
Epoch: uint64(e.Epoch),
ValidatorList: validatorList,
NextPageToken: e.NextPageToken,
TotalSize: e.TotalSize,
}, nil
}

View File

@@ -38,13 +38,12 @@ go_library(
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_gorilla_mux//:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@io_opencensus_go//trace:go_default_library",
@@ -87,7 +86,7 @@ go_test(
"//consensus-types/primitives:go_default_library",
"//crypto/bls:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",
"//testing/mock:go_default_library",

View File

@@ -13,7 +13,6 @@ import (
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/gorilla/mux"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/builder"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/cache"
@@ -30,7 +29,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
validator2 "github.com/prysmaticlabs/prysm/v4/consensus-types/validator"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/time/slots"
log "github.com/sirupsen/logrus"
@@ -44,20 +43,18 @@ func (s *Server) GetAggregateAttestation(w http.ResponseWriter, r *http.Request)
ctx, span := trace.StartSpan(r.Context(), "validator.GetAggregateAttestation")
defer span.End()
attDataRoot := r.URL.Query().Get("attestation_data_root")
attDataRootBytes, valid := shared.ValidateHex(w, "Attestation data root", attDataRoot, fieldparams.RootLength)
if !valid {
_, attDataRoot, ok := shared.HexFromQuery(w, r, "attestation_data_root", fieldparams.RootLength, true)
if !ok {
return
}
rawSlot := r.URL.Query().Get("slot")
slot, valid := shared.ValidateUint(w, "Slot", rawSlot)
if !valid {
_, slot, ok := shared.UintFromQuery(w, r, "slot", true)
if !ok {
return
}
if err := s.AttestationsPool.AggregateUnaggregatedAttestations(ctx); err != nil {
http2.HandleError(w, "Could not aggregate unaggregated attestations: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not aggregate unaggregated attestations: "+err.Error(), http.StatusBadRequest)
return
}
@@ -67,10 +64,10 @@ func (s *Server) GetAggregateAttestation(w http.ResponseWriter, r *http.Request)
if att.Data.Slot == primitives.Slot(slot) {
root, err := att.Data.HashTreeRoot()
if err != nil {
http2.HandleError(w, "Could not get attestation data root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get attestation data root: "+err.Error(), http.StatusInternalServerError)
return
}
if bytes.Equal(root[:], attDataRootBytes) {
if bytes.Equal(root[:], attDataRoot) {
if bestMatchingAtt == nil || len(att.AggregationBits) > len(bestMatchingAtt.AggregationBits) {
bestMatchingAtt = att
}
@@ -78,7 +75,7 @@ func (s *Server) GetAggregateAttestation(w http.ResponseWriter, r *http.Request)
}
}
if bestMatchingAtt == nil {
http2.HandleError(w, "No matching attestation found", http.StatusNotFound)
httputil.HandleError(w, "No matching attestation found", http.StatusNotFound)
return
}
@@ -100,7 +97,7 @@ func (s *Server) GetAggregateAttestation(w http.ResponseWriter, r *http.Request)
},
Signature: hexutil.Encode(bestMatchingAtt.Signature),
}}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// SubmitContributionAndProofs publishes multiple signed sync committee contribution and proofs.
@@ -112,26 +109,26 @@ func (s *Server) SubmitContributionAndProofs(w http.ResponseWriter, r *http.Requ
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
for _, item := range req.Data {
consensusItem, err := item.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request contribution to consensus contribution: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request contribution to consensus contribution: "+err.Error(), http.StatusBadRequest)
return
}
rpcError := s.CoreService.SubmitSignedContributionAndProof(ctx, consensusItem)
if rpcError != nil {
http2.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
httputil.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
}
}
}
@@ -145,14 +142,14 @@ func (s *Server) SubmitAggregateAndProofs(w http.ResponseWriter, r *http.Request
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
@@ -160,7 +157,7 @@ func (s *Server) SubmitAggregateAndProofs(w http.ResponseWriter, r *http.Request
for _, item := range req.Data {
consensusItem, err := item.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request aggregate to consensus aggregate: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request aggregate to consensus aggregate: "+err.Error(), http.StatusBadRequest)
return
}
rpcError := s.CoreService.SubmitSignedAggregateSelectionProof(
@@ -172,14 +169,14 @@ func (s *Server) SubmitAggregateAndProofs(w http.ResponseWriter, r *http.Request
if ok {
broadcastFailed = true
} else {
http2.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
httputil.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
return
}
}
}
if broadcastFailed {
http2.HandleError(w, "Could not broadcast one or more signed aggregated attestations", http.StatusInternalServerError)
httputil.HandleError(w, "Could not broadcast one or more signed aggregated attestations", http.StatusInternalServerError)
}
}
@@ -200,20 +197,20 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
st, err := s.HeadFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
currEpoch := slots.ToEpoch(st.Slot())
@@ -222,13 +219,13 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
for i, item := range req.Data {
consensusItem, err := item.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request subscription to consensus subscription: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request subscription to consensus subscription: "+err.Error(), http.StatusBadRequest)
return
}
subscriptions[i] = consensusItem
val, err := st.ValidatorAtIndexReadOnly(consensusItem.ValidatorIndex)
if err != nil {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Could not get validator at index %d: %s", consensusItem.ValidatorIndex, err.Error()),
http.StatusInternalServerError,
@@ -237,7 +234,7 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
}
valStatus, err := rpchelpers.ValidatorSubStatus(val, currEpoch)
if err != nil {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Could not get validator status at index %d: %s", consensusItem.ValidatorIndex, err.Error()),
http.StatusInternalServerError,
@@ -245,7 +242,7 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
return
}
if valStatus != validator2.ActiveOngoing && valStatus != validator2.ActiveExiting {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Validator at index %d is not active or exiting", consensusItem.ValidatorIndex),
http.StatusBadRequest,
@@ -257,13 +254,13 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
startEpoch, err := slots.SyncCommitteePeriodStartEpoch(currEpoch)
if err != nil {
http2.HandleError(w, "Could not get sync committee period start epoch: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee period start epoch: "+err.Error(), http.StatusInternalServerError)
return
}
for i, sub := range subscriptions {
if sub.UntilEpoch <= currEpoch {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Epoch for subscription at index %d is in the past. It must be at least %d", i, currEpoch+1),
http.StatusBadRequest,
@@ -272,7 +269,7 @@ func (s *Server) SubmitSyncCommitteeSubscription(w http.ResponseWriter, r *http.
}
maxValidUntilEpoch := startEpoch + params.BeaconConfig().EpochsPerSyncCommitteePeriod*2
if sub.UntilEpoch > maxValidUntilEpoch {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Epoch for subscription at index %d is too far in the future. It can be at most %d", i, maxValidUntilEpoch),
http.StatusBadRequest,
@@ -310,20 +307,20 @@ func (s *Server) SubmitBeaconCommitteeSubscription(w http.ResponseWriter, r *htt
err := json.NewDecoder(r.Body).Decode(&req.Data)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(req.Data) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
st, err := s.HeadFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -333,17 +330,17 @@ func (s *Server) SubmitBeaconCommitteeSubscription(w http.ResponseWriter, r *htt
for i, item := range req.Data {
consensusItem, err := item.ToConsensus()
if err != nil {
http2.HandleError(w, "Could not convert request subscription to consensus subscription: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not convert request subscription to consensus subscription: "+err.Error(), http.StatusBadRequest)
return
}
subscriptions[i] = consensusItem
val, err := st.ValidatorAtIndexReadOnly(consensusItem.ValidatorIndex)
if err != nil {
if errors.Is(err, consensus_types.ErrOutOfBounds) {
http2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusBadRequest)
return
}
http2.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator: "+err.Error(), http.StatusInternalServerError)
return
}
validators[i] = val
@@ -361,7 +358,7 @@ func (s *Server) SubmitBeaconCommitteeSubscription(w http.ResponseWriter, r *htt
// Request the head validator indices of epoch represented by the first requested slot.
currValsLen, err := fetchValsLen(subscriptions[0].Slot)
if err != nil {
http2.HandleError(w, "Could not retrieve head validator length: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not retrieve head validator length: "+err.Error(), http.StatusInternalServerError)
return
}
currEpoch := slots.ToEpoch(subscriptions[0].Slot)
@@ -370,7 +367,7 @@ func (s *Server) SubmitBeaconCommitteeSubscription(w http.ResponseWriter, r *htt
if currEpoch != slots.ToEpoch(sub.Slot) {
currValsLen, err = fetchValsLen(sub.Slot)
if err != nil {
http2.HandleError(w, "Could not retrieve head validator length: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not retrieve head validator length: "+err.Error(), http.StatusInternalServerError)
return
}
currEpoch = slots.ToEpoch(sub.Slot)
@@ -397,14 +394,12 @@ func (s *Server) GetAttestationData(w http.ResponseWriter, r *http.Request) {
return
}
rawSlot := r.URL.Query().Get("slot")
slot, valid := shared.ValidateUint(w, "Slot", rawSlot)
if !valid {
_, slot, ok := shared.UintFromQuery(w, r, "slot", true)
if !ok {
return
}
rawCommitteeIndex := r.URL.Query().Get("committee_index")
committeeIndex, valid := shared.ValidateUint(w, "Committee Index", rawCommitteeIndex)
if !valid {
_, committeeIndex, ok := shared.UintFromQuery(w, r, "committee_index", true)
if !ok {
return
}
@@ -414,7 +409,7 @@ func (s *Server) GetAttestationData(w http.ResponseWriter, r *http.Request) {
})
if rpcError != nil {
http2.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
httputil.HandleError(w, rpcError.Err.Error(), core.ErrorReasonToHTTP(rpcError.Reason))
return
}
@@ -433,7 +428,7 @@ func (s *Server) GetAttestationData(w http.ResponseWriter, r *http.Request) {
},
},
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// ProduceSyncCommitteeContribution requests that the beacon node produce a sync committee contribution.
@@ -441,20 +436,18 @@ func (s *Server) ProduceSyncCommitteeContribution(w http.ResponseWriter, r *http
ctx, span := trace.StartSpan(r.Context(), "validator.ProduceSyncCommitteeContribution")
defer span.End()
subIndex := r.URL.Query().Get("subcommittee_index")
index, valid := shared.ValidateUint(w, "Subcommittee Index", subIndex)
if !valid {
_, index, ok := shared.UintFromQuery(w, r, "subcommittee_index", true)
if !ok {
return
}
rawSlot := r.URL.Query().Get("slot")
slot, valid := shared.ValidateUint(w, "Slot", rawSlot)
if !valid {
_, slot, ok := shared.UintFromQuery(w, r, "slot", true)
if !ok {
return
}
rawBlockRoot := r.URL.Query().Get("beacon_block_root")
blockRoot, err := hexutil.Decode(rawBlockRoot)
if err != nil {
http2.HandleError(w, "Invalid Beacon Block Root: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Invalid Beacon Block Root: "+err.Error(), http.StatusBadRequest)
return
}
contribution, ok := s.produceSyncCommitteeContribution(ctx, w, primitives.Slot(slot), index, blockRoot)
@@ -464,7 +457,7 @@ func (s *Server) ProduceSyncCommitteeContribution(w http.ResponseWriter, r *http
response := &ProduceSyncCommitteeContributionResponse{
Data: contribution,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// ProduceSyncCommitteeContribution requests that the beacon node produce a sync committee contribution.
@@ -477,11 +470,11 @@ func (s *Server) produceSyncCommitteeContribution(
) (*shared.SyncCommitteeContribution, bool) {
msgs, err := s.SyncCommitteePool.SyncCommitteeMessages(slot)
if err != nil {
http2.HandleError(w, "Could not get sync subcommittee messages: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync subcommittee messages: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
if len(msgs) == 0 {
http2.HandleError(w, "No subcommittee messages found", http.StatusNotFound)
httputil.HandleError(w, "No subcommittee messages found", http.StatusNotFound)
return nil, false
}
sig, aggregatedBits, err := s.CoreService.AggregatedSigAndAggregationBits(
@@ -494,7 +487,7 @@ func (s *Server) produceSyncCommitteeContribution(
},
)
if err != nil {
http2.HandleError(w, "Could not get contribution data: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get contribution data: "+err.Error(), http.StatusInternalServerError)
return nil, false
}
@@ -513,7 +506,7 @@ func (s *Server) RegisterValidator(w http.ResponseWriter, r *http.Request) {
defer span.End()
if s.BlockBuilder == nil || !s.BlockBuilder.Configured() {
http2.HandleError(w, fmt.Sprintf("Could not register block builder: %v", builder.ErrNoBuilder), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Could not register block builder: %v", builder.ErrNoBuilder), http.StatusBadRequest)
return
}
@@ -521,10 +514,10 @@ func (s *Server) RegisterValidator(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&jsonRegistrations)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
@@ -532,18 +525,18 @@ func (s *Server) RegisterValidator(w http.ResponseWriter, r *http.Request) {
for i, registration := range jsonRegistrations {
reg, err := registration.ToConsensus()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
registrations[i] = reg
}
if len(registrations) == 0 {
http2.HandleError(w, "Validator registration request is empty", http.StatusBadRequest)
httputil.HandleError(w, "Validator registration request is empty", http.StatusBadRequest)
return
}
if err := s.BlockBuilder.RegisterValidator(ctx, registrations); err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
}
@@ -557,21 +550,21 @@ func (s *Server) PrepareBeaconProposer(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&jsonFeeRecipients)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
var feeRecipients []common.Address
var validatorIndices []primitives.ValidatorIndex
// filter for found fee recipients
for _, r := range jsonFeeRecipients {
validatorIndex, valid := shared.ValidateUint(w, "Validator Index", r.ValidatorIndex)
validatorIndex, valid := shared.ValidateUint(w, "validator_index", r.ValidatorIndex)
if !valid {
return
}
feeRecipientBytes, valid := shared.ValidateHex(w, "Fee Recipient", r.FeeRecipient, fieldparams.FeeRecipientLength)
feeRecipientBytes, valid := shared.ValidateHex(w, "fee_recipient", r.FeeRecipient, fieldparams.FeeRecipientLength)
if !valid {
return
}
@@ -581,7 +574,7 @@ func (s *Server) PrepareBeaconProposer(w http.ResponseWriter, r *http.Request) {
feeRecipients = append(feeRecipients, common.BytesToAddress(bytesutil.SafeCopyBytes(feeRecipientBytes)))
validatorIndices = append(validatorIndices, primitives.ValidatorIndex(validatorIndex))
case err != nil:
http2.HandleError(w, fmt.Sprintf("Could not get fee recipient by validator index: %v", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get fee recipient by validator index: %v", err), http.StatusInternalServerError)
return
default:
if common.BytesToAddress(feeRecipientBytes) != f {
@@ -594,7 +587,7 @@ func (s *Server) PrepareBeaconProposer(w http.ResponseWriter, r *http.Request) {
return
}
if err := s.BeaconDB.SaveFeeRecipientsByValidatorIDs(ctx, validatorIndices, feeRecipients); err != nil {
http2.HandleError(w, fmt.Sprintf("Could not save fee recipients: %v", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not save fee recipients: %v", err), http.StatusInternalServerError)
return
}
log.WithFields(log.Fields{
@@ -612,9 +605,8 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
return
}
rawEpoch := mux.Vars(r)["epoch"]
requestedEpochUint, valid := shared.ValidateUint(w, "Epoch", rawEpoch)
if !valid {
_, requestedEpochUint, ok := shared.UintFromRoute(w, r, "epoch")
if !ok {
return
}
requestedEpoch := primitives.Epoch(requestedEpochUint)
@@ -622,14 +614,14 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&indices)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(indices) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
requestedValIndices := make([]primitives.ValidatorIndex, len(indices))
@@ -645,7 +637,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
currentEpoch := slots.ToEpoch(cs)
nextEpoch := currentEpoch + 1
if requestedEpoch > nextEpoch {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Request epoch %d can not be greater than next epoch %d", requestedEpoch, nextEpoch),
http.StatusBadRequest,
@@ -660,24 +652,24 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
startSlot, err = slots.EpochStart(requestedEpoch)
}
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get start slot from epoch %d: %v", requestedEpoch, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get start slot from epoch %d: %v", requestedEpoch, err), http.StatusInternalServerError)
return
}
st, err := s.Stater.StateBySlot(ctx, startSlot)
if err != nil {
http2.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get state: "+err.Error(), http.StatusInternalServerError)
return
}
committeeAssignments, _, err := helpers.CommitteeAssignments(ctx, st, requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not compute committee assignments: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not compute committee assignments: "+err.Error(), http.StatusInternalServerError)
return
}
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, st, requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get active validator count: "+err.Error(), http.StatusInternalServerError)
return
}
committeesAtSlot := helpers.SlotCommitteeCount(activeValidatorCount)
@@ -687,7 +679,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
pubkey := st.PubkeyAtIndex(index)
var zeroPubkey [fieldparams.BLSPubkeyLength]byte
if bytes.Equal(pubkey[:], zeroPubkey[:]) {
http2.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Invalid validator index %d", index), http.StatusBadRequest)
return
}
committee := committeeAssignments[index]
@@ -716,12 +708,12 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
dependentRoot, err := attestationDependentRoot(st, requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not get dependent root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get dependent root: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -730,7 +722,7 @@ func (s *Server) GetAttesterDuties(w http.ResponseWriter, r *http.Request) {
Data: duties,
ExecutionOptimistic: isOptimistic,
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// GetProposerDuties requests beacon node to provide all validators that are scheduled to propose a block in the given epoch.
@@ -742,9 +734,8 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
return
}
rawEpoch := mux.Vars(r)["epoch"]
requestedEpochUint, valid := shared.ValidateUint(w, "Epoch", rawEpoch)
if !valid {
_, requestedEpochUint, ok := shared.UintFromRoute(w, r, "epoch")
if !ok {
return
}
requestedEpoch := primitives.Epoch(requestedEpochUint)
@@ -754,7 +745,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
nextEpoch := currentEpoch + 1
var nextEpochLookahead bool
if requestedEpoch > nextEpoch {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Request epoch %d can not be greater than next epoch %d", requestedEpoch, currentEpoch+1),
http.StatusBadRequest,
@@ -768,7 +759,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
epochStartSlot, err := slots.EpochStart(requestedEpoch)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get start slot of epoch %d: %v", requestedEpoch, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get start slot of epoch %d: %v", requestedEpoch, err), http.StatusInternalServerError)
return
}
var st state.BeaconState
@@ -776,25 +767,25 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
if requestedEpoch < currentEpoch {
st, err = s.Stater.StateBySlot(ctx, epochStartSlot)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get state for slot %d: %v ", epochStartSlot, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get state for slot %d: %v ", epochStartSlot, err), http.StatusInternalServerError)
return
}
} else {
st, err = s.HeadFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get head state: %v ", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get head state: %v ", err), http.StatusInternalServerError)
return
}
// Advance state with empty transitions up to the requested epoch start slot.
if st.Slot() < epochStartSlot {
headRoot, err := s.HeadFetcher.HeadRoot(ctx)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get head root: %v ", err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get head root: %v ", err), http.StatusInternalServerError)
return
}
st, err = transition.ProcessSlotsUsingNextSlotCache(ctx, st, headRoot, epochStartSlot)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not process slots up to %d: %v ", epochStartSlot, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not process slots up to %d: %v ", epochStartSlot, err), http.StatusInternalServerError)
return
}
}
@@ -807,7 +798,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
_, proposals, err = helpers.CommitteeAssignments(ctx, st, requestedEpoch)
}
if err != nil {
http2.HandleError(w, "Could not compute committee assignments: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not compute committee assignments: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -815,7 +806,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
for index, proposalSlots := range proposals {
val, err := st.ValidatorAtIndexReadOnly(index)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %v", index, err), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not get validator at index %d: %v", index, err), http.StatusInternalServerError)
return
}
pubkey48 := val.PublicKey()
@@ -834,12 +825,12 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
dependentRoot, err := proposalDependentRoot(st, requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not get dependent root: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get dependent root: "+err.Error(), http.StatusInternalServerError)
return
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
if !sortProposerDuties(w, duties) {
@@ -851,7 +842,7 @@ func (s *Server) GetProposerDuties(w http.ResponseWriter, r *http.Request) {
Data: duties,
ExecutionOptimistic: isOptimistic,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetSyncCommitteeDuties provides a set of sync committee duties for a particular epoch.
@@ -873,28 +864,27 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
return
}
rawEpoch := mux.Vars(r)["epoch"]
requestedEpochUint, valid := shared.ValidateUint(w, "Epoch", rawEpoch)
if !valid {
_, requestedEpochUint, ok := shared.UintFromRoute(w, r, "epoch")
if !ok {
return
}
requestedEpoch := primitives.Epoch(requestedEpochUint)
if requestedEpoch < params.BeaconConfig().AltairForkEpoch {
http2.HandleError(w, "Sync committees are not supported for Phase0", http.StatusBadRequest)
httputil.HandleError(w, "Sync committees are not supported for Phase0", http.StatusBadRequest)
return
}
var indices []string
err := json.NewDecoder(r.Body).Decode(&indices)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(indices) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
requestedValIndices := make([]primitives.ValidatorIndex, len(indices))
@@ -909,7 +899,7 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
currentEpoch := slots.ToEpoch(s.TimeFetcher.CurrentSlot())
lastValidEpoch := syncCommitteeDutiesLastValidEpoch(currentEpoch)
if requestedEpoch > lastValidEpoch {
http2.HandleError(w, fmt.Sprintf("Epoch is too far in the future, maximum valid epoch is %d", lastValidEpoch), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Epoch is too far in the future, maximum valid epoch is %d", lastValidEpoch), http.StatusBadRequest)
return
}
@@ -919,18 +909,18 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
}
slot, err := slots.EpochStart(startingEpoch)
if err != nil {
http2.HandleError(w, "Could not get sync committee slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee slot: "+err.Error(), http.StatusInternalServerError)
return
}
st, err := s.Stater.State(ctx, []byte(strconv.FormatUint(uint64(slot), 10)))
if err != nil {
http2.HandleError(w, "Could not get sync committee state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee state: "+err.Error(), http.StatusInternalServerError)
return
}
currentSyncCommitteeFirstEpoch, err := slots.SyncCommitteePeriodStartEpoch(startingEpoch)
if err != nil {
http2.HandleError(w, "Could not get sync committee period start epoch: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee period start epoch: "+err.Error(), http.StatusInternalServerError)
return
}
nextSyncCommitteeFirstEpoch := currentSyncCommitteeFirstEpoch + params.BeaconConfig().EpochsPerSyncCommitteePeriod
@@ -939,13 +929,13 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
if isCurrentCommitteeRequested {
committee, err = st.CurrentSyncCommittee()
if err != nil {
http2.HandleError(w, "Could not get sync committee: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
committee, err = st.NextSyncCommittee()
if err != nil {
http2.HandleError(w, "Could not get sync committee: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get sync committee: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -956,7 +946,7 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
}
duties, vals, err := syncCommitteeDutiesAndVals(st, requestedValIndices, committeePubkeys)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusBadRequest)
httputil.HandleError(w, err.Error(), http.StatusBadRequest)
return
}
@@ -970,18 +960,18 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
pk := v.PublicKey()
valStatus, err := rpchelpers.ValidatorStatus(v, requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get validator status: "+err.Error(), http.StatusInternalServerError)
return
}
if err := registerSyncSubnet(st, requestedEpoch, pk[:], valStatus); err != nil {
http2.HandleError(w, fmt.Sprintf("Could not register sync subnet for pubkey %#x", pk), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not register sync subnet for pubkey %#x", pk), http.StatusInternalServerError)
return
}
}
isOptimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
http2.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not check optimistic status: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -989,7 +979,7 @@ func (s *Server) GetSyncCommitteeDuties(w http.ResponseWriter, r *http.Request)
Data: duties,
ExecutionOptimistic: isOptimistic,
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// GetLiveness requests the beacon node to indicate if a validator has been observed to be live in a given epoch.
@@ -1003,9 +993,8 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "validator.GetLiveness")
defer span.End()
rawEpoch := mux.Vars(r)["epoch"]
requestedEpochUint, valid := shared.ValidateUint(w, "Epoch", rawEpoch)
if !valid {
_, requestedEpochUint, ok := shared.UintFromRoute(w, r, "epoch")
if !ok {
return
}
requestedEpoch := primitives.Epoch(requestedEpochUint)
@@ -1013,14 +1002,14 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
err := json.NewDecoder(r.Body).Decode(&indices)
switch {
case err == io.EOF:
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
case err != nil:
http2.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
httputil.HandleError(w, "Could not decode request body: "+err.Error(), http.StatusBadRequest)
return
}
if len(indices) == 0 {
http2.HandleError(w, "No data submitted", http.StatusBadRequest)
httputil.HandleError(w, "No data submitted", http.StatusBadRequest)
return
}
requestedValIndices := make([]primitives.ValidatorIndex, len(indices))
@@ -1038,12 +1027,12 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
// We can also use the head state to get participation info for the previous epoch.
headSt, err := s.HeadFetcher.HeadState(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
currEpoch := slots.ToEpoch(headSt.Slot())
if requestedEpoch > currEpoch {
http2.HandleError(w, "Requested epoch cannot be in the future", http.StatusBadRequest)
httputil.HandleError(w, "Requested epoch cannot be in the future", http.StatusBadRequest)
return
}
@@ -1053,30 +1042,30 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
st = headSt
participation, err = st.CurrentEpochParticipation()
if err != nil {
http2.HandleError(w, "Could not get current epoch participation: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get current epoch participation: "+err.Error(), http.StatusInternalServerError)
return
}
} else if requestedEpoch == currEpoch-1 {
st = headSt
participation, err = st.PreviousEpochParticipation()
if err != nil {
http2.HandleError(w, "Could not get previous epoch participation: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get previous epoch participation: "+err.Error(), http.StatusInternalServerError)
return
}
} else {
epochEnd, err := slots.EpochEnd(requestedEpoch)
if err != nil {
http2.HandleError(w, "Could not get requested epoch's end slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get requested epoch's end slot: "+err.Error(), http.StatusInternalServerError)
return
}
st, err = s.Stater.StateBySlot(ctx, epochEnd)
if err != nil {
http2.HandleError(w, "Could not get slot for requested epoch: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get slot for requested epoch: "+err.Error(), http.StatusInternalServerError)
return
}
participation, err = st.CurrentEpochParticipation()
if err != nil {
http2.HandleError(w, "Could not get current epoch participation: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get current epoch participation: "+err.Error(), http.StatusInternalServerError)
return
}
}
@@ -1086,7 +1075,7 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
}
for i, vi := range requestedValIndices {
if vi >= primitives.ValidatorIndex(len(participation)) {
http2.HandleError(w, fmt.Sprintf("Validator index %d is invalid", vi), http.StatusBadRequest)
httputil.HandleError(w, fmt.Sprintf("Validator index %d is invalid", vi), http.StatusBadRequest)
return
}
resp.Data[i] = &Liveness{
@@ -1095,7 +1084,7 @@ func (s *Server) GetLiveness(w http.ResponseWriter, r *http.Request) {
}
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}
// attestationDependentRoot is get_block_root_at_slot(state, compute_start_slot_at_epoch(epoch - 1) - 1)
@@ -1184,13 +1173,13 @@ func sortProposerDuties(w http.ResponseWriter, duties []*ProposerDuty) bool {
sort.Slice(duties, func(i, j int) bool {
si, err := strconv.ParseUint(duties[i].Slot, 10, 64)
if err != nil {
http2.HandleError(w, "Could not parse slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not parse slot: "+err.Error(), http.StatusInternalServerError)
ok = false
return false
}
sj, err := strconv.ParseUint(duties[j].Slot, 10, 64)
if err != nil {
http2.HandleError(w, "Could not parse slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not parse slot: "+err.Error(), http.StatusInternalServerError)
ok = false
return false
}

View File

@@ -15,7 +15,8 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"go.opencensus.io/trace"
@@ -56,18 +57,18 @@ func (s *Server) ProduceBlockV2(w http.ResponseWriter, r *http.Request) {
if rawSkipRandaoVerification == "true" {
randaoReveal = primitives.PointAtInfinity
} else {
rr, err := shared.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
rr, err := bytesutil.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
return
}
randaoReveal = rr
}
var graffiti []byte
if rawGraffiti != "" {
g, err := shared.DecodeHexWithLength(rawGraffiti, 32)
g, err := bytesutil.DecodeHexWithLength(rawGraffiti, 32)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
return
}
graffiti = g
@@ -108,18 +109,18 @@ func (s *Server) ProduceBlindedBlock(w http.ResponseWriter, r *http.Request) {
if rawSkipRandaoVerification == "true" {
randaoReveal = primitives.PointAtInfinity
} else {
rr, err := shared.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
rr, err := bytesutil.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
return
}
randaoReveal = rr
}
var graffiti []byte
if rawGraffiti != "" {
g, err := shared.DecodeHexWithLength(rawGraffiti, 32)
g, err := bytesutil.DecodeHexWithLength(rawGraffiti, 32)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
return
}
graffiti = g
@@ -164,18 +165,18 @@ func (s *Server) ProduceBlockV3(w http.ResponseWriter, r *http.Request) {
if rawSkipRandaoVerification == "true" {
randaoReveal = primitives.PointAtInfinity
} else {
rr, err := shared.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
rr, err := bytesutil.DecodeHexWithLength(rawRandaoReveal, fieldparams.BLSSignatureLength)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode randao reveal").Error(), http.StatusBadRequest)
return
}
randaoReveal = rr
}
var graffiti []byte
if rawGraffiti != "" {
g, err := shared.DecodeHexWithLength(rawGraffiti, 32)
g, err := bytesutil.DecodeHexWithLength(rawGraffiti, 32)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
httputil.HandleError(w, errors.Wrap(err, "Unable to decode graffiti").Error(), http.StatusBadRequest)
return
}
graffiti = g
@@ -190,24 +191,24 @@ func (s *Server) ProduceBlockV3(w http.ResponseWriter, r *http.Request) {
}
func (s *Server) produceBlockV3(ctx context.Context, w http.ResponseWriter, r *http.Request, v1alpha1req *eth.BlockRequest, requiredType blockType) {
isSSZ := http2.SszRequested(r)
isSSZ := httputil.SszRequested(r)
v1alpha1resp, err := s.V1Alpha1Server.GetBeaconBlock(ctx, v1alpha1req)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
if requiredType == blinded && !v1alpha1resp.IsBlinded {
http2.HandleError(w, "Prepared block is not blinded", http.StatusInternalServerError)
httputil.HandleError(w, "Prepared block is not blinded", http.StatusInternalServerError)
return
} else if requiredType == full && v1alpha1resp.IsBlinded {
http2.HandleError(w, "Prepared block is blinded", http.StatusInternalServerError)
httputil.HandleError(w, "Prepared block is blinded", http.StatusInternalServerError)
return
}
consensusBlockValue, httpError := getConsensusBlockValue(ctx, s.BlockRewardFetcher, v1alpha1resp.Block)
if httpError != nil {
http2.WriteError(w, httpError)
httputil.WriteError(w, httpError)
return
}
@@ -230,11 +231,11 @@ func (s *Server) produceBlockV3(ctx context.Context, w http.ResponseWriter, r *h
}
optimistic, err := s.OptimisticModeFetcher.IsOptimistic(ctx)
if err != nil {
http2.HandleError(w, errors.Wrap(err, "Could not determine if the node is a optimistic node").Error(), http.StatusInternalServerError)
httputil.HandleError(w, errors.Wrap(err, "Could not determine if the node is a optimistic node").Error(), http.StatusInternalServerError)
return
}
if optimistic {
http2.HandleError(w, "The node is currently optimistic and cannot serve validators", http.StatusServiceUnavailable)
httputil.HandleError(w, "The node is currently optimistic and cannot serve validators", http.StatusServiceUnavailable)
return
}
blindedBellatrixBlock, ok := v1alpha1resp.Block.(*eth.GenericBeaconBlock_BlindedBellatrix)
@@ -275,7 +276,7 @@ func (s *Server) produceBlockV3(ctx context.Context, w http.ResponseWriter, r *h
}
}
func getConsensusBlockValue(ctx context.Context, blockRewardsFetcher rewards.BlockRewardsFetcher, i interface{} /* block as argument */) (string, *http2.DefaultErrorJson) {
func getConsensusBlockValue(ctx context.Context, blockRewardsFetcher rewards.BlockRewardsFetcher, i interface{} /* block as argument */) (string, *httputil.DefaultErrorJson) {
var wrapper interfaces.ReadOnlySignedBeaconBlock
var err error
@@ -300,13 +301,13 @@ func getConsensusBlockValue(ctx context.Context, blockRewardsFetcher rewards.Blo
case *eth.GenericBeaconBlock_BlindedDeneb:
wrapper, err = blocks.NewSignedBeaconBlock(&eth.GenericSignedBeaconBlock_BlindedDeneb{BlindedDeneb: &eth.SignedBlindedBeaconBlockDeneb{Message: b.BlindedDeneb}})
default:
return "", &http2.DefaultErrorJson{
return "", &httputil.DefaultErrorJson{
Message: fmt.Errorf("type %T is not supported", b).Error(),
Code: http.StatusInternalServerError,
}
}
if err != nil {
return "", &http2.DefaultErrorJson{
return "", &httputil.DefaultErrorJson{
Message: err.Error(),
Code: http.StatusInternalServerError,
}
@@ -329,23 +330,18 @@ func handleProducePhase0V3(
if isSSZ {
sszResp, err := blk.Phase0.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "phase0Block.ssz")
httputil.WriteSsz(w, sszResp, "phase0Block.ssz")
return
}
block, err := shared.BeaconBlockFromConsensus(blk.Phase0)
jsonBytes, err := json.Marshal(shared.BeaconBlockFromConsensus(blk.Phase0))
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Phase0),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: fmt.Sprintf("%d", payloadValue), // mev not available at this point
@@ -364,23 +360,18 @@ func handleProduceAltairV3(
if isSSZ {
sszResp, err := blk.Altair.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "altairBlock.ssz")
httputil.WriteSsz(w, sszResp, "altairBlock.ssz")
return
}
block, err := shared.BeaconBlockAltairFromConsensus(blk.Altair)
jsonBytes, err := json.Marshal(shared.BeaconBlockAltairFromConsensus(blk.Altair))
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Altair),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue), // mev not available at this point
@@ -399,23 +390,23 @@ func handleProduceBellatrixV3(
if isSSZ {
sszResp, err := blk.Bellatrix.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "bellatrixBlock.ssz")
httputil.WriteSsz(w, sszResp, "bellatrixBlock.ssz")
return
}
block, err := shared.BeaconBlockBellatrixFromConsensus(blk.Bellatrix)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Bellatrix),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue), // mev not available at this point
@@ -434,23 +425,23 @@ func handleProduceBlindedBellatrixV3(
if isSSZ {
sszResp, err := blk.BlindedBellatrix.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "blindedBellatrixBlock.ssz")
httputil.WriteSsz(w, sszResp, "blindedBellatrixBlock.ssz")
return
}
block, err := shared.BlindedBeaconBlockBellatrixFromConsensus(blk.BlindedBellatrix)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Bellatrix),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue),
@@ -469,23 +460,23 @@ func handleProduceBlindedCapellaV3(
if isSSZ {
sszResp, err := blk.BlindedCapella.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "blindedCapellaBlock.ssz")
httputil.WriteSsz(w, sszResp, "blindedCapellaBlock.ssz")
return
}
block, err := shared.BlindedBeaconBlockCapellaFromConsensus(blk.BlindedCapella)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Capella),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue),
@@ -504,23 +495,23 @@ func handleProduceCapellaV3(
if isSSZ {
sszResp, err := blk.Capella.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "capellaBlock.ssz")
httputil.WriteSsz(w, sszResp, "capellaBlock.ssz")
return
}
block, err := shared.BeaconBlockCapellaFromConsensus(blk.Capella)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(block)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Capella),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue), // mev not available at this point
@@ -539,23 +530,23 @@ func handleProduceBlindedDenebV3(
if isSSZ {
sszResp, err := blk.BlindedDeneb.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "blindedDenebBlockContents.ssz")
httputil.WriteSsz(w, sszResp, "blindedDenebBlockContents.ssz")
return
}
blindedBlock, err := shared.BlindedBeaconBlockDenebFromConsensus(blk.BlindedDeneb)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(blindedBlock)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Deneb),
ExecutionPayloadBlinded: true,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue),
@@ -574,24 +565,24 @@ func handleProduceDenebV3(
if isSSZ {
sszResp, err := blk.Deneb.MarshalSSZ()
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteSsz(w, sszResp, "denebBlockContents.ssz")
httputil.WriteSsz(w, sszResp, "denebBlockContents.ssz")
return
}
blockContents, err := shared.BeaconBlockContentsDenebFromConsensus(blk.Deneb)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
jsonBytes, err := json.Marshal(blockContents)
if err != nil {
http2.HandleError(w, err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, err.Error(), http.StatusInternalServerError)
return
}
http2.WriteJson(w, &ProduceBlockV3Response{
httputil.WriteJson(w, &ProduceBlockV3Response{
Version: version.String(version.Deneb),
ExecutionPayloadBlinded: false,
ExecutionPayloadValue: fmt.Sprintf("%d", executionPayloadValue), // mev not available at this point

View File

@@ -17,7 +17,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
rpctesting "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared/testing"
mockSync "github.com/prysmaticlabs/prysm/v4/beacon-chain/sync/initial-sync/testing"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
mock2 "github.com/prysmaticlabs/prysm/v4/testing/mock"
@@ -140,7 +140,7 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)
@@ -203,7 +203,7 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)
@@ -265,7 +265,7 @@ func TestProduceBlockV2(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)
@@ -448,7 +448,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)
@@ -513,7 +513,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)
@@ -576,7 +576,7 @@ func TestProduceBlockV2SSZ(t *testing.T) {
writer.Body = &bytes.Buffer{}
server.ProduceBlockV2(writer, request)
assert.Equal(t, http.StatusInternalServerError, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusInternalServerError, e.Code)
assert.StringContains(t, "Prepared block is blinded", e.Message)

View File

@@ -39,7 +39,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/crypto/bls"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpbalpha "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -192,7 +192,7 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusNotFound, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusNotFound, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No matching attestation found"))
@@ -205,10 +205,10 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Attestation data root is required"))
assert.Equal(t, true, strings.Contains(e.Message, "attestation_data_root is required"))
})
t.Run("invalid attestation_data_root provided", func(t *testing.T) {
url := "http://example.com?attestation_data_root=foo&slot=2"
@@ -218,10 +218,10 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Attestation data root is invalid"))
assert.Equal(t, true, strings.Contains(e.Message, "attestation_data_root is invalid"))
})
t.Run("no slot provided", func(t *testing.T) {
attDataRoot := hexutil.Encode(bytesutil.PadTo([]byte("foo"), 32))
@@ -232,10 +232,10 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Slot is required"))
assert.Equal(t, true, strings.Contains(e.Message, "slot is required"))
})
t.Run("invalid slot provided", func(t *testing.T) {
attDataRoot := hexutil.Encode(bytesutil.PadTo([]byte("foo"), 32))
@@ -246,10 +246,10 @@ func TestGetAggregateAttestation(t *testing.T) {
s.GetAggregateAttestation(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Slot is invalid"))
assert.Equal(t, true, strings.Contains(e.Message, "slot is invalid"))
})
}
@@ -366,7 +366,7 @@ func TestSubmitContributionAndProofs(t *testing.T) {
s.SubmitContributionAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -381,7 +381,7 @@ func TestSubmitContributionAndProofs(t *testing.T) {
s.SubmitContributionAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -398,7 +398,7 @@ func TestSubmitContributionAndProofs(t *testing.T) {
s.SubmitContributionAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -451,7 +451,7 @@ func TestSubmitAggregateAndProofs(t *testing.T) {
s.SubmitAggregateAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -466,7 +466,7 @@ func TestSubmitAggregateAndProofs(t *testing.T) {
s.SubmitAggregateAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -481,7 +481,7 @@ func TestSubmitAggregateAndProofs(t *testing.T) {
s.SubmitAggregateAndProofs(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -558,7 +558,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -573,7 +573,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -588,7 +588,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -602,7 +602,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Epoch for subscription at index 0 is in the past"))
@@ -628,7 +628,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Epoch for subscription at index 0 is too far in the future"))
@@ -650,7 +650,7 @@ func TestSubmitSyncCommitteeSubscription(t *testing.T) {
s.SubmitSyncCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Beacon node is currently syncing"))
@@ -744,7 +744,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) {
s.SubmitBeaconCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -759,7 +759,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) {
s.SubmitBeaconCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "No data submitted"))
@@ -774,7 +774,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) {
s.SubmitBeaconCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -795,7 +795,7 @@ func TestSubmitBeaconCommitteeSubscription(t *testing.T) {
s.SubmitBeaconCommitteeSubscription(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Beacon node is currently syncing"))
@@ -905,7 +905,7 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "syncing"))
@@ -940,7 +940,7 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "optimistic"))
@@ -1066,7 +1066,7 @@ func TestGetAttestationData(t *testing.T) {
s.GetAttestationData(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "invalid request"))
@@ -1390,7 +1390,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "Slot is required", errors.New(writer.Body.String()))
require.ErrorContains(t, "slot is required", errors.New(writer.Body.String()))
})
t.Run("no subcommittee_index provided", func(t *testing.T) {
url := "http://example.com?slot=1&beacon_block_root=0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2"
@@ -1402,7 +1402,7 @@ func TestProduceSyncCommitteeContribution(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, writer.Code)
resp := &ProduceSyncCommitteeContributionResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.ErrorContains(t, "Subcommittee Index is required", errors.New(writer.Body.String()))
require.ErrorContains(t, "subcommittee_index is required", errors.New(writer.Body.String()))
})
t.Run("no beacon_block_root provided", func(t *testing.T) {
url := "http://example.com?slot=1&subcommittee_index=1"
@@ -1610,7 +1610,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -1626,7 +1626,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -1642,7 +1642,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -1682,7 +1682,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, fmt.Sprintf("Request epoch %d can not be greater than next epoch %d", currentEpoch+2, currentEpoch+1)))
@@ -1698,7 +1698,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, fmt.Sprintf("Invalid validator index %d", len(pubKeys))))
@@ -1774,7 +1774,7 @@ func TestGetAttesterDuties(t *testing.T) {
s.GetAttesterDuties(writer, request)
require.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
})
@@ -1952,7 +1952,7 @@ func TestGetProposerDuties(t *testing.T) {
s.GetProposerDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, fmt.Sprintf("Request epoch %d can not be greater than next epoch %d", currentEpoch+2, currentEpoch+1), e.Message)
@@ -2016,7 +2016,7 @@ func TestGetProposerDuties(t *testing.T) {
s.GetProposerDuties(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
})
@@ -2107,7 +2107,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -2123,7 +2123,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -2139,7 +2139,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
})
@@ -2187,7 +2187,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Invalid validator index", e.Message)
@@ -2300,7 +2300,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "Epoch is too far in the future", e.Message)
@@ -2378,7 +2378,7 @@ func TestGetSyncCommitteeDuties(t *testing.T) {
s.GetSyncCommitteeDuties(writer, request)
assert.Equal(t, http.StatusServiceUnavailable, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusServiceUnavailable, e.Code)
})
@@ -2409,7 +2409,7 @@ func TestPrepareBeaconProposer(t *testing.T) {
},
},
code: http.StatusBadRequest,
wantErr: "Invalid Fee Recipient",
wantErr: "Invalid fee_recipient",
},
}
for _, tt := range tests {
@@ -2649,7 +2649,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.StringContains(t, "Requested epoch cannot be in the future", e.Message)
@@ -2664,10 +2664,10 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Epoch is required"))
assert.Equal(t, true, strings.Contains(e.Message, "epoch is required"))
})
t.Run("invalid epoch provided", func(t *testing.T) {
var body bytes.Buffer
@@ -2680,10 +2680,10 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.Equal(t, true, strings.Contains(e.Message, "Epoch is invalid"))
assert.Equal(t, true, strings.Contains(e.Message, "epoch is invalid"))
})
t.Run("no body", func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "http://example.com/eth/v1/validator/liveness/{epoch}", nil)
@@ -2693,7 +2693,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -2709,7 +2709,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
assert.StringContains(t, "No data submitted", e.Message)
@@ -2725,7 +2725,7 @@ func TestGetLiveness(t *testing.T) {
s.GetLiveness(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, e.Code)
require.StringContains(t, "Validator index 2 is invalid", e.Message)

View File

@@ -17,7 +17,7 @@ go_library(
"//beacon-chain/state/stategen:go_default_library",
"//beacon-chain/sync:go_default_library",
"//config/params:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//time/slots:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@io_opencensus_go//trace:go_default_library",

View File

@@ -10,7 +10,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/helpers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/config/params"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/time/slots"
"go.opencensus.io/trace"
)
@@ -27,27 +27,27 @@ func (s *Server) GetWeakSubjectivity(w http.ResponseWriter, r *http.Request) {
hs, err := s.HeadFetcher.HeadStateReadOnly(ctx)
if err != nil {
http2.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get head state: "+err.Error(), http.StatusInternalServerError)
return
}
wsEpoch, err := helpers.LatestWeakSubjectivityEpoch(ctx, hs, params.BeaconConfig())
if err != nil {
http2.HandleError(w, "Could not get weak subjectivity epoch: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get weak subjectivity epoch: "+err.Error(), http.StatusInternalServerError)
return
}
wsSlot, err := slots.EpochStart(wsEpoch)
if err != nil {
http2.HandleError(w, "Could not get weak subjectivity slot: "+err.Error(), http.StatusInternalServerError)
httputil.HandleError(w, "Could not get weak subjectivity slot: "+err.Error(), http.StatusInternalServerError)
return
}
cbr, err := s.CanonicalHistory.BlockRootForSlot(ctx, wsSlot)
if err != nil {
http2.HandleError(w, fmt.Sprintf("Could not find highest block below slot %d: %s", wsSlot, err.Error()), http.StatusInternalServerError)
httputil.HandleError(w, fmt.Sprintf("Could not find highest block below slot %d: %s", wsSlot, err.Error()), http.StatusInternalServerError)
return
}
cb, err := s.BeaconDB.Block(ctx, cbr)
if err != nil {
http2.HandleError(
httputil.HandleError(
w,
fmt.Sprintf("Block with root %#x from slot index %d not found in db: %s", cbr, wsSlot, err.Error()),
http.StatusInternalServerError,
@@ -66,5 +66,5 @@ func (s *Server) GetWeakSubjectivity(w http.ResponseWriter, r *http.Request) {
StateRoot: hexutil.Encode(stateRoot[:]),
},
}
http2.WriteJson(w, resp)
httputil.WriteJson(w, resp)
}

View File

@@ -17,11 +17,12 @@ go_library(
"//beacon-chain/p2p/peers:go_default_library",
"//beacon-chain/p2p/peers/peerdata:go_default_library",
"//beacon-chain/sync:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_libp2p_go_libp2p//core/network:go_default_library",
"@com_github_libp2p_go_libp2p//core/peer:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@io_opencensus_go//trace:go_default_library",
],
)
@@ -36,7 +37,7 @@ go_test(
"//beacon-chain/p2p:go_default_library",
"//beacon-chain/p2p/peers:go_default_library",
"//beacon-chain/p2p/testing:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"@com_github_ethereum_go_ethereum//p2p/enode:go_default_library",

View File

@@ -12,23 +12,27 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers/peerdata"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"go.opencensus.io/trace"
)
// ListTrustedPeer retrieves data about the node's trusted peers.
func (s *Server) ListTrustedPeer(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "node.ListTrustedPeer")
defer span.End()
peerStatus := s.PeersFetcher.Peers()
allIds := s.PeersFetcher.Peers().GetTrustedPeers()
allPeers := make([]*Peer, 0, len(allIds))
for _, id := range allIds {
p, err := httpPeerInfo(peerStatus, id)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, "Could not get peer info").Error(),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
// peers added into trusted set but never connected should also be listed
@@ -44,37 +48,40 @@ func (s *Server) ListTrustedPeer(w http.ResponseWriter, r *http.Request) {
allPeers = append(allPeers, p)
}
response := &PeersResponse{Peers: allPeers}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
// AddTrustedPeer adds a new peer into node's trusted peer set by Multiaddr
func (s *Server) AddTrustedPeer(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "node.AddTrustedPeer")
defer span.End()
body, err := io.ReadAll(r.Body)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, "Could not read request body").Error(),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
var addrRequest *AddrRequest
err = json.Unmarshal(body, &addrRequest)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, "Could not decode request body into peer address").Error(),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
info, err := peer.AddrInfoFromString(addrRequest.Addr)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, "Could not derive peer info from multiaddress").Error(),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
@@ -86,23 +93,26 @@ func (s *Server) AddTrustedPeer(w http.ResponseWriter, r *http.Request) {
s.PeersFetcher.Peers().Add(nil, info.ID, info.Addrs[0], direction)
}
var peers []peer.ID
peers = append(peers, info.ID)
s.PeersFetcher.Peers().SetTrustedPeers(peers)
var ids []peer.ID
ids = append(ids, info.ID)
s.PeersFetcher.Peers().SetTrustedPeers(ids)
w.WriteHeader(http.StatusOK)
}
// RemoveTrustedPeer removes peer from our trusted peer set but does not close connection.
func (s *Server) RemoveTrustedPeer(w http.ResponseWriter, r *http.Request) {
_, span := trace.StartSpan(r.Context(), "node.RemoveTrustedPeer")
defer span.End()
segments := strings.Split(r.URL.Path, "/")
id := segments[len(segments)-1]
peerId, err := peer.Decode(id)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: errors.Wrapf(err, "Could not decode peer id").Error(),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
@@ -112,9 +122,9 @@ func (s *Server) RemoveTrustedPeer(w http.ResponseWriter, r *http.Request) {
return
}
var peers []peer.ID
peers = append(peers, peerId)
s.PeersFetcher.Peers().DeleteTrustedPeers(peers)
var ids []peer.ID
ids = append(ids, peerId)
s.PeersFetcher.Peers().DeleteTrustedPeers(ids)
w.WriteHeader(http.StatusOK)
}

View File

@@ -17,7 +17,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/peers"
mockp2p "github.com/prysmaticlabs/prysm/v4/beacon-chain/p2p/testing"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
@@ -188,7 +188,7 @@ func TestAddTrustedPeer_EmptyBody(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.AddTrustedPeer(writer, request)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.Equal(t, "Could not decode request body into peer address: unexpected end of JSON input", e.Message)
@@ -213,7 +213,7 @@ func TestAddTrustedPeer_BadAddress(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.AddTrustedPeer(writer, request)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.StringContains(t, "Could not derive peer info from multiaddress", e.Message)
@@ -243,7 +243,7 @@ func TestRemoveTrustedPeer_EmptyParameter(t *testing.T) {
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}
s.RemoveTrustedPeer(writer, request)
e := &http2.DefaultErrorJson{}
e := &httputil.DefaultErrorJson{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.Equal(t, http.StatusBadRequest, writer.Code)
assert.Equal(t, "Could not decode peer id: failed to parse peer ID: invalid cid: cid too short", e.Message)

View File

@@ -20,7 +20,7 @@ go_library(
"//beacon-chain/sync:go_default_library",
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/eth/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//time/slots:go_default_library",
@@ -48,7 +48,7 @@ go_test(
"//config/params:go_default_library",
"//consensus-types/primitives:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
"//testing/require:go_default_library",

View File

@@ -13,7 +13,7 @@ import (
statenative "github.com/prysmaticlabs/prysm/v4/beacon-chain/state/state-native"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/consensus-types/validator"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/eth/v1"
eth "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/time/slots"
@@ -59,23 +59,23 @@ type Count struct {
// }
// ]
// }
func (vs *Server) GetValidatorCount(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "beacon.GetValidatorCount")
func (s *Server) GetValidatorCount(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "validator.GetValidatorCount")
defer span.End()
stateID := mux.Vars(r)["state_id"]
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateID), vs.OptimisticModeFetcher, vs.Stater, vs.ChainInfoFetcher, vs.BeaconDB)
isOptimistic, err := helpers.IsOptimistic(ctx, []byte(stateID), s.OptimisticModeFetcher, s.Stater, s.ChainInfoFetcher, s.BeaconDB)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: fmt.Sprintf("could not check if slot's block is optimistic: %v", err),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
st, err := vs.Stater.State(ctx, []byte(stateID))
st, err := s.Stater.State(ctx, []byte(stateID))
if err != nil {
shared.WriteStateFetchError(w, err)
return
@@ -83,25 +83,25 @@ func (vs *Server) GetValidatorCount(w http.ResponseWriter, r *http.Request) {
blockRoot, err := st.LatestBlockHeader().HashTreeRoot()
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: fmt.Sprintf("could not calculate root of latest block header: %v", err),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
isFinalized := vs.FinalizationFetcher.IsFinalized(ctx, blockRoot)
isFinalized := s.FinalizationFetcher.IsFinalized(ctx, blockRoot)
var statusVals []validator.Status
for _, status := range r.URL.Query()["status"] {
statusVal, ok := ethpb.ValidatorStatus_value[strings.ToUpper(status)]
if !ok {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: fmt.Sprintf("invalid status query parameter: %v", status),
Code: http.StatusBadRequest,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
@@ -118,11 +118,11 @@ func (vs *Server) GetValidatorCount(w http.ResponseWriter, r *http.Request) {
epoch := slots.ToEpoch(st.Slot())
valCount, err := validatorCountByStatus(st.Validators(), statusVals, epoch)
if err != nil {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: fmt.Sprintf("could not get validator count: %v", err),
Code: http.StatusInternalServerError,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
return
}
@@ -132,7 +132,7 @@ func (vs *Server) GetValidatorCount(w http.ResponseWriter, r *http.Request) {
Data: valCount,
}
http2.WriteJson(w, valCountResponse)
httputil.WriteJson(w, valCountResponse)
}
// validatorCountByStatus returns a slice of validator count for each status in the given epoch.

View File

@@ -15,7 +15,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/state"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/lookup"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/gorilla/mux"
chainMock "github.com/prysmaticlabs/prysm/v4/beacon-chain/blockchain/testing"
@@ -101,7 +101,7 @@ func TestGetValidatorCountInvalidRequest(t *testing.T) {
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
var errJson http2.DefaultErrorJson
var errJson httputil.DefaultErrorJson
err = json.Unmarshal(body, &errJson)
require.NoError(t, err)
require.Equal(t, test.statusCode, errJson.Code)

View File

@@ -6,8 +6,9 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/core"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"go.opencensus.io/trace"
)
type PerformanceRequest struct {
@@ -28,7 +29,10 @@ type PerformanceResponse struct {
}
// GetValidatorPerformance is an HTTP handler for GetValidatorPerformance.
func (vs *Server) GetValidatorPerformance(w http.ResponseWriter, r *http.Request) {
func (s *Server) GetValidatorPerformance(w http.ResponseWriter, r *http.Request) {
ctx, span := trace.StartSpan(r.Context(), "validator.GetValidatorPerformance")
defer span.End()
var req PerformanceRequest
if r.Body != http.NoBody {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -36,8 +40,8 @@ func (vs *Server) GetValidatorPerformance(w http.ResponseWriter, r *http.Request
return
}
}
computed, err := vs.CoreService.ComputeValidatorPerformance(
r.Context(),
computed, err := s.CoreService.ComputeValidatorPerformance(
ctx,
&ethpb.ValidatorPerformanceRequest{
PublicKeys: req.PublicKeys,
Indices: req.Indices,
@@ -58,13 +62,13 @@ func (vs *Server) GetValidatorPerformance(w http.ResponseWriter, r *http.Request
MissingValidators: computed.MissingValidators,
InactivityScores: computed.InactivityScores, // Only populated in Altair
}
http2.WriteJson(w, response)
httputil.WriteJson(w, response)
}
func handleHTTPError(w http.ResponseWriter, message string, code int) {
errJson := &http2.DefaultErrorJson{
errJson := &httputil.DefaultErrorJson{
Message: message,
Code: code,
}
http2.WriteError(w, errJson)
httputil.WriteError(w, errJson)
}

View File

@@ -46,6 +46,7 @@ go_test(
data = glob(["testdata/**"]),
embed = [":go_default_library"],
deps = [
"//api/server:go_default_library",
"//beacon-chain/rpc/eth/beacon:go_default_library",
"//beacon-chain/rpc/eth/config:go_default_library",
"//beacon-chain/rpc/eth/shared:go_default_library",

View File

@@ -12,6 +12,7 @@ import (
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/prysmaticlabs/prysm/v4/api/server"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/config"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
@@ -220,8 +221,8 @@ func TestCallWithdrawalEndpoint_Errors(t *testing.T) {
if r.Method == http.MethodPost && r.RequestURI == "/eth/v1/beacon/pool/bls_to_execution_changes" {
w.WriteHeader(400)
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(&shared.IndexedVerificationFailureError{
Failures: []*shared.IndexedVerificationFailure{
err = json.NewEncoder(w).Encode(&server.IndexedVerificationFailureError{
Failures: []*server.IndexedVerificationFailure{
{Index: 0, Message: "Could not validate SignedBLSToExecutionChange"},
},
})

View File

@@ -1,6 +1,7 @@
package slice
import (
"fmt"
"strings"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
@@ -391,3 +392,12 @@ func Reverse[E any](s []E) []E {
}
return s
}
// VerifyMaxLength takes a slice and a maximum length and validates the length.
func VerifyMaxLength[T any](v []T, max int) error {
l := len(v)
if l > max {
return fmt.Errorf("length of %d exceeds max of %d", l, max)
}
return nil
}

View File

@@ -16,6 +16,8 @@ go_library(
deps = [
"//config/fieldparams:go_default_library",
"//consensus-types/primitives:go_default_library",
"//container/slice:go_default_library",
"//math:go_default_library",
"@com_github_ethereum_go_ethereum//common/hexutil:go_default_library",
"@com_github_pkg_errors//:go_default_library",
],

View File

@@ -1,6 +1,13 @@
package bytesutil
import "regexp"
import (
"fmt"
"regexp"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/container/slice"
)
var hexRegex = regexp.MustCompile("^0x[0-9a-fA-F]+$")
@@ -11,3 +18,30 @@ func IsHex(b []byte) bool {
}
return hexRegex.Match(b)
}
// DecodeHexWithLength takes a string and a length in bytes,
// and validates whether the string is a hex and has the correct length.
func DecodeHexWithLength(s string, length int) ([]byte, error) {
bytes, err := hexutil.Decode(s)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%s is not a valid hex", s))
}
if len(bytes) != length {
return nil, fmt.Errorf("%s is not length %d bytes", s, length)
}
return bytes, nil
}
// DecodeHexWithMaxLength takes a string and a length in bytes,
// and validates whether the string is a hex and has the correct length.
func DecodeHexWithMaxLength(s string, maxLength int) ([]byte, error) {
bytes, err := hexutil.Decode(s)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("%s is not a valid hex", s))
}
err = slice.VerifyMaxLength(bytes, maxLength)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("length of %s exceeds max of %d bytes", s, maxLength))
}
return bytes, nil
}

View File

@@ -2,7 +2,11 @@ package bytesutil
import (
"encoding/binary"
"errors"
"fmt"
"math/big"
"github.com/prysmaticlabs/prysm/v4/math"
)
// ToBytes returns integer x to bytes in little-endian format at the specified length.
@@ -150,3 +154,15 @@ func BigIntToLittleEndianBytes(bigInt *big.Int) []byte {
// big.Int.Bytes() returns bytes in big-endian order, so we need to reverse the byte order
return ReverseByteOrder(bigInt.Bytes())
}
// Uint256ToSSZBytes takes a string representation of uint256 and returns its bytes stored as little-endian
func Uint256ToSSZBytes(num string) ([]byte, error) {
uint256, ok := new(big.Int).SetString(num, 10)
if !ok {
return nil, errors.New("could not parse Uint256")
}
if !math.IsValidUint256(uint256) {
return nil, fmt.Errorf("%s is not a valid Uint256", num)
}
return PadTo(ReverseByteOrder(uint256.Bytes()), 32), nil
}

View File

@@ -7,7 +7,7 @@ go_library(
"reader.go",
"writer.go",
],
importpath = "github.com/prysmaticlabs/prysm/v4/network/http",
importpath = "github.com/prysmaticlabs/prysm/v4/network/httputil",
visibility = ["//visibility:public"],
deps = [
"//api:go_default_library",

View File

@@ -1,4 +1,4 @@
package http
package httputil
import (
"net/http"

View File

@@ -1,4 +1,4 @@
package http
package httputil
import (
"net/http"

View File

@@ -1,4 +1,4 @@
package http
package httputil
import (
"fmt"

View File

@@ -1,4 +1,4 @@
package http
package httputil
import (
"bytes"

View File

@@ -3513,7 +3513,7 @@ func (b *BeaconBlockBodyCapella) MarshalSSZTo(buf []byte) (dst []byte, err error
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -4088,7 +4088,7 @@ func (b *BlindedBeaconBlockBodyCapella) MarshalSSZTo(buf []byte) (dst []byte, er
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -4667,7 +4667,7 @@ func (b *BlindedBeaconBlockBodyDeneb) MarshalSSZTo(buf []byte) (dst []byte, err
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -5306,7 +5306,7 @@ func (b *BeaconBlockBodyDeneb) MarshalSSZTo(buf []byte) (dst []byte, err error)
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {

View File

@@ -5476,7 +5476,7 @@ func (b *BeaconBlockBodyDeneb) MarshalSSZTo(buf []byte) (dst []byte, err error)
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -6375,7 +6375,7 @@ func (b *BeaconBlockBodyCapella) MarshalSSZTo(buf []byte) (dst []byte, err error
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -7214,7 +7214,7 @@ func (b *BlindedBeaconBlockBodyCapella) MarshalSSZTo(buf []byte) (dst []byte, er
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {
@@ -8057,7 +8057,7 @@ func (b *BlindedBeaconBlockBodyDeneb) MarshalSSZTo(buf []byte) (dst []byte, err
// Field (10) 'BlsToExecutionChanges'
if size := len(b.BlsToExecutionChanges); size > 16 {
err = ssz.ErrListTooBigFn("--.BlsToExecutionChanges", size, 16)
err = ssz.ErrListTooBigFn("--.BLSToExecutionChanges", size, 16)
return
}
for ii := 0; ii < len(b.BlsToExecutionChanges); ii++ {

View File

@@ -239,8 +239,8 @@ go_test(
"@web3signer",
],
eth_network = "minimal",
flaky = True,
shard_count = 2,
# flaky = True,
# shard_count = 2,
tags = [
"exclusive",
"manual",

View File

@@ -40,7 +40,7 @@ go_library(
"//encoding/bytesutil:go_default_library",
"//encoding/ssz/detect:go_default_library",
"//network/forks:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/interop:go_default_library",
"//runtime/version:go_default_library",

View File

@@ -10,7 +10,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/testing/endtoend/params"
"github.com/prysmaticlabs/prysm/v4/testing/endtoend/policies"
@@ -35,7 +35,7 @@ func optimisticSyncEnabled(_ *types.EvaluationContext, conns ...*grpc.ClientConn
return err
}
if httpResp.StatusCode != http.StatusOK {
e := http2.DefaultErrorJson{}
e := httputil.DefaultErrorJson{}
if err = json.NewDecoder(httpResp.Body).Decode(&e); err != nil {
return err
}
@@ -65,7 +65,7 @@ func optimisticSyncEnabled(_ *types.EvaluationContext, conns ...*grpc.ClientConn
continue
}
if httpResp.StatusCode != http.StatusOK {
e := http2.DefaultErrorJson{}
e := httputil.DefaultErrorJson{}
if err = json.NewDecoder(httpResp.Body).Decode(&e); err != nil {
return err
}

View File

@@ -616,13 +616,9 @@ func submitWithdrawal(ec *e2etypes.EvaluationContext, conns ...*grpc.ClientConn)
return err
}
signature := privKeys[idx].Sign(sigRoot[:]).Marshal()
change, err := shared.BlsToExecutionChangeFromConsensus(message)
if err != nil {
return err
}
changes = append(changes, &shared.SignedBLSToExecutionChange{
Message: change,
Message: shared.BLSChangeFromConsensus(message),
Signature: hexutil.Encode(signature),
})
}

View File

@@ -10,12 +10,13 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/core/altair"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/debug"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/shared"
"github.com/prysmaticlabs/prysm/v4/config/params"
"github.com/prysmaticlabs/prysm/v4/consensus-types/blocks"
"github.com/prysmaticlabs/prysm/v4/consensus-types/interfaces"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v4/encoding/bytesutil"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/runtime/version"
"github.com/prysmaticlabs/prysm/v4/testing/endtoend/helpers"
@@ -138,7 +139,7 @@ func validatorsParticipating(_ *types.EvaluationContext, conns ...*grpc.ClientCo
return err
}
if httpResp.StatusCode != http.StatusOK {
e := http2.DefaultErrorJson{}
e := httputil.DefaultErrorJson{}
if err = json.NewDecoder(httpResp.Body).Decode(&e); err != nil {
return err
}
@@ -153,19 +154,19 @@ func validatorsParticipating(_ *types.EvaluationContext, conns ...*grpc.ClientCo
case version.String(version.Phase0):
// Do Nothing
case version.String(version.Altair):
st := &debug.BeaconStateAltair{}
st := &shared.BeaconStateAltair{}
if err = json.Unmarshal(resp.Data, st); err != nil {
return err
}
respPrevEpochParticipation = st.PreviousEpochParticipation
case version.String(version.Bellatrix):
st := &debug.BeaconStateBellatrix{}
st := &shared.BeaconStateBellatrix{}
if err = json.Unmarshal(resp.Data, st); err != nil {
return err
}
respPrevEpochParticipation = st.PreviousEpochParticipation
case version.String(version.Capella):
st := &debug.BeaconStateCapella{}
st := &shared.BeaconStateCapella{}
if err = json.Unmarshal(resp.Data, st); err != nil {
return err
}

View File

@@ -53,7 +53,7 @@ go_library(
"//consensus-types/validator:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/forks:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
@@ -126,7 +126,7 @@ go_test(
"//consensus-types/primitives:go_default_library",
"//consensus-types/validator:go_default_library",
"//encoding/bytesutil:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -380,7 +380,7 @@ func (c beaconApiBeaconBlockConverter) ConvertRESTCapellaBlockToProto(block *sha
return nil, errors.Wrap(err, "failed to get withdrawals")
}
blsToExecutionChanges, err := convertBlsToExecutionChangesToProto(block.Body.BlsToExecutionChanges)
blsToExecutionChanges, err := convertBlsToExecutionChangesToProto(block.Body.BLSToExecutionChanges)
if err != nil {
return nil, errors.Wrap(err, "failed to get bls to execution changes")
}

View File

@@ -487,7 +487,7 @@ func TestGetBeaconBlockConverter_CapellaError(t *testing.T) {
expectedErrorMessage: "failed to get bls to execution changes",
generateData: func() *shared.BeaconBlockCapella {
beaconBlock := test_helpers.GenerateJsonCapellaBeaconBlock()
beaconBlock.Body.BlsToExecutionChanges[0] = nil
beaconBlock.Body.BLSToExecutionChanges[0] = nil
return beaconBlock
},
},

View File

@@ -8,7 +8,6 @@ import (
enginev1 "github.com/prysmaticlabs/prysm/v4/proto/engine/v1"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
func TestBeaconBlockJsonHelpers_JsonifyTransactions(t *testing.T) {
@@ -64,9 +63,7 @@ func TestBeaconBlockJsonHelpers_JsonifyBlsToExecutionChanges(t *testing.T) {
},
}
result, err := shared.SignedBlsToExecutionChangesFromConsensus(input)
require.NoError(t, err)
assert.DeepEqual(t, expectedResult, result)
assert.DeepEqual(t, expectedResult, shared.SignedBLSChangesFromConsensus(input))
}
func TestBeaconBlockJsonHelpers_JsonifyEth1Data(t *testing.T) {

View File

@@ -9,12 +9,12 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
type GenesisProvider interface {
GetGenesis(ctx context.Context) (*beacon.Genesis, *http2.DefaultErrorJson, error)
GetGenesis(ctx context.Context) (*beacon.Genesis, *httputil.DefaultErrorJson, error)
}
type beaconApiGenesisProvider struct {
@@ -61,7 +61,7 @@ func (c beaconApiValidatorClient) waitForChainStart(ctx context.Context) (*ethpb
}
// GetGenesis gets the genesis information from the beacon node via the /eth/v1/beacon/genesis endpoint
func (c beaconApiGenesisProvider) GetGenesis(ctx context.Context) (*beacon.Genesis, *http2.DefaultErrorJson, error) {
func (c beaconApiGenesisProvider) GetGenesis(ctx context.Context) (*beacon.Genesis, *httputil.DefaultErrorJson, error) {
genesisJson := &beacon.GetGenesisResponse{}
errorJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/beacon/genesis", genesisJson)
if err != nil {

View File

@@ -7,7 +7,7 @@ import (
"github.com/golang/mock/gomock"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
"github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api/mock"
@@ -41,7 +41,7 @@ func TestGetGenesis_ValidGenesis(t *testing.T) {
genesisProvider := &beaconApiGenesisProvider{jsonRestHandler: jsonRestHandler}
resp, httpError, err := genesisProvider.GetGenesis(ctx)
assert.NoError(t, err)
assert.Equal(t, (*http2.DefaultErrorJson)(nil), httpError)
assert.Equal(t, (*httputil.DefaultErrorJson)(nil), httpError)
require.NotNil(t, resp)
assert.Equal(t, "1234", resp.GenesisTime)
assert.Equal(t, "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", resp.GenesisValidatorsRoot)
@@ -69,7 +69,7 @@ func TestGetGenesis_NilData(t *testing.T) {
genesisProvider := &beaconApiGenesisProvider{jsonRestHandler: jsonRestHandler}
_, httpError, err := genesisProvider.GetGenesis(ctx)
assert.Equal(t, (*http2.DefaultErrorJson)(nil), httpError)
assert.Equal(t, (*httputil.DefaultErrorJson)(nil), httpError)
assert.ErrorContains(t, "genesis data is nil", err)
}
@@ -79,7 +79,7 @@ func TestGetGenesis_JsonResponseError(t *testing.T) {
ctx := context.Background()
expectedHttpErrorJson := &http2.DefaultErrorJson{
expectedHttpErrorJson := &httputil.DefaultErrorJson{
Message: "http error message",
Code: 999,
}

View File

@@ -12,7 +12,7 @@ import (
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/validator"
"github.com/prysmaticlabs/prysm/v4/consensus-types/primitives"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -532,7 +532,7 @@ func TestGetBeaconBlock_FallbackToBlindedBlock(t *testing.T) {
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
).Return(
&http2.DefaultErrorJson{Code: http.StatusNotFound},
&httputil.DefaultErrorJson{Code: http.StatusNotFound},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().Get(
@@ -585,7 +585,7 @@ func TestGetBeaconBlock_FallbackToFullBlock(t *testing.T) {
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
).Return(
&http2.DefaultErrorJson{Code: http.StatusNotFound},
&httputil.DefaultErrorJson{Code: http.StatusNotFound},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().Get(
@@ -593,7 +593,7 @@ func TestGetBeaconBlock_FallbackToFullBlock(t *testing.T) {
fmt.Sprintf("/eth/v1/validator/blinded_blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&abstractProduceBlockResponseJson{},
).Return(
&http2.DefaultErrorJson{Code: http.StatusInternalServerError},
&httputil.DefaultErrorJson{Code: http.StatusInternalServerError},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().Get(

View File

@@ -9,12 +9,12 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
)
type JsonRestHandler interface {
Get(ctx context.Context, query string, resp interface{}) (*http2.DefaultErrorJson, error)
Post(ctx context.Context, endpoint string, headers map[string]string, data *bytes.Buffer, resp interface{}) (*http2.DefaultErrorJson, error)
Get(ctx context.Context, query string, resp interface{}) (*httputil.DefaultErrorJson, error)
Post(ctx context.Context, endpoint string, headers map[string]string, data *bytes.Buffer, resp interface{}) (*httputil.DefaultErrorJson, error)
}
type beaconApiJsonRestHandler struct {
@@ -24,7 +24,7 @@ type beaconApiJsonRestHandler struct {
// Get sends a GET request and decodes the response body as a JSON object into the passed in object.
// If an HTTP error is returned, the body is decoded as a DefaultErrorJson JSON object and returned as the first return value.
func (c beaconApiJsonRestHandler) Get(ctx context.Context, endpoint string, resp interface{}) (*http2.DefaultErrorJson, error) {
func (c beaconApiJsonRestHandler) Get(ctx context.Context, endpoint string, resp interface{}) (*httputil.DefaultErrorJson, error) {
if resp == nil {
return nil, errors.New("resp is nil")
}
@@ -56,7 +56,7 @@ func (c beaconApiJsonRestHandler) Post(
headers map[string]string,
data *bytes.Buffer,
resp interface{},
) (*http2.DefaultErrorJson, error) {
) (*httputil.DefaultErrorJson, error) {
if data == nil {
return nil, errors.New("data is nil")
}
@@ -85,7 +85,7 @@ func (c beaconApiJsonRestHandler) Post(
return decodeResp(httpResp, resp)
}
func decodeResp(httpResp *http.Response, resp interface{}) (*http2.DefaultErrorJson, error) {
func decodeResp(httpResp *http.Response, resp interface{}) (*httputil.DefaultErrorJson, error) {
body, err := io.ReadAll(httpResp.Body)
if err != nil {
return nil, errors.Wrapf(err, "failed to read response body for %s", httpResp.Request.URL)
@@ -95,12 +95,12 @@ func decodeResp(httpResp *http.Response, resp interface{}) (*http2.DefaultErrorJ
if httpResp.StatusCode == http.StatusOK {
return nil, nil
}
return &http2.DefaultErrorJson{Code: httpResp.StatusCode, Message: string(body)}, nil
return &httputil.DefaultErrorJson{Code: httpResp.StatusCode, Message: string(body)}, nil
}
decoder := json.NewDecoder(bytes.NewBuffer(body))
if httpResp.StatusCode != http.StatusOK {
errorJson := &http2.DefaultErrorJson{}
errorJson := &httputil.DefaultErrorJson{}
if err = decoder.Decode(errorJson); err != nil {
return nil, errors.Wrapf(err, "failed to decode response body into error json for %s", httpResp.Request.URL)
}

View File

@@ -12,7 +12,7 @@ import (
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/network/httputil"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
@@ -146,7 +146,7 @@ func decodeRespTest(t *testing.T) {
})
t.Run("non-200 JSON", func(t *testing.T) {
body := bytes.Buffer{}
b, err := json.Marshal(&http2.DefaultErrorJson{Code: http.StatusInternalServerError, Message: "error"})
b, err := json.Marshal(&httputil.DefaultErrorJson{Code: http.StatusInternalServerError, Message: "error"})
require.NoError(t, err)
body.Write(b)
r := &http.Response{StatusCode: http.StatusInternalServerError, Body: io.NopCloser(&body), Header: map[string][]string{"Content-Type": {api.JsonMediaType}}}

View File

@@ -16,7 +16,7 @@ go_library(
"//beacon-chain/rpc/eth/shared:go_default_library",
"//beacon-chain/rpc/eth/validator:go_default_library",
"//consensus-types/primitives:go_default_library",
"//network/http:go_default_library",
"//network/httputil:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_golang_mock//gomock:go_default_library",
],

Some files were not shown because too many files have changed in this diff Show More