Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions beacon-chain/rpc/eth/validator/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -1146,18 +1146,18 @@ type ptcDuty struct {
slot primitives.Slot
}

// ptcDuties returns PTC slot assignments for the requested validators in the epoch derived from the state's slot.
// ptcDuties returns PTC slot assignments for the requested validators in the given epoch.
// The state must be from an epoch that allows computing PTC assignments for the target epoch.
// Validators not in any PTC for the epoch will not appear in the result.
func ptcDuties(
ctx context.Context,
st state.ReadOnlyBeaconState,
epoch primitives.Epoch,
validators map[primitives.ValidatorIndex]struct{},
) ([]ptcDuty, error) {
if len(validators) == 0 {
return nil, nil
}

epoch := slots.ToEpoch(st.Slot())
startSlot, err := slots.EpochStart(epoch)
if err != nil {
return nil, err
Expand Down Expand Up @@ -1242,17 +1242,24 @@ func (s *Server) GetPTCDuties(w http.ResponseWriter, r *http.Request) {
requestedValIndices[i] = primitives.ValidatorIndex(valIx)
}

// PTC assignments are not stable for the next epoch, so only allow current epoch.
// Limit how far in the future we can query (current + 1 epoch).
cs := s.TimeFetcher.CurrentSlot()
currentEpoch := slots.ToEpoch(cs)
if requestedEpoch > currentEpoch {
nextEpoch := currentEpoch + 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i guess we can do .Add(1) here too

if requestedEpoch > nextEpoch {
httputil.HandleError(w,
fmt.Sprintf("Request epoch %d can not be greater than current epoch %d", requestedEpoch, currentEpoch),
fmt.Sprintf("Request epoch %d can not be greater than next epoch %d", requestedEpoch, nextEpoch),
http.StatusBadRequest)
return
}

st, err := s.Stater.StateByEpoch(ctx, requestedEpoch)
// For next epoch requests, we use the current epoch's state since PTC
// assignments for next epoch can be computed from current epoch's state.
epochForState := requestedEpoch
if requestedEpoch == nextEpoch {
epochForState = currentEpoch
}
st, err := s.Stater.StateByEpoch(ctx, epochForState)
if err != nil {
shared.WriteStateFetchError(w, err)
return
Expand All @@ -1277,7 +1284,7 @@ func (s *Server) GetPTCDuties(w http.ResponseWriter, r *http.Request) {
}

// Compute PTC duties.
computedDuties, err := ptcDuties(ctx, st, requestedSet)
computedDuties, err := ptcDuties(ctx, st, requestedEpoch, requestedSet)
if err != nil {
httputil.HandleError(w, "Could not compute PTC duties: "+err.Error(), http.StatusInternalServerError)
return
Expand Down
55 changes: 53 additions & 2 deletions beacon-chain/rpc/eth/validator/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3109,7 +3109,7 @@ func TestGetPTCDuties(t *testing.T) {
}

// Test ptcDuties directly.
directDuties, err := ptcDuties(t.Context(), st, requestedSet)
directDuties, err := ptcDuties(t.Context(), st, 0, requestedSet)
require.NoError(t, err)
// Should return some duties (not necessarily all 100, depends on PTC selection).
require.NotEmpty(t, directDuties, "Should return at least some duties")
Expand Down Expand Up @@ -3276,6 +3276,57 @@ func TestGetPTCDuties(t *testing.T) {
assert.StringContains(t, "Invalid validator index", e.Message)
})

t.Run("next epoch returns duties in correct slot range", func(t *testing.T) {
// Request epoch 1 (next epoch) while current slot is 0 (epoch 0).
// The handler should accept this and return duties with slots in [SlotsPerEpoch, 2*SlotsPerEpoch).
var indices []string
for i := range numVals {
indices = append(indices, strconv.FormatUint(i, 10))
}
indicesJSON, err := json.Marshal(indices)
require.NoError(t, err)

request := httptest.NewRequest(http.MethodPost, "http://www.example.com/eth/v1/validator/duties/ptc/{epoch}", bytes.NewReader(indicesJSON))
request.SetPathValue("epoch", "1") // next epoch
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}

s.GetPTCDuties(writer, request)
require.Equal(t, http.StatusOK, writer.Code)
resp := &structs.GetPTCDutiesResponse{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), resp))
require.NotEmpty(t, resp.Data, "expected PTC duties for next epoch")

slotsPerEpoch := params.BeaconConfig().SlotsPerEpoch
for _, duty := range resp.Data {
slotVal, err := strconv.ParseUint(duty.Slot, 10, 64)
require.NoError(t, err)
if slotVal < uint64(slotsPerEpoch) {
t.Errorf("next-epoch duty slot %d is below epoch 1 start %d", slotVal, slotsPerEpoch)
}
if slotVal >= uint64(slotsPerEpoch*2) {
t.Errorf("next-epoch duty slot %d is at or after epoch 1 end %d", slotVal, slotsPerEpoch*2)
}
}
})

t.Run("epoch current+2 is rejected", func(t *testing.T) {
// Epoch 2 should be rejected when current epoch is 0 (next epoch is 1).
var body bytes.Buffer
_, err := body.WriteString("[\"0\"]")
require.NoError(t, err)
request := httptest.NewRequest(http.MethodPost, "http://www.example.com/eth/v1/validator/duties/ptc/{epoch}", &body)
request.SetPathValue("epoch", "2")
writer := httptest.NewRecorder()
writer.Body = &bytes.Buffer{}

s.GetPTCDuties(writer, request)
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.StringContains(t, "can not be greater than next epoch", e.Message)
})

t.Run("epoch too far in future", func(t *testing.T) {
var body bytes.Buffer
_, err := body.WriteString("[\"0\"]")
Expand All @@ -3289,7 +3340,7 @@ func TestGetPTCDuties(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, writer.Code)
e := &httputil.DefaultJsonError{}
require.NoError(t, json.Unmarshal(writer.Body.Bytes(), e))
assert.StringContains(t, "can not be greater than current epoch", e.Message)
assert.StringContains(t, "can not be greater than next epoch", e.Message)
})
}

Expand Down
10 changes: 9 additions & 1 deletion beacon-chain/rpc/prysm/v1alpha1/validator/duties_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,18 +94,22 @@ func (vs *Server) dutiesv2(ctx context.Context, req *ethpb.DutiesRequest) (*ethp
return nil, status.Errorf(core.ErrorReasonToGRPC(rpcErr.Reason), "%v", rpcErr.Err)
}
}
// PTC assignments are not stable for the next epoch, so only compute for current epoch.
currentPTCDuties, rpcErr := vs.CoreService.PTCDuties(ctx, s, req.Epoch, requestIndices)
if rpcErr != nil {
return nil, status.Errorf(core.ErrorReasonToGRPC(rpcErr.Reason), "%v", rpcErr.Err)
}
nextPTCDuties, rpcErr := vs.CoreService.PTCDuties(ctx, s, req.Epoch+1, requestIndices)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I realized we can probably use .Add(1) instead of +1 for this and other ones

if rpcErr != nil {
return nil, status.Errorf(core.ErrorReasonToGRPC(rpcErr.Reason), "%v", rpcErr.Err)
}

// Build index maps for O(1) lookup
currentAttesterMap := buildAttesterMap(currentAttesterDuties)
nextAttesterMap := buildAttesterMap(nextAttesterDuties)
proposerMap := buildProposerMap(proposerDuties)
nextProposerMap := buildProposerMap(nextProposerDuties)
currentPTCAssignments := buildPTCMap(currentPTCDuties)
nextPTCAssignments := buildPTCMap(nextPTCDuties)
validatorAssignments := make([]*ethpb.DutiesV2Response_Duty, 0, len(req.PublicKeys))
nextValidatorAssignments := make([]*ethpb.DutiesV2Response_Duty, 0, len(req.PublicKeys))

Expand Down Expand Up @@ -160,6 +164,10 @@ func (vs *Server) dutiesv2(ctx context.Context, req *ethpb.DutiesRequest) (*ethp
nextDuty.CommitteesAtSlot = ad.CommitteesAtSlot
nextDuty.ValidatorCommitteeIndex = ad.ValidatorCommitteeIndex
}
if ptcSlots, ok := nextPTCAssignments[info.index]; ok {
nextDuty.PtcSlots = ptcSlots
}

// Sync committee flags
if coreTime.HigherEqualThanAltairVersionAndEpoch(s, req.Epoch) {
inSync, err := helpers.IsCurrentPeriodSyncCommittee(s, info.index)
Expand Down
18 changes: 15 additions & 3 deletions beacon-chain/rpc/prysm/v1alpha1/validator/duties_v2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -816,12 +816,24 @@ func TestGetDutiesV2_PTC_OK(t *testing.T) {
res, err := vs.GetDutiesV2(t.Context(), req)
require.NoError(t, err)

// PTC assignments are not stable for the next epoch, so only current epoch should be populated.
// Next-epoch duties span slots [SlotsPerEpoch, 2*SlotsPerEpoch).
nextEpochStart := params.BeaconConfig().SlotsPerEpoch
nextEpochEnd := nextEpochStart * 2
nextPTCCount := 0
for _, d := range res.NextEpochDuties {
if len(d.PtcSlots) > 0 {
t.Error("expected no next-epoch PTC assignments (not stable for next epoch)")
for _, ptcSlot := range d.PtcSlots {
nextPTCCount++
if ptcSlot < nextEpochStart {
t.Errorf("next-epoch PtcSlot %d below epoch start %d", ptcSlot, nextEpochStart)
}
if ptcSlot >= nextEpochEnd {
t.Errorf("next-epoch PtcSlot %d at or after epoch end %d", ptcSlot, nextEpochEnd)
}
}
}
if nextPTCCount == 0 {
t.Error("expected next-epoch PTC assignments with GloasForkEpoch=0")
}

currentCount := 0
for _, d := range res.CurrentEpochDuties {
Expand Down
3 changes: 3 additions & 0 deletions changelog/satushh_ptc-duties-next-epoch-lookahead.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Changed

- Re-add next-epoch lookahead for PTC duties and fix REST handler to use explicit requested epoch
Loading