Better error handling in REST VC (#13203)

This commit is contained in:
Radosław Kapka
2023-11-21 17:42:55 +01:00
committed by GitHub
parent 10ccf1840f
commit a7edec9b98
67 changed files with 683 additions and 893 deletions

View File

@@ -19,5 +19,8 @@ go_test(
name = "go_default_test",
srcs = ["reader_test.go"],
embed = [":go_default_library"],
deps = ["//testing/assert:go_default_library"],
deps = [
"//api:go_default_library",
"//testing/assert:go_default_library",
],
)

View File

@@ -5,48 +5,49 @@ import (
"net/http/httptest"
"testing"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
)
func TestSSZRequested(t *testing.T) {
t.Run("ssz_requested", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{octetStreamMediaType}
request.Header["Accept"] = []string{api.OctetStreamMediaType}
result := SszRequested(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_first", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s", octetStreamMediaType, jsonMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s", api.OctetStreamMediaType, api.JsonMediaType)}
result := SszRequested(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_preferred_1", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.9,%s", jsonMediaType, octetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.9,%s", api.JsonMediaType, api.OctetStreamMediaType)}
result := SszRequested(request)
assert.Equal(t, true, result)
})
t.Run("ssz_content_type_preferred_2", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.95,%s;q=0.9", octetStreamMediaType, jsonMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s;q=0.95,%s;q=0.9", api.OctetStreamMediaType, api.JsonMediaType)}
result := SszRequested(request)
assert.Equal(t, true, result)
})
t.Run("other_content_type_preferred", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9", jsonMediaType, octetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9", api.JsonMediaType, api.OctetStreamMediaType)}
result := SszRequested(request)
assert.Equal(t, false, result)
})
t.Run("other_params", func(t *testing.T) {
request := httptest.NewRequest("GET", "http://foo.example", nil)
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9,otherparam=xyz", jsonMediaType, octetStreamMediaType)}
request.Header["Accept"] = []string{fmt.Sprintf("%s,%s;q=0.9,otherparam=xyz", api.JsonMediaType, api.OctetStreamMediaType)}
result := SszRequested(request)
assert.Equal(t, false, result)
})

View File

@@ -3,18 +3,15 @@ package http
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"github.com/prysmaticlabs/prysm/v4/api"
log "github.com/sirupsen/logrus"
)
const (
jsonMediaType = "application/json"
octetStreamMediaType = "application/octet-stream"
)
type HasStatusCode interface {
StatusCode() int
}
@@ -29,9 +26,13 @@ func (e *DefaultErrorJson) StatusCode() int {
return e.Code
}
func (e *DefaultErrorJson) Error() string {
return fmt.Sprintf("HTTP request unsuccessful (%d: %s)", e.Code, e.Message)
}
// WriteJson writes the response message in JSON format.
func WriteJson(w http.ResponseWriter, v any) {
w.Header().Set("Content-Type", jsonMediaType)
w.Header().Set("Content-Type", api.JsonMediaType)
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(v); err != nil {
log.WithError(err).Error("Could not write response message")
@@ -41,7 +42,7 @@ func WriteJson(w http.ResponseWriter, v any) {
// WriteSsz writes the response message in ssz format
func WriteSsz(w http.ResponseWriter, respSsz []byte, fileName string) {
w.Header().Set("Content-Length", strconv.Itoa(len(respSsz)))
w.Header().Set("Content-Type", octetStreamMediaType)
w.Header().Set("Content-Type", api.OctetStreamMediaType)
w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(respSsz))); err != nil {
log.WithError(err).Error("could not write response message")
@@ -56,7 +57,7 @@ func WriteError(w http.ResponseWriter, errJson HasStatusCode) {
return
}
w.Header().Set("Content-Length", strconv.Itoa(len(j)))
w.Header().Set("Content-Type", jsonMediaType)
w.Header().Set("Content-Type", api.JsonMediaType)
w.WriteHeader(errJson.StatusCode())
if _, err := io.Copy(w, io.NopCloser(bytes.NewReader(j))); err != nil {
log.WithError(err).Error("Could not write error message")

View File

@@ -15,6 +15,7 @@ go_library(
"domain_data.go",
"doppelganger.go",
"duties.go",
"errors.go",
"genesis.go",
"get_beacon_block.go",
"index.go",
@@ -39,7 +40,6 @@ go_library(
visibility = ["//validator:__subpackages__"],
deps = [
"//api:go_default_library",
"//api/gateway/apimiddleware:go_default_library",
"//beacon-chain/core/helpers:go_default_library",
"//beacon-chain/core/signing:go_default_library",
"//beacon-chain/rpc/apimiddleware:go_default_library",
@@ -53,6 +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",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//runtime/version:go_default_library",
@@ -113,7 +114,7 @@ go_test(
],
embed = [":go_default_library"],
deps = [
"//api/gateway/apimiddleware:go_default_library",
"//api:go_default_library",
"//beacon-chain/rpc/apimiddleware:go_default_library",
"//beacon-chain/rpc/eth/beacon:go_default_library",
"//beacon-chain/rpc/eth/node:go_default_library",
@@ -125,6 +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",
"//proto/engine/v1:go_default_library",
"//proto/prysm/v1alpha1:go_default_library",
"//testing/assert:go_default_library",

View File

@@ -113,10 +113,10 @@ func TestActivation_Nominal(t *testing.T) {
// Instantiate a cancellable context.
ctx, cancel := context.WithCancel(context.Background())
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// GetRestJsonResponse does not return any result for non existing key
jsonRestHandler.EXPECT().GetRestJsonResponse(
// Get does not return any result for non existing key
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -238,8 +238,8 @@ func TestActivation_InvalidData(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
gomock.Any(),
@@ -278,8 +278,8 @@ func TestActivation_JsonResponseError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
gomock.Any(),

View File

@@ -24,8 +24,12 @@ func (c beaconApiValidatorClient) getAttestationData(
query := buildURL("/eth/v1/validator/attestation_data", params)
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, query, &produceAttestationDataResponseJson); err != nil {
return nil, errors.Wrap(err, "failed to get json response")
errJson, err := c.jsonRestHandler.Get(ctx, query, &produceAttestationDataResponseJson)
if err != nil {
return nil, errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if produceAttestationDataResponseJson.Data == nil {

View File

@@ -30,10 +30,10 @@ func TestGetAttestationData_ValidAttestation(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/attestation_data?committee_index=%d&slot=%d", expectedCommitteeIndex, expectedSlot),
&produceAttestationDataResponseJson,
@@ -183,8 +183,8 @@ func TestGetAttestationData_InvalidData(t *testing.T) {
defer ctrl.Finish()
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/validator/attestation_data?committee_index=2&slot=1",
&produceAttestationDataResponseJson,
@@ -212,9 +212,9 @@ func TestGetAttestationData_JsonResponseError(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/attestation_data?committee_index=%d&slot=%d", committeeIndex, slot),
&produceAttestationDataResponseJson,
@@ -225,7 +225,6 @@ func TestGetAttestationData_JsonResponseError(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
_, err := validatorClient.getAttestationData(ctx, slot, committeeIndex)
assert.ErrorContains(t, "failed to get json response", err)
assert.ErrorContains(t, "some specific json response error", err)
}

View File

@@ -22,7 +22,7 @@ import (
type beaconApiBeaconChainClient struct {
fallbackClient iface.BeaconChainClient
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
stateValidatorsProvider stateValidatorsProvider
}
@@ -30,8 +30,12 @@ const getValidatorPerformanceEndpoint = "/prysm/validators/performance"
func (c beaconApiBeaconChainClient) getHeadBlockHeaders(ctx context.Context) (*beacon.GetBlockHeaderResponse, error) {
blockHeader := beacon.GetBlockHeaderResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/beacon/headers/head", &blockHeader); err != nil {
return nil, errors.Wrap(err, "failed to get head block header")
errJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/beacon/headers/head", &blockHeader)
if err != nil {
return nil, errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if blockHeader.Data == nil || blockHeader.Data.Header == nil {
@@ -49,8 +53,12 @@ func (c beaconApiBeaconChainClient) GetChainHead(ctx context.Context, _ *empty.E
const endpoint = "/eth/v1/beacon/states/head/finality_checkpoints"
finalityCheckpoints := beacon.GetFinalityCheckpointsResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, endpoint, &finalityCheckpoints); err != nil {
return nil, errors.Wrapf(err, "failed to query %s", endpoint)
errJson, err := c.jsonRestHandler.Get(ctx, endpoint, &finalityCheckpoints)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if finalityCheckpoints.Data == nil {
@@ -330,14 +338,12 @@ func (c beaconApiBeaconChainClient) GetValidatorPerformance(ctx context.Context,
return nil, errors.Wrap(err, "failed to marshal request")
}
resp := &validator.PerformanceResponse{}
if _, err := c.jsonRestHandler.PostRestJson(
ctx,
getValidatorPerformanceEndpoint,
nil,
bytes.NewBuffer(request),
resp,
); err != nil {
return nil, errors.Wrap(err, "failed to get validator performance")
errJson, err := c.jsonRestHandler.Post(ctx, getValidatorPerformanceEndpoint, nil, bytes.NewBuffer(request), resp)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return &ethpb.ValidatorPerformanceResponse{

View File

@@ -12,7 +12,6 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/golang/mock/gomock"
gatewaymiddleware "github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"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/beacon-chain/rpc/prysm/validator"
@@ -122,8 +121,8 @@ func TestListValidators(t *testing.T) {
nil,
)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, blockHeaderEndpoint, gomock.Any()).Return(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(ctx, blockHeaderEndpoint, gomock.Any()).Return(
nil,
errors.New("bar error"),
)
@@ -135,7 +134,7 @@ func TestListValidators(t *testing.T) {
_, err := beaconChainClient.ListValidators(ctx, &ethpb.ListValidatorsRequest{
QueryFilter: nil,
})
assert.ErrorContains(t, "failed to get head block header: bar error", err)
assert.ErrorContains(t, "bar error", err)
})
t.Run("fails to read block header response", func(t *testing.T) {
@@ -198,8 +197,8 @@ func TestListValidators(t *testing.T) {
nil,
)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, blockHeaderEndpoint, gomock.Any()).Return(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(ctx, blockHeaderEndpoint, gomock.Any()).Return(
nil,
nil,
).SetArg(
@@ -620,7 +619,7 @@ func TestGetChainHead(t *testing.T) {
{
name: "query failed",
finalityCheckpointsError: errors.New("foo error"),
expectedError: fmt.Sprintf("failed to query %s: foo error", finalityCheckpointsEndpoint),
expectedError: "foo error",
generateFinalityCheckpointsResponse: func() beacon.GetFinalityCheckpointsResponse {
return beacon.GetFinalityCheckpointsResponse{}
},
@@ -751,8 +750,8 @@ func TestGetChainHead(t *testing.T) {
ctx := context.Background()
finalityCheckpointsResponse := beacon.GetFinalityCheckpointsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
nil,
testCase.finalityCheckpointsError,
).SetArg(
@@ -849,10 +848,10 @@ func TestGetChainHead(t *testing.T) {
defer ctrl.Finish()
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
finalityCheckpointsResponse := beacon.GetFinalityCheckpointsResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
jsonRestHandler.EXPECT().Get(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
nil,
nil,
).SetArg(
@@ -861,7 +860,7 @@ func TestGetChainHead(t *testing.T) {
)
headBlockHeadersResponse := beacon.GetBlockHeaderResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, headBlockHeadersEndpoint, &headBlockHeadersResponse).Return(
jsonRestHandler.EXPECT().Get(ctx, headBlockHeadersEndpoint, &headBlockHeadersResponse).Return(
nil,
testCase.headBlockHeadersError,
).SetArg(
@@ -881,10 +880,10 @@ func TestGetChainHead(t *testing.T) {
defer ctrl.Finish()
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
finalityCheckpointsResponse := beacon.GetFinalityCheckpointsResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
jsonRestHandler.EXPECT().Get(ctx, finalityCheckpointsEndpoint, &finalityCheckpointsResponse).Return(
nil,
nil,
).SetArg(
@@ -893,7 +892,7 @@ func TestGetChainHead(t *testing.T) {
)
headBlockHeadersResponse := beacon.GetBlockHeaderResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(ctx, headBlockHeadersEndpoint, &headBlockHeadersResponse).Return(
jsonRestHandler.EXPECT().Get(ctx, headBlockHeadersEndpoint, &headBlockHeadersResponse).Return(
nil,
nil,
).SetArg(
@@ -950,15 +949,15 @@ func Test_beaconApiBeaconChainClient_GetValidatorPerformance(t *testing.T) {
wantResponse := &validator.PerformanceResponse{}
want := &ethpb.ValidatorPerformanceResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
getValidatorPerformanceEndpoint,
nil,
bytes.NewBuffer(request),
wantResponse,
).Return(
&gatewaymiddleware.DefaultErrorJson{},
nil,
nil,
)

View File

@@ -55,12 +55,12 @@ func (c *beaconApiValidatorClient) getFork(ctx context.Context) (*beacon.GetStat
stateForkResponseJson := &beacon.GetStateForkResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(
ctx,
endpoint,
stateForkResponseJson,
); err != nil {
return nil, errors.Wrapf(err, "failed to get json response from `%s` REST endpoint", endpoint)
errJson, err := c.jsonRestHandler.Get(ctx, endpoint, stateForkResponseJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return stateForkResponseJson, nil
@@ -71,12 +71,12 @@ func (c *beaconApiValidatorClient) getHeaders(ctx context.Context) (*beacon.GetB
blockHeadersResponseJson := &beacon.GetBlockHeadersResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(
ctx,
endpoint,
blockHeadersResponseJson,
); err != nil {
return nil, errors.Wrapf(err, "failed to get json response from `%s` REST endpoint", endpoint)
errJson, err := c.jsonRestHandler.Get(ctx, endpoint, blockHeadersResponseJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return blockHeadersResponseJson, nil
@@ -93,8 +93,12 @@ func (c *beaconApiValidatorClient) getLiveness(ctx context.Context, epoch primit
return nil, errors.Wrapf(err, "failed to marshal validator indexes")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, url, nil, bytes.NewBuffer(marshalledJsonValidatorIndexes), livenessResponseJson); err != nil {
return nil, errors.Wrapf(err, "failed to send POST data to `%s` REST URL", url)
errJson, err := c.jsonRestHandler.Post(ctx, url, nil, bytes.NewBuffer(marshalledJsonValidatorIndexes), livenessResponseJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return livenessResponseJson, nil
@@ -105,12 +109,12 @@ func (c *beaconApiValidatorClient) getSyncing(ctx context.Context) (*node.SyncSt
syncingResponseJson := &node.SyncStatusResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(
ctx,
endpoint,
syncingResponseJson,
); err != nil {
return nil, errors.Wrapf(err, "failed to get json response from `%s` REST endpoint", endpoint)
errJson, err := c.jsonRestHandler.Get(ctx, endpoint, syncingResponseJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return syncingResponseJson, nil

View File

@@ -99,7 +99,7 @@ func TestGetFork_Nominal(t *testing.T) {
defer ctrl.Finish()
stateForkResponseJson := beacon.GetStateForkResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
expected := beacon.GetStateForkResponse{
Data: &shared.Fork{
@@ -111,7 +111,7 @@ func TestGetFork_Nominal(t *testing.T) {
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
forkEndpoint,
&stateForkResponseJson,
@@ -136,11 +136,11 @@ func TestGetFork_Invalid(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
forkEndpoint,
gomock.Any(),
@@ -154,7 +154,7 @@ func TestGetFork_Invalid(t *testing.T) {
}
_, err := validatorClient.getFork(ctx)
require.ErrorContains(t, "failed to get json response from `/eth/v1/beacon/states/head/fork` REST endpoint", err)
require.ErrorContains(t, "custom error", err)
}
const headersEndpoint = "/eth/v1/beacon/headers"
@@ -164,7 +164,7 @@ func TestGetHeaders_Nominal(t *testing.T) {
defer ctrl.Finish()
blockHeadersResponseJson := beacon.GetBlockHeadersResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
expected := beacon.GetBlockHeadersResponse{
Data: []*shared.SignedBeaconBlockHeaderContainer{
@@ -180,7 +180,7 @@ func TestGetHeaders_Nominal(t *testing.T) {
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
headersEndpoint,
&blockHeadersResponseJson,
@@ -205,11 +205,11 @@ func TestGetHeaders_Invalid(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
headersEndpoint,
gomock.Any(),
@@ -223,7 +223,7 @@ func TestGetHeaders_Invalid(t *testing.T) {
}
_, err := validatorClient.getHeaders(ctx)
require.ErrorContains(t, "failed to get json response from `/eth/v1/beacon/headers` REST endpoint", err)
require.ErrorContains(t, "custom error", err)
}
const livenessEndpoint = "/eth/v1/validator/liveness/42"
@@ -253,8 +253,8 @@ func TestGetLiveness_Nominal(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
livenessEndpoint,
nil,
@@ -281,8 +281,8 @@ func TestGetLiveness_Invalid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
livenessEndpoint,
nil,
@@ -296,7 +296,7 @@ func TestGetLiveness_Invalid(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
_, err := validatorClient.getLiveness(ctx, 42, nil)
require.ErrorContains(t, "failed to send POST data to `/eth/v1/validator/liveness/42` REST URL", err)
require.ErrorContains(t, "custom error", err)
}
const syncingEnpoint = "/eth/v1/node/syncing"
@@ -322,7 +322,7 @@ func TestGetIsSyncing_Nominal(t *testing.T) {
defer ctrl.Finish()
syncingResponseJson := node.SyncStatusResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
expected := node.SyncStatusResponse{
Data: &node.SyncStatusResponseData{
@@ -332,7 +332,7 @@ func TestGetIsSyncing_Nominal(t *testing.T) {
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
syncingEnpoint,
&syncingResponseJson,
@@ -360,11 +360,11 @@ func TestGetIsSyncing_Invalid(t *testing.T) {
defer ctrl.Finish()
syncingResponseJson := node.SyncStatusResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
syncingEnpoint,
&syncingResponseJson,

View File

@@ -18,14 +18,18 @@ import (
type beaconApiNodeClient struct {
fallbackClient iface.NodeClient
jsonRestHandler jsonRestHandler
genesisProvider genesisProvider
jsonRestHandler JsonRestHandler
genesisProvider GenesisProvider
}
func (c *beaconApiNodeClient) GetSyncStatus(ctx context.Context, _ *empty.Empty) (*ethpb.SyncStatus, error) {
syncingResponse := node.SyncStatusResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/node/syncing", &syncingResponse); err != nil {
return nil, errors.Wrap(err, "failed to get sync status")
errJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/node/syncing", &syncingResponse)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if syncingResponse.Data == nil {
@@ -38,10 +42,13 @@ func (c *beaconApiNodeClient) GetSyncStatus(ctx context.Context, _ *empty.Empty)
}
func (c *beaconApiNodeClient) GetGenesis(ctx context.Context, _ *empty.Empty) (*ethpb.Genesis, error) {
genesisJson, _, err := c.genesisProvider.GetGenesis(ctx)
genesisJson, errJson, err := c.genesisProvider.GetGenesis(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get genesis")
}
if errJson != nil {
return nil, errJson
}
genesisValidatorRoot, err := hexutil.Decode(genesisJson.GenesisValidatorsRoot)
if err != nil {
@@ -54,8 +61,12 @@ func (c *beaconApiNodeClient) GetGenesis(ctx context.Context, _ *empty.Empty) (*
}
depositContractJson := apimiddleware.DepositContractResponseJson{}
if _, err = c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/config/deposit_contract", &depositContractJson); err != nil {
return nil, errors.Wrapf(err, "failed to query deposit contract information")
errJson, err = c.jsonRestHandler.Get(ctx, "/eth/v1/config/deposit_contract", &depositContractJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if depositContractJson.Data == nil {
@@ -78,8 +89,12 @@ func (c *beaconApiNodeClient) GetGenesis(ctx context.Context, _ *empty.Empty) (*
func (c *beaconApiNodeClient) GetVersion(ctx context.Context, _ *empty.Empty) (*ethpb.Version, error) {
var versionResponse node.GetVersionResponse
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/node/version", &versionResponse); err != nil {
return nil, errors.Wrapf(err, "failed to query node version")
errJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/node/version", &versionResponse)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if versionResponse.Data == nil || versionResponse.Data.Version == "" {

View File

@@ -57,7 +57,7 @@ func TestGetGenesis(t *testing.T) {
},
depositContractError: errors.New("foo error"),
queriesDepositContract: true,
expectedError: "failed to query deposit contract information: foo error",
expectedError: "foo error",
},
{
name: "fails to read nil deposit contract data",
@@ -113,7 +113,7 @@ func TestGetGenesis(t *testing.T) {
defer ctrl.Finish()
ctx := context.Background()
genesisProvider := mock.NewMockgenesisProvider(ctrl)
genesisProvider := mock.NewMockGenesisProvider(ctrl)
genesisProvider.EXPECT().GetGenesis(
ctx,
).Return(
@@ -123,10 +123,10 @@ func TestGetGenesis(t *testing.T) {
)
depositContractJson := apimiddleware.DepositContractResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
if testCase.queriesDepositContract {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/config/deposit_contract",
&depositContractJson,
@@ -167,7 +167,7 @@ func TestGetSyncStatus(t *testing.T) {
{
name: "fails to query REST endpoint",
restEndpointError: errors.New("foo error"),
expectedError: "failed to get sync status: foo error",
expectedError: "foo error",
},
{
name: "returns nil syncing data",
@@ -205,8 +205,8 @@ func TestGetSyncStatus(t *testing.T) {
ctx := context.Background()
syncingResponse := node.SyncStatusResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
syncingEndpoint,
&syncingResponse,
@@ -243,7 +243,7 @@ func TestGetVersion(t *testing.T) {
{
name: "fails to query REST endpoint",
restEndpointError: errors.New("foo error"),
expectedError: "failed to query node version",
expectedError: "foo error",
},
{
name: "returns nil version data",
@@ -270,8 +270,8 @@ func TestGetVersion(t *testing.T) {
ctx := context.Background()
var versionResponse node.GetVersionResponse
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
versionEndpoint,
&versionResponse,

View File

@@ -15,10 +15,10 @@ import (
)
type beaconApiValidatorClient struct {
genesisProvider genesisProvider
genesisProvider GenesisProvider
dutiesProvider dutiesProvider
stateValidatorsProvider stateValidatorsProvider
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
beaconBlockConverter beaconBlockConverter
prysmBeaconChainCLient iface.PrysmBeaconChainClient
}

View File

@@ -30,9 +30,9 @@ func TestBeaconApiValidatorClient_GetAttestationDataValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/attestation_data?committee_index=%d&slot=%d", committeeIndex, slot),
&produceAttestationDataResponseJson,
@@ -71,9 +71,9 @@ func TestBeaconApiValidatorClient_GetAttestationDataError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
produceAttestationDataResponseJson := validator.GetAttestationDataResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/attestation_data?committee_index=%d&slot=%d", committeeIndex, slot),
&produceAttestationDataResponseJson,
@@ -117,7 +117,7 @@ func TestBeaconApiValidatorClient_DomainDataValid(t *testing.T) {
ctx := context.Background()
genesisProvider := mock.NewMockgenesisProvider(ctrl)
genesisProvider := mock.NewMockGenesisProvider(ctrl)
genesisProvider.EXPECT().GetGenesis(ctx).Return(
&beacon.Genesis{GenesisValidatorsRoot: genesisValidatorRoot},
nil,
@@ -147,8 +147,8 @@ func TestBeaconApiValidatorClient_ProposeBeaconBlockValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blocks",
map[string]string{"Eth-Consensus-Version": "phase0"},
@@ -184,8 +184,8 @@ func TestBeaconApiValidatorClient_ProposeBeaconBlockError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blocks",
map[string]string{"Eth-Consensus-Version": "phase0"},

View File

@@ -19,9 +19,12 @@ func (c beaconApiValidatorClient) getDomainData(ctx context.Context, epoch primi
}
// Get the genesis validator root
genesis, _, err := c.genesisProvider.GetGenesis(ctx)
genesis, errJson, err := c.genesisProvider.GetGenesis(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to get genesis info")
return nil, errors.Wrapf(err, "failed to get genesis info")
}
if errJson != nil {
return nil, errJson
}
if !validRoot(genesis.GenesisValidatorsRoot) {

View File

@@ -36,7 +36,7 @@ func TestGetDomainData_ValidDomainData(t *testing.T) {
ctx := context.Background()
// Make sure that GetGenesis() is called exactly once
genesisProvider := mock.NewMockgenesisProvider(ctrl)
genesisProvider := mock.NewMockGenesisProvider(ctrl)
genesisProvider.EXPECT().GetGenesis(ctx).Return(
&beacon.Genesis{GenesisValidatorsRoot: genesisValidatorRoot},
nil,
@@ -66,7 +66,7 @@ func TestGetDomainData_GenesisError(t *testing.T) {
ctx := context.Background()
// Make sure that GetGenesis() is called exactly once
genesisProvider := mock.NewMockgenesisProvider(ctrl)
genesisProvider := mock.NewMockGenesisProvider(ctrl)
genesisProvider.EXPECT().GetGenesis(ctx).Return(nil, nil, errors.New("foo error")).Times(1)
validatorClient := &beaconApiValidatorClient{genesisProvider: genesisProvider}
@@ -85,7 +85,7 @@ func TestGetDomainData_InvalidGenesisRoot(t *testing.T) {
ctx := context.Background()
// Make sure that GetGenesis() is called exactly once
genesisProvider := mock.NewMockgenesisProvider(ctrl)
genesisProvider := mock.NewMockGenesisProvider(ctrl)
genesisProvider.EXPECT().GetGenesis(ctx).Return(
&beacon.Genesis{GenesisValidatorsRoot: "foo"},
nil,

View File

@@ -292,14 +292,14 @@ func TestCheckDoppelGanger_Nominal(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
if testCase.getSyncingOutput != nil {
syncingResponseJson := node.SyncStatusResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
syncingEnpoint,
&syncingResponseJson,
@@ -315,7 +315,7 @@ func TestCheckDoppelGanger_Nominal(t *testing.T) {
if testCase.getForkOutput != nil {
stateForkResponseJson := beacon.GetStateForkResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
forkEndpoint,
&stateForkResponseJson,
@@ -331,7 +331,7 @@ func TestCheckDoppelGanger_Nominal(t *testing.T) {
if testCase.getHeadersOutput != nil {
blockHeadersResponseJson := beacon.GetBlockHeadersResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
headersEndpoint,
&blockHeadersResponseJson,
@@ -351,7 +351,7 @@ func TestCheckDoppelGanger_Nominal(t *testing.T) {
marshalledIndexes, err := json.Marshal(iface.inputStringIndexes)
require.NoError(t, err)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
iface.inputUrl,
nil,
@@ -732,14 +732,14 @@ func TestCheckDoppelGanger_Errors(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
if testCase.getSyncingOutput != nil {
syncingResponseJson := node.SyncStatusResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
syncingEnpoint,
&syncingResponseJson,
@@ -755,7 +755,7 @@ func TestCheckDoppelGanger_Errors(t *testing.T) {
if testCase.getForkOutput != nil {
stateForkResponseJson := beacon.GetStateForkResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
forkEndpoint,
&stateForkResponseJson,
@@ -771,7 +771,7 @@ func TestCheckDoppelGanger_Errors(t *testing.T) {
if testCase.getHeadersOutput != nil {
blockHeadersResponseJson := beacon.GetBlockHeadersResponse{}
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
headersEndpoint,
&blockHeadersResponseJson,
@@ -805,7 +805,7 @@ func TestCheckDoppelGanger_Errors(t *testing.T) {
marshalledIndexes, err := json.Marshal(iface.inputStringIndexes)
require.NoError(t, err)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
iface.inputUrl,
nil,

View File

@@ -25,7 +25,7 @@ type dutiesProvider interface {
}
type beaconApiDutiesProvider struct {
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
}
type committeeIndexSlotPair struct {
@@ -207,8 +207,12 @@ func (c beaconApiDutiesProvider) GetCommittees(ctx context.Context, epoch primit
committeesRequest := buildURL("/eth/v1/beacon/states/head/committees", committeeParams)
var stateCommittees beacon.GetCommitteesResponse
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, committeesRequest, &stateCommittees); err != nil {
return nil, errors.Wrapf(err, "failed to query committees for epoch `%d`", epoch)
errJson, err := c.jsonRestHandler.Get(ctx, committeesRequest, &stateCommittees)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if stateCommittees.Data == nil {
@@ -237,8 +241,18 @@ func (c beaconApiDutiesProvider) GetAttesterDuties(ctx context.Context, epoch pr
}
attesterDuties := &validator.GetAttesterDutiesResponse{}
if _, err := c.jsonRestHandler.PostRestJson(ctx, fmt.Sprintf("/eth/v1/validator/duties/attester/%d", epoch), nil, bytes.NewBuffer(validatorIndicesBytes), attesterDuties); err != nil {
return nil, errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
fmt.Sprintf("/eth/v1/validator/duties/attester/%d", epoch),
nil,
bytes.NewBuffer(validatorIndicesBytes),
attesterDuties,
)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
for index, attesterDuty := range attesterDuties.Data {
@@ -253,8 +267,12 @@ func (c beaconApiDutiesProvider) GetAttesterDuties(ctx context.Context, epoch pr
// GetProposerDuties retrieves the proposer duties for the given epoch
func (c beaconApiDutiesProvider) GetProposerDuties(ctx context.Context, epoch primitives.Epoch) ([]*validator.ProposerDuty, error) {
proposerDuties := validator.GetProposerDutiesResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, fmt.Sprintf("/eth/v1/validator/duties/proposer/%d", epoch), &proposerDuties); err != nil {
return nil, errors.Wrapf(err, "failed to query proposer duties for epoch `%d`", epoch)
errJson, err := c.jsonRestHandler.Get(ctx, fmt.Sprintf("/eth/v1/validator/duties/proposer/%d", epoch), &proposerDuties)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if proposerDuties.Data == nil {
@@ -283,8 +301,18 @@ func (c beaconApiDutiesProvider) GetSyncDuties(ctx context.Context, epoch primit
}
syncDuties := validator.GetSyncCommitteeDutiesResponse{}
if _, err := c.jsonRestHandler.PostRestJson(ctx, fmt.Sprintf("/eth/v1/validator/duties/sync/%d", epoch), nil, bytes.NewBuffer(validatorIndicesBytes), &syncDuties); err != nil {
return nil, errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
fmt.Sprintf("/eth/v1/validator/duties/sync/%d", epoch),
nil,
bytes.NewBuffer(validatorIndicesBytes),
&syncDuties,
)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if syncDuties.Data == nil {

View File

@@ -66,8 +66,8 @@ func TestGetAttesterDuties_Valid(t *testing.T) {
ctx := context.Background()
validatorIndices := []primitives.ValidatorIndex{2, 9}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getAttesterDutiesTestEndpoint, epoch),
nil,
@@ -95,8 +95,8 @@ func TestGetAttesterDuties_HttpError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getAttesterDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -110,7 +110,6 @@ func TestGetAttesterDuties_HttpError(t *testing.T) {
dutiesProvider := &beaconApiDutiesProvider{jsonRestHandler: jsonRestHandler}
_, err := dutiesProvider.GetAttesterDuties(ctx, epoch, nil)
assert.ErrorContains(t, "foo error", err)
assert.ErrorContains(t, "failed to send POST data to REST endpoint", err)
}
func TestGetAttesterDuties_NilAttesterDuty(t *testing.T) {
@@ -121,8 +120,8 @@ func TestGetAttesterDuties_NilAttesterDuty(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getAttesterDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -166,8 +165,8 @@ func TestGetProposerDuties_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s/%d", getProposerDutiesTestEndpoint, epoch),
&validator.GetProposerDutiesResponse{},
@@ -193,8 +192,8 @@ func TestGetProposerDuties_HttpError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s/%d", getProposerDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -206,7 +205,6 @@ func TestGetProposerDuties_HttpError(t *testing.T) {
dutiesProvider := &beaconApiDutiesProvider{jsonRestHandler: jsonRestHandler}
_, err := dutiesProvider.GetProposerDuties(ctx, epoch)
assert.ErrorContains(t, "foo error", err)
assert.ErrorContains(t, "failed to query proposer duties for epoch `1`", err)
}
func TestGetProposerDuties_NilData(t *testing.T) {
@@ -217,8 +215,8 @@ func TestGetProposerDuties_NilData(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s/%d", getProposerDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -245,8 +243,8 @@ func TestGetProposerDuties_NilProposerDuty(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s/%d", getProposerDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -299,8 +297,8 @@ func TestGetSyncDuties_Valid(t *testing.T) {
ctx := context.Background()
validatorIndices := []primitives.ValidatorIndex{2, 6}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getSyncDutiesTestEndpoint, epoch),
nil,
@@ -328,8 +326,8 @@ func TestGetSyncDuties_HttpError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getSyncDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -343,7 +341,6 @@ func TestGetSyncDuties_HttpError(t *testing.T) {
dutiesProvider := &beaconApiDutiesProvider{jsonRestHandler: jsonRestHandler}
_, err := dutiesProvider.GetSyncDuties(ctx, epoch, nil)
assert.ErrorContains(t, "foo error", err)
assert.ErrorContains(t, "failed to send POST data to REST endpoint", err)
}
func TestGetSyncDuties_NilData(t *testing.T) {
@@ -354,8 +351,8 @@ func TestGetSyncDuties_NilData(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getSyncDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -384,8 +381,8 @@ func TestGetSyncDuties_NilSyncDuty(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", getSyncDutiesTestEndpoint, epoch),
gomock.Any(),
@@ -435,8 +432,8 @@ func TestGetCommittees_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?epoch=%d", getCommitteesTestEndpoint, epoch),
&beacon.GetCommitteesResponse{},
@@ -462,8 +459,8 @@ func TestGetCommittees_HttpError(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?epoch=%d", getCommitteesTestEndpoint, epoch),
gomock.Any(),
@@ -475,7 +472,6 @@ func TestGetCommittees_HttpError(t *testing.T) {
dutiesProvider := &beaconApiDutiesProvider{jsonRestHandler: jsonRestHandler}
_, err := dutiesProvider.GetCommittees(ctx, epoch)
assert.ErrorContains(t, "foo error", err)
assert.ErrorContains(t, "failed to query committees for epoch `1`", err)
}
func TestGetCommittees_NilData(t *testing.T) {
@@ -486,8 +482,8 @@ func TestGetCommittees_NilData(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?epoch=%d", getCommitteesTestEndpoint, epoch),
gomock.Any(),
@@ -514,8 +510,8 @@ func TestGetCommittees_NilCommittee(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?epoch=%d", getCommitteesTestEndpoint, epoch),
gomock.Any(),

View File

@@ -0,0 +1,5 @@
package beacon_api
const (
msgUnexpectedError = "unexpected error when making request"
)

View File

@@ -8,17 +8,17 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
)
type genesisProvider interface {
GetGenesis(ctx context.Context) (*beacon.Genesis, *apimiddleware.DefaultErrorJson, error)
type GenesisProvider interface {
GetGenesis(ctx context.Context) (*beacon.Genesis, *http2.DefaultErrorJson, error)
}
type beaconApiGenesisProvider struct {
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
}
func (c beaconApiValidatorClient) waitForChainStart(ctx context.Context) (*ethpb.ChainStartResponse, error) {
@@ -61,9 +61,9 @@ 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, *apimiddleware.DefaultErrorJson, error) {
func (c beaconApiGenesisProvider) GetGenesis(ctx context.Context) (*beacon.Genesis, *http2.DefaultErrorJson, error) {
genesisJson := &beacon.GetGenesisResponse{}
errorJson, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/beacon/genesis", genesisJson)
errorJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/beacon/genesis", genesisJson)
if err != nil {
return nil, errorJson, errors.Wrap(err, "failed to get json response")
}

View File

@@ -6,8 +6,8 @@ import (
"github.com/golang/mock/gomock"
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
"github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api/mock"
@@ -20,8 +20,8 @@ func TestGetGenesis_ValidGenesis(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -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, (*apimiddleware.DefaultErrorJson)(nil), httpError)
assert.Equal(t, (*http2.DefaultErrorJson)(nil), httpError)
require.NotNil(t, resp)
assert.Equal(t, "1234", resp.GenesisTime)
assert.Equal(t, "0xcf8e0d4e9587369b2301d0790347320302cc0943d5a1884560367e8208d920f2", resp.GenesisValidatorsRoot)
@@ -54,8 +54,8 @@ func TestGetGenesis_NilData(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -69,7 +69,7 @@ func TestGetGenesis_NilData(t *testing.T) {
genesisProvider := &beaconApiGenesisProvider{jsonRestHandler: jsonRestHandler}
_, httpError, err := genesisProvider.GetGenesis(ctx)
assert.Equal(t, (*apimiddleware.DefaultErrorJson)(nil), httpError)
assert.Equal(t, (*http2.DefaultErrorJson)(nil), httpError)
assert.ErrorContains(t, "genesis data is nil", err)
}
@@ -79,14 +79,14 @@ func TestGetGenesis_JsonResponseError(t *testing.T) {
ctx := context.Background()
expectedHttpErrorJson := &apimiddleware.DefaultErrorJson{
expectedHttpErrorJson := &http2.DefaultErrorJson{
Message: "http error message",
Code: 999,
}
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -97,7 +97,6 @@ func TestGetGenesis_JsonResponseError(t *testing.T) {
genesisProvider := &beaconApiGenesisProvider{jsonRestHandler: jsonRestHandler}
_, httpError, err := genesisProvider.GetGenesis(ctx)
assert.ErrorContains(t, "failed to get json response", err)
assert.ErrorContains(t, "some specific json response error", err)
assert.DeepEqual(t, expectedHttpErrorJson, httpError)
}

View File

@@ -37,7 +37,7 @@ func (c beaconApiValidatorClient) getBeaconBlock(ctx context.Context, slot primi
// We try the blinded block endpoint first. If it fails, we assume that we got a full block and try the full block endpoint.
queryUrl := buildURL(fmt.Sprintf("/eth/v3/validator/blocks/%d", slot), queryParams)
produceBlockV3ResponseJson := validator.ProduceBlockV3Response{}
errJson, err := c.jsonRestHandler.GetRestJsonResponse(ctx, queryUrl, &produceBlockV3ResponseJson)
errJson, err := c.jsonRestHandler.Get(ctx, queryUrl, &produceBlockV3ResponseJson)
if err == nil {
ver = produceBlockV3ResponseJson.Version
blinded = produceBlockV3ResponseJson.ExecutionPayloadBlinded
@@ -48,7 +48,7 @@ func (c beaconApiValidatorClient) getBeaconBlock(ctx context.Context, slot primi
log.Debug("Endpoint /eth/v3/validator/blocks is not supported, falling back to older endpoints for block proposal.")
produceBlindedBlockResponseJson := abstractProduceBlockResponseJson{}
queryUrl = buildURL(fmt.Sprintf("/eth/v1/validator/blinded_blocks/%d", slot), queryParams)
errJson, err = c.jsonRestHandler.GetRestJsonResponse(ctx, queryUrl, &produceBlindedBlockResponseJson)
errJson, err = c.jsonRestHandler.Get(ctx, queryUrl, &produceBlindedBlockResponseJson)
if err == nil {
ver = produceBlindedBlockResponseJson.Version
blinded = true
@@ -57,7 +57,7 @@ func (c beaconApiValidatorClient) getBeaconBlock(ctx context.Context, slot primi
log.Debug("Endpoint /eth/v1/validator/blinded_blocks failed to produce a blinded block, trying /eth/v2/validator/blocks.")
produceBlockResponseJson := abstractProduceBlockResponseJson{}
queryUrl = buildURL(fmt.Sprintf("/eth/v2/validator/blocks/%d", slot), queryParams)
errJson, err = c.jsonRestHandler.GetRestJsonResponse(ctx, queryUrl, &produceBlockResponseJson)
errJson, err = c.jsonRestHandler.Get(ctx, queryUrl, &produceBlockResponseJson)
if err != nil {
return nil, errors.Wrap(err, "failed to query GET REST endpoint")
}

View File

@@ -5,14 +5,14 @@ import (
"encoding/json"
"errors"
"fmt"
http2 "net/http"
"net/http"
"testing"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"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"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
@@ -26,8 +26,8 @@ func TestGetBeaconBlock_RequestFailed(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
gomock.Any(),
@@ -125,8 +125,8 @@ func TestGetBeaconBlock_Error(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
&validator.ProduceBlockV3Response{},
@@ -162,8 +162,8 @@ func TestGetBeaconBlock_Phase0Valid(t *testing.T) {
graffiti := []byte{3}
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -206,8 +206,8 @@ func TestGetBeaconBlock_AltairValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -250,8 +250,8 @@ func TestGetBeaconBlock_BellatrixValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -296,8 +296,8 @@ func TestGetBeaconBlock_BlindedBellatrixValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -342,8 +342,8 @@ func TestGetBeaconBlock_CapellaValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -388,8 +388,8 @@ func TestGetBeaconBlock_BlindedCapellaValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -434,8 +434,8 @@ func TestGetBeaconBlock_DenebValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -480,8 +480,8 @@ func TestGetBeaconBlock_BlindedDenebValid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
@@ -526,16 +526,16 @@ func TestGetBeaconBlock_FallbackToBlindedBlock(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
).Return(
&apimiddleware.DefaultErrorJson{Code: http2.StatusNotFound},
&http2.DefaultErrorJson{Code: http.StatusNotFound},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/blinded_blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&abstractProduceBlockResponseJson{},
@@ -579,24 +579,24 @@ func TestGetBeaconBlock_FallbackToFullBlock(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v3/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&validator.ProduceBlockV3Response{},
).Return(
&apimiddleware.DefaultErrorJson{Code: http2.StatusNotFound},
&http2.DefaultErrorJson{Code: http.StatusNotFound},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/blinded_blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&abstractProduceBlockResponseJson{},
).Return(
&apimiddleware.DefaultErrorJson{Code: http2.StatusInternalServerError},
&http2.DefaultErrorJson{Code: http.StatusInternalServerError},
errors.New("foo"),
).Times(1)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v2/validator/blocks/%d?graffiti=%s&randao_reveal=%s", slot, hexutil.Encode(graffiti), hexutil.Encode(randaoReveal)),
&abstractProduceBlockResponseJson{},

View File

@@ -36,9 +36,9 @@ func TestIndex_Nominal(t *testing.T) {
ctx := context.Background()
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -85,9 +85,9 @@ func TestIndex_UnexistingValidator(t *testing.T) {
ctx := context.Background()
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -126,9 +126,9 @@ func TestIndex_BadIndexError(t *testing.T) {
ctx := context.Background()
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -174,9 +174,9 @@ func TestIndex_JsonResponseError(t *testing.T) {
ctx := context.Background()
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,

View File

@@ -9,12 +9,12 @@ import (
"github.com/pkg/errors"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
)
type jsonRestHandler interface {
GetRestJsonResponse(ctx context.Context, query string, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error)
PostRestJson(ctx context.Context, apiEndpoint string, headers map[string]string, data *bytes.Buffer, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error)
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)
}
type beaconApiJsonRestHandler struct {
@@ -22,41 +22,46 @@ type beaconApiJsonRestHandler struct {
host string
}
// GetRestJsonResponse sends a GET requests to apiEndpoint and decodes the response body as a JSON object into responseJson.
// If an HTTP error is returned, the body is decoded as a DefaultErrorJson JSON object instead and returned as the first return value.
// TODO: GetRestJsonResponse and PostRestJson have converged to the point of being nearly identical, but with some inconsistencies
// (like responseJson is being checked for nil one but not the other). We should merge them into a single method
// with variadic functional options for headers and data.
func (c beaconApiJsonRestHandler) GetRestJsonResponse(ctx context.Context, apiEndpoint string, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
if responseJson == nil {
return nil, errors.New("responseJson is nil")
// 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) {
if resp == nil {
return nil, errors.New("resp is nil")
}
url := c.host + apiEndpoint
url := c.host + endpoint
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to create request with context")
}
resp, err := c.httpClient.Do(req)
httpResp, err := c.httpClient.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "failed to query REST API %s", url)
return nil, errors.Wrap(err, "failed to perform request with HTTP client")
}
defer func() {
if err := resp.Body.Close(); err != nil {
if err := httpResp.Body.Close(); err != nil {
return
}
}()
return decodeJsonResp(resp, responseJson)
return decodeResp(httpResp, resp)
}
// PostRestJson sends a POST requests to apiEndpoint and decodes the response body as a JSON object into responseJson. If responseJson
// is nil, nothing is decoded. If an HTTP error is returned, the body is decoded as a DefaultErrorJson JSON object instead and returned
// as the first return value.
func (c beaconApiJsonRestHandler) PostRestJson(ctx context.Context, apiEndpoint string, headers map[string]string, data *bytes.Buffer, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
// Post sends a POST 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) Post(
ctx context.Context,
apiEndpoint string,
headers map[string]string,
data *bytes.Buffer,
resp interface{},
) (*http2.DefaultErrorJson, error) {
if data == nil {
return nil, errors.New("POST data is nil")
return nil, errors.New("data is nil")
}
if resp == nil {
return nil, errors.New("resp is nil")
}
url := c.host + apiEndpoint
@@ -70,46 +75,39 @@ func (c beaconApiJsonRestHandler) PostRestJson(ctx context.Context, apiEndpoint
}
req.Header.Set("Content-Type", api.JsonMediaType)
resp, err := c.httpClient.Do(req)
httpResp, err := c.httpClient.Do(req)
if err != nil {
return nil, errors.Wrapf(err, "failed to send POST data to REST endpoint %s", url)
return nil, errors.Wrap(err, "failed to perform request with HTTP client")
}
defer func() {
if err = resp.Body.Close(); err != nil {
if err = httpResp.Body.Close(); err != nil {
return
}
}()
return decodeJsonResp(resp, responseJson)
return decodeResp(httpResp, resp)
}
func decodeJsonResp(resp *http.Response, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
decoder := json.NewDecoder(resp.Body)
if resp.StatusCode != http.StatusOK {
errorJson := &apimiddleware.DefaultErrorJson{}
if err := decoder.Decode(errorJson); err != nil {
if resp.StatusCode == http.StatusNotFound {
errorJson = &apimiddleware.DefaultErrorJson{Code: http.StatusNotFound, Message: "Resource not found"}
} else {
remaining, readErr := io.ReadAll(decoder.Buffered())
if readErr == nil {
log.Debugf("Undecoded value: %s", string(remaining))
}
return nil, errors.Wrapf(err, "failed to decode error json for %s", resp.Request.URL)
}
}
return errorJson, errors.Errorf("error %d: %s", errorJson.Code, errorJson.Message)
func decodeResp(httpResp *http.Response, resp interface{}) (*http2.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)
}
if responseJson != nil {
if err := decoder.Decode(responseJson); err != nil {
remaining, readErr := io.ReadAll(decoder.Buffered())
if readErr == nil {
log.Debugf("Undecoded value: %s", string(remaining))
}
return nil, errors.Wrapf(err, "failed to decode response json for %s", resp.Request.URL)
if httpResp.Header.Get("Content-Type") != api.JsonMediaType {
return &http2.DefaultErrorJson{Code: httpResp.StatusCode, Message: string(body)}, nil
}
decoder := json.NewDecoder(bytes.NewBuffer(body))
if httpResp.StatusCode != http.StatusOK {
errorJson := &http2.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)
}
return errorJson, nil
}
if err = decoder.Decode(resp); err != nil {
return nil, errors.Wrapf(err, "failed to decode response body into json for %s", httpResp.Request.URL)
}
return nil, nil

View File

@@ -10,15 +10,15 @@ import (
"testing"
"time"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"github.com/prysmaticlabs/prysm/v4/api"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
)
func TestGetRestJsonResponse_Valid(t *testing.T) {
func TestGet(t *testing.T) {
ctx := context.Background()
const endpoint = "/example/rest/api/endpoint"
genesisJson := &beacon.GetGenesisResponse{
Data: &beacon.Genesis{
GenesisTime: "123",
@@ -26,18 +26,12 @@ func TestGetRestJsonResponse_Valid(t *testing.T) {
GenesisForkVersion: "0x789",
},
}
ctx := context.Background()
mux := http.NewServeMux()
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
// Make sure the url parameters match
assert.Equal(t, "abc", r.URL.Query().Get("arg1"))
assert.Equal(t, "def", r.URL.Query().Get("arg2"))
marshalledJson, err := json.Marshal(genesisJson)
require.NoError(t, err)
w.Header().Set("Content-Type", api.JsonMediaType)
_, err = w.Write(marshalledJson)
require.NoError(t, err)
})
@@ -48,132 +42,18 @@ func TestGetRestJsonResponse_Valid(t *testing.T) {
httpClient: http.Client{Timeout: time.Second * 5},
host: server.URL,
}
responseJson := &beacon.GetGenesisResponse{}
_, err := jsonRestHandler.GetRestJsonResponse(ctx, endpoint+"?arg1=abc&arg2=def", responseJson)
resp := &beacon.GetGenesisResponse{}
errJson, err := jsonRestHandler.Get(ctx, endpoint+"?arg1=abc&arg2=def", resp)
assert.Equal(t, true, errJson == nil)
assert.NoError(t, err)
assert.DeepEqual(t, genesisJson, responseJson)
assert.DeepEqual(t, genesisJson, resp)
}
func TestGetRestJsonResponse_Error(t *testing.T) {
const endpoint = "/example/rest/api/endpoint"
testCases := []struct {
name string
funcHandler func(w http.ResponseWriter, r *http.Request)
expectedErrorJson *apimiddleware.DefaultErrorJson
expectedErrorMessage string
timeout time.Duration
responseJson interface{}
}{
{
name: "nil response json",
funcHandler: invalidJsonResponseHandler,
expectedErrorMessage: "responseJson is nil",
timeout: time.Second * 5,
responseJson: nil,
},
{
name: "400 error",
funcHandler: httpErrorJsonHandler(http.StatusBadRequest, "Bad request"),
expectedErrorMessage: "error 400: Bad request",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusBadRequest,
Message: "Bad request",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "404 error",
funcHandler: httpErrorJsonHandler(http.StatusNotFound, "Not found"),
expectedErrorMessage: "error 404: Not found",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusNotFound,
Message: "Not found",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "500 error",
funcHandler: httpErrorJsonHandler(http.StatusInternalServerError, "Internal server error"),
expectedErrorMessage: "error 500: Internal server error",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusInternalServerError,
Message: "Internal server error",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "999 error",
funcHandler: httpErrorJsonHandler(999, "Invalid error"),
expectedErrorMessage: "error 999: Invalid error",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: 999,
Message: "Invalid error",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "bad error json formatting",
funcHandler: invalidJsonErrHandler,
expectedErrorMessage: "failed to decode error json",
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "bad response json formatting",
funcHandler: invalidJsonResponseHandler,
expectedErrorMessage: "failed to decode response json",
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "timeout",
funcHandler: httpErrorJsonHandler(http.StatusNotFound, "Not found"),
expectedErrorMessage: "failed to query REST API",
timeout: 1,
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "resource not found",
funcHandler: resourceNotFoundHandler,
expectedErrorMessage: "error 404: Resource not found",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: 404,
Message: "Resource not found",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc(endpoint, testCase.funcHandler)
server := httptest.NewServer(mux)
defer server.Close()
ctx := context.Background()
jsonRestHandler := beaconApiJsonRestHandler{
httpClient: http.Client{Timeout: testCase.timeout},
host: server.URL,
}
errorJson, err := jsonRestHandler.GetRestJsonResponse(ctx, endpoint, testCase.responseJson)
assert.ErrorContains(t, testCase.expectedErrorMessage, err)
assert.DeepEqual(t, testCase.expectedErrorJson, errorJson)
})
}
}
func TestPostRestJson_Valid(t *testing.T) {
func TestPost(t *testing.T) {
ctx := context.Background()
const endpoint = "/example/rest/api/endpoint"
dataBytes := []byte{1, 2, 3, 4, 5}
headers := map[string]string{"foo": "bar"}
genesisJson := &beacon.GetGenesisResponse{
Data: &beacon.Genesis{
@@ -183,269 +63,42 @@ func TestPostRestJson_Valid(t *testing.T) {
},
}
testCases := []struct {
name string
headers map[string]string
data *bytes.Buffer
responseJson interface{}
}{
{
name: "nil headers",
headers: nil,
data: bytes.NewBuffer(dataBytes),
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "empty headers",
headers: map[string]string{},
data: bytes.NewBuffer(dataBytes),
responseJson: &beacon.GetGenesisResponse{},
},
{
name: "nil response json",
headers: map[string]string{"DummyHeaderKey": "DummyHeaderValue"},
data: bytes.NewBuffer(dataBytes),
responseJson: nil,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
// Make sure the request headers have been set
for headerKey, headerValue := range testCase.headers {
assert.Equal(t, headerValue, r.Header.Get(headerKey))
}
// Make sure the data matches
receivedBytes := make([]byte, len(dataBytes))
numBytes, err := r.Body.Read(receivedBytes)
assert.Equal(t, io.EOF, err)
assert.Equal(t, len(dataBytes), numBytes)
assert.DeepEqual(t, dataBytes, receivedBytes)
marshalledJson, err := json.Marshal(genesisJson)
require.NoError(t, err)
_, err = w.Write(marshalledJson)
require.NoError(t, err)
})
server := httptest.NewServer(mux)
defer server.Close()
ctx := context.Background()
jsonRestHandler := beaconApiJsonRestHandler{
httpClient: http.Client{Timeout: time.Second * 5},
host: server.URL,
}
_, err := jsonRestHandler.PostRestJson(
ctx,
endpoint,
testCase.headers,
testCase.data,
testCase.responseJson,
)
assert.NoError(t, err)
if testCase.responseJson != nil {
assert.DeepEqual(t, genesisJson, testCase.responseJson)
}
})
}
}
func TestPostRestJson_Error(t *testing.T) {
const endpoint = "/example/rest/api/endpoint"
testCases := []struct {
name string
funcHandler func(w http.ResponseWriter, r *http.Request)
expectedErrorJson *apimiddleware.DefaultErrorJson
expectedErrorMessage string
timeout time.Duration
responseJson *beacon.GetGenesisResponse
data *bytes.Buffer
}{
{
name: "nil POST data",
funcHandler: httpErrorJsonHandler(http.StatusNotFound, "Not found"),
expectedErrorMessage: "POST data is nil",
timeout: time.Second * 5,
data: nil,
},
{
name: "400 error",
funcHandler: httpErrorJsonHandler(http.StatusBadRequest, "Bad request"),
expectedErrorMessage: "error 400: Bad request",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusBadRequest,
Message: "Bad request",
},
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
data: &bytes.Buffer{},
},
{
name: "404 error",
funcHandler: httpErrorJsonHandler(http.StatusNotFound, "Not found"),
expectedErrorMessage: "error 404: Not found",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusNotFound,
Message: "Not found",
},
timeout: time.Second * 5,
data: &bytes.Buffer{},
},
{
name: "500 error",
funcHandler: httpErrorJsonHandler(http.StatusInternalServerError, "Internal server error"),
expectedErrorMessage: "error 500: Internal server error",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: http.StatusInternalServerError,
Message: "Internal server error",
},
timeout: time.Second * 5,
data: &bytes.Buffer{},
},
{
name: "999 error",
funcHandler: httpErrorJsonHandler(999, "Invalid error"),
expectedErrorMessage: "error 999: Invalid error",
expectedErrorJson: &apimiddleware.DefaultErrorJson{
Code: 999,
Message: "Invalid error",
},
timeout: time.Second * 5,
data: &bytes.Buffer{},
},
{
name: "bad error json formatting",
funcHandler: invalidJsonErrHandler,
expectedErrorMessage: "failed to decode error json",
timeout: time.Second * 5,
data: &bytes.Buffer{},
},
{
name: "bad response json formatting",
funcHandler: invalidJsonResponseHandler,
expectedErrorMessage: "failed to decode response json",
timeout: time.Second * 5,
responseJson: &beacon.GetGenesisResponse{},
data: &bytes.Buffer{},
},
{
name: "timeout",
funcHandler: httpErrorJsonHandler(http.StatusNotFound, "Not found"),
expectedErrorMessage: "failed to send POST data to REST endpoint",
timeout: 1,
data: &bytes.Buffer{},
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc(endpoint, testCase.funcHandler)
server := httptest.NewServer(mux)
defer server.Close()
ctx := context.Background()
jsonRestHandler := beaconApiJsonRestHandler{
httpClient: http.Client{Timeout: testCase.timeout},
host: server.URL,
}
errorJson, err := jsonRestHandler.PostRestJson(
ctx,
endpoint,
map[string]string{},
testCase.data,
testCase.responseJson,
)
assert.ErrorContains(t, testCase.expectedErrorMessage, err)
assert.DeepEqual(t, testCase.expectedErrorJson, errorJson)
})
}
}
func TestJsonHandler_ContextError(t *testing.T) {
const endpoint = "/example/rest/api/endpoint"
mux := http.NewServeMux()
mux.HandleFunc(endpoint, func(writer http.ResponseWriter, request *http.Request) {})
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
// Make sure the request headers have been set
assert.Equal(t, "bar", r.Header.Get("foo"))
assert.Equal(t, api.JsonMediaType, r.Header.Get("Content-Type"))
// Make sure the data matches
receivedBytes := make([]byte, len(dataBytes))
numBytes, err := r.Body.Read(receivedBytes)
assert.Equal(t, io.EOF, err)
assert.Equal(t, len(dataBytes), numBytes)
assert.DeepEqual(t, dataBytes, receivedBytes)
marshalledJson, err := json.Marshal(genesisJson)
require.NoError(t, err)
w.Header().Set("Content-Type", api.JsonMediaType)
_, err = w.Write(marshalledJson)
require.NoError(t, err)
})
server := httptest.NewServer(mux)
defer server.Close()
// Instantiate a cancellable context.
ctx, cancel := context.WithCancel(context.Background())
// Cancel the context which results in "context canceled" error.
cancel()
jsonRestHandler := beaconApiJsonRestHandler{
httpClient: http.Client{},
httpClient: http.Client{Timeout: time.Second * 5},
host: server.URL,
}
_, err := jsonRestHandler.PostRestJson(
resp := &beacon.GetGenesisResponse{}
errJson, err := jsonRestHandler.Post(
ctx,
endpoint,
map[string]string{},
&bytes.Buffer{},
nil,
headers,
bytes.NewBuffer(dataBytes),
resp,
)
assert.ErrorContains(t, context.Canceled.Error(), err)
_, err = jsonRestHandler.GetRestJsonResponse(
ctx,
endpoint,
&beacon.GetGenesisResponse{},
)
assert.ErrorContains(t, context.Canceled.Error(), err)
}
func httpErrorJsonHandler(statusCode int, errorMessage string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, _ *http.Request) {
errorJson := &apimiddleware.DefaultErrorJson{
Code: statusCode,
Message: errorMessage,
}
marshalledError, err := json.Marshal(errorJson)
if err != nil {
panic(err)
}
w.WriteHeader(statusCode)
_, err = w.Write(marshalledError)
if err != nil {
panic(err)
}
}
}
func resourceNotFoundHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
func invalidJsonErrHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, err := w.Write([]byte("foo"))
if err != nil {
panic(err)
}
}
func invalidJsonResponseHandler(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("foo"))
if err != nil {
panic(err)
}
assert.Equal(t, true, errJson == nil)
assert.NoError(t, err)
assert.DeepEqual(t, genesisJson, resp)
}

View File

@@ -12,12 +12,12 @@ go_library(
importpath = "github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api/mock",
visibility = ["//visibility:public"],
deps = [
"//api/gateway/apimiddleware:go_default_library",
"//beacon-chain/rpc/apimiddleware:go_default_library",
"//beacon-chain/rpc/eth/beacon:go_default_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",
"//proto/prysm/v1alpha1:go_default_library",
"@com_github_golang_mock//gomock:go_default_library",
],

View File

@@ -1,5 +1,5 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: validator/client/beacon-api/genesis.go
// Source: github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api (interfaces: GenesisProvider)
// Package mock is a generated GoMock package.
package mock
@@ -9,45 +9,45 @@ import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
apimiddleware "github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
beacon "github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http "github.com/prysmaticlabs/prysm/v4/network/http"
)
// MockgenesisProvider is a mock of genesisProvider interface.
type MockgenesisProvider struct {
// MockGenesisProvider is a mock of GenesisProvider interface.
type MockGenesisProvider struct {
ctrl *gomock.Controller
recorder *MockgenesisProviderMockRecorder
recorder *MockGenesisProviderMockRecorder
}
// MockgenesisProviderMockRecorder is the mock recorder for MockgenesisProvider.
type MockgenesisProviderMockRecorder struct {
mock *MockgenesisProvider
// MockGenesisProviderMockRecorder is the mock recorder for MockGenesisProvider.
type MockGenesisProviderMockRecorder struct {
mock *MockGenesisProvider
}
// NewMockgenesisProvider creates a new mock instance.
func NewMockgenesisProvider(ctrl *gomock.Controller) *MockgenesisProvider {
mock := &MockgenesisProvider{ctrl: ctrl}
mock.recorder = &MockgenesisProviderMockRecorder{mock}
// NewMockGenesisProvider creates a new mock instance.
func NewMockGenesisProvider(ctrl *gomock.Controller) *MockGenesisProvider {
mock := &MockGenesisProvider{ctrl: ctrl}
mock.recorder = &MockGenesisProviderMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockgenesisProvider) EXPECT() *MockgenesisProviderMockRecorder {
func (m *MockGenesisProvider) EXPECT() *MockGenesisProviderMockRecorder {
return m.recorder
}
// GetGenesis mocks base method.
func (m *MockgenesisProvider) GetGenesis(ctx context.Context) (*beacon.Genesis, *apimiddleware.DefaultErrorJson, error) {
func (m *MockGenesisProvider) GetGenesis(arg0 context.Context) (*beacon.Genesis, *http.DefaultErrorJson, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetGenesis", ctx)
ret := m.ctrl.Call(m, "GetGenesis", arg0)
ret0, _ := ret[0].(*beacon.Genesis)
ret1, _ := ret[1].(*apimiddleware.DefaultErrorJson)
ret1, _ := ret[1].(*http.DefaultErrorJson)
ret2, _ := ret[2].(error)
return ret0, ret1, ret2
}
// GetGenesis indicates an expected call of GetGenesis.
func (mr *MockgenesisProviderMockRecorder) GetGenesis(ctx interface{}) *gomock.Call {
func (mr *MockGenesisProviderMockRecorder) GetGenesis(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGenesis", reflect.TypeOf((*MockgenesisProvider)(nil).GetGenesis), ctx)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetGenesis", reflect.TypeOf((*MockGenesisProvider)(nil).GetGenesis), arg0)
}

View File

@@ -1,5 +1,5 @@
// Code generated by MockGen. DO NOT EDIT.
// Source: validator/client/beacon-api/json_rest_handler.go
// Source: github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api (interfaces: JsonRestHandler)
// Package mock is a generated GoMock package.
package mock
@@ -10,58 +10,58 @@ import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
apimiddleware "github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
http "github.com/prysmaticlabs/prysm/v4/network/http"
)
// MockjsonRestHandler is a mock of jsonRestHandler interface.
type MockjsonRestHandler struct {
// MockJsonRestHandler is a mock of JsonRestHandler interface.
type MockJsonRestHandler struct {
ctrl *gomock.Controller
recorder *MockjsonRestHandlerMockRecorder
recorder *MockJsonRestHandlerMockRecorder
}
// MockjsonRestHandlerMockRecorder is the mock recorder for MockjsonRestHandler.
type MockjsonRestHandlerMockRecorder struct {
mock *MockjsonRestHandler
// MockJsonRestHandlerMockRecorder is the mock recorder for MockJsonRestHandler.
type MockJsonRestHandlerMockRecorder struct {
mock *MockJsonRestHandler
}
// NewMockjsonRestHandler creates a new mock instance.
func NewMockjsonRestHandler(ctrl *gomock.Controller) *MockjsonRestHandler {
mock := &MockjsonRestHandler{ctrl: ctrl}
mock.recorder = &MockjsonRestHandlerMockRecorder{mock}
// NewMockJsonRestHandler creates a new mock instance.
func NewMockJsonRestHandler(ctrl *gomock.Controller) *MockJsonRestHandler {
mock := &MockJsonRestHandler{ctrl: ctrl}
mock.recorder = &MockJsonRestHandlerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockjsonRestHandler) EXPECT() *MockjsonRestHandlerMockRecorder {
func (m *MockJsonRestHandler) EXPECT() *MockJsonRestHandlerMockRecorder {
return m.recorder
}
// GetRestJsonResponse mocks base method.
func (m *MockjsonRestHandler) GetRestJsonResponse(ctx context.Context, query string, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
// Get mocks base method.
func (m *MockJsonRestHandler) Get(arg0 context.Context, arg1 string, arg2 interface{}) (*http.DefaultErrorJson, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRestJsonResponse", ctx, query, responseJson)
ret0, _ := ret[0].(*apimiddleware.DefaultErrorJson)
ret := m.ctrl.Call(m, "Get", arg0, arg1, arg2)
ret0, _ := ret[0].(*http.DefaultErrorJson)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetRestJsonResponse indicates an expected call of GetRestJsonResponse.
func (mr *MockjsonRestHandlerMockRecorder) GetRestJsonResponse(ctx, query, responseJson interface{}) *gomock.Call {
// Get indicates an expected call of Get.
func (mr *MockJsonRestHandlerMockRecorder) Get(arg0, arg1, arg2 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRestJsonResponse", reflect.TypeOf((*MockjsonRestHandler)(nil).GetRestJsonResponse), ctx, query, responseJson)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockJsonRestHandler)(nil).Get), arg0, arg1, arg2)
}
// PostRestJson mocks base method.
func (m *MockjsonRestHandler) PostRestJson(ctx context.Context, apiEndpoint string, headers map[string]string, data *bytes.Buffer, responseJson interface{}) (*apimiddleware.DefaultErrorJson, error) {
// Post mocks base method.
func (m *MockJsonRestHandler) Post(arg0 context.Context, arg1 string, arg2 map[string]string, arg3 *bytes.Buffer, arg4 interface{}) (*http.DefaultErrorJson, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "PostRestJson", ctx, apiEndpoint, headers, data, responseJson)
ret0, _ := ret[0].(*apimiddleware.DefaultErrorJson)
ret := m.ctrl.Call(m, "Post", arg0, arg1, arg2, arg3, arg4)
ret0, _ := ret[0].(*http.DefaultErrorJson)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// PostRestJson indicates an expected call of PostRestJson.
func (mr *MockjsonRestHandlerMockRecorder) PostRestJson(ctx, apiEndpoint, headers, data, responseJson interface{}) *gomock.Call {
// Post indicates an expected call of Post.
func (mr *MockJsonRestHandlerMockRecorder) Post(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PostRestJson", reflect.TypeOf((*MockjsonRestHandler)(nil).PostRestJson), ctx, apiEndpoint, headers, data, responseJson)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Post", reflect.TypeOf((*MockJsonRestHandler)(nil).Post), arg0, arg1, arg2, arg3, arg4)
}

View File

@@ -26,8 +26,18 @@ func (c *beaconApiValidatorClient) prepareBeaconProposer(ctx context.Context, re
return errors.Wrap(err, "failed to marshal recipients")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/validator/prepare_beacon_proposer", nil, bytes.NewBuffer(marshalledJsonRecipients), nil); err != nil {
return errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
"/eth/v1/validator/prepare_beacon_proposer",
nil,
bytes.NewBuffer(marshalledJsonRecipients),
nil,
)
if err != nil {
return errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return errJson
}
return nil

View File

@@ -46,8 +46,8 @@ func TestPrepareBeaconProposer_Valid(t *testing.T) {
marshalledJsonRecipients, err := json.Marshal(jsonRecipients)
require.NoError(t, err)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
prepareBeaconProposerTestEndpoint,
nil,
@@ -91,8 +91,8 @@ func TestPrepareBeaconProposer_BadRequest(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
prepareBeaconProposerTestEndpoint,
nil,
@@ -105,6 +105,5 @@ func TestPrepareBeaconProposer_BadRequest(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
err := validatorClient.prepareBeaconProposer(ctx, nil)
assert.ErrorContains(t, "failed to send POST data to REST endpoint", err)
assert.ErrorContains(t, "foo error", err)
}

View File

@@ -19,8 +19,12 @@ func (c beaconApiValidatorClient) proposeAttestation(ctx context.Context, attest
return nil, err
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/beacon/pool/attestations", nil, bytes.NewBuffer(marshalledAttestation), nil); err != nil {
return nil, errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(ctx, "/eth/v1/beacon/pool/attestations", nil, bytes.NewBuffer(marshalledAttestation), nil)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
attestationDataRoot, err := attestation.Data.HashTreeRoot()

View File

@@ -114,7 +114,7 @@ func TestProposeAttestation(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
var marshalledAttestations []byte
if checkNilAttestation(test.attestation) == nil {
@@ -125,7 +125,7 @@ func TestProposeAttestation(t *testing.T) {
ctx := context.Background()
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/pool/attestations",
nil,

View File

@@ -133,7 +133,7 @@ func (c beaconApiValidatorClient) proposeBeaconBlock(ctx context.Context, in *et
}
headers := map[string]string{"Eth-Consensus-Version": consensusVersion}
if httpError, err := c.jsonRestHandler.PostRestJson(ctx, endpoint, headers, bytes.NewBuffer(marshalledSignedBeaconBlockJson), nil); err != nil {
if httpError, err := c.jsonRestHandler.Post(ctx, endpoint, headers, bytes.NewBuffer(marshalledSignedBeaconBlockJson), nil); err != nil {
if httpError != nil && httpError.Code == http.StatusAccepted {
// Error 202 means that the block was successfully broadcasted, but validation failed
return nil, errors.Wrap(err, "block was successfully broadcasted but failed validation")

View File

@@ -19,7 +19,7 @@ import (
func TestProposeBeaconBlock_Altair(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
altairBlock := generateSignedAltairBlock()
@@ -57,7 +57,7 @@ func TestProposeBeaconBlock_Altair(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "altair"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blocks",
headers,

View File

@@ -20,7 +20,7 @@ import (
func TestProposeBeaconBlock_Bellatrix(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
bellatrixBlock := generateSignedBellatrixBlock()
@@ -74,7 +74,7 @@ func TestProposeBeaconBlock_Bellatrix(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "bellatrix"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blocks",
headers,

View File

@@ -21,7 +21,7 @@ import (
func TestProposeBeaconBlock_BlindedBellatrix(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
blindedBellatrixBlock := generateSignedBlindedBellatrixBlock()
@@ -75,7 +75,7 @@ func TestProposeBeaconBlock_BlindedBellatrix(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "bellatrix"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blinded_blocks",
headers,

View File

@@ -21,7 +21,7 @@ import (
func TestProposeBeaconBlock_BlindedCapella(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
blindedCapellaBlock := generateSignedBlindedCapellaBlock()
@@ -77,7 +77,7 @@ func TestProposeBeaconBlock_BlindedCapella(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "capella"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blinded_blocks",
headers,

View File

@@ -17,7 +17,7 @@ import (
func TestProposeBeaconBlock_BlindedDeneb(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
var blockContents shared.SignedBlindedBeaconBlockContentsDeneb
err := json.Unmarshal([]byte(rpctesting.BlindedDenebBlockContents), &blockContents)
@@ -29,7 +29,7 @@ func TestProposeBeaconBlock_BlindedDeneb(t *testing.T) {
require.NoError(t, err)
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "deneb"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/beacon/blinded_blocks",
headers,

View File

@@ -20,7 +20,7 @@ import (
func TestProposeBeaconBlock_Capella(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
capellaBlock := generateSignedCapellaBlock()
@@ -74,7 +74,7 @@ func TestProposeBeaconBlock_Capella(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "capella"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/beacon/blocks",
headers,

View File

@@ -17,7 +17,7 @@ import (
func TestProposeBeaconBlock_Deneb(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
var blockContents shared.SignedBeaconBlockContentsDeneb
err := json.Unmarshal([]byte(rpctesting.DenebBlockContents), &blockContents)
@@ -29,7 +29,7 @@ func TestProposeBeaconBlock_Deneb(t *testing.T) {
require.NoError(t, err)
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "deneb"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/beacon/blocks",
headers,

View File

@@ -19,7 +19,7 @@ import (
func TestProposeBeaconBlock_Phase0(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
phase0Block := generateSignedPhase0Block()
@@ -53,7 +53,7 @@ func TestProposeBeaconBlock_Phase0(t *testing.T) {
// Make sure that what we send in the POST body is the marshalled version of the protobuf block
headers := map[string]string{"Eth-Consensus-Version": "phase0"}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/beacon/blocks",
headers,

View File

@@ -7,7 +7,7 @@ import (
"testing"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
ethpb "github.com/prysmaticlabs/prysm/v4/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api/mock"
@@ -17,12 +17,12 @@ func TestProposeBeaconBlock_Error(t *testing.T) {
testSuites := []struct {
name string
expectedErrorMessage string
expectedHttpError *apimiddleware.DefaultErrorJson
expectedHttpError *http2.DefaultErrorJson
}{
{
name: "error 202",
expectedErrorMessage: "block was successfully broadcasted but failed validation",
expectedHttpError: &apimiddleware.DefaultErrorJson{
expectedHttpError: &http2.DefaultErrorJson{
Code: http.StatusAccepted,
Message: "202 error",
},
@@ -89,10 +89,10 @@ func TestProposeBeaconBlock_Error(t *testing.T) {
defer ctrl.Finish()
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
headers := map[string]string{"Eth-Consensus-Version": testCase.consensusVersion}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
testCase.endpoint,
headers,

View File

@@ -34,8 +34,18 @@ func (c beaconApiValidatorClient) proposeExit(ctx context.Context, signedVolunta
return nil, errors.Wrap(err, "failed to marshal signed voluntary exit")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/beacon/pool/voluntary_exits", nil, bytes.NewBuffer(marshalledSignedVoluntaryExit), nil); err != nil {
return nil, errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
"/eth/v1/beacon/pool/voluntary_exits",
nil,
bytes.NewBuffer(marshalledSignedVoluntaryExit),
nil,
)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
exitRoot, err := signedVoluntaryExit.Exit.HashTreeRoot()

View File

@@ -37,8 +37,8 @@ func TestProposeExit_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
proposeExitTestEndpoint,
nil,
@@ -87,8 +87,8 @@ func TestProposeExit_BadRequest(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
proposeExitTestEndpoint,
nil,
@@ -109,6 +109,5 @@ func TestProposeExit_BadRequest(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
_, err := validatorClient.proposeExit(ctx, protoSignedVoluntaryExit)
assert.ErrorContains(t, "failed to send POST data to REST endpoint", err)
assert.ErrorContains(t, "foo error", err)
}

View File

@@ -29,7 +29,7 @@ func NewPrysmBeaconChainClient(host string, timeout time.Duration, nodeClient if
}
type prysmBeaconChainClient struct {
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
nodeClient iface.NodeClient
}
@@ -52,8 +52,12 @@ func (c prysmBeaconChainClient) GetValidatorCount(ctx context.Context, stateID s
queryUrl := buildURL(fmt.Sprintf("/eth/v1/beacon/states/%s/validator_count", stateID), queryParams)
var validatorCountResponse validator.CountResponse
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, queryUrl, &validatorCountResponse); err != nil {
return nil, errors.Wrap(err, "failed to query GET REST endpoint")
errJson, err := c.jsonRestHandler.Get(ctx, queryUrl, &validatorCountResponse)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if validatorCountResponse.Data == nil {

View File

@@ -29,8 +29,12 @@ func (c *beaconApiValidatorClient) submitValidatorRegistrations(ctx context.Cont
return errors.Wrap(err, "failed to marshal registration")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, endpoint, nil, bytes.NewBuffer(marshalledJsonRegistration), nil); err != nil {
return errors.Wrapf(err, "failed to send POST data to `%s` REST endpoint", endpoint)
errJson, err := c.jsonRestHandler.Post(ctx, endpoint, nil, bytes.NewBuffer(marshalledJsonRegistration), nil)
if err != nil {
return errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return errJson
}
return nil

View File

@@ -66,8 +66,8 @@ func TestRegistration_Valid(t *testing.T) {
marshalledJsonRegistrations, err := json.Marshal(jsonRegistrations)
require.NoError(t, err)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/validator/register_validator",
nil,
@@ -142,8 +142,8 @@ func TestRegistration_BadRequest(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/validator/register_validator",
nil,
@@ -156,6 +156,5 @@ func TestRegistration_BadRequest(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
_, err := validatorClient.SubmitValidatorRegistrations(context.Background(), &ethpb.SignedValidatorRegistrationsV1{})
assert.ErrorContains(t, "failed to send POST data to `/eth/v1/validator/register_validator` REST endpoint", err)
assert.ErrorContains(t, "foo error", err)
}

View File

@@ -18,7 +18,7 @@ type stateValidatorsProvider interface {
}
type beaconApiStateValidatorsProvider struct {
jsonRestHandler jsonRestHandler
jsonRestHandler JsonRestHandler
}
func (c beaconApiStateValidatorsProvider) GetStateValidators(
@@ -96,8 +96,12 @@ func (c beaconApiStateValidatorsProvider) getStateValidatorsHelper(
url := buildURL(endpoint, params)
stateValidatorsJson := &beacon.GetValidatorsResponse{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, url, stateValidatorsJson); err != nil {
return &beacon.GetValidatorsResponse{}, errors.Wrap(err, "failed to get json response")
errJson, err := c.jsonRestHandler.Get(ctx, url, stateValidatorsJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
if stateValidatorsJson.Data == nil {

View File

@@ -28,7 +28,7 @@ func TestGetStateValidators_Nominal(t *testing.T) {
}, "")
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
wanted := []*beacon.ValidatorContainer{
{
@@ -63,7 +63,7 @@ func TestGetStateValidators_Nominal(t *testing.T) {
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -102,11 +102,11 @@ func TestGetStateValidators_GetRestJsonResponseOnError(t *testing.T) {
url := "/eth/v1/beacon/states/head/validators?id=0x8000091c2ae64ee414a54c1cc1fc67dec663408bc636cb86756e0200e41a75c8f86603f104f02c856983d2783116be13"
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
ctx := context.Background()
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,
@@ -123,7 +123,6 @@ func TestGetStateValidators_GetRestJsonResponseOnError(t *testing.T) {
nil,
)
assert.ErrorContains(t, "an error", err)
assert.ErrorContains(t, "failed to get json response", err)
}
func TestGetStateValidators_DataIsNil(t *testing.T) {
@@ -134,9 +133,9 @@ func TestGetStateValidators_DataIsNil(t *testing.T) {
ctx := context.Background()
stateValidatorsResponseJson := beacon.GetValidatorsResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
url,
&stateValidatorsResponseJson,

View File

@@ -54,7 +54,7 @@ func TestValidatorStatus_Nominal(t *testing.T) {
nil,
).Times(1)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
validatorClient := beaconApiValidatorClient{
stateValidatorsProvider: stateValidatorsProvider,
prysmBeaconChainCLient: prysmBeaconChainClient{
@@ -66,7 +66,7 @@ func TestValidatorStatus_Nominal(t *testing.T) {
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,
@@ -170,11 +170,11 @@ func TestMultipleValidatorStatus_Nominal(t *testing.T) {
nil,
).Times(1)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,
@@ -332,11 +332,11 @@ func TestGetValidatorsStatusResponse_Nominal_SomeActiveValidators(t *testing.T)
nil,
).Times(1)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,
@@ -349,7 +349,7 @@ func TestGetValidatorsStatusResponse_Nominal_SomeActiveValidators(t *testing.T)
).Times(1)
var validatorCountResponse validator2.CountResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/states/head/validator_count?",
&validatorCountResponse,
@@ -482,11 +482,11 @@ func TestGetValidatorsStatusResponse_Nominal_NoActiveValidators(t *testing.T) {
nil,
).Times(1)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,
@@ -722,11 +722,11 @@ func TestValidatorStatusResponse_InvalidData(t *testing.T) {
testCase.inputGetStateValidatorsInterface.outputErr,
).Times(1)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,

View File

@@ -73,8 +73,12 @@ func (c beaconApiValidatorClient) getHeadSignedBeaconBlock(ctx context.Context)
// Since we don't know yet what the json looks like, we unmarshal into an abstract structure that has only a version
// and a blob of data
signedBlockResponseJson := abstractSignedBlockResponseJson{}
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v2/beacon/blocks/head", &signedBlockResponseJson); err != nil {
return nil, errors.Wrap(err, "failed to query GET REST endpoint")
errJson, err := c.jsonRestHandler.Get(ctx, "/eth/v2/beacon/blocks/head", &signedBlockResponseJson)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
// Once we know what the consensus version is, we can go ahead and unmarshal into the specific structs unique to each version

View File

@@ -26,8 +26,8 @@ func TestStreamBlocks_UnsupportedConsensusVersion(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
&abstractSignedBlockResponseJson{},
@@ -149,8 +149,8 @@ func TestStreamBlocks_Error(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
gomock.Any(),
&abstractSignedBlockResponseJson{},
@@ -201,7 +201,7 @@ func TestStreamBlocks_Phase0Valid(t *testing.T) {
ctx := context.Background()
signedBlockResponseJson := abstractSignedBlockResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
beaconBlockConverter := mock.NewMockbeaconBlockConverter(ctrl)
// For the first call, return a block that satisfies the verifiedOnly condition. This block should be returned by the first Recv().
@@ -216,7 +216,7 @@ func TestStreamBlocks_Phase0Valid(t *testing.T) {
marshalledSignedBeaconBlockContainer1, err := json.Marshal(signedBeaconBlockContainer1)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -254,7 +254,7 @@ func TestStreamBlocks_Phase0Valid(t *testing.T) {
marshalledSignedBeaconBlockContainer2, err := json.Marshal(signedBeaconBlockContainer2)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -282,7 +282,7 @@ func TestStreamBlocks_Phase0Valid(t *testing.T) {
// The fourth call is only necessary when verifiedOnly == true since the previous block was optimistic
if testCase.verifiedOnly {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -365,7 +365,7 @@ func TestStreamBlocks_AltairValid(t *testing.T) {
ctx := context.Background()
signedBlockResponseJson := abstractSignedBlockResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
beaconBlockConverter := mock.NewMockbeaconBlockConverter(ctrl)
// For the first call, return a block that satisfies the verifiedOnly condition. This block should be returned by the first Recv().
@@ -380,7 +380,7 @@ func TestStreamBlocks_AltairValid(t *testing.T) {
marshalledSignedBeaconBlockContainer1, err := json.Marshal(signedBeaconBlockContainer1)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -418,7 +418,7 @@ func TestStreamBlocks_AltairValid(t *testing.T) {
marshalledSignedBeaconBlockContainer2, err := json.Marshal(signedBeaconBlockContainer2)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -446,7 +446,7 @@ func TestStreamBlocks_AltairValid(t *testing.T) {
// The fourth call is only necessary when verifiedOnly == true since the previous block was optimistic
if testCase.verifiedOnly {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -529,7 +529,7 @@ func TestStreamBlocks_BellatrixValid(t *testing.T) {
ctx := context.Background()
signedBlockResponseJson := abstractSignedBlockResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
beaconBlockConverter := mock.NewMockbeaconBlockConverter(ctrl)
// For the first call, return a block that satisfies the verifiedOnly condition. This block should be returned by the first Recv().
@@ -544,7 +544,7 @@ func TestStreamBlocks_BellatrixValid(t *testing.T) {
marshalledSignedBeaconBlockContainer1, err := json.Marshal(signedBeaconBlockContainer1)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -582,7 +582,7 @@ func TestStreamBlocks_BellatrixValid(t *testing.T) {
marshalledSignedBeaconBlockContainer2, err := json.Marshal(signedBeaconBlockContainer2)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -610,7 +610,7 @@ func TestStreamBlocks_BellatrixValid(t *testing.T) {
// The fourth call is only necessary when verifiedOnly == true since the previous block was optimistic
if testCase.verifiedOnly {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -693,7 +693,7 @@ func TestStreamBlocks_CapellaValid(t *testing.T) {
ctx := context.Background()
signedBlockResponseJson := abstractSignedBlockResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
beaconBlockConverter := mock.NewMockbeaconBlockConverter(ctrl)
// For the first call, return a block that satisfies the verifiedOnly condition. This block should be returned by the first Recv().
@@ -708,7 +708,7 @@ func TestStreamBlocks_CapellaValid(t *testing.T) {
marshalledSignedBeaconBlockContainer1, err := json.Marshal(signedBeaconBlockContainer1)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -746,7 +746,7 @@ func TestStreamBlocks_CapellaValid(t *testing.T) {
marshalledSignedBeaconBlockContainer2, err := json.Marshal(signedBeaconBlockContainer2)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -774,7 +774,7 @@ func TestStreamBlocks_CapellaValid(t *testing.T) {
// The fourth call is only necessary when verifiedOnly == true since the previous block was optimistic
if testCase.verifiedOnly {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -857,7 +857,7 @@ func TestStreamBlocks_DenebValid(t *testing.T) {
ctx := context.Background()
signedBlockResponseJson := abstractSignedBlockResponseJson{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
beaconBlockConverter := mock.NewMockbeaconBlockConverter(ctrl)
// For the first call, return a block that satisfies the verifiedOnly condition. This block should be returned by the first Recv().
@@ -872,7 +872,7 @@ func TestStreamBlocks_DenebValid(t *testing.T) {
marshalledSignedBeaconBlockContainer1, err := json.Marshal(denebBlock)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -902,7 +902,7 @@ func TestStreamBlocks_DenebValid(t *testing.T) {
marshalledSignedBeaconBlockContainer2, err := json.Marshal(denebBlock2)
require.NoError(t, err)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,
@@ -920,7 +920,7 @@ func TestStreamBlocks_DenebValid(t *testing.T) {
// The fourth call is only necessary when verifiedOnly == true since the previous block was optimistic
if testCase.verifiedOnly {
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v2/beacon/blocks/head",
&signedBlockResponseJson,

View File

@@ -91,8 +91,12 @@ func (c *beaconApiValidatorClient) getAggregateAttestation(ctx context.Context,
endpoint := buildURL("/eth/v1/validator/aggregate_attestation", params)
var aggregateAttestationResponse apimiddleware.AggregateAttestationResponseJson
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, endpoint, &aggregateAttestationResponse); err != nil {
return nil, errors.Wrap(err, "failed to get aggregate attestation")
errJson, err := c.jsonRestHandler.Get(ctx, endpoint, &aggregateAttestationResponse)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return &aggregateAttestationResponse, nil

View File

@@ -126,7 +126,7 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
attestationDataCalled: 1,
aggregateAttestationCalled: 1,
aggregateAttestationErr: errors.New("bad request"),
expectedErrorMsg: "failed to get aggregate attestation",
expectedErrorMsg: "bad request",
},
{
name: "validator is not an aggregator",
@@ -155,10 +155,10 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Call node syncing endpoint to check if head is optimistic.
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
syncingEndpoint,
&node.SyncStatusResponse{},
@@ -175,7 +175,7 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
).Times(1)
// Call validators endpoint to get validator index.
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?id=%s", validatorsEndpoint, pubkeyStr),
&beacon.GetValidatorsResponse{},
@@ -200,7 +200,7 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
// Call attester duties endpoint to get attester duties.
validatorIndicesBytes, err := json.Marshal([]string{validatorIndex})
require.NoError(t, err)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", attesterDutiesEndpoint, slots.ToEpoch(slot)),
nil,
@@ -217,7 +217,7 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
).Times(test.attesterDutiesCalled)
// Call attestation data to get attestation data root to query aggregate attestation.
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?committee_index=%d&slot=%d", attestationDataEndpoint, committeeIndex, slot),
&validator.GetAttestationDataResponse{},
@@ -230,7 +230,7 @@ func TestSubmitAggregateSelectionProof(t *testing.T) {
).Times(test.attestationDataCalled)
// Call attestation data to get attestation data root to query aggregate attestation.
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?attestation_data_root=%s&slot=%d", aggregateAttestationEndpoint, hexutil.Encode(attestationDataRootBytes[:]), slot),
&apimiddleware.AggregateAttestationResponseJson{},

View File

@@ -16,8 +16,12 @@ func (c *beaconApiValidatorClient) submitSignedAggregateSelectionProof(ctx conte
return nil, errors.Wrap(err, "failed to marshal SignedAggregateAttestationAndProof")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/validator/aggregate_and_proofs", nil, bytes.NewBuffer(body), nil); err != nil {
return nil, errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(ctx, "/eth/v1/validator/aggregate_and_proofs", nil, bytes.NewBuffer(body), nil)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
attestationDataRoot, err := in.SignedAggregateAndProof.Message.Aggregate.Data.HashTreeRoot()

View File

@@ -26,8 +26,8 @@ func TestSubmitSignedAggregateSelectionProof_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/validator/aggregate_and_proofs",
nil,
@@ -58,8 +58,8 @@ func TestSubmitSignedAggregateSelectionProof_BadRequest(t *testing.T) {
require.NoError(t, err)
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
"/eth/v1/validator/aggregate_and_proofs",
nil,
@@ -74,7 +74,6 @@ func TestSubmitSignedAggregateSelectionProof_BadRequest(t *testing.T) {
_, err = validatorClient.submitSignedAggregateSelectionProof(ctx, &ethpb.SignedAggregateSubmitRequest{
SignedAggregateAndProof: signedAggregateAndProof,
})
assert.ErrorContains(t, "failed to send POST data to REST endpoint", err)
assert.ErrorContains(t, "bad request", err)
}

View File

@@ -47,8 +47,18 @@ func (c beaconApiValidatorClient) submitSignedContributionAndProof(ctx context.C
return errors.Wrap(err, "failed to marshall signed contribution and proof")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/validator/contribution_and_proofs", nil, bytes.NewBuffer(jsonContributionAndProofsBytes), nil); err != nil {
return errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
"/eth/v1/validator/contribution_and_proofs",
nil,
bytes.NewBuffer(jsonContributionAndProofsBytes),
nil,
)
if err != nil {
return errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return errJson
}
return nil

View File

@@ -44,8 +44,8 @@ func TestSubmitSignedContributionAndProof_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
submitSignedContributionAndProofTestEndpoint,
nil,
@@ -108,7 +108,7 @@ func TestSubmitSignedContributionAndProof_Error(t *testing.T) {
},
},
httpRequestExpected: true,
expectedErrorMessage: "failed to send POST data to REST endpoint: foo error",
expectedErrorMessage: "foo error",
},
}
@@ -119,9 +119,9 @@ func TestSubmitSignedContributionAndProof_Error(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
if testCase.httpRequestExpected {
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
submitSignedContributionAndProofTestEndpoint,
gomock.Any(),

View File

@@ -73,8 +73,18 @@ func (c beaconApiValidatorClient) subscribeCommitteeSubnets(ctx context.Context,
return errors.Wrap(err, "failed to marshal committees subscriptions")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, "/eth/v1/validator/beacon_committee_subscriptions", nil, bytes.NewBuffer(committeeSubscriptionsBytes), nil); err != nil {
return errors.Wrap(err, "failed to send POST data to REST endpoint")
errJson, err := c.jsonRestHandler.Post(
ctx,
"/eth/v1/validator/beacon_committee_subscriptions",
nil,
bytes.NewBuffer(committeeSubscriptionsBytes),
nil,
)
if err != nil {
return errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return errJson
}
return nil

View File

@@ -47,8 +47,8 @@ func TestSubscribeCommitteeSubnets_Valid(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
ctx,
subscribeCommitteeSubnetsTestEndpoint,
nil,
@@ -248,7 +248,7 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) {
},
expectGetDutiesQuery: true,
expectSubscribeRestCall: true,
expectedErrorMessage: "failed to send POST data to REST endpoint: foo error",
expectedErrorMessage: "foo error",
},
}
@@ -271,9 +271,9 @@ func TestSubscribeCommitteeSubnets_Error(t *testing.T) {
).Times(1)
}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
if testCase.expectSubscribeRestCall {
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
subscribeCommitteeSubnetsTestEndpoint,
gomock.Any(),

View File

@@ -31,8 +31,12 @@ func (c *beaconApiValidatorClient) submitSyncMessage(ctx context.Context, syncMe
return errors.Wrap(err, "failed to marshal sync committee message")
}
if _, err := c.jsonRestHandler.PostRestJson(ctx, endpoint, nil, bytes.NewBuffer(marshalledJsonSyncCommitteeMessage), nil); err != nil {
return errors.Wrapf(err, "failed to send POST data to `%s` REST endpoint", endpoint)
errJson, err := c.jsonRestHandler.Post(ctx, endpoint, nil, bytes.NewBuffer(marshalledJsonSyncCommitteeMessage), nil)
if err != nil {
return errors.Wrap(err, msgUnexpectedError)
}
if errJson != nil {
return errJson
}
return nil
@@ -41,8 +45,12 @@ func (c *beaconApiValidatorClient) submitSyncMessage(ctx context.Context, syncMe
func (c *beaconApiValidatorClient) getSyncMessageBlockRoot(ctx context.Context) (*ethpb.SyncMessageBlockRootResponse, error) {
// Get head beacon block root.
var resp apimiddleware.BlockRootResponseJson
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, "/eth/v1/beacon/blocks/head/root", &resp); err != nil {
return nil, errors.Wrap(err, "failed to query GET REST endpoint")
errJson, err := c.jsonRestHandler.Get(ctx, "/eth/v1/beacon/blocks/head/root", &resp)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
// An optimistic validator MUST NOT participate in sync committees
@@ -88,8 +96,12 @@ func (c *beaconApiValidatorClient) getSyncCommitteeContribution(
url := buildURL("/eth/v1/validator/sync_committee_contribution", params)
var resp apimiddleware.ProduceSyncCommitteeContributionResponseJson
if _, err := c.jsonRestHandler.GetRestJsonResponse(ctx, url, &resp); err != nil {
return nil, errors.Wrap(err, "failed to query GET REST endpoint")
errJson, err := c.jsonRestHandler.Get(ctx, url, &resp)
if err != nil {
return nil, errors.Wrapf(err, msgUnexpectedError)
}
if errJson != nil {
return nil, errJson
}
return convertSyncContributionJsonToProto(resp.Data)

View File

@@ -46,8 +46,8 @@ func TestSubmitSyncMessage_Valid(t *testing.T) {
marshalledJsonRegistrations, err := json.Marshal([]*shared.SyncCommitteeMessage{jsonSyncCommitteeMessage})
require.NoError(t, err)
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/beacon/pool/sync_committees",
nil,
@@ -76,8 +76,8 @@ func TestSubmitSyncMessage_BadRequest(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Post(
context.Background(),
"/eth/v1/beacon/pool/sync_committees",
nil,
@@ -90,7 +90,6 @@ func TestSubmitSyncMessage_BadRequest(t *testing.T) {
validatorClient := &beaconApiValidatorClient{jsonRestHandler: jsonRestHandler}
_, err := validatorClient.SubmitSyncMessage(context.Background(), &ethpb.SyncCommitteeMessage{})
assert.ErrorContains(t, "failed to send POST data to `/eth/v1/beacon/pool/sync_committees` REST endpoint", err)
assert.ErrorContains(t, "foo error", err)
}
@@ -142,8 +141,8 @@ func TestGetSyncMessageBlockRoot(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/blocks/head/root",
&apimiddleware.BlockRootResponseJson{},
@@ -213,8 +212,8 @@ func TestGetSyncCommitteeContribution(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/blocks/head/root",
&apimiddleware.BlockRootResponseJson{},
@@ -230,7 +229,7 @@ func TestGetSyncCommitteeContribution(t *testing.T) {
nil,
).Times(1)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("/eth/v1/validator/sync_committee_contribution?beacon_block_root=%s&slot=%d&subcommittee_index=%d",
blockRoot, uint64(request.Slot), request.SubnetId),
@@ -316,8 +315,8 @@ func TestGetSyncSubCommitteeIndex(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
fmt.Sprintf("%s?id=%s", validatorsEndpoint, pubkeyStr),
&beacon.GetValidatorsResponse{},
@@ -347,7 +346,7 @@ func TestGetSyncSubCommitteeIndex(t *testing.T) {
syncDutiesCalled = 1
}
jsonRestHandler.EXPECT().PostRestJson(
jsonRestHandler.EXPECT().Post(
ctx,
fmt.Sprintf("%s/%d", syncDutiesEndpoint, slots.ToEpoch(slot)),
nil,

View File

@@ -114,11 +114,11 @@ func TestGetValidatorCount(t *testing.T) {
defer ctrl.Finish()
ctx := context.Background()
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// Expect node version endpoint call.
var nodeVersionResponse node.GetVersionResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/node/version",
&nodeVersionResponse,
@@ -131,7 +131,7 @@ func TestGetValidatorCount(t *testing.T) {
)
var validatorCountResponse validator2.CountResponse
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/states/head/validator_count?status=active",
&validatorCountResponse,

View File

@@ -8,8 +8,8 @@ import (
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/golang/mock/gomock"
"github.com/prysmaticlabs/prysm/v4/api/gateway/apimiddleware"
"github.com/prysmaticlabs/prysm/v4/beacon-chain/rpc/eth/beacon"
http2 "github.com/prysmaticlabs/prysm/v4/network/http"
"github.com/prysmaticlabs/prysm/v4/testing/assert"
"github.com/prysmaticlabs/prysm/v4/testing/require"
"github.com/prysmaticlabs/prysm/v4/validator/client/beacon-api/mock"
@@ -22,8 +22,8 @@ func TestWaitForChainStart_ValidGenesis(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -90,8 +90,8 @@ func TestWaitForChainStart_BadGenesis(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -119,8 +119,8 @@ func TestWaitForChainStart_JsonResponseError(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
@@ -143,15 +143,15 @@ func TestWaitForChainStart_JsonResponseError404(t *testing.T) {
ctx := context.Background()
genesisResponseJson := beacon.GetGenesisResponse{}
jsonRestHandler := mock.NewMockjsonRestHandler(ctrl)
jsonRestHandler := mock.NewMockJsonRestHandler(ctrl)
// First, mock a request that receives a 404 error (which means that the genesis data is not available yet)
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,
).Return(
&apimiddleware.DefaultErrorJson{
&http2.DefaultErrorJson{
Code: http.StatusNotFound,
Message: "404 error",
},
@@ -159,7 +159,7 @@ func TestWaitForChainStart_JsonResponseError404(t *testing.T) {
).Times(1)
// After receiving a 404 error, mock a request that actually has genesis data available
jsonRestHandler.EXPECT().GetRestJsonResponse(
jsonRestHandler.EXPECT().Get(
ctx,
"/eth/v1/beacon/genesis",
&genesisResponseJson,