Add in progress handler to committee cache (#9664)

* Add in progress handler for committee cache

* Remove debug print

* Update validators.go

* Fix all the tests

* More tests

* Update committee_disabled.go

* Update committee_disabled.go

* Update testing util

* Update main.go

Co-authored-by: Nishant Das <nishdas93@gmail.com>
This commit is contained in:
terence tsao
2021-09-26 08:27:57 -07:00
committed by GitHub
parent 6e4c2b4b20
commit 376d248c22
95 changed files with 474 additions and 323 deletions

View File

@@ -182,7 +182,7 @@ func (s *Service) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch)
if !s.hasHeadState() {
return []types.ValidatorIndex{}, nil
}
return helpers.ActiveValidatorIndices(s.headState(ctx), epoch)
return helpers.ActiveValidatorIndices(ctx, s.headState(ctx), epoch)
}
// HeadSeed returns the seed from the head view of a given epoch.

View File

@@ -80,7 +80,7 @@ func (s *Service) onAttestation(ctx context.Context, a *ethpb.Attestation) error
}
// Use the target state to verify attesting indices are valid.
committee, err := helpers.BeaconCommitteeFromState(baseState, a.Data.Slot, a.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, baseState, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return err
}

View File

@@ -323,7 +323,7 @@ func (s *Service) handleEpochBoundary(ctx context.Context, postState state.Beaco
if err != nil {
return err
}
if err := helpers.UpdateProposerIndicesInCache(copied); err != nil {
if err := helpers.UpdateProposerIndicesInCache(ctx, copied); err != nil {
return err
}
} else if postState.Slot() >= s.nextEpochBoundarySlot {
@@ -341,7 +341,7 @@ func (s *Service) handleEpochBoundary(ctx context.Context, postState state.Beaco
if err := helpers.UpdateCommitteeCache(postState, core.CurrentEpoch(postState)); err != nil {
return err
}
if err := helpers.UpdateProposerIndicesInCache(postState); err != nil {
if err := helpers.UpdateProposerIndicesInCache(ctx, postState); err != nil {
return err
}
}
@@ -363,7 +363,7 @@ func (s *Service) insertBlockAndAttestationsToForkChoiceStore(ctx context.Contex
}
// Feed in block's attestations to fork choice store.
for _, a := range blk.Body().Attestations() {
committee, err := helpers.BeaconCommitteeFromState(st, a.Data.Slot, a.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, st, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return err
}

View File

@@ -296,7 +296,7 @@ func (s *Service) initializeBeaconChain(
if err := helpers.UpdateCommitteeCache(genesisState, 0 /* genesis epoch */); err != nil {
return nil, err
}
if err := helpers.UpdateProposerIndicesInCache(genesisState); err != nil {
if err := helpers.UpdateProposerIndicesInCache(ctx, genesisState); err != nil {
return nil, err
}

View File

@@ -300,11 +300,11 @@ func (s *ChainService) AttestationPreState(_ context.Context, _ *ethpb.Attestati
}
// HeadValidatorsIndices mocks the same method in the chain service.
func (s *ChainService) HeadValidatorsIndices(_ context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) {
func (s *ChainService) HeadValidatorsIndices(ctx context.Context, epoch types.Epoch) ([]types.ValidatorIndex, error) {
if s.State == nil {
return []types.ValidatorIndex{}, nil
}
return helpers.ActiveValidatorIndices(s.State, epoch)
return helpers.ActiveValidatorIndices(ctx, s.State, epoch)
}
// HeadSeed mocks the same method in the chain service.

View File

@@ -3,8 +3,12 @@
package cache
import (
"context"
"errors"
"fmt"
"math"
"sync"
"time"
lru "github.com/hashicorp/golang-lru"
"github.com/prometheus/client_golang/prometheus"
@@ -13,7 +17,7 @@ import (
lruwrpr "github.com/prysmaticlabs/prysm/cache/lru"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/container/slice"
"github.com/prysmaticlabs/prysm/math"
mathutil "github.com/prysmaticlabs/prysm/math"
)
var (
@@ -37,6 +41,7 @@ var (
type CommitteeCache struct {
CommitteeCache *lru.Cache
lock sync.RWMutex
inProgress map[string]bool
}
// committeeKeyFn takes the seed as the key to retrieve shuffled indices of a committee in a given epoch.
@@ -52,14 +57,16 @@ func committeeKeyFn(obj interface{}) (string, error) {
func NewCommitteesCache() *CommitteeCache {
return &CommitteeCache{
CommitteeCache: lruwrpr.New(int(maxCommitteesCacheSize)),
inProgress: make(map[string]bool),
}
}
// Committee fetches the shuffled indices by slot and committee index. Every list of indices
// represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil.
func (c *CommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
c.lock.RLock()
defer c.lock.RUnlock()
func (c *CommitteeCache) Committee(ctx context.Context, slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
if err := c.checkInProgress(ctx, seed); err != nil {
return nil, err
}
obj, exists := c.CommitteeCache.Get(key(seed))
if exists {
@@ -79,7 +86,7 @@ func (c *CommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.C
committeeCountPerSlot = item.CommitteeCount / uint64(params.BeaconConfig().SlotsPerEpoch)
}
indexOffSet, err := math.Add64(uint64(index), uint64(slot.ModSlot(params.BeaconConfig().SlotsPerEpoch).Mul(committeeCountPerSlot)))
indexOffSet, err := mathutil.Add64(uint64(index), uint64(slot.ModSlot(params.BeaconConfig().SlotsPerEpoch).Mul(committeeCountPerSlot)))
if err != nil {
return nil, err
}
@@ -106,14 +113,16 @@ func (c *CommitteeCache) AddCommitteeShuffledList(committees *Committees) error
}
// ActiveIndices returns the active indices of a given seed stored in cache.
func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, error) {
c.lock.RLock()
defer c.lock.RUnlock()
func (c *CommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]types.ValidatorIndex, error) {
if err := c.checkInProgress(ctx, seed); err != nil {
return nil, err
}
obj, exists := c.CommitteeCache.Get(key(seed))
if exists {
CommitteeCacheHit.Inc()
} else {
fmt.Println("cache miss active indices")
CommitteeCacheMiss.Inc()
return nil, nil
}
@@ -127,9 +136,11 @@ func (c *CommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, e
}
// ActiveIndicesCount returns the active indices count of a given seed stored in cache.
func (c *CommitteeCache) ActiveIndicesCount(seed [32]byte) (int, error) {
c.lock.RLock()
defer c.lock.RUnlock()
func (c *CommitteeCache) ActiveIndicesCount(ctx context.Context, seed [32]byte) (int, error) {
if err := c.checkInProgress(ctx, seed); err != nil {
return 0, err
}
obj, exists := c.CommitteeCache.Get(key(seed))
if exists {
CommitteeCacheHit.Inc()
@@ -152,6 +163,29 @@ func (c *CommitteeCache) HasEntry(seed string) bool {
return ok
}
// MarkInProgress a request so that any other similar requests will block on
// Get until MarkNotInProgress is called.
func (c *CommitteeCache) MarkInProgress(seed [32]byte) error {
c.lock.Lock()
defer c.lock.Unlock()
s := key(seed)
if c.inProgress[s] {
return ErrAlreadyInProgress
}
c.inProgress[s] = true
return nil
}
// MarkNotInProgress will release the lock on a given request. This should be
// called after put.
func (c *CommitteeCache) MarkNotInProgress(seed [32]byte) error {
c.lock.Lock()
defer c.lock.Unlock()
s := key(seed)
delete(c.inProgress, s)
return nil
}
func startEndIndices(c *Committees, index uint64) (uint64, uint64) {
validatorCount := uint64(len(c.ShuffledIndices))
start := slice.SplitOffset(validatorCount, c.CommitteeCount, index)
@@ -166,3 +200,28 @@ func startEndIndices(c *Committees, index uint64) (uint64, uint64) {
func key(seed [32]byte) string {
return string(seed[:])
}
func (c *CommitteeCache) checkInProgress(ctx context.Context, seed [32]byte) error {
delay := minDelay
// Another identical request may be in progress already. Let's wait until
// any in progress request resolves or our timeout is exceeded.
for {
if ctx.Err() != nil {
return ctx.Err()
}
c.lock.RLock()
if !c.inProgress[key(seed)] {
c.lock.RUnlock()
break
}
c.lock.RUnlock()
// This increasing backoff is to decrease the CPU cycles while waiting
// for the in progress boolean to flip to false.
time.Sleep(time.Duration(delay) * time.Nanosecond)
delay *= delayFactor
delay = math.Min(delay, maxDelay)
}
return nil
}

View File

@@ -3,7 +3,11 @@
// This file is used in fuzzer builds to bypass global committee caches.
package cache
import types "github.com/prysmaticlabs/eth2-types"
import (
"context"
types "github.com/prysmaticlabs/eth2-types"
)
// FakeCommitteeCache is a struct with 1 queue for looking up shuffled indices list by seed.
type FakeCommitteeCache struct {
@@ -16,7 +20,7 @@ func NewCommitteesCache() *FakeCommitteeCache {
// Committee fetches the shuffled indices by slot and committee index. Every list of indices
// represent one committee. Returns true if the list exists with slot and committee index. Otherwise returns false, nil.
func (c *FakeCommitteeCache) Committee(slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
func (c *FakeCommitteeCache) Committee(ctx context.Context, slot types.Slot, seed [32]byte, index types.CommitteeIndex) ([]types.ValidatorIndex, error) {
return nil, nil
}
@@ -32,12 +36,12 @@ func (c *FakeCommitteeCache) AddProposerIndicesList(seed [32]byte, indices []typ
}
// ActiveIndices returns the active indices of a given seed stored in cache.
func (c *FakeCommitteeCache) ActiveIndices(seed [32]byte) ([]types.ValidatorIndex, error) {
func (c *FakeCommitteeCache) ActiveIndices(ctx context.Context, seed [32]byte) ([]types.ValidatorIndex, error) {
return nil, nil
}
// ActiveIndicesCount returns the active indices count of a given seed stored in cache.
func (c *FakeCommitteeCache) ActiveIndicesCount(seed [32]byte) (int, error) {
func (c *FakeCommitteeCache) ActiveIndicesCount(ctx context.Context, seed [32]byte) (int, error) {
return 0, nil
}
@@ -55,3 +59,13 @@ func (c *FakeCommitteeCache) ProposerIndices(seed [32]byte) ([]types.ValidatorIn
func (c *FakeCommitteeCache) HasEntry(string) bool {
return false
}
// MarkInProgress is a stub.
func (c *FakeCommitteeCache) MarkInProgress(seed [32]byte) error {
return nil
}
// MarkNotInProgress is a stub.
func (c *FakeCommitteeCache) MarkNotInProgress(seed [32]byte) error {
return nil
}

View File

@@ -1,6 +1,7 @@
package cache
import (
"context"
"testing"
fuzz "github.com/google/gofuzz"
@@ -28,7 +29,7 @@ func TestCommitteeCache_FuzzCommitteesByEpoch(t *testing.T) {
for i := 0; i < 100000; i++ {
fuzzer.Fuzz(c)
require.NoError(t, cache.AddCommitteeShuffledList(c))
_, err := cache.Committee(0, c.Seed, 0)
_, err := cache.Committee(context.Background(), 0, c.Seed, 0)
require.NoError(t, err)
}
@@ -44,7 +45,7 @@ func TestCommitteeCache_FuzzActiveIndices(t *testing.T) {
fuzzer.Fuzz(c)
require.NoError(t, cache.AddCommitteeShuffledList(c))
indices, err := cache.ActiveIndices(c.Seed)
indices, err := cache.ActiveIndices(context.Background(), c.Seed)
require.NoError(t, err)
assert.DeepEqual(t, c.SortedIndices, indices)
}

View File

@@ -1,6 +1,7 @@
package cache
import (
"context"
"math"
"sort"
"strconv"
@@ -41,7 +42,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
slot := params.BeaconConfig().SlotsPerEpoch
committeeIndex := types.CommitteeIndex(1)
indices, err := cache.Committee(slot, item.Seed, committeeIndex)
indices, err := cache.Committee(context.Background(), slot, item.Seed, committeeIndex)
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee not to exist in empty cache")
@@ -49,7 +50,7 @@ func TestCommitteeCache_CommitteesByEpoch(t *testing.T) {
require.NoError(t, cache.AddCommitteeShuffledList(item))
wantedIndex := types.CommitteeIndex(0)
indices, err = cache.Committee(slot, item.Seed, wantedIndex)
indices, err = cache.Committee(context.Background(), slot, item.Seed, wantedIndex)
require.NoError(t, err)
start, end := startEndIndices(item, uint64(wantedIndex))
@@ -60,7 +61,7 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) {
cache := NewCommitteesCache()
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}}
indices, err := cache.ActiveIndices(item.Seed)
indices, err := cache.ActiveIndices(context.Background(), item.Seed)
require.NoError(t, err)
if indices != nil {
t.Error("Expected committee not to exist in empty cache")
@@ -68,7 +69,7 @@ func TestCommitteeCache_ActiveIndices(t *testing.T) {
require.NoError(t, cache.AddCommitteeShuffledList(item))
indices, err = cache.ActiveIndices(item.Seed)
indices, err = cache.ActiveIndices(context.Background(), item.Seed)
require.NoError(t, err)
assert.DeepEqual(t, item.SortedIndices, indices)
}
@@ -77,13 +78,13 @@ func TestCommitteeCache_ActiveCount(t *testing.T) {
cache := NewCommitteesCache()
item := &Committees{Seed: [32]byte{'A'}, SortedIndices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}}
count, err := cache.ActiveIndicesCount(item.Seed)
count, err := cache.ActiveIndicesCount(context.Background(), item.Seed)
require.NoError(t, err)
assert.Equal(t, 0, count, "Expected active count not to exist in empty cache")
require.NoError(t, cache.AddCommitteeShuffledList(item))
count, err = cache.ActiveIndicesCount(item.Seed)
count, err = cache.ActiveIndicesCount(context.Background(), item.Seed)
require.NoError(t, err)
assert.Equal(t, len(item.SortedIndices), count)
}
@@ -127,6 +128,6 @@ func TestCommitteeCacheOutOfRange(t *testing.T) {
assert.NoError(t, err)
_ = cache.CommitteeCache.Add(key, comms)
_, err = cache.Committee(0, seed, math.MaxUint64) // Overflow!
_, err = cache.Committee(context.Background(), 0, seed, math.MaxUint64) // Overflow!
require.NotNil(t, err, "Did not fail as expected")
}

View File

@@ -65,7 +65,7 @@ func ProcessAttestationNoVerifySignature(
if err != nil {
return nil, err
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, beaconState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, err
}
@@ -74,7 +74,7 @@ func ProcessAttestationNoVerifySignature(
return nil, err
}
return SetParticipationAndRewardProposer(beaconState, att.Data.Target.Epoch, indices, participatedFlags, totalBalance)
return SetParticipationAndRewardProposer(ctx, beaconState, att.Data.Target.Epoch, indices, participatedFlags, totalBalance)
}
// SetParticipationAndRewardProposer retrieves and sets the epoch participation bits in state. Based on the epoch participation, it rewards
@@ -99,6 +99,7 @@ func ProcessAttestationNoVerifySignature(
// proposer_reward = Gwei(proposer_reward_numerator // proposer_reward_denominator)
// increase_balance(state, get_beacon_proposer_index(state), proposer_reward)
func SetParticipationAndRewardProposer(
ctx context.Context,
beaconState state.BeaconState,
targetEpoch types.Epoch,
indices []uint64,
@@ -133,7 +134,7 @@ func SetParticipationAndRewardProposer(
}
}
if err := RewardProposer(beaconState, proposerRewardNumerator); err != nil {
if err := RewardProposer(ctx, beaconState, proposerRewardNumerator); err != nil {
return nil, err
}
@@ -196,11 +197,11 @@ func EpochParticipation(beaconState state.BeaconState, indices []uint64, epochPa
// proposer_reward_denominator = (WEIGHT_DENOMINATOR - PROPOSER_WEIGHT) * WEIGHT_DENOMINATOR // PROPOSER_WEIGHT
// proposer_reward = Gwei(proposer_reward_numerator // proposer_reward_denominator)
// increase_balance(state, get_beacon_proposer_index(state), proposer_reward)
func RewardProposer(beaconState state.BeaconState, proposerRewardNumerator uint64) error {
func RewardProposer(ctx context.Context, beaconState state.BeaconState, proposerRewardNumerator uint64) error {
cfg := params.BeaconConfig()
d := (cfg.WeightDenominator - cfg.ProposerWeight) * cfg.WeightDenominator / cfg.ProposerWeight
proposerReward := proposerRewardNumerator / d
i, err := helpers.BeaconProposerIndex(beaconState)
i, err := helpers.BeaconProposerIndex(ctx, beaconState)
if err != nil {
return err
}

View File

@@ -211,7 +211,7 @@ func TestProcessAttestations_OK(t *testing.T) {
cfc.Root = mockRoot[:]
require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cfc))
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -269,7 +269,7 @@ func TestProcessAttestationNoVerify_SourceTargetHead(t *testing.T) {
p, err := beaconState.CurrentEpochParticipation()
require.NoError(t, err)
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
indices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -388,7 +388,6 @@ func TestFuzzProcessAttestationsNoVerify_10000(t *testing.T) {
fuzzer := fuzz.NewWithSeed(0)
state := &ethpb.BeaconStateAltair{}
b := &ethpb.SignedBeaconBlockAltair{Block: &ethpb.BeaconBlockAltair{}}
ctx := context.Background()
for i := 0; i < 10000; i++ {
fuzzer.Fuzz(state)
fuzzer.Fuzz(b)
@@ -399,7 +398,7 @@ func TestFuzzProcessAttestationsNoVerify_10000(t *testing.T) {
require.NoError(t, err)
wsb, err := wrapper.WrappedAltairSignedBeaconBlock(b)
require.NoError(t, err)
r, err := altair.ProcessAttestationsNoVerifySignature(ctx, s, wsb)
r, err := altair.ProcessAttestationsNoVerifySignature(context.Background(), s, wsb)
if err != nil && r != nil {
t.Fatalf("return value should be nil on err. found: %v on error: %v for state: %v and block: %v", r, err, state, b)
}
@@ -480,10 +479,10 @@ func TestSetParticipationAndRewardProposer(t *testing.T) {
b, err := helpers.TotalActiveBalance(beaconState)
require.NoError(t, err)
st, err := altair.SetParticipationAndRewardProposer(beaconState, test.epoch, test.indices, test.participatedFlags, b)
st, err := altair.SetParticipationAndRewardProposer(context.Background(), beaconState, test.epoch, test.indices, test.participatedFlags, b)
require.NoError(t, err)
i, err := helpers.BeaconProposerIndex(st)
i, err := helpers.BeaconProposerIndex(context.Background(), st)
require.NoError(t, err)
b, err = beaconState.BalanceAtIndex(i)
require.NoError(t, err)
@@ -586,8 +585,8 @@ func TestRewardProposer(t *testing.T) {
{rewardNumerator: 1000000000000, want: 34234377253},
}
for _, test := range tests {
require.NoError(t, altair.RewardProposer(beaconState, test.rewardNumerator))
i, err := helpers.BeaconProposerIndex(beaconState)
require.NoError(t, altair.RewardProposer(context.Background(), beaconState, test.rewardNumerator))
i, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
b, err := beaconState.BalanceAtIndex(i)
require.NoError(t, err)

View File

@@ -1,6 +1,7 @@
package altair
import (
"context"
"errors"
types "github.com/prysmaticlabs/eth2-types"
@@ -42,7 +43,7 @@ import (
// increase_balance(state, get_beacon_proposer_index(state), proposer_reward)
// else:
// decrease_balance(state, participant_index, participant_reward)
func ProcessSyncAggregate(s state.BeaconStateAltair, sync *ethpb.SyncAggregate) (state.BeaconStateAltair, error) {
func ProcessSyncAggregate(ctx context.Context, s state.BeaconStateAltair, sync *ethpb.SyncAggregate) (state.BeaconStateAltair, error) {
votedKeys, votedIndices, didntVoteIndices, err := FilterSyncCommitteeVotes(s, sync)
if err != nil {
return nil, err
@@ -52,7 +53,7 @@ func ProcessSyncAggregate(s state.BeaconStateAltair, sync *ethpb.SyncAggregate)
return nil, err
}
return ApplySyncRewardsPenalties(s, votedIndices, didntVoteIndices)
return ApplySyncRewardsPenalties(ctx, s, votedIndices, didntVoteIndices)
}
// FilterSyncCommitteeVotes filters the validator public keys and indices for the ones that voted and didn't vote.
@@ -124,7 +125,7 @@ func VerifySyncCommitteeSig(s state.BeaconStateAltair, syncKeys []bls.PublicKey,
}
// ApplySyncRewardsPenalties applies rewards and penalties for proposer and sync committee participants.
func ApplySyncRewardsPenalties(s state.BeaconStateAltair, votedIndices, didntVoteIndices []types.ValidatorIndex) (state.BeaconStateAltair, error) {
func ApplySyncRewardsPenalties(ctx context.Context, s state.BeaconStateAltair, votedIndices, didntVoteIndices []types.ValidatorIndex) (state.BeaconStateAltair, error) {
activeBalance, err := helpers.TotalActiveBalance(s)
if err != nil {
return nil, err
@@ -143,7 +144,7 @@ func ApplySyncRewardsPenalties(s state.BeaconStateAltair, votedIndices, didntVot
earnedProposerReward += proposerReward
}
// Apply proposer rewards.
proposerIndex, err := helpers.BeaconProposerIndex(s)
proposerIndex, err := helpers.BeaconProposerIndex(ctx, s)
if err != nil {
return nil, err
}

View File

@@ -50,7 +50,7 @@ func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) {
SyncCommitteeSignature: aggregatedSig,
}
beaconState, err = altair.ProcessSyncAggregate(beaconState, syncAggregate)
beaconState, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate)
require.NoError(t, err)
// Use a non-sync committee index to compare profitability.
@@ -71,7 +71,7 @@ func TestProcessSyncCommittee_PerfectParticipation(t *testing.T) {
require.Equal(t, true, balances[indices[0]] > balances[nonSyncIndex])
// Proposer should be more profitable than rest of the sync committee
proposerIndex, err := helpers.BeaconProposerIndex(beaconState)
proposerIndex, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
require.Equal(t, true, balances[proposerIndex] > balances[indices[0]])
@@ -124,7 +124,7 @@ func TestProcessSyncCommittee_MixParticipation_BadSignature(t *testing.T) {
SyncCommitteeSignature: aggregatedSig,
}
_, err = altair.ProcessSyncAggregate(beaconState, syncAggregate)
_, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate)
require.ErrorContains(t, "invalid sync committee signature", err)
}
@@ -161,7 +161,7 @@ func TestProcessSyncCommittee_MixParticipation_GoodSignature(t *testing.T) {
SyncCommitteeSignature: aggregatedSig,
}
_, err = altair.ProcessSyncAggregate(beaconState, syncAggregate)
_, err = altair.ProcessSyncAggregate(context.Background(), beaconState, syncAggregate)
require.NoError(t, err)
}
@@ -239,7 +239,7 @@ func Test_VerifySyncCommitteeSig(t *testing.T) {
func Test_ApplySyncRewardsPenalties(t *testing.T) {
beaconState, _ := util.DeterministicGenesisStateAltair(t, params.BeaconConfig().MaxValidatorsPerCommittee)
beaconState, err := altair.ApplySyncRewardsPenalties(beaconState,
beaconState, err := altair.ApplySyncRewardsPenalties(context.Background(), beaconState,
[]types.ValidatorIndex{0, 1}, // voted
[]types.ValidatorIndex{2, 3}) // didn't vote
require.NoError(t, err)
@@ -248,7 +248,7 @@ func Test_ApplySyncRewardsPenalties(t *testing.T) {
require.Equal(t, balances[0], balances[1])
require.Equal(t, uint64(31999999012), balances[2])
require.Equal(t, balances[2], balances[3])
proposerIndex, err := helpers.BeaconProposerIndex(beaconState)
proposerIndex, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
require.Equal(t, uint64(32000000282), balances[proposerIndex])
}

View File

@@ -98,7 +98,7 @@ func NextSyncCommittee(ctx context.Context, s state.BeaconStateAltair) (*ethpb.S
// return sync_committee_indices
func NextSyncCommitteeIndices(ctx context.Context, s state.BeaconStateAltair) ([]types.ValidatorIndex, error) {
epoch := core.NextEpoch(s)
indices, err := helpers.ActiveValidatorIndices(s, epoch)
indices, err := helpers.ActiveValidatorIndices(ctx, s, epoch)
if err != nil {
return nil, err
}

View File

@@ -63,7 +63,7 @@ func ProcessEpoch(ctx context.Context, state state.BeaconStateAltair) (state.Bea
return nil, errors.Wrap(err, "could not process rewards and penalties")
}
state, err = e.ProcessRegistryUpdates(state)
state, err = e.ProcessRegistryUpdates(ctx, state)
if err != nil {
return nil, errors.Wrap(err, "could not process registry updates")
}

View File

@@ -103,7 +103,7 @@ func UpgradeToAltair(ctx context.Context, state state.BeaconState) (state.Beacon
if err != nil {
return nil, err
}
newState, err = TranslateParticipation(newState, prevEpochAtts)
newState, err = TranslateParticipation(ctx, newState, prevEpochAtts)
if err != nil {
return nil, err
}
@@ -137,7 +137,7 @@ func UpgradeToAltair(ctx context.Context, state state.BeaconState) (state.Beacon
// for index in get_attesting_indices(state, data, attestation.aggregation_bits):
// for flag_index in participation_flag_indices:
// epoch_participation[index] = add_flag(epoch_participation[index], flag_index)
func TranslateParticipation(state *statealtair.BeaconState, atts []*ethpb.PendingAttestation) (*statealtair.BeaconState, error) {
func TranslateParticipation(ctx context.Context, state *statealtair.BeaconState, atts []*ethpb.PendingAttestation) (*statealtair.BeaconState, error) {
epochParticipation, err := state.PreviousEpochParticipation()
if err != nil {
return nil, err
@@ -148,7 +148,7 @@ func TranslateParticipation(state *statealtair.BeaconState, atts []*ethpb.Pendin
if err != nil {
return nil, err
}
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, state, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -19,13 +19,14 @@ import (
)
func TestTranslateParticipation(t *testing.T) {
ctx := context.Background()
s, _ := util.DeterministicGenesisStateAltair(t, 64)
st, ok := s.(*stateAltair.BeaconState)
require.Equal(t, true, ok)
require.NoError(t, st.SetSlot(st.Slot()+params.BeaconConfig().MinAttestationInclusionDelay))
var err error
newState, err := altair.TranslateParticipation(st, nil)
newState, err := altair.TranslateParticipation(ctx, st, nil)
require.NoError(t, err)
participation, err := newState.PreviousEpochParticipation()
require.NoError(t, err)
@@ -50,13 +51,13 @@ func TestTranslateParticipation(t *testing.T) {
})
}
newState, err = altair.TranslateParticipation(newState, pendingAtts)
newState, err = altair.TranslateParticipation(ctx, newState, pendingAtts)
require.NoError(t, err)
participation, err = newState.PreviousEpochParticipation()
require.NoError(t, err)
require.DeepNotSSZEqual(t, make([]byte, 64), participation)
committee, err := helpers.BeaconCommitteeFromState(st, pendingAtts[0].Data.Slot, pendingAtts[0].Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, st, pendingAtts[0].Data.Slot, pendingAtts[0].Data.CommitteeIndex)
require.NoError(t, err)
indices, err := attestation.AttestingIndices(pendingAtts[0].AggregationBits, committee)
require.NoError(t, err)

View File

@@ -96,7 +96,7 @@ func VerifyAttestationNoVerifySignature(
params.BeaconConfig().SlotsPerEpoch,
)
}
activeValidatorCount, err := helpers.ActiveValidatorCount(beaconState, att.Data.Target.Epoch)
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, beaconState, att.Data.Target.Epoch)
if err != nil {
return err
}
@@ -105,12 +105,12 @@ func VerifyAttestationNoVerifySignature(
return fmt.Errorf("committee index %d >= committee count %d", att.Data.CommitteeIndex, c)
}
if err := helpers.VerifyAttestationBitfieldLengths(beaconState, att); err != nil {
if err := helpers.VerifyAttestationBitfieldLengths(ctx, beaconState, att); err != nil {
return errors.Wrap(err, "could not verify attestation bitfields")
}
// Verify attesting indices are correct.
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, beaconState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return err
}
@@ -139,7 +139,7 @@ func ProcessAttestationNoVerifySignature(
currEpoch := core.CurrentEpoch(beaconState)
data := att.Data
s := att.Data.Slot
proposerIndex, err := helpers.BeaconProposerIndex(beaconState)
proposerIndex, err := helpers.BeaconProposerIndex(ctx, beaconState)
if err != nil {
return nil, err
}
@@ -169,7 +169,7 @@ func VerifyAttestationSignature(ctx context.Context, beaconState state.ReadOnlyB
if err := helpers.ValidateNilAttestation(att); err != nil {
return err
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, beaconState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return err
}

View File

@@ -40,7 +40,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) {
require.NoError(t, beaconState.SetCurrentJustifiedCheckpoint(cfc))
require.NoError(t, beaconState.AppendCurrentEpochAttestations(&ethpb.PendingAttestation{}))
committee, err := helpers.BeaconCommitteeFromState(beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
require.NoError(t, err)
attestingIndices1, err := attestation.AttestingIndices(att1.AggregationBits, committee)
require.NoError(t, err)
@@ -62,7 +62,7 @@ func TestProcessAggregatedAttestation_OverlappingBits(t *testing.T) {
AggregationBits: aggBits2,
}
committee, err = helpers.BeaconCommitteeFromState(beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
committee, err = helpers.BeaconCommitteeFromState(context.Background(), beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
require.NoError(t, err)
attestingIndices2, err := attestation.AttestingIndices(att2.AggregationBits, committee)
require.NoError(t, err)
@@ -227,7 +227,7 @@ func TestConvertToIndexed_OK(t *testing.T) {
Signature: att.Signature,
}
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
ia, err := attestation.ConvertToIndexed(context.Background(), att, committee)
require.NoError(t, err)
@@ -405,7 +405,7 @@ func TestVerifyAttestations_HandlesPlannedFork(t *testing.T) {
PreviousVersion: params.BeaconConfig().GenesisForkVersion,
}))
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
comm1, err := helpers.BeaconCommitteeFromState(context.Background(), st, 1 /*slot*/, 0 /*committeeIndex*/)
require.NoError(t, err)
att1 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
@@ -424,7 +424,7 @@ func TestVerifyAttestations_HandlesPlannedFork(t *testing.T) {
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1*params.BeaconConfig().SlotsPerEpoch+1 /*slot*/, 1 /*committeeIndex*/)
comm2, err := helpers.BeaconCommitteeFromState(context.Background(), st, 1*params.BeaconConfig().SlotsPerEpoch+1 /*slot*/, 1 /*committeeIndex*/)
require.NoError(t, err)
att2 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),
@@ -464,7 +464,7 @@ func TestRetrieveAttestationSignatureSet_VerifiesMultipleAttestations(t *testing
require.NoError(t, st.SetSlot(5))
require.NoError(t, st.SetValidators(validators))
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
comm1, err := helpers.BeaconCommitteeFromState(context.Background(), st, 1 /*slot*/, 0 /*committeeIndex*/)
require.NoError(t, err)
att1 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
@@ -483,7 +483,7 @@ func TestRetrieveAttestationSignatureSet_VerifiesMultipleAttestations(t *testing
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 1 /*committeeIndex*/)
comm2, err := helpers.BeaconCommitteeFromState(context.Background(), st, 1 /*slot*/, 1 /*committeeIndex*/)
require.NoError(t, err)
att2 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),
@@ -528,7 +528,7 @@ func TestRetrieveAttestationSignatureSet_AcrossFork(t *testing.T) {
require.NoError(t, st.SetValidators(validators))
require.NoError(t, st.SetFork(&ethpb.Fork{Epoch: 1, CurrentVersion: []byte{0, 1, 2, 3}, PreviousVersion: []byte{0, 1, 1, 1}}))
comm1, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 0 /*committeeIndex*/)
comm1, err := helpers.BeaconCommitteeFromState(ctx, st, 1 /*slot*/, 0 /*committeeIndex*/)
require.NoError(t, err)
att1 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm1))),
@@ -547,7 +547,7 @@ func TestRetrieveAttestationSignatureSet_AcrossFork(t *testing.T) {
}
att1.Signature = bls.AggregateSignatures(sigs).Marshal()
comm2, err := helpers.BeaconCommitteeFromState(st, 1 /*slot*/, 1 /*committeeIndex*/)
comm2, err := helpers.BeaconCommitteeFromState(ctx, st, 1 /*slot*/, 1 /*committeeIndex*/)
require.NoError(t, err)
att2 := util.HydrateAttestation(&ethpb.Attestation{
AggregationBits: bitfield.NewBitlist(uint64(len(comm2))),

View File

@@ -65,7 +65,7 @@ func ProcessAttesterSlashings(
if beaconState.Version() == version.Altair {
slashingQuotient = cfg.MinSlashingPenaltyQuotientAltair
}
beaconState, err = slashFunc(beaconState, types.ValidatorIndex(validatorIndex), slashingQuotient, cfg.ProposerRewardQuotient)
beaconState, err = slashFunc(ctx, beaconState, types.ValidatorIndex(validatorIndex), slashingQuotient, cfg.ProposerRewardQuotient)
if err != nil {
return nil, errors.Wrapf(err, "could not slash validator index %d",
validatorIndex)

View File

@@ -125,7 +125,7 @@ func TestFuzzProcessBlockHeaderNoVerify_10000(t *testing.T) {
fuzzer.Fuzz(block)
s, err := v1.InitializeFromProtoUnsafe(state)
require.NoError(t, err)
_, err = ProcessBlockHeaderNoVerify(s, block.Slot, block.ProposerIndex, block.ParentRoot, []byte{})
_, err = ProcessBlockHeaderNoVerify(context.Background(), s, block.Slot, block.ProposerIndex, block.ParentRoot, []byte{})
_ = err
}
}

View File

@@ -44,7 +44,7 @@ var ValidatorCannotExitYetMsg = "validator has not been active long enough to ex
// # Initiate exit
// initiate_validator_exit(state, voluntary_exit.validator_index)
func ProcessVoluntaryExits(
_ context.Context,
ctx context.Context,
beaconState state.BeaconState,
exits []*ethpb.SignedVoluntaryExit,
) (state.BeaconState, error) {
@@ -59,7 +59,7 @@ func ProcessVoluntaryExits(
if err := VerifyExitAndSignature(val, beaconState.Slot(), beaconState.Fork(), exit, beaconState.GenesisValidatorRoot()); err != nil {
return nil, errors.Wrapf(err, "could not verify exit %d", idx)
}
beaconState, err = v.InitiateValidatorExit(beaconState, exit.Exit.ValidatorIndex)
beaconState, err = v.InitiateValidatorExit(ctx, beaconState, exit.Exit.ValidatorIndex)
if err != nil {
return nil, err
}

View File

@@ -39,7 +39,7 @@ import (
// proposer = state.validators[block.proposer_index]
// assert not proposer.slashed
func ProcessBlockHeader(
_ context.Context,
ctx context.Context,
beaconState state.BeaconState,
block block.SignedBeaconBlock,
) (state.BeaconState, error) {
@@ -50,7 +50,7 @@ func ProcessBlockHeader(
if err != nil {
return nil, err
}
beaconState, err = ProcessBlockHeaderNoVerify(beaconState, block.Block().Slot(), block.Block().ProposerIndex(), block.Block().ParentRoot(), bodyRoot[:])
beaconState, err = ProcessBlockHeaderNoVerify(ctx, beaconState, block.Block().Slot(), block.Block().ProposerIndex(), block.Block().ParentRoot(), bodyRoot[:])
if err != nil {
return nil, err
}
@@ -92,6 +92,7 @@ func ProcessBlockHeader(
// proposer = state.validators[block.proposer_index]
// assert not proposer.slashed
func ProcessBlockHeaderNoVerify(
ctx context.Context,
beaconState state.BeaconState,
slot types.Slot, proposerIndex types.ValidatorIndex,
parentRoot, bodyRoot []byte,
@@ -99,7 +100,7 @@ func ProcessBlockHeaderNoVerify(
if beaconState.Slot() != slot {
return nil, fmt.Errorf("state slot: %d is different than block slot: %d", beaconState.Slot(), slot)
}
idx, err := helpers.BeaconProposerIndex(beaconState)
idx, err := helpers.BeaconProposerIndex(ctx, beaconState)
if err != nil {
return nil, err
}

View File

@@ -50,7 +50,7 @@ func TestProcessBlockHeader_ImproperBlockSlot(t *testing.T) {
currentEpoch := core.CurrentEpoch(state)
priv, err := bls.RandKey()
require.NoError(t, err)
pID, err := helpers.BeaconProposerIndex(state)
pID, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.ProposerIndex = pID
@@ -60,7 +60,7 @@ func TestProcessBlockHeader_ImproperBlockSlot(t *testing.T) {
block.Signature, err = helpers.ComputeDomainAndSign(state, currentEpoch, block.Block, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(state)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()
@@ -82,7 +82,7 @@ func TestProcessBlockHeader_WrongProposerSig(t *testing.T) {
lbhdr, err := beaconState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
block := util.NewBeaconBlock()
@@ -165,7 +165,7 @@ func TestProcessBlockHeader_PreviousBlockRootNotSignedRoot(t *testing.T) {
blockSig, err := helpers.ComputeDomainAndSign(state, currentEpoch, &sszBytes, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
validators[5896].PublicKey = priv.PublicKey().Marshal()
pID, err := helpers.BeaconProposerIndex(state)
pID, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.Slot = 10
@@ -207,7 +207,7 @@ func TestProcessBlockHeader_SlashedProposer(t *testing.T) {
require.NoError(t, err)
validators[12683].PublicKey = priv.PublicKey().Marshal()
pID, err := helpers.BeaconProposerIndex(state)
pID, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.Slot = 10
@@ -246,7 +246,7 @@ func TestProcessBlockHeader_OK(t *testing.T) {
currentEpoch := core.CurrentEpoch(state)
priv, err := bls.RandKey()
require.NoError(t, err)
pID, err := helpers.BeaconProposerIndex(state)
pID, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.ProposerIndex = pID
@@ -258,7 +258,7 @@ func TestProcessBlockHeader_OK(t *testing.T) {
bodyRoot, err := block.Block.Body.HashTreeRoot()
require.NoError(t, err, "Failed to hash block bytes got")
proposerIdx, err := helpers.BeaconProposerIndex(state)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()
@@ -305,7 +305,7 @@ func TestBlockSignatureSet_OK(t *testing.T) {
currentEpoch := core.CurrentEpoch(state)
priv, err := bls.RandKey()
require.NoError(t, err)
pID, err := helpers.BeaconProposerIndex(state)
pID, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.Slot = 10
@@ -314,7 +314,7 @@ func TestBlockSignatureSet_OK(t *testing.T) {
block.Block.ParentRoot = latestBlockSignedRoot[:]
block.Signature, err = helpers.ComputeDomainAndSign(state, currentEpoch, block.Block, params.BeaconConfig().DomainBeaconProposer, priv)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(state)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
validators[proposerIdx].Slashed = false
validators[proposerIdx].PublicKey = priv.PublicKey().Marshal()

View File

@@ -15,7 +15,7 @@ import (
"google.golang.org/protobuf/proto"
)
type slashValidatorFunc func(st state.BeaconState, vid types.ValidatorIndex, penaltyQuotient, proposerRewardQuotient uint64) (state.BeaconState, error)
type slashValidatorFunc func(ctx context.Context, st state.BeaconState, vid types.ValidatorIndex, penaltyQuotient, proposerRewardQuotient uint64) (state.BeaconState, error)
// ProcessProposerSlashings is one of the operations performed
// on each processed beacon block to slash proposers based on
@@ -43,7 +43,7 @@ type slashValidatorFunc func(st state.BeaconState, vid types.ValidatorIndex, pen
//
// slash_validator(state, header_1.proposer_index)
func ProcessProposerSlashings(
_ context.Context,
ctx context.Context,
beaconState state.BeaconState,
slashings []*ethpb.ProposerSlashing,
slashFunc slashValidatorFunc,
@@ -61,7 +61,7 @@ func ProcessProposerSlashings(
if beaconState.Version() == version.Altair {
slashingQuotient = cfg.MinSlashingPenaltyQuotientAltair
}
beaconState, err = slashFunc(beaconState, slashing.Header_1.Header.ProposerIndex, slashingQuotient, cfg.ProposerRewardQuotient)
beaconState, err = slashFunc(ctx, beaconState, slashing.Header_1.Header.ProposerIndex, slashingQuotient, cfg.ProposerRewardQuotient)
if err != nil {
return nil, errors.Wrapf(err, "could not slash proposer index %d", slashing.Header_1.Header.ProposerIndex)
}

View File

@@ -27,7 +27,7 @@ import (
// mix = xor(get_randao_mix(state, epoch), hash(body.randao_reveal))
// state.randao_mixes[epoch % EPOCHS_PER_HISTORICAL_VECTOR] = mix
func ProcessRandao(
_ context.Context,
ctx context.Context,
beaconState state.BeaconState,
b block.SignedBeaconBlock,
) (state.BeaconState, error) {
@@ -35,7 +35,7 @@ func ProcessRandao(
return nil, err
}
body := b.Block().Body()
buf, proposerPub, domain, err := randaoSigningData(beaconState)
buf, proposerPub, domain, err := randaoSigningData(ctx, beaconState)
if err != nil {
return nil, err
}

View File

@@ -20,7 +20,7 @@ import (
func TestProcessRandao_IncorrectProposerFailsVerification(t *testing.T) {
beaconState, privKeys := util.DeterministicGenesisState(t, 100)
// We fetch the proposer's index as that is whom the RANDAO will be verified against.
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
epoch := types.Epoch(0)
buf := make([]byte, 32)
@@ -81,7 +81,7 @@ func TestRandaoSignatureSet_OK(t *testing.T) {
},
}
set, err := blocks.RandaoSignatureSet(beaconState, block.Body.RandaoReveal)
set, err := blocks.RandaoSignatureSet(context.Background(), beaconState, block.Body.RandaoReveal)
require.NoError(t, err)
verified, err := set.Verify()
require.NoError(t, err)

View File

@@ -120,10 +120,12 @@ func BlockSignatureSet(beaconState state.ReadOnlyBeaconState,
// RandaoSignatureSet retrieves the relevant randao specific signature set object
// from a block and its corresponding state.
func RandaoSignatureSet(beaconState state.ReadOnlyBeaconState,
func RandaoSignatureSet(
ctx context.Context,
beaconState state.ReadOnlyBeaconState,
reveal []byte,
) (*bls.SignatureSet, error) {
buf, proposerPub, domain, err := randaoSigningData(beaconState)
buf, proposerPub, domain, err := randaoSigningData(ctx, beaconState)
if err != nil {
return nil, err
}
@@ -135,8 +137,8 @@ func RandaoSignatureSet(beaconState state.ReadOnlyBeaconState,
}
// retrieves the randao related signing data from the state.
func randaoSigningData(beaconState state.ReadOnlyBeaconState) ([]byte, []byte, []byte, error) {
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
func randaoSigningData(ctx context.Context, beaconState state.ReadOnlyBeaconState) ([]byte, []byte, []byte, error) {
proposerIdx, err := helpers.BeaconProposerIndex(ctx, beaconState)
if err != nil {
return nil, nil, nil, errors.Wrap(err, "could not get beacon proposer index")
}
@@ -169,7 +171,7 @@ func createAttestationSignatureSet(
msgs := make([][32]byte, len(atts))
for i, a := range atts {
sigs[i] = a.Signature
c, err := helpers.BeaconCommitteeFromState(beaconState, a.Data.Slot, a.Data.CommitteeIndex)
c, err := helpers.BeaconCommitteeFromState(ctx, beaconState, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -5,6 +5,7 @@
package epoch
import (
"context"
"fmt"
"sort"
@@ -55,8 +56,8 @@ func (s sortableIndices) Less(i, j int) bool {
// Note: ``get_total_balance`` returns ``EFFECTIVE_BALANCE_INCREMENT`` Gwei minimum to avoid divisions by zero.
// """
// return get_total_balance(state, get_unslashed_attesting_indices(state, attestations))
func AttestingBalance(state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) (uint64, error) {
indices, err := UnslashedAttestingIndices(state, atts)
func AttestingBalance(ctx context.Context, state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) (uint64, error) {
indices, err := UnslashedAttestingIndices(ctx, state, atts)
if err != nil {
return 0, errors.Wrap(err, "could not get attesting indices")
}
@@ -86,7 +87,7 @@ func AttestingBalance(state state.ReadOnlyBeaconState, atts []*ethpb.PendingAtte
// for index in activation_queue[:get_validator_churn_limit(state)]:
// validator = state.validators[index]
// validator.activation_epoch = compute_activation_exit_epoch(get_current_epoch(state))
func ProcessRegistryUpdates(state state.BeaconState) (state.BeaconState, error) {
func ProcessRegistryUpdates(ctx context.Context, state state.BeaconState) (state.BeaconState, error) {
currentEpoch := core.CurrentEpoch(state)
vals := state.Validators()
var err error
@@ -105,7 +106,7 @@ func ProcessRegistryUpdates(state state.BeaconState) (state.BeaconState, error)
isActive := helpers.IsActiveValidator(validator, currentEpoch)
belowEjectionBalance := validator.EffectiveBalance <= ejectionBal
if isActive && belowEjectionBalance {
state, err = validators.InitiateValidatorExit(state, types.ValidatorIndex(idx))
state, err = validators.InitiateValidatorExit(ctx, state, types.ValidatorIndex(idx))
if err != nil {
return nil, errors.Wrapf(err, "could not initiate exit for validator %d", idx)
}
@@ -124,7 +125,7 @@ func ProcessRegistryUpdates(state state.BeaconState) (state.BeaconState, error)
// Only activate just enough validators according to the activation churn limit.
limit := uint64(len(activationQ))
activeValidatorCount, err := helpers.ActiveValidatorCount(state, currentEpoch)
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, state, currentEpoch)
if err != nil {
return nil, errors.Wrap(err, "could not get active validator count")
}
@@ -460,12 +461,12 @@ func ProcessFinalUpdates(state state.BeaconState) (state.BeaconState, error) {
// for a in attestations:
// output = output.union(get_attesting_indices(state, a.data, a.aggregation_bits))
// return set(filter(lambda index: not state.validators[index].slashed, output))
func UnslashedAttestingIndices(state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) ([]types.ValidatorIndex, error) {
func UnslashedAttestingIndices(ctx context.Context, state state.ReadOnlyBeaconState, atts []*ethpb.PendingAttestation) ([]types.ValidatorIndex, error) {
var setIndices []types.ValidatorIndex
seen := make(map[uint64]bool)
for _, att := range atts {
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, state, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -1,6 +1,7 @@
package epoch_test
import (
"context"
"fmt"
"testing"
@@ -46,7 +47,7 @@ func TestUnslashedAttestingIndices_CanSortAndFilter(t *testing.T) {
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
indices, err := epoch.UnslashedAttestingIndices(beaconState, atts)
indices, err := epoch.UnslashedAttestingIndices(context.Background(), beaconState, atts)
require.NoError(t, err)
for i := 0; i < len(indices)-1; i++ {
if indices[i] >= indices[i+1] {
@@ -59,7 +60,7 @@ func TestUnslashedAttestingIndices_CanSortAndFilter(t *testing.T) {
validators = beaconState.Validators()
validators[slashedValidator].Slashed = true
require.NoError(t, beaconState.SetValidators(validators))
indices, err = epoch.UnslashedAttestingIndices(beaconState, atts)
indices, err = epoch.UnslashedAttestingIndices(context.Background(), beaconState, atts)
require.NoError(t, err)
for i := 0; i < len(indices); i++ {
assert.NotEqual(t, slashedValidator, indices[i], "Slashed validator %d is not filtered", slashedValidator)
@@ -92,7 +93,7 @@ func TestUnslashedAttestingIndices_DuplicatedAttestations(t *testing.T) {
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
indices, err := epoch.UnslashedAttestingIndices(beaconState, atts)
indices, err := epoch.UnslashedAttestingIndices(context.Background(), beaconState, atts)
require.NoError(t, err)
for i := 0; i < len(indices)-1; i++ {
@@ -138,7 +139,7 @@ func TestAttestingBalance_CorrectBalance(t *testing.T) {
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
balance, err := epoch.AttestingBalance(beaconState, atts)
balance, err := epoch.AttestingBalance(context.Background(), beaconState, atts)
require.NoError(t, err)
wanted := 256 * params.BeaconConfig().MaxEffectiveBalance
assert.Equal(t, wanted, balance)
@@ -292,7 +293,7 @@ func TestProcessRegistryUpdates_NoRotation(t *testing.T) {
}
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := epoch.ProcessRegistryUpdates(beaconState)
newState, err := epoch.ProcessRegistryUpdates(context.Background(), beaconState)
require.NoError(t, err)
for i, validator := range newState.Validators() {
assert.Equal(t, params.BeaconConfig().MaxSeedLookahead, validator.ExitEpoch, "Could not update registry %d", i)
@@ -316,7 +317,7 @@ func TestProcessRegistryUpdates_EligibleToActivate(t *testing.T) {
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
currentEpoch := core.CurrentEpoch(beaconState)
newState, err := epoch.ProcessRegistryUpdates(beaconState)
newState, err := epoch.ProcessRegistryUpdates(context.Background(), beaconState)
require.NoError(t, err)
for i, validator := range newState.Validators() {
assert.Equal(t, currentEpoch+1, validator.ActivationEligibilityEpoch, "Could not update registry %d, unexpected activation eligibility epoch", i)
@@ -344,7 +345,7 @@ func TestProcessRegistryUpdates_ActivationCompletes(t *testing.T) {
}
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := epoch.ProcessRegistryUpdates(beaconState)
newState, err := epoch.ProcessRegistryUpdates(context.Background(), beaconState)
require.NoError(t, err)
for i, validator := range newState.Validators() {
assert.Equal(t, params.BeaconConfig().MaxSeedLookahead, validator.ExitEpoch, "Could not update registry %d, unexpected exit slot", i)
@@ -368,7 +369,7 @@ func TestProcessRegistryUpdates_ValidatorsEjected(t *testing.T) {
}
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := epoch.ProcessRegistryUpdates(beaconState)
newState, err := epoch.ProcessRegistryUpdates(context.Background(), beaconState)
require.NoError(t, err)
for i, validator := range newState.Validators() {
assert.Equal(t, params.BeaconConfig().MaxSeedLookahead+1, validator.ExitEpoch, "Could not update registry %d, unexpected exit slot", i)
@@ -393,7 +394,7 @@ func TestProcessRegistryUpdates_CanExits(t *testing.T) {
}
beaconState, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := epoch.ProcessRegistryUpdates(beaconState)
newState, err := epoch.ProcessRegistryUpdates(context.Background(), beaconState)
require.NoError(t, err)
for i, validator := range newState.Validators() {
assert.Equal(t, exitEpoch, validator.ExitEpoch, "Could not update registry %d, unexpected exit slot", i)

View File

@@ -53,7 +53,7 @@ func ProcessAttestations(
return nil, nil, errors.Wrap(err, "could not check validator attested previous epoch")
}
committee, err := helpers.BeaconCommitteeFromState(state, a.Data.Slot, a.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, state, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return nil, nil, err
}

View File

@@ -181,7 +181,7 @@ func TestProcessAttestations(t *testing.T) {
pVals, _, err = precompute.ProcessAttestations(context.Background(), beaconState, pVals, &precompute.Balance{})
require.NoError(t, err)
committee, err := helpers.BeaconCommitteeFromState(beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att1.Data.Slot, att1.Data.CommitteeIndex)
require.NoError(t, err)
indices, err := attestation.AttestingIndices(att1.AggregationBits, committee)
require.NoError(t, err)
@@ -190,7 +190,7 @@ func TestProcessAttestations(t *testing.T) {
t.Error("Not a prev epoch attester")
}
}
committee, err = helpers.BeaconCommitteeFromState(beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
committee, err = helpers.BeaconCommitteeFromState(context.Background(), beaconState, att2.Data.Slot, att2.Data.CommitteeIndex)
require.NoError(t, err)
indices, err = attestation.AttestingIndices(att2.AggregationBits, committee)
require.NoError(t, err)

View File

@@ -100,7 +100,7 @@ func TestAttestationDeltaPrecompute(t *testing.T) {
bp.PrevEpochHeadAttested = bp.PrevEpochHeadAttested * 2 / 3
rewards, penalties, err := AttestationsDelta(beaconState, bp, vp)
require.NoError(t, err)
attestedBalance, err := epoch.AttestingBalance(beaconState, atts)
attestedBalance, err := epoch.AttestingBalance(context.Background(), beaconState, atts)
require.NoError(t, err)
totalBalance, err := helpers.TotalActiveBalance(beaconState)
require.NoError(t, err)

View File

@@ -51,6 +51,8 @@ go_library(
"//time:go_default_library",
"@com_github_ferranbt_fastssz//:go_default_library",
"@com_github_pkg_errors//:go_default_library",
"@com_github_prometheus_client_golang//prometheus:go_default_library",
"@com_github_prometheus_client_golang//prometheus/promauto:go_default_library",
"@com_github_prysmaticlabs_eth2_types//:go_default_library",
"@com_github_prysmaticlabs_go_bitfield//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",

View File

@@ -1,6 +1,7 @@
package helpers_test
import (
"context"
"strconv"
"testing"
"time"
@@ -22,7 +23,7 @@ import (
func TestAttestation_IsAggregator(t *testing.T) {
t.Run("aggregator", func(t *testing.T) {
beaconState, privKeys := util.DeterministicGenesisState(t, 100)
committee, err := helpers.BeaconCommitteeFromState(beaconState, 0, 0)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, 0, 0)
require.NoError(t, err)
sig := privKeys[0].Sign([]byte{'A'})
agg, err := helpers.IsAggregator(uint64(len(committee)), sig.Marshal())
@@ -35,7 +36,7 @@ func TestAttestation_IsAggregator(t *testing.T) {
defer params.UseMainnetConfig()
beaconState, privKeys := util.DeterministicGenesisState(t, 2048)
committee, err := helpers.BeaconCommitteeFromState(beaconState, 0, 0)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, 0, 0)
require.NoError(t, err)
sig := privKeys[0].Sign([]byte{'A'})
agg, err := helpers.IsAggregator(uint64(len(committee)), sig.Marshal())
@@ -117,7 +118,7 @@ func TestAttestation_ComputeSubnetForAttestation(t *testing.T) {
},
Signature: []byte{'B'},
}
valCount, err := helpers.ActiveValidatorCount(state, core.SlotToEpoch(att.Data.Slot))
valCount, err := helpers.ActiveValidatorCount(context.Background(), state, core.SlotToEpoch(att.Data.Slot))
require.NoError(t, err)
sub := helpers.ComputeSubnetForAttestation(valCount, att)
assert.Equal(t, uint64(6), sub, "Did not get correct subnet for attestation")

View File

@@ -4,6 +4,7 @@ package helpers
import (
"bytes"
"context"
"fmt"
"sort"
@@ -71,14 +72,14 @@ func SlotCommitteeCount(activeValidatorCount uint64) uint64 {
// index=(slot % SLOTS_PER_EPOCH) * committees_per_slot + index,
// count=committees_per_slot * SLOTS_PER_EPOCH,
// )
func BeaconCommitteeFromState(state state.ReadOnlyBeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) {
func BeaconCommitteeFromState(ctx context.Context, state state.ReadOnlyBeaconState, slot types.Slot, committeeIndex types.CommitteeIndex) ([]types.ValidatorIndex, error) {
epoch := core.SlotToEpoch(slot)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, errors.Wrap(err, "could not get seed")
}
committee, err := committeeCache.Committee(slot, seed, committeeIndex)
committee, err := committeeCache.Committee(ctx, slot, seed, committeeIndex)
if err != nil {
return nil, errors.Wrap(err, "could not interface with committee cache")
}
@@ -86,12 +87,12 @@ func BeaconCommitteeFromState(state state.ReadOnlyBeaconState, slot types.Slot,
return committee, nil
}
activeIndices, err := ActiveValidatorIndices(state, epoch)
activeIndices, err := ActiveValidatorIndices(ctx, state, epoch)
if err != nil {
return nil, errors.Wrap(err, "could not get active indices")
}
return BeaconCommittee(activeIndices, seed, slot, committeeIndex)
return BeaconCommittee(ctx, activeIndices, seed, slot, committeeIndex)
}
// BeaconCommittee returns the beacon committee of a given slot and committee index. The
@@ -112,12 +113,13 @@ func BeaconCommitteeFromState(state state.ReadOnlyBeaconState, slot types.Slot,
// count=committees_per_slot * SLOTS_PER_EPOCH,
// )
func BeaconCommittee(
ctx context.Context,
validatorIndices []types.ValidatorIndex,
seed [32]byte,
slot types.Slot,
committeeIndex types.CommitteeIndex,
) ([]types.ValidatorIndex, error) {
committee, err := committeeCache.Committee(slot, seed, committeeIndex)
committee, err := committeeCache.Committee(ctx, slot, seed, committeeIndex)
if err != nil {
return nil, errors.Wrap(err, "could not interface with committee cache")
}
@@ -151,6 +153,7 @@ type CommitteeAssignmentContainer struct {
// 3. Determine the attesting slot for each committee.
// 4. Construct a map of validator indices pointing to the respective committees.
func CommitteeAssignments(
ctx context.Context,
state state.BeaconState,
epoch types.Epoch,
) (map[types.ValidatorIndex]*CommitteeAssignmentContainer, map[types.ValidatorIndex][]types.Slot, error) {
@@ -181,14 +184,14 @@ func CommitteeAssignments(
if err := state.SetSlot(slot); err != nil {
return nil, nil, err
}
i, err := BeaconProposerIndex(state)
i, err := BeaconProposerIndex(ctx, state)
if err != nil {
return nil, nil, errors.Wrapf(err, "could not check proposer at slot %d", state.Slot())
}
proposerIndexToSlots[i] = append(proposerIndexToSlots[i], slot)
}
activeValidatorIndices, err := ActiveValidatorIndices(state, epoch)
activeValidatorIndices, err := ActiveValidatorIndices(ctx, state, epoch)
if err != nil {
return nil, nil, err
}
@@ -202,7 +205,7 @@ func CommitteeAssignments(
// Compute committees.
for j := uint64(0); j < numCommitteesPerSlot; j++ {
slot := startSlot + i
committee, err := BeaconCommitteeFromState(state, slot, types.CommitteeIndex(j) /*committee index*/)
committee, err := BeaconCommitteeFromState(ctx, state, slot, types.CommitteeIndex(j) /*committee index*/)
if err != nil {
return nil, nil, err
}
@@ -234,8 +237,8 @@ func VerifyBitfieldLength(bf bitfield.Bitfield, committeeSize uint64) error {
// VerifyAttestationBitfieldLengths verifies that an attestations aggregation bitfields is
// a valid length matching the size of the committee.
func VerifyAttestationBitfieldLengths(state state.ReadOnlyBeaconState, att *ethpb.Attestation) error {
committee, err := BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
func VerifyAttestationBitfieldLengths(ctx context.Context, state state.ReadOnlyBeaconState, att *ethpb.Attestation) error {
committee, err := BeaconCommitteeFromState(ctx, state, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return errors.Wrap(err, "could not retrieve beacon committees")
}
@@ -280,7 +283,6 @@ func UpdateCommitteeCache(state state.ReadOnlyBeaconState, epoch types.Epoch) er
if err != nil {
return err
}
if committeeCache.HasEntry(string(seed[:])) {
return nil
}
@@ -315,7 +317,7 @@ func UpdateCommitteeCache(state state.ReadOnlyBeaconState, epoch types.Epoch) er
}
// UpdateProposerIndicesInCache updates proposer indices entry of the committee cache.
func UpdateProposerIndicesInCache(state state.ReadOnlyBeaconState) error {
func UpdateProposerIndicesInCache(ctx context.Context, state state.ReadOnlyBeaconState) error {
// The cache uses the state root at the (current epoch - 2)'s slot as key. (e.g. for epoch 2, the key is root at slot 31)
// Which is the reason why we skip genesis epoch.
if core.CurrentEpoch(state) <= params.BeaconConfig().GenesisEpoch+params.BeaconConfig().MinSeedLookahead {
@@ -348,7 +350,7 @@ func UpdateProposerIndicesInCache(state state.ReadOnlyBeaconState) error {
return nil
}
indices, err := ActiveValidatorIndices(state, core.CurrentEpoch(state))
indices, err := ActiveValidatorIndices(ctx, state, core.CurrentEpoch(state))
if err != nil {
return err
}

View File

@@ -1,6 +1,7 @@
package helpers
import (
"context"
"fmt"
"strconv"
"testing"
@@ -44,7 +45,7 @@ func TestComputeCommittee_WithoutCache(t *testing.T) {
require.NoError(t, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(t, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
@@ -94,7 +95,7 @@ func TestCommitteeAssignments_CannotRetrieveFutureEpoch(t *testing.T) {
Slot: 0, // Epoch 0.
})
require.NoError(t, err)
_, _, err = CommitteeAssignments(state, epoch+1)
_, _, err = CommitteeAssignments(context.Background(), state, epoch+1)
assert.ErrorContains(t, "can't be greater than next epoch", err)
}
@@ -117,7 +118,7 @@ func TestCommitteeAssignments_NoProposerForSlot0(t *testing.T) {
})
require.NoError(t, err)
ClearCache()
_, proposerIndexToSlots, err := CommitteeAssignments(state, 0)
_, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, 0)
require.NoError(t, err, "Failed to determine CommitteeAssignments")
for _, slots := range proposerIndexToSlots {
for _, s := range slots {
@@ -189,7 +190,7 @@ func TestCommitteeAssignments_CanRetrieve(t *testing.T) {
for i, tt := range tests {
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
ClearCache()
validatorIndexToCommittee, proposerIndexToSlots, err := CommitteeAssignments(state, core.SlotToEpoch(tt.slot))
validatorIndexToCommittee, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, core.SlotToEpoch(tt.slot))
require.NoError(t, err, "Failed to determine CommitteeAssignments")
cac := validatorIndexToCommittee[tt.index]
assert.Equal(t, tt.committeeIndex, cac.CommitteeIndex, "Unexpected committeeIndex for validator index %d", tt.index)
@@ -224,11 +225,11 @@ func TestCommitteeAssignments_CannotRetrieveFuture(t *testing.T) {
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
require.NoError(t, err)
_, proposerIndxs, err := CommitteeAssignments(state, core.CurrentEpoch(state))
_, proposerIndxs, err := CommitteeAssignments(context.Background(), state, core.CurrentEpoch(state))
require.NoError(t, err)
require.NotEqual(t, 0, len(proposerIndxs), "wanted non-zero proposer index set")
_, proposerIndxs, err = CommitteeAssignments(state, core.CurrentEpoch(state)+1)
_, proposerIndxs, err = CommitteeAssignments(context.Background(), state, core.CurrentEpoch(state)+1)
require.NoError(t, err)
require.Equal(t, 0, len(proposerIndxs), "wanted empty proposer index set")
}
@@ -250,7 +251,7 @@ func TestCommitteeAssignments_EverySlotHasMin1Proposer(t *testing.T) {
require.NoError(t, err)
ClearCache()
epoch := types.Epoch(1)
_, proposerIndexToSlots, err := CommitteeAssignments(state, epoch)
_, proposerIndexToSlots, err := CommitteeAssignments(context.Background(), state, epoch)
require.NoError(t, err, "Failed to determine CommitteeAssignments")
slotsWithProposers := make(map[types.Slot]bool)
@@ -358,7 +359,7 @@ func TestVerifyAttestationBitfieldLengths_OK(t *testing.T) {
for i, tt := range tests {
ClearCache()
require.NoError(t, state.SetSlot(tt.stateSlot))
err := VerifyAttestationBitfieldLengths(state, tt.attestation)
err := VerifyAttestationBitfieldLengths(context.Background(), state, tt.attestation)
if tt.verificationFailure {
assert.NotNil(t, err, "Verification succeeded when it was supposed to fail")
} else {
@@ -391,7 +392,7 @@ func TestUpdateCommitteeCache_CanUpdate(t *testing.T) {
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
indices, err = committeeCache.Committee(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)), seed, idx)
indices, err = committeeCache.Committee(context.Background(), params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)), seed, idx)
require.NoError(t, err)
assert.Equal(t, params.BeaconConfig().TargetCommitteeSize, uint64(len(indices)), "Did not save correct indices lengths")
}
@@ -410,7 +411,7 @@ func BenchmarkComputeCommittee300000_WithPreCache(b *testing.B) {
require.NoError(b, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(b, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(b, err)
@@ -444,7 +445,7 @@ func BenchmarkComputeCommittee3000000_WithPreCache(b *testing.B) {
require.NoError(b, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(b, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(b, err)
@@ -478,7 +479,7 @@ func BenchmarkComputeCommittee128000_WithOutPreCache(b *testing.B) {
require.NoError(b, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(b, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(b, err)
@@ -513,7 +514,7 @@ func BenchmarkComputeCommittee1000000_WithOutCache(b *testing.B) {
require.NoError(b, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(b, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(b, err)
@@ -548,7 +549,7 @@ func BenchmarkComputeCommittee4000000_WithOutCache(b *testing.B) {
require.NoError(b, err)
epoch := core.CurrentEpoch(state)
indices, err := ActiveValidatorIndices(state, epoch)
indices, err := ActiveValidatorIndices(context.Background(), state, epoch)
require.NoError(b, err)
seed, err := Seed(state, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(b, err)
@@ -584,13 +585,13 @@ func TestBeaconCommitteeFromState_UpdateCacheForPreviousEpoch(t *testing.T) {
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
require.NoError(t, err)
_, err = BeaconCommitteeFromState(state, 1 /* previous epoch */, 0)
_, err = BeaconCommitteeFromState(context.Background(), state, 1 /* previous epoch */, 0)
require.NoError(t, err)
// Verify previous epoch is cached
seed, err := Seed(state, 0, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
activeIndices, err := committeeCache.ActiveIndices(seed)
activeIndices, err := committeeCache.ActiveIndices(context.Background(), seed)
require.NoError(t, err)
assert.NotNil(t, activeIndices, "Did not cache active indices")
}
@@ -609,7 +610,7 @@ func TestPrecomputeProposerIndices_Ok(t *testing.T) {
})
require.NoError(t, err)
indices, err := ActiveValidatorIndices(state, 0)
indices, err := ActiveValidatorIndices(context.Background(), state, 0)
require.NoError(t, err)
proposerIndices, err := precomputeProposerIndices(state, indices)

View File

@@ -2,6 +2,7 @@ package helpers_test
import (
"bytes"
"context"
"testing"
fuzz "github.com/google/gofuzz"
@@ -80,7 +81,7 @@ func TestSigningRoot_ComputeDomainAndSign(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
beaconState, privKeys := tt.genState(t)
idx, err := helpers.BeaconProposerIndex(beaconState)
idx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
require.NoError(t, err)
block := tt.genBlock(t, beaconState, privKeys)
got, err := helpers.ComputeDomainAndSign(

View File

@@ -2,9 +2,13 @@ package helpers
import (
"bytes"
"context"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/cache"
"github.com/prysmaticlabs/prysm/beacon-chain/core"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/config/params"
@@ -12,8 +16,14 @@ import (
"github.com/prysmaticlabs/prysm/crypto/hash"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
log "github.com/sirupsen/logrus"
)
var CommitteeCacheInProgressHit = promauto.NewCounter(prometheus.CounterOpts{
Name: "committee_cache_in_progress_hit",
Help: "The number of committee requests that are present in the cache.",
})
// IsActiveValidator returns the boolean value on whether the validator
// is active or not.
//
@@ -73,18 +83,39 @@ func checkValidatorSlashable(activationEpoch, withdrawableEpoch types.Epoch, sla
// Return the sequence of active validator indices at ``epoch``.
// """
// return [ValidatorIndex(i) for i, v in enumerate(state.validators) if is_active_validator(v, epoch)]
func ActiveValidatorIndices(s state.ReadOnlyBeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) {
func ActiveValidatorIndices(ctx context.Context, s state.ReadOnlyBeaconState, epoch types.Epoch) ([]types.ValidatorIndex, error) {
seed, err := Seed(s, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return nil, errors.Wrap(err, "could not get seed")
}
activeIndices, err := committeeCache.ActiveIndices(seed)
activeIndices, err := committeeCache.ActiveIndices(ctx, seed)
if err != nil {
return nil, errors.Wrap(err, "could not interface with committee cache")
}
if activeIndices != nil {
return activeIndices, nil
}
if err := committeeCache.MarkInProgress(seed); err != nil {
if errors.Is(err, cache.ErrAlreadyInProgress) {
activeIndices, err := committeeCache.ActiveIndices(ctx, seed)
if err != nil {
return nil, err
}
if activeIndices == nil {
return nil, errors.New("nil active indices")
}
CommitteeCacheInProgressHit.Inc()
return activeIndices, nil
}
return nil, errors.Wrap(err, "could not mark committee cache as in progress")
}
defer func() {
if err := committeeCache.MarkNotInProgress(seed); err != nil {
log.WithError(err).Error("Could not mark cache not in progress")
}
}()
var indices []types.ValidatorIndex
if err := s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error {
if IsActiveValidatorUsingTrie(val, epoch) {
@@ -104,12 +135,12 @@ func ActiveValidatorIndices(s state.ReadOnlyBeaconState, epoch types.Epoch) ([]t
// ActiveValidatorCount returns the number of active validators in the state
// at the given epoch.
func ActiveValidatorCount(s state.ReadOnlyBeaconState, epoch types.Epoch) (uint64, error) {
func ActiveValidatorCount(ctx context.Context, s state.ReadOnlyBeaconState, epoch types.Epoch) (uint64, error) {
seed, err := Seed(s, epoch, params.BeaconConfig().DomainBeaconAttester)
if err != nil {
return 0, errors.Wrap(err, "could not get seed")
}
activeCount, err := committeeCache.ActiveIndicesCount(seed)
activeCount, err := committeeCache.ActiveIndicesCount(ctx, seed)
if err != nil {
return 0, errors.Wrap(err, "could not interface with committee cache")
}
@@ -117,6 +148,23 @@ func ActiveValidatorCount(s state.ReadOnlyBeaconState, epoch types.Epoch) (uint6
return uint64(activeCount), nil
}
if err := committeeCache.MarkInProgress(seed); err != nil {
if errors.Is(err, cache.ErrAlreadyInProgress) {
activeCount, err := committeeCache.ActiveIndicesCount(ctx, seed)
if err != nil {
return 0, err
}
CommitteeCacheInProgressHit.Inc()
return uint64(activeCount), nil
}
return 0, errors.Wrap(err, "could not mark committee cache as in progress")
}
defer func() {
if err := committeeCache.MarkNotInProgress(seed); err != nil {
log.WithError(err).Error("Could not mark cache not in progress")
}
}()
count := uint64(0)
if err := s.ReadFromEveryValidator(func(idx int, val state.ReadOnlyValidator) error {
if IsActiveValidatorUsingTrie(val, epoch) {
@@ -176,7 +224,7 @@ func ValidatorChurnLimit(activeValidatorCount uint64) (uint64, error) {
// seed = hash(get_seed(state, epoch, DOMAIN_BEACON_PROPOSER) + uint_to_bytes(state.slot))
// indices = get_active_validator_indices(state, epoch)
// return compute_proposer_index(state, indices, seed)
func BeaconProposerIndex(state state.ReadOnlyBeaconState) (types.ValidatorIndex, error) {
func BeaconProposerIndex(ctx context.Context, state state.ReadOnlyBeaconState) (types.ValidatorIndex, error) {
e := core.CurrentEpoch(state)
// The cache uses the state root of the previous epoch - minimum_seed_lookahead last slot as key. (e.g. Starting epoch 1, slot 32, the key would be block root at slot 31)
// For simplicity, the node will skip caching of genesis epoch.
@@ -204,7 +252,7 @@ func BeaconProposerIndex(state state.ReadOnlyBeaconState) (types.ValidatorIndex,
}
return proposerIndices[state.Slot()%params.BeaconConfig().SlotsPerEpoch], nil
}
if err := UpdateProposerIndicesInCache(state); err != nil {
if err := UpdateProposerIndicesInCache(ctx, state); err != nil {
return 0, errors.Wrap(err, "could not update committee cache")
}
}
@@ -218,7 +266,7 @@ func BeaconProposerIndex(state state.ReadOnlyBeaconState) (types.ValidatorIndex,
seedWithSlot := append(seed[:], bytesutil.Bytes8(uint64(state.Slot()))...)
seedWithSlotHash := hash.Hash(seedWithSlot)
indices, err := ActiveValidatorIndices(state, e)
indices, err := ActiveValidatorIndices(ctx, state, e)
if err != nil {
return 0, errors.Wrap(err, "could not get active indices")
}

View File

@@ -1,6 +1,7 @@
package helpers
import (
"context"
"errors"
"testing"
@@ -270,7 +271,7 @@ func TestBeaconProposerIndex_OK(t *testing.T) {
for _, tt := range tests {
ClearCache()
require.NoError(t, state.SetSlot(tt.slot))
result, err := BeaconProposerIndex(state)
result, err := BeaconProposerIndex(context.Background(), state)
require.NoError(t, err, "Failed to get shard and committees at slot")
assert.Equal(t, tt.index, result, "Result index was an unexpected value")
}
@@ -304,7 +305,7 @@ func TestBeaconProposerIndex_BadState(t *testing.T) {
// Set a very high slot, so that retrieved block root will be
// non existent for the proposer cache.
require.NoError(t, state.SetSlot(100))
_, err = BeaconProposerIndex(state)
_, err = BeaconProposerIndex(context.Background(), state)
require.NoError(t, err)
assert.Equal(t, 0, len(proposerIndicesCache.ProposerIndicesCache.ListKeys()))
}
@@ -323,7 +324,7 @@ func TestComputeProposerIndex_Compatibility(t *testing.T) {
})
require.NoError(t, err)
indices, err := ActiveValidatorIndices(state, 0)
indices, err := ActiveValidatorIndices(context.Background(), state, 0)
require.NoError(t, err)
var proposerIndices []types.ValidatorIndex
@@ -375,7 +376,7 @@ func TestActiveValidatorCount_Genesis(t *testing.T) {
seed, err := Seed(beaconState, 0, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
require.NoError(t, committeeCache.AddCommitteeShuffledList(&cache.Committees{Seed: seed, ShuffledIndices: []types.ValidatorIndex{1, 2, 3}}))
validatorCount, err := ActiveValidatorCount(beaconState, core.CurrentEpoch(beaconState))
validatorCount, err := ActiveValidatorCount(context.Background(), beaconState, core.CurrentEpoch(beaconState))
require.NoError(t, err)
assert.Equal(t, uint64(c), validatorCount, "Did not get the correct validator count")
}
@@ -406,7 +407,7 @@ func TestChurnLimit_OK(t *testing.T) {
RandaoMixes: make([][]byte, params.BeaconConfig().EpochsPerHistoricalVector),
})
require.NoError(t, err)
validatorCount, err := ActiveValidatorCount(beaconState, core.CurrentEpoch(beaconState))
validatorCount, err := ActiveValidatorCount(context.Background(), beaconState, core.CurrentEpoch(beaconState))
require.NoError(t, err)
resultChurn, err := ValidatorChurnLimit(validatorCount)
require.NoError(t, err)
@@ -591,7 +592,7 @@ func TestActiveValidatorIndices(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
s, err := v1.InitializeFromProto(tt.args.state)
require.NoError(t, err)
got, err := ActiveValidatorIndices(s, tt.args.epoch)
got, err := ActiveValidatorIndices(context.Background(), s, tt.args.epoch)
if tt.wantedErr != "" {
assert.ErrorContains(t, tt.wantedErr, err)
return

View File

@@ -2,6 +2,7 @@ package helpers
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
@@ -52,12 +53,12 @@ import (
// )
//
// return ws_period
func ComputeWeakSubjectivityPeriod(st state.ReadOnlyBeaconState) (types.Epoch, error) {
func ComputeWeakSubjectivityPeriod(ctx context.Context, st state.ReadOnlyBeaconState) (types.Epoch, error) {
// Weak subjectivity period cannot be smaller than withdrawal delay.
wsp := uint64(params.BeaconConfig().MinValidatorWithdrawabilityDelay)
// Cardinality of active validator set.
N, err := ActiveValidatorCount(st, core.CurrentEpoch(st))
N, err := ActiveValidatorCount(ctx, st, core.CurrentEpoch(st))
if err != nil {
return 0, fmt.Errorf("cannot obtain active valiadtor count: %w", err)
}
@@ -120,7 +121,7 @@ func ComputeWeakSubjectivityPeriod(st state.ReadOnlyBeaconState) (types.Epoch, e
// current_epoch = compute_epoch_at_slot(get_current_slot(store))
// return current_epoch <= ws_state_epoch + ws_period
func IsWithinWeakSubjectivityPeriod(
currentEpoch types.Epoch, wsState state.ReadOnlyBeaconState, wsCheckpoint *eth.WeakSubjectivityCheckpoint) (bool, error) {
ctx context.Context, currentEpoch types.Epoch, wsState state.ReadOnlyBeaconState, wsCheckpoint *eth.WeakSubjectivityCheckpoint) (bool, error) {
// Make sure that incoming objects are not nil.
if wsState == nil || wsState.IsNil() || wsState.LatestBlockHeader() == nil || wsCheckpoint == nil {
return false, errors.New("invalid weak subjectivity state or checkpoint")
@@ -137,7 +138,7 @@ func IsWithinWeakSubjectivityPeriod(
}
// Compare given epoch to state epoch + weak subjectivity period.
wsPeriod, err := ComputeWeakSubjectivityPeriod(wsState)
wsPeriod, err := ComputeWeakSubjectivityPeriod(ctx, wsState)
if err != nil {
return false, fmt.Errorf("cannot compute weak subjectivity period: %w", err)
}
@@ -151,8 +152,8 @@ func IsWithinWeakSubjectivityPeriod(
// Within the weak subjectivity period, if two conflicting blocks are finalized, 1/3 - D (D := safety decay)
// of validators will get slashed. Therefore, it is safe to assume that any finalized checkpoint within that
// period is protected by this safety margin.
func LatestWeakSubjectivityEpoch(st state.ReadOnlyBeaconState) (types.Epoch, error) {
wsPeriod, err := ComputeWeakSubjectivityPeriod(st)
func LatestWeakSubjectivityEpoch(ctx context.Context, st state.ReadOnlyBeaconState) (types.Epoch, error) {
wsPeriod, err := ComputeWeakSubjectivityPeriod(ctx, st)
if err != nil {
return 0, err
}

View File

@@ -1,6 +1,7 @@
package helpers_test
import (
"context"
"fmt"
"testing"
@@ -47,7 +48,7 @@ func TestWeakSubjectivity_ComputeWeakSubjectivityPeriod(t *testing.T) {
t.Run(fmt.Sprintf("valCount: %d, avgBalance: %d", tt.valCount, tt.avgBalance), func(t *testing.T) {
// Reset committee cache - as we need to recalculate active validator set for each test.
helpers.ClearCache()
got, err := helpers.ComputeWeakSubjectivityPeriod(genState(t, tt.valCount, tt.avgBalance))
got, err := helpers.ComputeWeakSubjectivityPeriod(context.Background(), genState(t, tt.valCount, tt.avgBalance))
require.NoError(t, err)
assert.Equal(t, tt.want, got, "valCount: %v, avgBalance: %v", tt.valCount, tt.avgBalance)
})
@@ -192,7 +193,7 @@ func TestWeakSubjectivity_IsWithinWeakSubjectivityPeriod(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := helpers.IsWithinWeakSubjectivityPeriod(tt.epoch, tt.genWsState(), tt.genWsCheckpoint())
got, err := helpers.IsWithinWeakSubjectivityPeriod(context.Background(), tt.epoch, tt.genWsState(), tt.genWsCheckpoint())
if tt.wantedErr != "" {
assert.Equal(t, false, got)
assert.ErrorContains(t, tt.wantedErr, err)

View File

@@ -52,7 +52,7 @@ func TestExecuteAltairStateTransitionNoVerify_FullProcess(t *testing.T) {
require.NoError(t, err)
parentRoot, err := nextSlotState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(nextSlotState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), nextSlotState)
require.NoError(t, err)
block := util.NewBeaconBlockAltair()
block.Block.ProposerIndex = proposerIdx
@@ -139,7 +139,7 @@ func TestExecuteAltairStateTransitionNoVerifySignature_CouldNotVerifyStateRoot(t
require.NoError(t, err)
parentRoot, err := nextSlotState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(nextSlotState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), nextSlotState)
require.NoError(t, err)
block := util.NewBeaconBlockAltair()
block.Block.ProposerIndex = proposerIdx

View File

@@ -380,7 +380,7 @@ func ProcessEpochPrecompute(ctx context.Context, state state.BeaconState) (state
return nil, errors.Wrap(err, "could not process rewards and penalties")
}
state, err = e.ProcessRegistryUpdates(state)
state, err = e.ProcessRegistryUpdates(ctx, state)
if err != nil {
return nil, errors.Wrap(err, "could not process registry updates")
}

View File

@@ -157,7 +157,7 @@ func CalculateStateRoot(
if err != nil {
return [32]byte{}, err
}
state, err = altair.ProcessSyncAggregate(state, sa)
state, err = altair.ProcessSyncAggregate(ctx, state, sa)
if err != nil {
return [32]byte{}, err
}
@@ -203,7 +203,7 @@ func ProcessBlockNoVerifyAnySig(
if err != nil {
return nil, nil, err
}
state, err = altair.ProcessSyncAggregate(state, sa)
state, err = altair.ProcessSyncAggregate(ctx, state, sa)
if err != nil {
return nil, nil, err
}
@@ -214,7 +214,7 @@ func ProcessBlockNoVerifyAnySig(
tracing.AnnotateError(span, err)
return nil, nil, errors.Wrap(err, "could not retrieve block signature set")
}
rSet, err := b.RandaoSignatureSet(state, signed.Block().Body().RandaoReveal())
rSet, err := b.RandaoSignatureSet(ctx, state, signed.Block().Body().RandaoReveal())
if err != nil {
tracing.AnnotateError(span, err)
return nil, nil, errors.Wrap(err, "could not retrieve randao signature set")
@@ -304,7 +304,7 @@ func ProcessBlockForStateRoot(
if err != nil {
return nil, err
}
state, err = b.ProcessBlockHeaderNoVerify(state, blk.Slot(), blk.ProposerIndex(), blk.ParentRoot(), bodyRoot[:])
state, err = b.ProcessBlockHeaderNoVerify(ctx, state, blk.Slot(), blk.ProposerIndex(), blk.ParentRoot(), bodyRoot[:])
if err != nil {
tracing.AnnotateError(span, err)
return nil, errors.Wrap(err, "could not process block header")

View File

@@ -43,7 +43,7 @@ func TestExecuteStateTransitionNoVerify_FullProcess(t *testing.T) {
require.NoError(t, err)
parentRoot, err := nextSlotState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(nextSlotState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), nextSlotState)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.ProposerIndex = proposerIdx
@@ -95,7 +95,7 @@ func TestExecuteStateTransitionNoVerifySignature_CouldNotVerifyStateRoot(t *test
require.NoError(t, err)
parentRoot, err := nextSlotState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(nextSlotState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), nextSlotState)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.ProposerIndex = proposerIdx

View File

@@ -76,7 +76,7 @@ func TestExecuteStateTransition_FullProcess(t *testing.T) {
require.NoError(t, err)
parentRoot, err := nextSlotState.LatestBlockHeader().HashTreeRoot()
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(nextSlotState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), nextSlotState)
require.NoError(t, err)
block := util.NewBeaconBlock()
block.Block.ProposerIndex = proposerIdx
@@ -299,7 +299,7 @@ func createFullBlockWithOperations(t *testing.T) (state.BeaconState,
AggregationBits: aggBits,
})
committee, err := helpers.BeaconCommitteeFromState(beaconState, blockAtt.Data.Slot, blockAtt.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, blockAtt.Data.Slot, blockAtt.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(blockAtt.AggregationBits, committee)
require.NoError(t, err)
@@ -333,7 +333,7 @@ func createFullBlockWithOperations(t *testing.T) (state.BeaconState,
require.NoError(t, copied.SetSlot(beaconState.Slot()+1))
randaoReveal, err := util.RandaoReveal(copied, currentEpoch, privKeys)
require.NoError(t, err)
proposerIndex, err := helpers.BeaconProposerIndex(copied)
proposerIndex, err := helpers.BeaconProposerIndex(context.Background(), copied)
require.NoError(t, err)
block := util.HydrateSignedBeaconBlock(&ethpb.SignedBeaconBlock{
Block: &ethpb.BeaconBlock{
@@ -582,10 +582,9 @@ func TestProcessSlots_OnlyAltairEpoch(t *testing.T) {
}
func TestProcessSlotsUsingNextSlotCache(t *testing.T) {
ctx := context.Background()
s, _ := util.DeterministicGenesisState(t, 1)
r := []byte{'a'}
s, err := transition.ProcessSlotsUsingNextSlotCache(ctx, s, r, 5)
s, err := transition.ProcessSlotsUsingNextSlotCache(context.Background(), s, r, 5)
require.NoError(t, err)
require.Equal(t, types.Slot(5), s.Slot())
}

View File

@@ -5,6 +5,8 @@
package validators
import (
"context"
"github.com/pkg/errors"
types "github.com/prysmaticlabs/eth2-types"
"github.com/prysmaticlabs/prysm/beacon-chain/core"
@@ -37,7 +39,7 @@ import (
// # Set validator exit epoch and withdrawable epoch
// validator.exit_epoch = exit_queue_epoch
// validator.withdrawable_epoch = Epoch(validator.exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY)
func InitiateValidatorExit(s state.BeaconState, idx types.ValidatorIndex) (state.BeaconState, error) {
func InitiateValidatorExit(ctx context.Context, s state.BeaconState, idx types.ValidatorIndex) (state.BeaconState, error) {
validator, err := s.ValidatorAtIndex(idx)
if err != nil {
return nil, err
@@ -76,7 +78,7 @@ func InitiateValidatorExit(s state.BeaconState, idx types.ValidatorIndex) (state
if err != nil {
return nil, err
}
activeValidatorCount, err := helpers.ActiveValidatorCount(s, core.CurrentEpoch(s))
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, s, core.CurrentEpoch(s))
if err != nil {
return nil, errors.Wrap(err, "could not get active validator count")
}
@@ -123,11 +125,12 @@ func InitiateValidatorExit(s state.BeaconState, idx types.ValidatorIndex) (state
// increase_balance(state, proposer_index, proposer_reward)
// increase_balance(state, whistleblower_index, Gwei(whistleblower_reward - proposer_reward))
func SlashValidator(
ctx context.Context,
s state.BeaconState,
slashedIdx types.ValidatorIndex,
penaltyQuotient uint64,
proposerRewardQuotient uint64) (state.BeaconState, error) {
s, err := InitiateValidatorExit(s, slashedIdx)
s, err := InitiateValidatorExit(ctx, s, slashedIdx)
if err != nil {
return nil, errors.Wrapf(err, "could not initiate validator %d exit", slashedIdx)
}
@@ -157,7 +160,7 @@ func SlashValidator(
return nil, err
}
proposerIdx, err := helpers.BeaconProposerIndex(s)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, s)
if err != nil {
return nil, errors.Wrap(err, "could not get proposer idx")
}

View File

@@ -1,6 +1,7 @@
package validators
import (
"context"
"testing"
types "github.com/prysmaticlabs/eth2-types"
@@ -46,7 +47,7 @@ func TestInitiateValidatorExit_AlreadyExited(t *testing.T) {
}}
state, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := InitiateValidatorExit(state, 0)
newState, err := InitiateValidatorExit(context.Background(), state, 0)
require.NoError(t, err)
v, err := newState.ValidatorAtIndex(0)
require.NoError(t, err)
@@ -64,7 +65,7 @@ func TestInitiateValidatorExit_ProperExit(t *testing.T) {
}}
state, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := InitiateValidatorExit(state, idx)
newState, err := InitiateValidatorExit(context.Background(), state, idx)
require.NoError(t, err)
v, err := newState.ValidatorAtIndex(idx)
require.NoError(t, err)
@@ -83,7 +84,7 @@ func TestInitiateValidatorExit_ChurnOverflow(t *testing.T) {
}}
state, err := v1.InitializeFromProto(base)
require.NoError(t, err)
newState, err := InitiateValidatorExit(state, idx)
newState, err := InitiateValidatorExit(context.Background(), state, idx)
require.NoError(t, err)
// Because of exit queue overflow,
@@ -121,12 +122,12 @@ func TestSlashValidator_OK(t *testing.T) {
slashedIdx := types.ValidatorIndex(2)
proposer, err := helpers.BeaconProposerIndex(state)
proposer, err := helpers.BeaconProposerIndex(context.Background(), state)
require.NoError(t, err, "Could not get proposer")
proposerBal, err := state.BalanceAtIndex(proposer)
require.NoError(t, err)
cfg := params.BeaconConfig()
slashedState, err := SlashValidator(state, slashedIdx, cfg.MinSlashingPenaltyQuotient, cfg.ProposerRewardQuotient)
slashedState, err := SlashValidator(context.Background(), state, slashedIdx, cfg.MinSlashingPenaltyQuotient, cfg.ProposerRewardQuotient)
require.NoError(t, err, "Could not slash validator")
state, ok := slashedState.(*v1.BeaconState)
require.Equal(t, true, ok)
@@ -318,7 +319,7 @@ func TestExitedValidatorIndices(t *testing.T) {
for _, tt := range tests {
s, err := v1.InitializeFromProto(tt.state)
require.NoError(t, err)
activeCount, err := helpers.ActiveValidatorCount(s, core.PrevEpoch(s))
activeCount, err := helpers.ActiveValidatorCount(context.Background(), s, core.PrevEpoch(s))
require.NoError(t, err)
exitedIndices, err := ExitedValidatorIndices(0, tt.state.Validators, activeCount)
require.NoError(t, err)

View File

@@ -1,6 +1,7 @@
package p2p
import (
"context"
"math"
"reflect"
"strings"
@@ -133,7 +134,7 @@ func (s *Service) retrieveActiveValidators() (uint64, error) {
if genState == nil || genState.IsNil() {
return 0, errors.New("no genesis state exists")
}
activeVals, err := helpers.ActiveValidatorCount(genState, core.CurrentEpoch(genState))
activeVals, err := helpers.ActiveValidatorCount(context.Background(), genState, core.CurrentEpoch(genState))
if err != nil {
return 0, err
}
@@ -148,7 +149,7 @@ func (s *Service) retrieveActiveValidators() (uint64, error) {
if bState == nil || bState.IsNil() {
return 0, errors.Errorf("no state with root %#x exists", rt)
}
activeVals, err := helpers.ActiveValidatorCount(bState, core.CurrentEpoch(bState))
activeVals, err := helpers.ActiveValidatorCount(context.Background(), bState, core.CurrentEpoch(bState))
if err != nil {
return 0, err
}

View File

@@ -40,7 +40,7 @@ func TestProcessDeposit_OK(t *testing.T) {
err = web3Service.processDeposit(context.Background(), eth1Data, deposits[0])
require.NoError(t, err, "could not process deposit")
valcount, err := helpers.ActiveValidatorCount(web3Service.preGenesisState, 0)
valcount, err := helpers.ActiveValidatorCount(context.Background(), web3Service.preGenesisState, 0)
require.NoError(t, err)
require.Equal(t, 1, int(valcount), "Did not get correct active validator count")
}
@@ -230,7 +230,7 @@ func TestProcessDeposit_IncompleteDeposit(t *testing.T) {
err = web3Service.processDeposit(context.Background(), eth1Data, deposit)
require.NoError(t, err, fmt.Sprintf("Could not process deposit at %d", i))
valcount, err := helpers.ActiveValidatorCount(web3Service.preGenesisState, 0)
valcount, err := helpers.ActiveValidatorCount(context.Background(), web3Service.preGenesisState, 0)
require.NoError(t, err)
require.Equal(t, 0, int(valcount), "Did not get correct active validator count")
}
@@ -255,7 +255,7 @@ func TestProcessDeposit_AllDepositedSuccessfully(t *testing.T) {
err = web3Service.processDeposit(context.Background(), eth1Data, deposits[i])
require.NoError(t, err, fmt.Sprintf("Could not process deposit at %d", i))
valCount, err := helpers.ActiveValidatorCount(web3Service.preGenesisState, 0)
valCount, err := helpers.ActiveValidatorCount(context.Background(), web3Service.preGenesisState, 0)
require.NoError(t, err)
require.Equal(t, uint64(i+1), valCount, "Did not get correct active validator count")

View File

@@ -183,7 +183,7 @@ func (s *Service) ProcessDepositLog(ctx context.Context, depositLog gethTypes.Lo
if !s.chainStartData.Chainstarted {
deposits := len(s.chainStartData.ChainstartDeposits)
if deposits%512 == 0 {
valCount, err := helpers.ActiveValidatorCount(s.preGenesisState, 0)
valCount, err := helpers.ActiveValidatorCount(ctx, s.preGenesisState, 0)
if err != nil {
log.WithError(err).Error("Could not determine active validator count from pre genesis state")
}
@@ -336,7 +336,7 @@ func (s *Service) processPastLogs(ctx context.Context) error {
for _, filterLog := range logs {
if filterLog.BlockNumber > currentBlockNum {
if err := s.checkHeaderRange(currentBlockNum, filterLog.BlockNumber-1, headersMap, requestHeaders); err != nil {
if err := s.checkHeaderRange(ctx, currentBlockNum, filterLog.BlockNumber-1, headersMap, requestHeaders); err != nil {
return err
}
// set new block number after checking for chainstart for previous block.
@@ -347,7 +347,7 @@ func (s *Service) processPastLogs(ctx context.Context) error {
return err
}
}
if err := s.checkHeaderRange(currentBlockNum, end, headersMap, requestHeaders); err != nil {
if err := s.checkHeaderRange(ctx, currentBlockNum, end, headersMap, requestHeaders); err != nil {
return err
}
currentBlockNum = end
@@ -434,15 +434,15 @@ func (s *Service) checkBlockNumberForChainStart(ctx context.Context, blkNum *big
if err != nil {
return err
}
s.checkForChainstart(hash, blkNum, timeStamp)
s.checkForChainstart(ctx, hash, blkNum, timeStamp)
return nil
}
func (s *Service) checkHeaderForChainstart(header *gethTypes.Header) {
s.checkForChainstart(header.Hash(), header.Number, header.Time)
func (s *Service) checkHeaderForChainstart(ctx context.Context, header *gethTypes.Header) {
s.checkForChainstart(ctx, header.Hash(), header.Number, header.Time)
}
func (s *Service) checkHeaderRange(start, end uint64, headersMap map[uint64]*gethTypes.Header,
func (s *Service) checkHeaderRange(ctx context.Context, start, end uint64, headersMap map[uint64]*gethTypes.Header,
requestHeaders func(uint64, uint64) error) error {
for i := start; i <= end; i++ {
if !s.chainStartData.Chainstarted {
@@ -455,7 +455,7 @@ func (s *Service) checkHeaderRange(start, end uint64, headersMap map[uint64]*get
i--
continue
}
s.checkHeaderForChainstart(h)
s.checkHeaderForChainstart(ctx, h)
}
}
return nil
@@ -463,11 +463,11 @@ func (s *Service) checkHeaderRange(start, end uint64, headersMap map[uint64]*get
// retrieves the current active validator count and genesis time from
// the provided block time.
func (s *Service) currentCountAndTime(blockTime uint64) (uint64, uint64) {
func (s *Service) currentCountAndTime(ctx context.Context, blockTime uint64) (uint64, uint64) {
if s.preGenesisState.NumValidators() == 0 {
return 0, 0
}
valCount, err := helpers.ActiveValidatorCount(s.preGenesisState, 0)
valCount, err := helpers.ActiveValidatorCount(ctx, s.preGenesisState, 0)
if err != nil {
log.WithError(err).Error("Could not determine active validator count from pre genesis state")
return 0, 0
@@ -475,8 +475,8 @@ func (s *Service) currentCountAndTime(blockTime uint64) (uint64, uint64) {
return valCount, s.createGenesisTime(blockTime)
}
func (s *Service) checkForChainstart(blockHash [32]byte, blockNumber *big.Int, blockTime uint64) {
valCount, genesisTime := s.currentCountAndTime(blockTime)
func (s *Service) checkForChainstart(ctx context.Context, blockHash [32]byte, blockNumber *big.Int, blockTime uint64) {
valCount, genesisTime := s.currentCountAndTime(ctx, blockTime)
if valCount == 0 {
return
}

View File

@@ -553,7 +553,7 @@ func TestCheckForChainstart_NoValidator(t *testing.T) {
require.NoError(t, err, "Unable to set up simulated backend")
beaconDB := testDB.SetupDB(t)
s := newPowchainService(t, testAcc, beaconDB)
s.checkForChainstart([32]byte{}, nil, 0)
s.checkForChainstart(context.Background(), [32]byte{}, nil, 0)
require.LogsDoNotContain(t, hook, "Could not determine active validator count from pre genesis state")
}

View File

@@ -823,13 +823,13 @@ func (s *Service) run(done <-chan struct{}) {
chainstartTicker.Stop()
continue
}
s.logTillChainStart()
s.logTillChainStart(context.Background())
}
}
}
// logs the current thresholds required to hit chainstart every minute.
func (s *Service) logTillChainStart() {
func (s *Service) logTillChainStart(ctx context.Context) {
if s.chainStartData.Chainstarted {
return
}
@@ -838,7 +838,7 @@ func (s *Service) logTillChainStart() {
log.Error(err)
return
}
valCount, genesisTime := s.currentCountAndTime(blockTime)
valCount, genesisTime := s.currentCountAndTime(ctx, blockTime)
valNeeded := uint64(0)
if valCount < params.BeaconConfig().MinGenesisActiveValidatorCount {
valNeeded = params.BeaconConfig().MinGenesisActiveValidatorCount - valCount

View File

@@ -148,7 +148,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees
if req.Epoch != nil {
epoch = *req.Epoch
}
activeCount, err := corehelpers.ActiveValidatorCount(st, epoch)
activeCount, err := corehelpers.ActiveValidatorCount(ctx, st, epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get active validator count: %v", err)
}
@@ -171,7 +171,7 @@ func (bs *Server) ListCommittees(ctx context.Context, req *ethpb.StateCommittees
if req.Index != nil && index != *req.Index {
continue
}
committee, err := corehelpers.BeaconCommitteeFromState(st, slot, index)
committee, err := corehelpers.BeaconCommitteeFromState(ctx, st, slot, index)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get committee: %v", err)
}

View File

@@ -56,11 +56,11 @@ func (vs *Server) GetAttesterDuties(ctx context.Context, req *ethpbv1.AttesterDu
return nil, status.Errorf(codes.Internal, "Could not advance state to requested epoch start slot: %v", err)
}
committeeAssignments, _, err := helpers.CommitteeAssignments(s, req.Epoch)
committeeAssignments, _, err := helpers.CommitteeAssignments(ctx, s, req.Epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not compute committee assignments: %v", err)
}
activeValidatorCount, err := helpers.ActiveValidatorCount(s, req.Epoch)
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, s, req.Epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get active validator count: %v", err)
}
@@ -130,7 +130,7 @@ func (vs *Server) GetProposerDuties(ctx context.Context, req *ethpbv1.ProposerDu
return nil, status.Errorf(codes.Internal, "Could not advance state to requested epoch start slot: %v", err)
}
_, proposals, err := helpers.CommitteeAssignments(s, req.Epoch)
_, proposals, err := helpers.CommitteeAssignments(ctx, s, req.Epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not compute committee assignments: %v", err)
}

View File

@@ -80,7 +80,7 @@ func (bs *Server) ListValidatorAssignments(
}
}
activeIndices, err := helpers.ActiveValidatorIndices(requestedState, requestedEpoch)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, requestedState, requestedEpoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not retrieve active validator indices: %v", err)
}
@@ -102,7 +102,7 @@ func (bs *Server) ListValidatorAssignments(
}
// Initialize all committee related data.
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(requestedState, requestedEpoch)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(ctx, requestedState, requestedEpoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not compute committee assignments: %v", err)
}

View File

@@ -208,9 +208,9 @@ func TestServer_ListAssignments_Pagination_DefaultPageSize_NoArchive(t *testing.
// Construct the wanted assignments.
var wanted []*ethpb.ValidatorAssignments_CommitteeAssignment
activeIndices, err := helpers.ActiveValidatorIndices(s, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, s, 0)
require.NoError(t, err)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(context.Background(), s, 0)
require.NoError(t, err)
for _, index := range activeIndices[0:params.BeaconConfig().DefaultPageSize] {
val, err := s.ValidatorAtIndex(index)
@@ -277,9 +277,9 @@ func TestServer_ListAssignments_FilterPubkeysIndices_NoPagination(t *testing.T)
// Construct the wanted assignments.
var wanted []*ethpb.ValidatorAssignments_CommitteeAssignment
activeIndices, err := helpers.ActiveValidatorIndices(s, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, s, 0)
require.NoError(t, err)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(context.Background(), s, 0)
require.NoError(t, err)
for _, index := range activeIndices[1:4] {
val, err := s.ValidatorAtIndex(index)
@@ -342,9 +342,9 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin
// Construct the wanted assignments.
var assignments []*ethpb.ValidatorAssignments_CommitteeAssignment
activeIndices, err := helpers.ActiveValidatorIndices(s, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, s, 0)
require.NoError(t, err)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(context.Background(), s, 0)
require.NoError(t, err)
for _, index := range activeIndices[3:5] {
val, err := s.ValidatorAtIndex(index)
@@ -372,7 +372,7 @@ func TestServer_ListAssignments_CanFilterPubkeysIndices_WithPagination(t *testin
req = &ethpb.ListValidatorAssignmentsRequest{Indices: []types.ValidatorIndex{1, 2, 3, 4, 5, 6}, PageSize: 5, PageToken: "1"}
res, err = bs.ListValidatorAssignments(context.Background(), req)
require.NoError(t, err)
cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, 0)
cAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(context.Background(), s, 0)
require.NoError(t, err)
for _, index := range activeIndices[6:7] {
val, err := s.ValidatorAtIndex(index)

View File

@@ -172,7 +172,7 @@ func (bs *Server) ListIndexedAttestations(
}
for i := 0; i < len(atts); i++ {
att := atts[i]
committee, err := helpers.BeaconCommitteeFromState(attState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, attState, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, status.Errorf(
codes.Internal,

View File

@@ -543,7 +543,7 @@ func TestServer_ListIndexedAttestations_GenesisEpoch(t *testing.T) {
indexedAtts := make([]*ethpb.IndexedAttestation, len(atts)+len(atts2))
for i := 0; i < len(atts); i++ {
att := atts[i]
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
idxAtt, err := attestation.ConvertToIndexed(ctx, atts[i], committee)
require.NoError(t, err, "Could not convert attestation to indexed")
@@ -551,7 +551,7 @@ func TestServer_ListIndexedAttestations_GenesisEpoch(t *testing.T) {
}
for i := 0; i < len(atts2); i++ {
att := atts2[i]
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
idxAtt, err := attestation.ConvertToIndexed(ctx, atts2[i], committee)
require.NoError(t, err, "Could not convert attestation to indexed")
@@ -650,7 +650,7 @@ func TestServer_ListIndexedAttestations_OldEpoch(t *testing.T) {
indexedAtts := make([]*ethpb.IndexedAttestation, len(atts))
for i := 0; i < len(atts); i++ {
att := atts[i]
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
idxAtt, err := attestation.ConvertToIndexed(ctx, atts[i], committee)
require.NoError(t, err, "Could not convert attestation to indexed")
@@ -861,12 +861,12 @@ func TestServer_StreamIndexedAttestations_OK(t *testing.T) {
require.NoError(t, db.SaveGenesisBlockRoot(ctx, gRoot))
require.NoError(t, db.SaveState(ctx, headState, gRoot))
activeIndices, err := helpers.ActiveValidatorIndices(headState, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, headState, 0)
require.NoError(t, err)
epoch := types.Epoch(0)
attesterSeed, err := helpers.Seed(headState, epoch, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
committees, err := computeCommittees(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)), activeIndices, attesterSeed)
committees, err := computeCommittees(context.Background(), params.BeaconConfig().SlotsPerEpoch.Mul(uint64(epoch)), activeIndices, attesterSeed)
require.NoError(t, err)
count := params.BeaconConfig().SlotsPerEpoch

View File

@@ -557,7 +557,7 @@ func (bs *Server) GetWeakSubjectivityCheckpoint(ctx context.Context, _ *emptypb.
if err != nil {
return nil, status.Error(codes.Internal, "Could not get head state")
}
wsEpoch, err := helpers.LatestWeakSubjectivityEpoch(hs)
wsEpoch, err := helpers.LatestWeakSubjectivityEpoch(ctx, hs)
if err != nil {
return nil, status.Error(codes.Internal, "Could not get weak subjectivity epoch")
}

View File

@@ -778,7 +778,7 @@ func TestServer_GetWeakSubjectivityCheckpoint(t *testing.T) {
StateGen: stategen.New(db),
}
wsEpoch, err := helpers.ComputeWeakSubjectivityPeriod(beaconState)
wsEpoch, err := helpers.ComputeWeakSubjectivityPeriod(context.Background(), beaconState)
require.NoError(t, err)
c, err := server.GetWeakSubjectivityCheckpoint(ctx, &emptypb.Empty{})

View File

@@ -81,12 +81,12 @@ func (bs *Server) retrieveCommitteesForEpoch(
if err != nil {
return nil, nil, status.Error(codes.Internal, "Could not get seed")
}
activeIndices, err := helpers.ActiveValidatorIndices(requestedState, epoch)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, requestedState, epoch)
if err != nil {
return nil, nil, status.Error(codes.Internal, "Could not get active indices")
}
committeesListsBySlot, err := computeCommittees(startSlot, activeIndices, seed)
committeesListsBySlot, err := computeCommittees(ctx, startSlot, activeIndices, seed)
if err != nil {
return nil, nil, status.Errorf(
codes.InvalidArgument,
@@ -114,7 +114,7 @@ func (bs *Server) retrieveCommitteesForRoot(
if err != nil {
return nil, nil, status.Error(codes.Internal, "Could not get seed")
}
activeIndices, err := helpers.ActiveValidatorIndices(requestedState, epoch)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, requestedState, epoch)
if err != nil {
return nil, nil, status.Error(codes.Internal, "Could not get active indices")
}
@@ -123,7 +123,7 @@ func (bs *Server) retrieveCommitteesForRoot(
if err != nil {
return nil, nil, err
}
committeesListsBySlot, err := computeCommittees(startSlot, activeIndices, seed)
committeesListsBySlot, err := computeCommittees(ctx, startSlot, activeIndices, seed)
if err != nil {
return nil, nil, status.Errorf(
codes.InvalidArgument,
@@ -138,6 +138,7 @@ func (bs *Server) retrieveCommitteesForRoot(
// Compute committees given a start slot, active validator indices, and
// the attester seeds value.
func computeCommittees(
ctx context.Context,
startSlot types.Slot,
activeIndices []types.ValidatorIndex,
attesterSeed [32]byte,
@@ -153,7 +154,7 @@ func computeCommittees(
}
committeeItems := make([]*ethpb.BeaconCommittees_CommitteeItem, countAtSlot)
for committeeIndex := uint64(0); committeeIndex < countAtSlot; committeeIndex++ {
committee, err := helpers.BeaconCommittee(activeIndices, attesterSeed, slot, types.CommitteeIndex(committeeIndex))
committee, err := helpers.BeaconCommittee(ctx, activeIndices, attesterSeed, slot, types.CommitteeIndex(committeeIndex))
if err != nil {
return nil, status.Errorf(
codes.Internal,

View File

@@ -47,11 +47,11 @@ func TestServer_ListBeaconCommittees_CurrentEpoch(t *testing.T) {
require.NoError(t, db.SaveGenesisBlockRoot(ctx, gRoot))
require.NoError(t, db.SaveState(ctx, headState, gRoot))
activeIndices, err := helpers.ActiveValidatorIndices(headState, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, headState, 0)
require.NoError(t, err)
attesterSeed, err := helpers.Seed(headState, 0, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
committees, err := computeCommittees(0, activeIndices, attesterSeed)
committees, err := computeCommittees(context.Background(), 0, activeIndices, attesterSeed)
require.NoError(t, err)
wanted := &ethpb.BeaconCommittees{
@@ -103,13 +103,13 @@ func TestServer_ListBeaconCommittees_PreviousEpoch(t *testing.T) {
StateGen: stategen.New(db),
}
activeIndices, err := helpers.ActiveValidatorIndices(headState, 1)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, headState, 1)
require.NoError(t, err)
attesterSeed, err := helpers.Seed(headState, 1, params.BeaconConfig().DomainBeaconAttester)
require.NoError(t, err)
startSlot, err := core.StartSlot(1)
require.NoError(t, err)
wanted, err := computeCommittees(startSlot, activeIndices, attesterSeed)
wanted, err := computeCommittees(context.Background(), startSlot, activeIndices, attesterSeed)
require.NoError(t, err)
tests := []struct {
@@ -173,10 +173,10 @@ func TestRetrieveCommitteesForRoot(t *testing.T) {
require.NoError(t, err)
require.NoError(t, headState.SetSlot(params.BeaconConfig().SlotsPerEpoch*10))
activeIndices, err := helpers.ActiveValidatorIndices(headState, 0)
activeIndices, err := helpers.ActiveValidatorIndices(ctx, headState, 0)
require.NoError(t, err)
wanted, err := computeCommittees(0, activeIndices, seed)
wanted, err := computeCommittees(context.Background(), 0, activeIndices, seed)
require.NoError(t, err)
committees, activeIndices, err := bs.retrieveCommitteesForRoot(context.Background(), gRoot[:])
require.NoError(t, err)

View File

@@ -421,7 +421,7 @@ func (bs *Server) GetValidatorActiveSetChanges(
return nil, status.Errorf(codes.Internal, "Could not get state: %v", err)
}
activeValidatorCount, err := helpers.ActiveValidatorCount(requestedState, core.CurrentEpoch(requestedState))
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, requestedState, core.CurrentEpoch(requestedState))
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get active validator count: %v", err)
}
@@ -603,7 +603,7 @@ func (bs *Server) GetValidatorQueue(
})
// Only activate just enough validators according to the activation churn limit.
activeValidatorCount, err := helpers.ActiveValidatorCount(headState, core.CurrentEpoch(headState))
activeValidatorCount, err := helpers.ActiveValidatorCount(ctx, headState, core.CurrentEpoch(headState))
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get active validator count: %v", err)
}

View File

@@ -1347,7 +1347,7 @@ func TestServer_GetValidatorQueue_PendingActivation(t *testing.T) {
pubKey(2),
pubKey(3),
}
activeValidatorCount, err := helpers.ActiveValidatorCount(headState, core.CurrentEpoch(headState))
activeValidatorCount, err := helpers.ActiveValidatorCount(context.Background(), headState, core.CurrentEpoch(headState))
require.NoError(t, err)
wantChurn, err := helpers.ValidatorChurnLimit(activeValidatorCount)
require.NoError(t, err)
@@ -1389,7 +1389,7 @@ func TestServer_GetValidatorQueue_ExitedValidatorLeavesQueue(t *testing.T) {
wanted := [][]byte{
bytesutil.PadTo([]byte("2"), 48),
}
activeValidatorCount, err := helpers.ActiveValidatorCount(headState, core.CurrentEpoch(headState))
activeValidatorCount, err := helpers.ActiveValidatorCount(context.Background(), headState, core.CurrentEpoch(headState))
require.NoError(t, err)
wantChurn, err := helpers.ValidatorChurnLimit(activeValidatorCount)
require.NoError(t, err)
@@ -1449,7 +1449,7 @@ func TestServer_GetValidatorQueue_PendingExit(t *testing.T) {
pubKey(2),
pubKey(3),
}
activeValidatorCount, err := helpers.ActiveValidatorCount(headState, core.CurrentEpoch(headState))
activeValidatorCount, err := helpers.ActiveValidatorCount(context.Background(), headState, core.CurrentEpoch(headState))
require.NoError(t, err)
wantChurn, err := helpers.ValidatorChurnLimit(activeValidatorCount)
require.NoError(t, err)

View File

@@ -74,7 +74,7 @@ func (ds *Server) GetInclusionSlot(ctx context.Context, req *pbrpc.InclusionSlot
}
targetStates[tr] = s
}
c, err := helpers.BeaconCommitteeFromState(s, a.Data.Slot, a.Data.CommitteeIndex)
c, err := helpers.BeaconCommitteeFromState(ctx, s, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get committee: %v", err)
}

View File

@@ -61,7 +61,7 @@ func TestServer_GetAttestationInclusionSlot(t *testing.T) {
s, _ := util.DeterministicGenesisState(t, 2048)
tr := [32]byte{'a'}
require.NoError(t, bs.StateGen.SaveState(ctx, tr, s))
c, err := helpers.BeaconCommitteeFromState(s, 1, 0)
c, err := helpers.BeaconCommitteeFromState(context.Background(), s, 1, 0)
require.NoError(t, err)
a := &ethpb.Attestation{

View File

@@ -38,7 +38,7 @@ func (vs *Server) SubmitAggregateSelectionProof(ctx context.Context, req *ethpb.
}
epoch := core.SlotToEpoch(req.Slot)
activeValidatorIndices, err := helpers.ActiveValidatorIndices(st, epoch)
activeValidatorIndices, err := helpers.ActiveValidatorIndices(ctx, st, epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get validators: %v", err)
}
@@ -46,7 +46,7 @@ func (vs *Server) SubmitAggregateSelectionProof(ctx context.Context, req *ethpb.
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not get seed: %v", err)
}
committee, err := helpers.BeaconCommittee(activeValidatorIndices, seed, req.Slot, req.CommitteeIndex)
committee, err := helpers.BeaconCommittee(ctx, activeValidatorIndices, seed, req.Slot, req.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -213,7 +213,7 @@ func generateAtt(state state.ReadOnlyBeaconState, index uint64, privKeys []bls.S
Data: &ethpb.AttestationData{CommitteeIndex: 1},
AggregationBits: aggBits,
})
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, err
}
@@ -252,7 +252,7 @@ func generateUnaggregatedAtt(state state.ReadOnlyBeaconState, index uint64, priv
},
AggregationBits: aggBits,
})
committee, err := helpers.BeaconCommitteeFromState(state, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, att.Data.Slot, att.Data.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -129,12 +129,12 @@ func (vs *Server) duties(ctx context.Context, req *ethpb.DutiesRequest) (*ethpb.
return nil, status.Errorf(codes.Internal, "Could not process slots up to %d: %v", epochStartSlot, err)
}
}
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(s, req.Epoch)
committeeAssignments, proposerIndexToSlots, err := helpers.CommitteeAssignments(ctx, s, req.Epoch)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not compute committee assignments: %v", err)
}
// Query the next epoch assignments for committee subnet subscriptions.
nextCommitteeAssignments, _, err := helpers.CommitteeAssignments(s, req.Epoch+1)
nextCommitteeAssignments, _, err := helpers.CommitteeAssignments(ctx, s, req.Epoch+1)
if err != nil {
return nil, status.Errorf(codes.Internal, "Could not compute next committee assignments: %v", err)
}

View File

@@ -245,7 +245,7 @@ func (vs *Server) buildPhase0BlockData(ctx context.Context, req *ethpb.BlockRequ
graffiti := bytesutil.ToBytes32(req.Graffiti)
// Calculate new proposer index.
idx, err := helpers.BeaconProposerIndex(head)
idx, err := helpers.BeaconProposerIndex(ctx, head)
if err != nil {
return nil, fmt.Errorf("could not calculate proposer index %v", err)
}

View File

@@ -311,7 +311,7 @@ func TestProposer_ComputeStateRoot_OK(t *testing.T) {
require.NoError(t, beaconState.SetSlot(beaconState.Slot()+1))
randaoReveal, err := util.RandaoReveal(beaconState, 0, privKeys)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, beaconState)
require.NoError(t, err)
require.NoError(t, beaconState.SetSlot(beaconState.Slot()-1))
req.Block.Body.RandaoReveal = randaoReveal
@@ -1908,7 +1908,7 @@ func TestProposer_FilterAttestation(t *testing.T) {
},
AggregationBits: bitfield.Bitlist{0b00000110},
})
committee, err := helpers.BeaconCommitteeFromState(state, atts[i].Data.Slot, atts[i].Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), state, atts[i].Data.Slot, atts[i].Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(atts[i].AggregationBits, committee)
require.NoError(t, err)

View File

@@ -154,7 +154,7 @@ func executeStateTransitionStateGen(
if err != nil {
return nil, err
}
state, err = altair.ProcessSyncAggregate(state, sa)
state, err = altair.ProcessSyncAggregate(ctx, state, sa)
if err != nil {
return nil, err
}

View File

@@ -117,7 +117,7 @@ func (s *Service) processPendingAtts(ctx context.Context) error {
}
s.setSeenCommitteeIndicesSlot(att.Aggregate.Data.Slot, att.Aggregate.Data.CommitteeIndex, att.Aggregate.AggregationBits)
valCount, err := helpers.ActiveValidatorCount(preState, core.SlotToEpoch(att.Aggregate.Data.Slot))
valCount, err := helpers.ActiveValidatorCount(ctx, preState, core.SlotToEpoch(att.Aggregate.Data.Slot))
if err != nil {
log.WithError(err).Debug("Could not retrieve active validator count")
continue

View File

@@ -78,7 +78,7 @@ func TestProcessPendingAtts_HasBlockSaveUnAggregatedAtt(t *testing.T) {
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -194,7 +194,7 @@ func TestProcessPendingAtts_NoBroadcastWithBadSignature(t *testing.T) {
},
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(s, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), s, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -268,7 +268,7 @@ func TestProcessPendingAtts_HasBlockSaveAggregatedAtt(t *testing.T) {
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)

View File

@@ -479,7 +479,7 @@ func TestService_ProcessPendingBlockOnCorrectSlot(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
st, err := util.NewBeaconState()
@@ -551,7 +551,7 @@ func TestService_ProcessBadPendingBlocks(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
st, err := util.NewBeaconState()

View File

@@ -234,7 +234,7 @@ func validateIndexInCommittee(ctx context.Context, bs state.ReadOnlyBeaconState,
ctx, span := trace.StartSpan(ctx, "sync.validateIndexInCommittee")
defer span.End()
committee, err := helpers.BeaconCommitteeFromState(bs, a.Data.Slot, a.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, bs, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
return err
}
@@ -264,7 +264,7 @@ func validateSelectionIndex(
_, span := trace.StartSpan(ctx, "sync.validateSelectionIndex")
defer span.End()
committee, err := helpers.BeaconCommitteeFromState(bs, data.Slot, data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, bs, data.Slot, data.CommitteeIndex)
if err != nil {
return nil, err
}

View File

@@ -45,7 +45,7 @@ func TestVerifyIndexInCommittee_CanVerify(t *testing.T) {
Target: &ethpb.Checkpoint{Epoch: 0}},
AggregationBits: bf}
committee, err := helpers.BeaconCommitteeFromState(s, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), s, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
indices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -69,7 +69,7 @@ func TestVerifyIndexInCommittee_ExistsInBeaconCommittee(t *testing.T) {
Target: &ethpb.Checkpoint{Epoch: 0}},
AggregationBits: bf}
committee, err := helpers.BeaconCommitteeFromState(s, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), s, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
require.NoError(t, validateIndexInCommittee(ctx, s, att, committee[0]))
@@ -322,7 +322,7 @@ func TestValidateAggregateAndProof_CanValidate(t *testing.T) {
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -416,7 +416,7 @@ func TestVerifyIndexInCommittee_SeenAggregatorEpoch(t *testing.T) {
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
require.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -528,7 +528,7 @@ func TestValidateAggregateAndProof_BadBlock(t *testing.T) {
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)
@@ -619,7 +619,7 @@ func TestValidateAggregateAndProof_RejectWhenAttEpochDoesntEqualTargetEpoch(t *t
AggregationBits: aggBits,
}
committee, err := helpers.BeaconCommitteeFromState(beaconState, att.Data.Slot, att.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), beaconState, att.Data.Slot, att.Data.CommitteeIndex)
assert.NoError(t, err)
attestingIndices, err := attestation.AttestingIndices(att.AggregationBits, committee)
require.NoError(t, err)

View File

@@ -138,7 +138,7 @@ func (s *Service) validateUnaggregatedAttTopic(ctx context.Context, a *eth.Attes
ctx, span := trace.StartSpan(ctx, "sync.validateUnaggregatedAttTopic")
defer span.End()
valCount, err := helpers.ActiveValidatorCount(bs, core.SlotToEpoch(a.Data.Slot))
valCount, err := helpers.ActiveValidatorCount(ctx, bs, core.SlotToEpoch(a.Data.Slot))
if err != nil {
tracing.AnnotateError(span, err)
return pubsub.ValidationIgnore, err
@@ -167,7 +167,7 @@ func (s *Service) validateUnaggregatedAttWithState(ctx context.Context, a *eth.A
ctx, span := trace.StartSpan(ctx, "sync.validateUnaggregatedAttWithState")
defer span.End()
committee, err := helpers.BeaconCommitteeFromState(bs, a.Data.Slot, a.Data.CommitteeIndex)
committee, err := helpers.BeaconCommitteeFromState(ctx, bs, a.Data.Slot, a.Data.CommitteeIndex)
if err != nil {
tracing.AnnotateError(span, err)
return pubsub.ValidationIgnore, err

View File

@@ -254,7 +254,7 @@ func TestService_validateCommitteeIndexBeaconAttestation(t *testing.T) {
helpers.ClearCache()
chain.ValidAttestation = tt.validAttestationSignature
if tt.validAttestationSignature {
com, err := helpers.BeaconCommitteeFromState(savedState, tt.msg.Data.Slot, tt.msg.Data.CommitteeIndex)
com, err := helpers.BeaconCommitteeFromState(context.Background(), savedState, tt.msg.Data.Slot, tt.msg.Data.CommitteeIndex)
require.NoError(t, err)
domain, err := helpers.Domain(savedState.Fork(), tt.msg.Data.Target.Epoch, params.BeaconConfig().DomainBeaconAttester, savedState.GenesisValidatorRoot())
require.NoError(t, err)

View File

@@ -211,7 +211,7 @@ func (s *Service) validateBeaconBlock(ctx context.Context, blk block.SignedBeaco
return err
}
}
idx, err := helpers.BeaconProposerIndex(parentState)
idx, err := helpers.BeaconProposerIndex(ctx, parentState)
if err != nil {
return err
}

View File

@@ -53,7 +53,7 @@ func TestValidateBeaconBlockPubSub_InvalidSignature(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ParentRoot = bRoot[:]
@@ -148,7 +148,7 @@ func TestValidateBeaconBlockPubSub_CanRecoverStateSummary(t *testing.T) {
require.NoError(t, db.SaveState(ctx, beaconState, bRoot))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ParentRoot = bRoot[:]
@@ -211,7 +211,7 @@ func TestValidateBeaconBlockPubSub_IsInCache(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ParentRoot = bRoot[:]
@@ -276,7 +276,7 @@ func TestValidateBeaconBlockPubSub_ValidProposerSignature(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ParentRoot = bRoot[:]
@@ -343,7 +343,7 @@ func TestValidateBeaconBlockPubSub_WithLookahead(t *testing.T) {
blkSlot := params.BeaconConfig().SlotsPerEpoch.Mul(uint64(core.NextEpoch(copied)))
copied, err = transition.ProcessSlots(context.Background(), copied, blkSlot)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ProposerIndex = proposerIdx
@@ -410,7 +410,7 @@ func TestValidateBeaconBlockPubSub_AdvanceEpochsForState(t *testing.T) {
blkSlot := params.BeaconConfig().SlotsPerEpoch * 2
copied, err = transition.ProcessSlots(context.Background(), copied, blkSlot)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ProposerIndex = proposerIdx
@@ -516,7 +516,7 @@ func TestValidateBeaconBlockPubSub_AcceptBlocksFromNearFuture(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
@@ -673,7 +673,7 @@ func TestValidateBeaconBlockPubSub_SeenProposerSlot(t *testing.T) {
bRoot, err := parentBlock.Block.HashTreeRoot()
require.NoError(t, err)
require.NoError(t, db.SaveState(ctx, beaconState, bRoot))
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, beaconState)
require.NoError(t, err)
msg := util.NewBeaconBlock()
@@ -801,7 +801,7 @@ func TestValidateBeaconBlockPubSub_ParentNotFinalizedDescendant(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.Slot = 1
@@ -864,7 +864,7 @@ func TestValidateBeaconBlockPubSub_InvalidParentBlock(t *testing.T) {
require.NoError(t, db.SaveStateSummary(ctx, &ethpb.StateSummary{Root: bRoot[:]}))
copied := beaconState.Copy()
require.NoError(t, copied.SetSlot(1))
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.ProposerIndex = proposerIdx
@@ -914,7 +914,7 @@ func TestValidateBeaconBlockPubSub_InvalidParentBlock(t *testing.T) {
assert.Equal(t, false, result)
require.NoError(t, copied.SetSlot(2))
proposerIdx, err = helpers.BeaconProposerIndex(copied)
proposerIdx, err = helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg = util.NewBeaconBlock()
@@ -957,7 +957,7 @@ func TestValidateBeaconBlockPubSub_RejectEvilBlocksFromFuture(t *testing.T) {
blkSlot := params.BeaconConfig().SlotsPerEpoch * 2
copied, err = transition.ProcessSlots(context.Background(), copied, blkSlot)
require.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(copied)
proposerIdx, err := helpers.BeaconProposerIndex(ctx, copied)
require.NoError(t, err)
msg := util.NewBeaconBlock()

View File

@@ -1,6 +1,7 @@
package epoch_processing
import (
"context"
"path"
"testing"
@@ -27,7 +28,7 @@ func RunRegistryUpdatesTests(t *testing.T, config string) {
}
func processRegistryUpdatesWrapper(t *testing.T, state state.BeaconState) (state.BeaconState, error) {
state, err := epoch.ProcessRegistryUpdates(state)
state, err := epoch.ProcessRegistryUpdates(context.Background(), state)
require.NoError(t, err, "Could not process registry updates")
return state, nil
}

View File

@@ -1,6 +1,7 @@
package operations
import (
"context"
"io/ioutil"
"path"
"strings"
@@ -51,7 +52,7 @@ func RunBlockHeaderTest(t *testing.T, config string) {
// Spectest blocks are not signed, so we'll call NoVerify to skip sig verification.
bodyRoot, err := block.Body.HashTreeRoot()
require.NoError(t, err)
beaconState, err := blocks.ProcessBlockHeaderNoVerify(preBeaconState, block.Slot, block.ProposerIndex, block.ParentRoot, bodyRoot[:])
beaconState, err := blocks.ProcessBlockHeaderNoVerify(context.Background(), preBeaconState, block.Slot, block.ProposerIndex, block.ParentRoot, bodyRoot[:])
if postSSZExists {
require.NoError(t, err)

View File

@@ -30,7 +30,7 @@ func RunSyncCommitteeTest(t *testing.T, config string) {
body := &ethpb.BeaconBlockBodyAltair{SyncAggregate: sc}
RunBlockOperationTest(t, folderPath, body, func(ctx context.Context, s state.BeaconState, b block.SignedBeaconBlock) (state.BeaconState, error) {
return altair.ProcessSyncAggregate(s, body.SyncAggregate)
return altair.ProcessSyncAggregate(context.Background(), s, body.SyncAggregate)
})
})
}

View File

@@ -1,6 +1,7 @@
package epoch_processing
import (
"context"
"path"
"testing"
@@ -27,7 +28,7 @@ func RunRegistryUpdatesTests(t *testing.T, config string) {
}
func processRegistryUpdatesWrapper(t *testing.T, state state.BeaconState) (state.BeaconState, error) {
state, err := epoch.ProcessRegistryUpdates(state)
state, err := epoch.ProcessRegistryUpdates(context.Background(), state)
require.NoError(t, err, "Could not process registry updates")
return state, nil
}

View File

@@ -1,6 +1,7 @@
package operations
import (
"context"
"io/ioutil"
"path"
"strings"
@@ -52,7 +53,7 @@ func RunBlockHeaderTest(t *testing.T, config string) {
// Spectest blocks are not signed, so we'll call NoVerify to skip sig verification.
bodyRoot, err := block.Body.HashTreeRoot()
require.NoError(t, err)
beaconState, err := blocks.ProcessBlockHeaderNoVerify(preBeaconState, block.Slot, block.ProposerIndex, block.ParentRoot, bodyRoot[:])
beaconState, err := blocks.ProcessBlockHeaderNoVerify(context.Background(), preBeaconState, block.Slot, block.ProposerIndex, block.ParentRoot, bodyRoot[:])
if postSSZExists {
require.NoError(t, err)

View File

@@ -299,7 +299,7 @@ func BlockSignatureAltair(
if err := bState.SetSlot(block.Slot); err != nil {
return nil, err
}
proposerIdx, err := helpers.BeaconProposerIndex(bState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), bState)
if err != nil {
return nil, err
}
@@ -405,7 +405,7 @@ func GenerateFullBlockAltair(
return nil, err
}
idx, err := helpers.BeaconProposerIndex(bState)
idx, err := helpers.BeaconProposerIndex(ctx, bState)
if err != nil {
return nil, err
}

View File

@@ -119,7 +119,7 @@ func GenerateAttestations(
headRoot = b
}
activeValidatorCount, err := helpers.ActiveValidatorCount(bState, currentEpoch)
activeValidatorCount, err := helpers.ActiveValidatorCount(context.Background(), bState, currentEpoch)
if err != nil {
return nil, err
}
@@ -154,7 +154,7 @@ func GenerateAttestations(
return nil, err
}
for c := types.CommitteeIndex(0); uint64(c) < committeesPerSlot && uint64(c) < numToGen; c++ {
committee, err := helpers.BeaconCommitteeFromState(bState, slot, c)
committee, err := helpers.BeaconCommitteeFromState(context.Background(), bState, slot, c)
if err != nil {
return nil, err
}

View File

@@ -154,7 +154,7 @@ func GenerateFullBlock(
return nil, err
}
idx, err := helpers.BeaconProposerIndex(bState)
idx, err := helpers.BeaconProposerIndex(ctx, bState)
if err != nil {
return nil, err
}
@@ -312,7 +312,7 @@ func generateAttesterSlashings(
randGen := rand.NewDeterministicGenerator()
for i := uint64(0); i < numSlashings; i++ {
committeeIndex := randGen.Uint64() % params.BeaconConfig().MaxCommitteesPerSlot
committee, err := helpers.BeaconCommitteeFromState(bState, bState.Slot(), types.CommitteeIndex(committeeIndex))
committee, err := helpers.BeaconCommitteeFromState(context.Background(), bState, bState.Slot(), types.CommitteeIndex(committeeIndex))
if err != nil {
return nil, err
}
@@ -376,7 +376,7 @@ func generateVoluntaryExits(
}
func randValIndex(bState state.BeaconState) (types.ValidatorIndex, error) {
activeCount, err := helpers.ActiveValidatorCount(bState, core.CurrentEpoch(bState))
activeCount, err := helpers.ActiveValidatorCount(context.Background(), bState, core.CurrentEpoch(bState))
if err != nil {
return 0, err
}

View File

@@ -2,6 +2,7 @@ package util
import (
"bytes"
"context"
"encoding/hex"
"testing"
@@ -254,7 +255,7 @@ func TestSetupInitialDeposits_1024Entries_PartialDeposits(t *testing.T) {
func TestDeterministicGenesisState_100Validators(t *testing.T) {
validatorCount := uint64(100)
beaconState, privKeys := DeterministicGenesisState(t, validatorCount)
activeValidators, err := helpers.ActiveValidatorCount(beaconState, 0)
activeValidators, err := helpers.ActiveValidatorCount(context.Background(), beaconState, 0)
require.NoError(t, err)
if len(privKeys) != int(validatorCount) {

View File

@@ -21,7 +21,7 @@ import (
// RandaoReveal returns a signature of the requested epoch using the beacon proposer private key.
func RandaoReveal(beaconState state.ReadOnlyBeaconState, epoch types.Epoch, privKeys []bls.SecretKey) ([]byte, error) {
// We fetch the proposer's index as that is whom the RANDAO will be verified against.
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
if err != nil {
return []byte{}, errors.Wrap(err, "could not get beacon proposer index")
}
@@ -59,7 +59,7 @@ func BlockSignature(
if err := bState.SetSlot(block.Slot); err != nil {
return nil, err
}
proposerIdx, err := helpers.BeaconProposerIndex(bState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), bState)
if err != nil {
return nil, err
}

View File

@@ -2,6 +2,7 @@ package util
import (
"bytes"
"context"
"encoding/binary"
"testing"
@@ -19,7 +20,7 @@ func TestBlockSignature(t *testing.T) {
require.NoError(t, err)
require.NoError(t, beaconState.SetSlot(beaconState.Slot()+1))
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
assert.NoError(t, err)
assert.NoError(t, beaconState.SetSlot(beaconState.Slot()-1))
@@ -42,7 +43,7 @@ func TestRandaoReveal(t *testing.T) {
randaoReveal, err := RandaoReveal(beaconState, epoch, privKeys)
assert.NoError(t, err)
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
assert.NoError(t, err)
buf := make([]byte, 32)
binary.LittleEndian.PutUint64(buf, uint64(epoch))

View File

@@ -137,7 +137,7 @@ func generateMarshalledFullStateAndBlock() error {
if err := beaconState.SetSlot(beaconState.Slot() + 1); err != nil {
return err
}
proposerIdx, err := helpers.BeaconProposerIndex(beaconState)
proposerIdx, err := helpers.BeaconProposerIndex(context.Background(), beaconState)
if err != nil {
return err
}