Skip to content

Commit

Permalink
validatorapi: supporting getValidators with post (#2849)
Browse files Browse the repository at this point in the history
Implemented POST get validators endpoint.

category: feature
ticket: #2840
  • Loading branch information
pinebit authored Feb 5, 2024
1 parent 300b14f commit 2f95ebc
Show file tree
Hide file tree
Showing 2 changed files with 115 additions and 5 deletions.
40 changes: 35 additions & 5 deletions core/validatorapi/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,12 +323,24 @@ func wrapTrace(endpoint string, handler http.HandlerFunc) http.Handler {
return otelhttp.NewHandler(handler, "core/validatorapi."+endpoint)
}

// getValidator returns a handler function for the get validators by pubkey or index endpoint.
// getValidators returns a handler function for the get validators by pubkey or index endpoint.
func getValidators(p eth2client.ValidatorsProvider) handlerFunc {
return func(ctx context.Context, params map[string]string, query url.Values, _ contentType, _ []byte) (any, http.Header, error) {
return func(ctx context.Context, params map[string]string, query url.Values, _ contentType, body []byte) (any, http.Header, error) {
stateID := params["state_id"]

resp, err := getValidatorsByID(ctx, p, stateID, getValidatorIDs(query)...)
// TODO: support 'status' param when go-eth2-client supports it
// https://github.com/ObolNetwork/charon/issues/2846
ids := getValidatorIDs(query)
if len(ids) == 0 && len(body) > 0 {
postIDs, err := getValidatorIDsFromJSON(body)
if err != nil {
return nil, nil, errors.Wrap(err, "getting validator ids from request body")
}

ids = postIDs
}

resp, err := getValidatorsByID(ctx, p, stateID, ids...)
if err != nil {
return nil, nil, err
} else if len(resp) == 0 {
Expand Down Expand Up @@ -1249,10 +1261,15 @@ func (w proxyResponseWriter) WriteHeader(statusCode int) {
w.writeFlusher.WriteHeader(statusCode)
}

// getValidatorIDs returns validator IDs as "id" query parameters (supporting csv values).
// getValidatorIDs returns validator IDs as "id" array query parameters.
func getValidatorIDs(query url.Values) []string {
return getQueryArrayParameter(query, "id")
}

// getQueryArrayParameter returns all array values passed as query parameter (supporting csv values).
func getQueryArrayParameter(query url.Values, param string) []string {
var resp []string
for _, csv := range query["id"] {
for _, csv := range query[param] {
for _, id := range strings.Split(csv, ",") {
resp = append(resp, strings.TrimSpace(id))
}
Expand All @@ -1261,6 +1278,19 @@ func getValidatorIDs(query url.Values) []string {
return resp
}

// getValidatorIDsFromJSON returns validator IDs as "id" field of json payload.
func getValidatorIDsFromJSON(b []byte) ([]string, error) {
requestBody := struct {
IDs []string `json:"ids"`
}{}

if err := json.Unmarshal(b, &requestBody); err != nil {
return nil, errors.Wrap(err, "failed to parse request body")
}

return requestBody.IDs, nil
}

// getValidatorsByID returns the validators with ids being either pubkeys or validator indexes.
func getValidatorsByID(ctx context.Context, p eth2client.ValidatorsProvider, stateID string, ids ...string) ([]v1Validator, error) {
flatten := func(kvs map[eth2p0.ValidatorIndex]*eth2v1.Validator) []v1Validator {
Expand Down
80 changes: 80 additions & 0 deletions core/validatorapi/router_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,86 @@ func TestRawRouter(t *testing.T) {
testRawRouter(t, handler, callback)
})

t.Run("get validators with post", func(t *testing.T) {
simpleValidatorsFunc := func(_ context.Context, opts *eth2api.ValidatorsOpts) (*eth2api.Response[map[eth2p0.ValidatorIndex]*eth2v1.Validator], error) { //nolint:golint,unparam
res := make(map[eth2p0.ValidatorIndex]*eth2v1.Validator)
if len(opts.Indices) == 0 {
opts.Indices = []eth2p0.ValidatorIndex{12, 35}
}

for _, index := range opts.Indices {
res[index] = &eth2v1.Validator{
Index: index,
Status: eth2v1.ValidatorStateActiveOngoing,
Validator: &eth2p0.Validator{
PublicKey: testutil.RandomEth2PubKey(t),
WithdrawalCredentials: []byte("12345678901234567890123456789012"),
},
}
}

return wrapResponse(res), nil
}

assertResults := func(t *testing.T, res *http.Response) {
t.Helper()

resp := struct {
Data []*eth2v1.Validator `json:"data"`
}{}
err := json.NewDecoder(res.Body).Decode(&resp)
require.NoError(t, err)
require.Len(t, resp.Data, 2)
require.EqualValues(t, eth2p0.ValidatorIndex(12), resp.Data[0].Index)
require.EqualValues(t, eth2p0.ValidatorIndex(35), resp.Data[1].Index)
}

t.Run("via query ids", func(t *testing.T) {
handler := testHandler{ValidatorsFunc: simpleValidatorsFunc}

callback := func(ctx context.Context, baseURL string) {
res, err := http.Post(baseURL+"/eth/v1/beacon/states/head/validators?id=12,35", "application/json", bytes.NewReader([]byte{}))
require.NoError(t, err)
assertResults(t, res)
}

testRawRouter(t, handler, callback)
})

t.Run("via post body", func(t *testing.T) {
handler := testHandler{ValidatorsFunc: simpleValidatorsFunc}

callback := func(ctx context.Context, baseURL string) {
b := struct {
IDs []string `json:"ids"`
}{
IDs: []string{"12", "35"},
}

bb, err := json.Marshal(b)
require.NoError(t, err)

res, err := http.Post(baseURL+"/eth/v1/beacon/states/head/validators", "application/json", bytes.NewReader(bb))
require.NoError(t, err)
assertResults(t, res)
}

testRawRouter(t, handler, callback)
})

t.Run("empty parameters", func(t *testing.T) {
handler := testHandler{ValidatorsFunc: simpleValidatorsFunc}

callback := func(ctx context.Context, baseURL string) {
res, err := http.Post(baseURL+"/eth/v1/beacon/states/head/validators", "application/json", bytes.NewReader([]byte{}))
require.NoError(t, err)
assertResults(t, res)
}

testRawRouter(t, handler, callback)
})
})

t.Run("submit bellatrix ssz proposal", func(t *testing.T) {
var done atomic.Bool
coreBlock := testutil.RandomBellatrixCoreVersionedSignedProposal()
Expand Down

0 comments on commit 2f95ebc

Please sign in to comment.