Compare commits

...

15 Commits

Author SHA1 Message Date
prestonvanloon
808ee6b039 Merge branch 'develop' of github.com:prysmaticlabs/prysm into complexity-reduction 2022-05-20 07:21:34 -05:00
Nishant Das
a984605064 Scenario End To End Testing (#10696)
* add new changes

* fix it all

* add nicer scenario

* some more cleanup

* restructure tests

* godoc

* skip one scenario

* space

* fix test

* clean up

* fix conflicts

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
2022-05-20 09:34:10 +00:00
Nishant Das
f28b47bd87 Raise Soft File Descriptor Limit Up To The Hard Limit (#10650)
* add changes

* comment

* kasey's review

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-05-20 08:12:52 +00:00
kasey
588dea83b7 Config registry (#10683)
* test coverage and updates to config twiddlers

* LoadChainConfigFile error if SetActive conflicts

* lint

* wip working around test issues

* more fixes, mass test updates

* lint

* linting

* thanks deepsource!

* fix undeclared vars

* fixing more undefined

* fix a bug, make a bug, repeat

* gaz

* use stock mainnet in case fork schedule matters

* remove unused KnownConfigs

* post-merge cleanup

* eliminating OverrideBeaconConfig outside tests

* more cleanup of OverrideBeaconConfig outside tests

* config for interop w/ genesis gen support

* improve var name

* API on package instead of exported value

* cleanup remainders of "registry" naming

* Nishant feedback

* add ropstein to configset

* lint

* lint #2

* ✂️

* revert accidental commented line

* check if active is nil (replace called on empty)

* Nishant feedback

* replace OverrideBeaconConfig call

* update interop instructions w/ new flag

* don't let interop replace config set via cli flags

Co-authored-by: kasey <kasey@users.noreply.github.com>
2022-05-20 07:16:53 +00:00
Nishant Das
1012ec1915 Drop Down Expected Sync Participation During Fork (#10708)
* reduce

* skip
2022-05-19 12:28:56 +00:00
Raul Jordan
b74947aa75 Fix Slasher E2E Flakiness (#10715)
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-05-19 08:51:31 +00:00
kasey
e3f69e4fad run e2e for 12 epochs (#10717)
* run for the original number of epochs

* to avoid race, wait 1/2 epoch after 1st ready node

* Update testing/endtoend/minimal_e2e_test.go

* Update testing/endtoend/minimal_e2e_test.go

Co-authored-by: Kasey Kirkham <kasey@users.noreply.github.com>
Co-authored-by: Nishant Das <nishdas93@gmail.com>
2022-05-19 06:45:58 +00:00
terencechain
092e9e1d19 Clean up various warnings (#10710)
* Clean up various warnings

* Update beacon-chain/rpc/prysm/v1alpha1/debug/state_test.go

Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>

* Fix redundant casting genState

Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
Co-authored-by: Preston Van Loon <preston@prysmaticlabs.com>
2022-05-19 04:38:04 +00:00
Sammy Rosso
1c51f6d1be Fix Tests in sync/validate_beacon_blocks.go to Pass for the Right Reasons (#10711)
* test: better InvalidSignature validation

Added digest to topic so that the test would not fail at decodePubsubMessage.
Generated a valid signature from an invalid key so that it would be considered invalid.
Added a check for the correct error: ErrSigFailedToVerify.
Related to #9791.

* test: better BlockAlreadyPresentInDB validation

Added digest to topic so that the test would not fail at decodePubsubMessage.
Added a check that the block is ignored.
Related to #9791.

* test: better Syncing validation

Replaced error silencing with NoError assertion.
Added check for the expected validation decision: ValidationIgnore.
Related to #9791.

* test: better IgnoreAndQueueBlocksFromNearFuture validation

Rename test to best describe it's function.
Replace error silencing with a check for the expected error.
Related to #9791.

* test: better RejectBlocksFromFuture validation

Added digest to topic so that the test would not fail at decodePubsubMessage.
Replaced error silencing with NoError assertion.
Added check for the expected validation decision: ValidationIgnore.
Related to #9791.

* test: better RejectBlocksFromThePast validation

Added digest to topic so that the test would not fail at decodePubsubMessage.
Replaced error silencing with a check for the expected error.
Added check for the expected validation decision: ValidationIgnore.
Related to #9791.

* test: better SeenProposerSlot validation

Added digest to topic so that the test would not fail at decodePubsubMessage.
Replaced error silencing with NoError assertion.
Added check for the expected validation decision: ValidationIgnore.
Related to #9791.

* test: fix topic and silenced errors

* set chain service slot

* test: better RejectBlocksFromBadParent validation

Set bad parent block.
Fixed expected errors and validation decision.

* revert: correct log msg for unknown parent block

Co-authored-by: Raul Jordan <raul@prysmaticlabs.com>
Co-authored-by: prylabs-bulldozer[bot] <58059840+prylabs-bulldozer[bot]@users.noreply.github.com>
2022-05-19 03:45:45 +00:00
prestonvanloon
3f6dc6ddf8 Merge branch 'develop' of github.com:prysmaticlabs/prysm into complexity-reduction 2022-05-09 14:56:00 -05:00
prestonvanloon
8b9b9a4700 refactor block streaming, add bellatrix 2022-04-22 14:46:43 -05:00
prestonvanloon
310b5325ef Refactor some metrics logging to be slightly less complex 2022-04-22 14:27:26 -05:00
Preston Van Loon
e8ee1093ae Lower threshold to 90 2022-04-21 13:49:48 +00:00
Preston Van Loon
5c404e823b Merge branch 'develop' into complexity-reduction 2022-04-18 09:34:44 -05:00
prestonvanloon
d55846c050 Lower complexity threshold to 100, fix a few complexity issues 2022-04-18 09:22:28 -05:00
173 changed files with 2948 additions and 1359 deletions

4
.github/CODEOWNERS vendored
View File

@@ -14,3 +14,7 @@ deps.bzl @prysmaticlabs/core-team
/beacon-chain/state/v2/ @rkapka @nisdas
/beacon-chain/state/v3/ @rkapka @nisdas
/beacon-chain/state/state-native/ @rkapka @nisdas
# Setting new static analysis exclusions generally should not occur.
# Any additions of exclusions should be approved by Preston and/or Nishant.
nogo_config.json @prestonvanloon @nisdas

View File

@@ -128,13 +128,13 @@ nogo(
"//tools/analyzers/recursivelock:go_default_library",
"//tools/analyzers/shadowpredecl:go_default_library",
"//tools/analyzers/slicedirect:go_default_library",
"//tools/analyzers/uintcast:go_default_library",
] + select({
# nogo checks that fail with coverage enabled.
":coverage_enabled": [],
"//conditions:default": [
"@org_golang_x_tools//go/analysis/passes/lostcancel:go_default_library",
"@org_golang_x_tools//go/analysis/passes/composite:go_default_library",
"//tools/analyzers/uintcast:go_default_library",
],
}),
)

View File

@@ -26,15 +26,18 @@ You can use `bazel run //tools/genesis-state-gen` to create a deterministic gene
### Usage
- **--genesis-time** uint: Unix timestamp used as the genesis time in the generated genesis state (defaults to now)
- **--mainnet-config** bool: Select whether genesis state should be generated with mainnet or minimal (default) params
- **--num-validators** int: Number of validators to deterministically include in the generated genesis state
- **--output-ssz** string: Output filename of the SSZ marshaling of the generated genesis state
- **--config-name=interop** string: name of the beacon chain config to use when generating the state. ex mainnet|minimal|interop
**deprecated flag: use --config-name instead**
- **--mainnet-config** bool: Select whether genesis state should be generated with mainnet or minimal (default) params
The example below creates 64 validator keys, instantiates a genesis state with those 64 validators and with genesis unix timestamp 1567542540,
and finally writes a ssz encoded output to ~/Desktop/genesis.ssz. This file can be used to kickstart the beacon chain in the next section.
and finally writes a ssz encoded output to ~/Desktop/genesis.ssz. This file can be used to kickstart the beacon chain in the next section. When using the `--interop-*` flags, the beacon node will assume the `interop` config should be used, unless a different config is specified on the command line.
```
bazel run //tools/genesis-state-gen -- --output-ssz ~/Desktop/genesis.ssz --num-validators 64 --genesis-time 1567542540
bazel run //tools/genesis-state-gen -- --config-name interop --output-ssz ~/Desktop/genesis.ssz --num-validators 64 --genesis-time 1567542540
```
## Launching a Beacon Node + Validator Client
@@ -46,8 +49,10 @@ Open up two terminal windows, run:
```
bazel run //beacon-chain -- \
--bootstrap-node= \
--deposit-contract $(curl -s https://prylabs.net/contract) \
--deposit-contract 0x8A04d14125D0FDCDc742F4A05C051De07232EDa4 \
--datadir=/tmp/beacon-chain-interop \
--force-clear-db \
--min-sync-peers=0 \
--interop-num-validators 64 \
--interop-eth1data-votes
```
@@ -69,8 +74,10 @@ Assuming you generated a `genesis.ssz` file with 64 validators, open up two term
```
bazel run //beacon-chain -- \
--bootstrap-node= \
--deposit-contract $(curl -s https://prylabs.net/contract) \
--deposit-contract 0x8A04d14125D0FDCDc742F4A05C051De07232EDa4 \
--datadir=/tmp/beacon-chain-interop \
--force-clear-db \
--min-sync-peers=0 \
--interop-genesis-state /path/to/genesis.ssz \
--interop-eth1data-votes
```

View File

@@ -46,10 +46,8 @@ const (
type StateOrBlockId string
const (
IdFinalized StateOrBlockId = "finalized"
IdGenesis StateOrBlockId = "genesis"
IdHead StateOrBlockId = "head"
IdJustified StateOrBlockId = "justified"
IdGenesis StateOrBlockId = "genesis"
IdHead StateOrBlockId = "head"
)
var ErrMalformedHostname = errors.New("hostname must include port, separated by one colon, like example.com:3500")
@@ -60,7 +58,7 @@ func IdFromRoot(r [32]byte) StateOrBlockId {
return StateOrBlockId(fmt.Sprintf("%#x", r))
}
// IdFromRoot encodes a Slot in the format expected by the API in places where a slot can be used to identify
// IdFromSlot encodes a Slot in the format expected by the API in places where a slot can be used to identify
// a BeaconState or SignedBeaconBlock.
func IdFromSlot(s types.Slot) StateOrBlockId {
return StateOrBlockId(strconv.FormatUint(uint64(s), 10))

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -34,7 +34,7 @@ func TestService_ReceiveBlock(t *testing.T) {
return blk
}
params.SetupTestConfigCleanup(t)
bc := params.BeaconConfig()
bc := params.BeaconConfig().Copy()
bc.ShardCommitteePeriod = 0 // Required for voluntary exits test in reasonable time.
params.OverrideBeaconConfig(bc)

View File

@@ -376,7 +376,7 @@ func (_ *ChainService) HeadGenesisValidatorsRoot() [32]byte {
return [32]byte{}
}
// VerifyBlkDescendant mocks VerifyBlkDescendant and always returns nil.
// VerifyFinalizedBlkDescendant mocks VerifyBlkDescendant and always returns nil.
func (s *ChainService) VerifyFinalizedBlkDescendant(_ context.Context, _ [32]byte) error {
return s.VerifyBlkDescendantErr
}
@@ -451,7 +451,7 @@ func (s *ChainService) IsOptimisticForRoot(_ context.Context, _ [32]byte) (bool,
return s.Optimistic, nil
}
// ProcessAttestationsAndUpdateHead mocks the same method in the chain service.
// UpdateHead mocks the same method in the chain service.
func (s *ChainService) UpdateHead(_ context.Context) error { return nil }
// ReceiveAttesterSlashing mocks the same method in the chain service.

View File

@@ -110,7 +110,7 @@ func TestCommitteeCache_CanRotate(t *testing.T) {
sort.Slice(k, func(i, j int) bool {
return k[i].(string) < k[j].(string)
})
wanted := end - int(maxCommitteesCacheSize)
wanted := end - maxCommitteesCacheSize
s := bytesutil.ToBytes32([]byte(strconv.Itoa(wanted)))
assert.Equal(t, key(s), k[0], "incorrect key received for slot 190")

View File

@@ -20,7 +20,9 @@ import (
var runAmount = 25
func BenchmarkExecuteStateTransition_FullBlock(b *testing.B) {
benchmark.SetBenchmarkConfig()
undo, err := benchmark.SetBenchmarkConfig()
require.NoError(b, err)
defer undo()
beaconState, err := benchmark.PreGenState1Epoch()
require.NoError(b, err)
cleanStates := clonedStates(beaconState)
@@ -37,7 +39,9 @@ func BenchmarkExecuteStateTransition_FullBlock(b *testing.B) {
}
func BenchmarkExecuteStateTransition_WithCache(b *testing.B) {
benchmark.SetBenchmarkConfig()
undo, err := benchmark.SetBenchmarkConfig()
require.NoError(b, err)
defer undo()
beaconState, err := benchmark.PreGenState1Epoch()
require.NoError(b, err)
@@ -67,7 +71,9 @@ func BenchmarkExecuteStateTransition_WithCache(b *testing.B) {
}
func BenchmarkProcessEpoch_2FullEpochs(b *testing.B) {
benchmark.SetBenchmarkConfig()
undo, err := benchmark.SetBenchmarkConfig()
require.NoError(b, err)
defer undo()
beaconState, err := benchmark.PreGenstateFullEpochs()
require.NoError(b, err)

View File

@@ -579,10 +579,10 @@ func TestProcessSlots_OnlyAltairEpoch(t *testing.T) {
func TestProcessSlots_OnlyBellatrixEpoch(t *testing.T) {
transition.SkipSlotCache.Disable()
conf := params.BeaconConfig()
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig().Copy()
conf.BellatrixForkEpoch = 5
params.OverrideBeaconConfig(conf)
defer params.UseMainnetConfig()
st, _ := util.DeterministicGenesisStateBellatrix(t, params.BeaconConfig().MaxValidatorsPerCommittee)
require.NoError(t, st.SetSlot(params.BeaconConfig().SlotsPerEpoch*6))

View File

@@ -14,7 +14,7 @@ var ErrNotFoundState = kv.ErrNotFoundState
// ErrNotFoundOriginBlockRoot wraps ErrNotFound for an error specific to the origin block root.
var ErrNotFoundOriginBlockRoot = kv.ErrNotFoundOriginBlockRoot
// ErrNotFoundOriginBlockRoot wraps ErrNotFound for an error specific to the origin block root.
// ErrNotFoundBackfillBlockRoot wraps ErrNotFound for an error specific to the backfill block root.
var ErrNotFoundBackfillBlockRoot = kv.ErrNotFoundBackfillBlockRoot
// ErrNotFoundGenesisBlockRoot means no genesis block root was found, indicating the db was not initialized with genesis

View File

@@ -16,7 +16,7 @@ var ErrNotFoundOriginBlockRoot = errors.Wrap(ErrNotFound, "OriginBlockRoot")
// ErrNotFoundGenesisBlockRoot means no genesis block root was found, indicating the db was not initialized with genesis
var ErrNotFoundGenesisBlockRoot = errors.Wrap(ErrNotFound, "OriginGenesisRoot")
// ErrNotFoundOriginBlockRoot is an error specifically for the origin block root getter
// ErrNotFoundBackfillBlockRoot is an error specifically for the origin block root getter
var ErrNotFoundBackfillBlockRoot = errors.Wrap(ErrNotFound, "BackfillBlockRoot")
// ErrNotFoundFeeRecipient is a not found error specifically for the fee recipient getter

View File

@@ -9,6 +9,7 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/db/iface"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
"github.com/prysmaticlabs/prysm/testing/util"
)
@@ -28,41 +29,70 @@ func testGenesisDataSaved(t *testing.T, db iface.Database) {
ctx := context.Background()
gb, err := db.GenesisBlock(ctx)
assert.NoError(t, err)
assert.NotNil(t, gb)
require.NoError(t, err)
require.NotNil(t, gb)
gbHTR, err := gb.Block().HashTreeRoot()
assert.NoError(t, err)
require.NoError(t, err)
gss, err := db.StateSummary(ctx, gbHTR)
assert.NoError(t, err)
assert.NotNil(t, gss)
require.NoError(t, err)
require.NotNil(t, gss)
head, err := db.HeadBlock(ctx)
assert.NoError(t, err)
assert.NotNil(t, head)
require.NoError(t, err)
require.NotNil(t, head)
headHTR, err := head.Block().HashTreeRoot()
assert.NoError(t, err)
assert.Equal(t, gbHTR, headHTR, "head block does not match genesis block")
require.NoError(t, err)
require.Equal(t, gbHTR, headHTR, "head block does not match genesis block")
}
func TestLoadGenesisFromFile(t *testing.T) {
// for this test to work, we need the active config to have these properties:
// - fork version schedule that matches mainnnet.genesis.ssz
// - name that does not match params.MainnetName - otherwise we'll trigger the codepath that loads the state
// from the compiled binary.
// to do that, first we need to rewrite the mainnet fork schedule so it won't conflict with a renamed config that
// uses the mainnet fork schedule. construct the differently named mainnet config and set it active.
// finally, revert all this at the end of the test.
// first get the real mainnet out of the way by overwriting it schedule.
cfg, err := params.ByName(params.MainnetName)
require.NoError(t, err)
cfg = cfg.Copy()
reversioned := cfg.Copy()
params.FillTestVersions(reversioned, 127)
undo, err := params.SetActiveWithUndo(reversioned)
require.NoError(t, err)
defer func() {
require.NoError(t, undo())
}()
// then set up a new config, which uses the real mainnet schedule, and activate it
cfg.ConfigName = "genesis-test"
undo2, err := params.SetActiveWithUndo(cfg)
require.NoError(t, err)
defer func() {
require.NoError(t, undo2())
}()
fp := "testdata/mainnet.genesis.ssz"
rfp, err := bazel.Runfile(fp)
if err == nil {
fp = rfp
}
sb, err := os.ReadFile(fp)
assert.NoError(t, err)
require.NoError(t, err)
db := setupDB(t)
assert.NoError(t, db.LoadGenesis(context.Background(), sb))
require.NoError(t, db.LoadGenesis(context.Background(), sb))
testGenesisDataSaved(t, db)
// Loading the same genesis again should not throw an error
assert.NoError(t, err)
assert.NoError(t, db.LoadGenesis(context.Background(), sb))
require.NoError(t, err)
require.NoError(t, db.LoadGenesis(context.Background(), sb))
testGenesisDataSaved(t, db)
}
func TestLoadGenesisFromFile_mismatchedForkVersion(t *testing.T) {
@@ -80,11 +110,15 @@ func TestLoadGenesisFromFile_mismatchedForkVersion(t *testing.T) {
}
func TestEnsureEmbeddedGenesis(t *testing.T) {
// Embedded Genesis works with Mainnet config
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg.ConfigName = params.MainnetName
params.OverrideBeaconConfig(cfg)
// Embedded Genesis works with Mainnet config
cfg := params.MainnetConfig().Copy()
cfg.SecondsPerSlot = 1
undo, err := params.SetActiveWithUndo(cfg)
require.NoError(t, err)
defer func() {
require.NoError(t, undo())
}()
ctx := context.Background()
db := setupDB(t)

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -12,11 +12,9 @@ import (
)
func TestSaveOrigin(t *testing.T) {
// Embedded Genesis works with Mainnet config
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg.ConfigName = params.MainnetName
params.OverrideBeaconConfig(cfg)
// Embedded Genesis works with Mainnet config
params.OverrideBeaconConfig(params.MainnetConfig().Copy())
ctx := context.Background()
db := setupDB(t)

View File

@@ -130,7 +130,7 @@ func TestUpdateSyncCommitteeTrackedVals(t *testing.T) {
func TestNewService(t *testing.T) {
config := &ValidatorMonitorConfig{}
tracked := []types.ValidatorIndex{}
var tracked []types.ValidatorIndex
ctx := context.Background()
_, err := NewService(ctx, config, tracked)
require.NoError(t, err)

View File

@@ -23,19 +23,22 @@ func configureTracing(cliCtx *cli.Context) error {
)
}
func configureChainConfig(cliCtx *cli.Context) {
func configureChainConfig(cliCtx *cli.Context) error {
if cliCtx.IsSet(cmd.ChainConfigFileFlag.Name) {
chainConfigFileName := cliCtx.String(cmd.ChainConfigFileFlag.Name)
params.LoadChainConfigFile(chainConfigFileName, nil)
return params.LoadChainConfigFile(chainConfigFileName, nil)
}
return nil
}
func configureHistoricalSlasher(cliCtx *cli.Context) {
func configureHistoricalSlasher(cliCtx *cli.Context) error {
if cliCtx.Bool(flags.HistoricalSlasherNode.Name) {
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
// Save a state every 4 epochs.
c.SlotsPerArchivedPoint = params.BeaconConfig().SlotsPerEpoch * 4
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
cmdConfig := cmd.Get()
// Allow up to 4096 attestations at a time to be requested from the beacon nde.
cmdConfig.MaxRPCPageSize = int(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().MaxAttestations)) // lint:ignore uintcast -- Page size should not exceed int64 with these constants.
@@ -46,40 +49,52 @@ func configureHistoricalSlasher(cliCtx *cli.Context) {
cmdConfig.MaxRPCPageSize,
)
}
return nil
}
func configureSafeSlotsToImportOptimistically(cliCtx *cli.Context) {
func configureSafeSlotsToImportOptimistically(cliCtx *cli.Context) error {
if cliCtx.IsSet(flags.SafeSlotsToImportOptimistically.Name) {
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
c.SafeSlotsToImportOptimistically = types.Slot(cliCtx.Int(flags.SafeSlotsToImportOptimistically.Name))
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
}
return nil
}
func configureSlotsPerArchivedPoint(cliCtx *cli.Context) {
func configureSlotsPerArchivedPoint(cliCtx *cli.Context) error {
if cliCtx.IsSet(flags.SlotsPerArchivedPoint.Name) {
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
c.SlotsPerArchivedPoint = types.Slot(cliCtx.Int(flags.SlotsPerArchivedPoint.Name))
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
}
return nil
}
func configureEth1Config(cliCtx *cli.Context) {
func configureEth1Config(cliCtx *cli.Context) error {
c := params.BeaconConfig().Copy()
if cliCtx.IsSet(flags.ChainID.Name) {
c := params.BeaconConfig()
c.DepositChainID = cliCtx.Uint64(flags.ChainID.Name)
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
}
if cliCtx.IsSet(flags.NetworkID.Name) {
c := params.BeaconConfig()
c.DepositNetworkID = cliCtx.Uint64(flags.NetworkID.Name)
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
}
if cliCtx.IsSet(flags.DepositContractFlag.Name) {
c := params.BeaconConfig()
c.DepositContractAddress = cliCtx.String(flags.DepositContractFlag.Name)
params.OverrideBeaconConfig(c)
if err := params.SetActive(c); err != nil {
return err
}
}
return nil
}
func configureNetwork(cliCtx *cli.Context) {
@@ -95,17 +110,22 @@ func configureNetwork(cliCtx *cli.Context) {
}
}
func configureInteropConfig(cliCtx *cli.Context) {
func configureInteropConfig(cliCtx *cli.Context) error {
// an explicit chain config was specified, don't mess with it
if cliCtx.IsSet(cmd.ChainConfigFileFlag.Name) {
return nil
}
genStateIsSet := cliCtx.IsSet(flags.InteropGenesisStateFlag.Name)
genTimeIsSet := cliCtx.IsSet(flags.InteropGenesisTimeFlag.Name)
numValsIsSet := cliCtx.IsSet(flags.InteropNumValidatorsFlag.Name)
votesIsSet := cliCtx.IsSet(flags.InteropMockEth1DataVotesFlag.Name)
if genStateIsSet || genTimeIsSet || numValsIsSet || votesIsSet {
bCfg := params.BeaconConfig()
bCfg.ConfigName = "interop"
params.OverrideBeaconConfig(bCfg)
if err := params.SetActive(params.InteropConfig().Copy()); err != nil {
return err
}
}
return nil
}
func configureExecutionSetting(cliCtx *cli.Context) error {
@@ -113,7 +133,7 @@ func configureExecutionSetting(cliCtx *cli.Context) error {
return nil
}
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
ha := cliCtx.String(flags.SuggestedFeeRecipient.Name)
if !common.IsHexAddress(ha) {
return fmt.Errorf("%s is not a valid fee recipient address", ha)
@@ -130,6 +150,5 @@ func configureExecutionSetting(cliCtx *cli.Context) error {
"to prevent spelling mistakes in your fee recipient Ethereum address", ha, checksumAddress.Hex())
}
c.DefaultFeeRecipient = checksumAddress
params.OverrideBeaconConfig(c)
return nil
return params.SetActive(c)
}

View File

@@ -26,7 +26,7 @@ func TestConfigureHistoricalSlasher(t *testing.T) {
set.Bool(flags.HistoricalSlasherNode.Name, true, "")
cliCtx := cli.NewContext(&app, set, nil)
configureHistoricalSlasher(cliCtx)
require.NoError(t, configureHistoricalSlasher(cliCtx))
assert.Equal(t, params.BeaconConfig().SlotsPerEpoch*4, params.BeaconConfig().SlotsPerArchivedPoint)
assert.LogsContain(t, hook,
@@ -46,7 +46,7 @@ func TestConfigureSafeSlotsToImportOptimistically(t *testing.T) {
require.NoError(t, set.Set(flags.SafeSlotsToImportOptimistically.Name, strconv.Itoa(128)))
cliCtx := cli.NewContext(&app, set, nil)
configureSafeSlotsToImportOptimistically(cliCtx)
require.NoError(t, configureSafeSlotsToImportOptimistically(cliCtx))
assert.Equal(t, types.Slot(128), params.BeaconConfig().SafeSlotsToImportOptimistically)
}
@@ -60,7 +60,7 @@ func TestConfigureSlotsPerArchivedPoint(t *testing.T) {
require.NoError(t, set.Set(flags.SlotsPerArchivedPoint.Name, strconv.Itoa(100)))
cliCtx := cli.NewContext(&app, set, nil)
configureSlotsPerArchivedPoint(cliCtx)
require.NoError(t, configureSlotsPerArchivedPoint(cliCtx))
assert.Equal(t, types.Slot(100), params.BeaconConfig().SlotsPerArchivedPoint)
}
@@ -78,7 +78,7 @@ func TestConfigureProofOfWork(t *testing.T) {
require.NoError(t, set.Set(flags.DepositContractFlag.Name, "deposit-contract"))
cliCtx := cli.NewContext(&app, set, nil)
configureEth1Config(cliCtx)
require.NoError(t, configureEth1Config(cliCtx))
assert.Equal(t, uint64(100), params.BeaconConfig().DepositChainID)
assert.Equal(t, uint64(200), params.BeaconConfig().DepositNetworkID)
@@ -198,7 +198,7 @@ func TestConfigureInterop(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
configureInteropConfig(tt.flagSetter())
require.NoError(t, configureInteropConfig(tt.flagSetter()))
assert.DeepEqual(t, tt.configName, params.BeaconConfig().ConfigName)
})
}

View File

@@ -118,16 +118,32 @@ func New(cliCtx *cli.Context, opts ...Option) (*BeaconNode, error) {
return nil, err
}
prereqs.WarnIfPlatformNotSupported(cliCtx.Context)
features.ConfigureBeaconChain(cliCtx)
cmd.ConfigureBeaconChain(cliCtx)
if err := features.ConfigureBeaconChain(cliCtx); err != nil {
return nil, err
}
if err := cmd.ConfigureBeaconChain(cliCtx); err != nil {
return nil, err
}
flags.ConfigureGlobalFlags(cliCtx)
configureChainConfig(cliCtx)
configureHistoricalSlasher(cliCtx)
configureSafeSlotsToImportOptimistically(cliCtx)
configureSlotsPerArchivedPoint(cliCtx)
configureEth1Config(cliCtx)
if err := configureChainConfig(cliCtx); err != nil {
return nil, err
}
if err := configureHistoricalSlasher(cliCtx); err != nil {
return nil, err
}
if err := configureSafeSlotsToImportOptimistically(cliCtx); err != nil {
return nil, err
}
if err := configureSlotsPerArchivedPoint(cliCtx); err != nil {
return nil, err
}
if err := configureEth1Config(cliCtx); err != nil {
return nil, err
}
configureNetwork(cliCtx)
configureInteropConfig(cliCtx)
if err := configureInteropConfig(cliCtx); err != nil {
return nil, err
}
if err := configureExecutionSetting(cliCtx); err != nil {
return nil, err
}

View File

@@ -410,7 +410,7 @@ func TestRefreshENR_ForkBoundaries(t *testing.T) {
assert.NoError(t, err)
// Update params
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.AltairForkEpoch = 5
params.OverrideBeaconConfig(cfg)
params.BeaconConfig().InitializeForkSchedule()
@@ -441,7 +441,7 @@ func TestRefreshENR_ForkBoundaries(t *testing.T) {
assert.NoError(t, err)
// Update params
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.AltairForkEpoch = 5
params.OverrideBeaconConfig(cfg)
params.BeaconConfig().InitializeForkSchedule()
@@ -471,7 +471,7 @@ func TestRefreshENR_ForkBoundaries(t *testing.T) {
assert.NoError(t, err)
// Update params
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.AltairForkEpoch = 5
params.OverrideBeaconConfig(cfg)
params.BeaconConfig().InitializeForkSchedule()

View File

@@ -114,6 +114,7 @@ func TestStartDiscv5_DifferentForkDigests(t *testing.T) {
}
func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
logrus.SetLevel(logrus.TraceLevel)
port := 2000
@@ -136,14 +137,13 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
UDPPort: uint(port),
}
params.SetupTestConfigCleanup(t)
var listeners []*discover.UDPv5
for i := 1; i <= 5; i++ {
port = 3000 + i
cfg.UDPPort = uint(port)
ipAddr, pkey := createAddrAndPrivKey(t)
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
nextForkEpoch := types.Epoch(i)
c.ForkVersionSchedule[[4]byte{'A', 'B', 'C', 'D'}] = nextForkEpoch
params.OverrideBeaconConfig(c)
@@ -209,7 +209,7 @@ func TestStartDiscv5_SameForkDigests_DifferentNextForkData(t *testing.T) {
func TestDiscv5_AddRetrieveForkEntryENR(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
c.ForkVersionSchedule = map[[4]byte]types.Epoch{
bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion): 0,
{0, 0, 0, 1}: 1,
@@ -264,7 +264,7 @@ func TestAddForkEntry_Genesis(t *testing.T) {
db, err := enode.OpenDB("")
require.NoError(t, err)
bCfg := params.BeaconConfig()
bCfg := params.MainnetConfig().Copy()
bCfg.ForkVersionSchedule = map[[4]byte]types.Epoch{}
bCfg.ForkVersionSchedule[bytesutil.ToBytes4(params.BeaconConfig().GenesisForkVersion)] = bCfg.GenesisEpoch
params.OverrideBeaconConfig(bCfg)

View File

@@ -15,7 +15,7 @@ import (
func TestCorrect_ActiveValidatorsCount(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg := params.MainnetConfig().Copy()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)

View File

@@ -12,6 +12,7 @@ import (
)
func TestMappingHasNoDuplicates(t *testing.T) {
params.SetupTestConfigCleanup(t)
m := make(map[reflect.Type]bool)
for _, v := range gossipTopicMappings {
if _, ok := m[reflect.TypeOf(v)]; ok {
@@ -23,7 +24,7 @@ func TestMappingHasNoDuplicates(t *testing.T) {
func TestGossipTopicMappings_CorrectBlockType(t *testing.T) {
params.SetupTestConfigCleanup(t)
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
altairForkEpoch := eth2types.Epoch(100)
BellatrixForkEpoch := eth2types.Epoch(200)

View File

@@ -17,6 +17,7 @@ import (
)
func TestMsgID_HashesCorrectly(t *testing.T) {
params.SetupTestConfigCleanup(t)
genesisValidatorsRoot := bytesutil.PadTo([]byte{'A'}, 32)
d, err := forks.CreateForkDigest(time.Now(), genesisValidatorsRoot)
assert.NoError(t, err)
@@ -36,6 +37,7 @@ func TestMsgID_HashesCorrectly(t *testing.T) {
}
func TestMessageIDFunction_HashesCorrectlyAltair(t *testing.T) {
params.SetupTestConfigCleanup(t)
genesisValidatorsRoot := bytesutil.PadTo([]byte{'A'}, 32)
d, err := signing.ComputeForkDigest(params.BeaconConfig().AltairForkVersion, genesisValidatorsRoot)
assert.NoError(t, err)
@@ -65,6 +67,7 @@ func TestMessageIDFunction_HashesCorrectlyAltair(t *testing.T) {
}
func TestMessageIDFunction_HashesCorrectlyBellatrix(t *testing.T) {
params.SetupTestConfigCleanup(t)
genesisValidatorsRoot := bytesutil.PadTo([]byte{'A'}, 32)
d, err := signing.ComputeForkDigest(params.BeaconConfig().BellatrixForkVersion, genesisValidatorsRoot)
assert.NoError(t, err)
@@ -94,6 +97,7 @@ func TestMessageIDFunction_HashesCorrectlyBellatrix(t *testing.T) {
}
func TestMsgID_WithNilTopic(t *testing.T) {
params.SetupTestConfigCleanup(t)
msg := &pubsubpb.Message{
Data: make([]byte, 32),
Topic: nil,

View File

@@ -17,6 +17,7 @@ import (
)
func TestPrivateKeyLoading(t *testing.T) {
params.SetupTestConfigCleanup(t)
file, err := os.CreateTemp(t.TempDir(), "key")
require.NoError(t, err)
key, _, err := crypto.GenerateSecp256k1Key(rand.Reader)
@@ -44,6 +45,7 @@ func TestPrivateKeyLoading(t *testing.T) {
}
func TestIPV6Support(t *testing.T) {
params.SetupTestConfigCleanup(t)
key, err := gethCrypto.GenerateKey()
require.NoError(t, err)
db, err := enode.OpenDB("")

View File

@@ -4,10 +4,12 @@ import (
"testing"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
)
func TestOverlayParameters(t *testing.T) {
params.SetupTestConfigCleanup(t)
pms := pubsubGossipParam()
assert.Equal(t, gossipSubD, pms.D, "gossipSubD")
assert.Equal(t, gossipSubDlo, pms.Dlo, "gossipSubDlo")
@@ -15,6 +17,7 @@ func TestOverlayParameters(t *testing.T) {
}
func TestGossipParameters(t *testing.T) {
params.SetupTestConfigCleanup(t)
setPubSubParameters()
pms := pubsubGossipParam()
assert.Equal(t, gossipSubMcacheLen, pms.HistoryLength, "gossipSubMcacheLen")
@@ -23,6 +26,7 @@ func TestGossipParameters(t *testing.T) {
}
func TestFanoutParameters(t *testing.T) {
params.SetupTestConfigCleanup(t)
pms := pubsubGossipParam()
if pms.FanoutTTL != gossipSubFanoutTTL {
t.Errorf("gossipSubFanoutTTL, wanted: %d, got: %d", gossipSubFanoutTTL, pms.FanoutTTL)
@@ -30,6 +34,7 @@ func TestFanoutParameters(t *testing.T) {
}
func TestHeartbeatParameters(t *testing.T) {
params.SetupTestConfigCleanup(t)
pms := pubsubGossipParam()
if pms.HeartbeatInterval != gossipSubHeartbeatInterval {
t.Errorf("gossipSubHeartbeatInterval, wanted: %d, got: %d", gossipSubHeartbeatInterval, pms.HeartbeatInterval)
@@ -37,6 +42,7 @@ func TestHeartbeatParameters(t *testing.T) {
}
func TestMiscParameters(t *testing.T) {
params.SetupTestConfigCleanup(t)
setPubSubParameters()
assert.Equal(t, randomSubD, pubsub.RandomSubD, "randomSubD")
}

View File

@@ -13,6 +13,7 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/encoder"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/network/forks"
"github.com/prysmaticlabs/prysm/testing/assert"
@@ -21,6 +22,7 @@ import (
)
func TestService_CanSubscribe(t *testing.T) {
params.SetupTestConfigCleanup(t)
currentFork := [4]byte{0x01, 0x02, 0x03, 0x04}
validProtocolSuffix := "/" + encoder.ProtocolSuffixSSZSnappy
genesisTime := time.Now()
@@ -115,11 +117,13 @@ func TestService_CanSubscribe(t *testing.T) {
}
func TestService_CanSubscribe_uninitialized(t *testing.T) {
params.SetupTestConfigCleanup(t)
s := &Service{}
require.Equal(t, false, s.CanSubscribe("foo"))
}
func Test_scanfcheck(t *testing.T) {
params.SetupTestConfigCleanup(t)
type args struct {
input string
format string
@@ -191,6 +195,7 @@ func Test_scanfcheck(t *testing.T) {
}
func TestGossipTopicMapping_scanfcheck_GossipTopicFormattingSanityCheck(t *testing.T) {
params.SetupTestConfigCleanup(t)
// scanfcheck only supports integer based substitutions at the moment. Any others will
// inaccurately fail validation.
for _, topic := range AllTopics() {
@@ -208,6 +213,7 @@ func TestGossipTopicMapping_scanfcheck_GossipTopicFormattingSanityCheck(t *testi
}
func TestService_FilterIncomingSubscriptions(t *testing.T) {
params.SetupTestConfigCleanup(t)
validProtocolSuffix := "/" + encoder.ProtocolSuffixSSZSnappy
genesisTime := time.Now()
valRoot := [32]byte{}
@@ -328,6 +334,7 @@ func TestService_FilterIncomingSubscriptions(t *testing.T) {
}
func TestService_MonitorsStateForkUpdates(t *testing.T) {
params.SetupTestConfigCleanup(t)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
notifier := &mock.MockStateNotifier{}

View File

@@ -15,6 +15,7 @@ import (
)
func TestVerifyRPCMappings(t *testing.T) {
params.SetupTestConfigCleanup(t)
assert.NoError(t, VerifyTopicMapping(RPCStatusTopicV1, &pb.Status{}), "Failed to verify status rpc topic")
assert.NotNil(t, VerifyTopicMapping(RPCStatusTopicV1, new([]byte)), "Incorrect message type verified for status rpc topic")
@@ -25,6 +26,7 @@ func TestVerifyRPCMappings(t *testing.T) {
}
func TestTopicDeconstructor(t *testing.T) {
params.SetupTestConfigCleanup(t)
tt := []struct {
name string
topic string
@@ -81,7 +83,7 @@ func TestTopicDeconstructor(t *testing.T) {
func TestTopicFromMessage_CorrectType(t *testing.T) {
params.SetupTestConfigCleanup(t)
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
forkEpoch := eth2types.Epoch(100)
bCfg.AltairForkEpoch = forkEpoch
bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = eth2types.Epoch(100)

View File

@@ -6,17 +6,18 @@ import (
"testing"
"time"
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/testing/util"
"github.com/libp2p/go-libp2p-core/network"
testp2p "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing"
"github.com/prysmaticlabs/prysm/config/params"
ethpb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
"github.com/prysmaticlabs/prysm/testing/util"
"google.golang.org/protobuf/proto"
)
func TestService_Send(t *testing.T) {
params.SetupTestConfigCleanup(t)
p1 := testp2p.NewTestP2P(t)
p2 := testp2p.NewTestP2P(t)
p1.Connect(p2)

View File

@@ -22,6 +22,7 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/encoder"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers"
"github.com/prysmaticlabs/prysm/beacon-chain/p2p/peers/scorers"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/network/forks"
"github.com/prysmaticlabs/prysm/testing/assert"
@@ -81,6 +82,7 @@ func createHost(t *testing.T, port int) (host.Host, *ecdsa.PrivateKey, net.IP) {
}
func TestService_Stop_SetsStartedToFalse(t *testing.T) {
params.SetupTestConfigCleanup(t)
s, err := NewService(context.Background(), &Config{StateNotifier: &mock.MockStateNotifier{}})
require.NoError(t, err)
s.started = true
@@ -90,12 +92,14 @@ func TestService_Stop_SetsStartedToFalse(t *testing.T) {
}
func TestService_Stop_DontPanicIfDv5ListenerIsNotInited(t *testing.T) {
params.SetupTestConfigCleanup(t)
s, err := NewService(context.Background(), &Config{StateNotifier: &mock.MockStateNotifier{}})
require.NoError(t, err)
assert.NoError(t, s.Stop())
}
func TestService_Start_OnlyStartsOnce(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
cfg := &Config{
@@ -131,12 +135,14 @@ func TestService_Start_OnlyStartsOnce(t *testing.T) {
}
func TestService_Status_NotRunning(t *testing.T) {
params.SetupTestConfigCleanup(t)
s := &Service{started: false}
s.dv5Listener = &mockListener{}
assert.ErrorContains(t, "not running", s.Status(), "Status returned wrong error")
}
func TestService_Status_NoGenesisTimeSet(t *testing.T) {
params.SetupTestConfigCleanup(t)
s := &Service{started: true}
s.dv5Listener = &mockListener{}
assert.ErrorContains(t, "no genesis time set", s.Status(), "Status returned wrong error")
@@ -147,6 +153,7 @@ func TestService_Status_NoGenesisTimeSet(t *testing.T) {
}
func TestListenForNewNodes(t *testing.T) {
params.SetupTestConfigCleanup(t)
// Setup bootnode.
notifier := &mock.MockStateNotifier{}
cfg := &Config{StateNotifier: notifier}
@@ -241,6 +248,7 @@ func TestListenForNewNodes(t *testing.T) {
}
func TestPeer_Disconnect(t *testing.T) {
params.SetupTestConfigCleanup(t)
h1, _, _ := createHost(t, 5000)
defer func() {
if err := h1.Close(); err != nil {
@@ -271,6 +279,7 @@ func TestPeer_Disconnect(t *testing.T) {
}
func TestService_JoinLeaveTopic(t *testing.T) {
params.SetupTestConfigCleanup(t)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
s, err := NewService(ctx, &Config{StateNotifier: &mock.MockStateNotifier{}})
@@ -329,6 +338,7 @@ func initializeStateWithForkDigest(ctx context.Context, t *testing.T, ef *event.
}
func TestService_connectWithPeer(t *testing.T) {
params.SetupTestConfigCleanup(t)
tests := []struct {
name string
peers *peers.Status

View File

@@ -17,6 +17,7 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/core/feed"
statefeed "github.com/prysmaticlabs/prysm/beacon-chain/core/feed/state"
"github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/consensus-types/wrapper"
pb "github.com/prysmaticlabs/prysm/proto/prysm/v1alpha1"
"github.com/prysmaticlabs/prysm/testing/assert"
@@ -24,6 +25,7 @@ import (
)
func TestStartDiscV5_DiscoverPeersWithSubnets(t *testing.T) {
params.SetupTestConfigCleanup(t)
// This test needs to be entirely rewritten and should be done in a follow up PR from #7885.
t.Skip("This test is now failing after PR 7885 due to false positive")
gFlags := new(flags.GlobalFlags)
@@ -146,6 +148,7 @@ func TestStartDiscV5_DiscoverPeersWithSubnets(t *testing.T) {
}
func Test_AttSubnets(t *testing.T) {
params.SetupTestConfigCleanup(t)
tests := []struct {
name string
record func(t *testing.T) *enr.Record
@@ -330,6 +333,7 @@ func Test_AttSubnets(t *testing.T) {
}
func Test_SyncSubnets(t *testing.T) {
params.SetupTestConfigCleanup(t)
tests := []struct {
name string
record func(t *testing.T) *enr.Record

View File

@@ -24,7 +24,7 @@ func TestInitializeDataMaps(t *testing.T) {
{
name: "fork version changes",
action: func() {
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.GenesisForkVersion = []byte{0x01, 0x02, 0x00, 0x00}
params.OverrideBeaconConfig(cfg)
},
@@ -33,7 +33,7 @@ func TestInitializeDataMaps(t *testing.T) {
{
name: "fork version changes with reset",
action: func() {
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.GenesisForkVersion = []byte{0x01, 0x02, 0x00, 0x00}
params.OverrideBeaconConfig(cfg)
InitializeDataMaps()

View File

@@ -6,6 +6,7 @@ import (
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
logTest "github.com/sirupsen/logrus/hooks/test"
@@ -14,6 +15,7 @@ import (
// Test `verifyConnectivity` function by trying to connect to google.com (successfully)
// and then by connecting to an unreachable IP and ensuring that a log is emitted
func TestVerifyConnectivity(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
cases := []struct {
address string
@@ -39,6 +41,7 @@ func TestVerifyConnectivity(t *testing.T) {
}
func TestSerializeENR(t *testing.T) {
params.SetupTestConfigCleanup(t)
t.Run("Ok", func(t *testing.T) {
key, err := crypto.GenerateKey()
require.NoError(t, err)

View File

@@ -26,7 +26,7 @@ const pubKeyErr = "could not convert bytes to public key"
func TestDepositContractAddress_EmptyAddress(t *testing.T) {
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.DepositContractAddress = ""
params.OverrideBeaconConfig(config)
@@ -36,7 +36,7 @@ func TestDepositContractAddress_EmptyAddress(t *testing.T) {
func TestDepositContractAddress_NotHexAddress(t *testing.T) {
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.DepositContractAddress = "abc?!"
params.OverrideBeaconConfig(config)

View File

@@ -488,7 +488,7 @@ func TestServer_getPowBlockHashAtTerminalTotalDifficulty(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.TerminalTotalDifficulty = tt.paramsTd
params.OverrideBeaconConfig(cfg)
var m map[[32]byte]*pb.ExecutionBlock

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -236,7 +236,7 @@ func TestProcessETH2GenesisLog_8DuplicatePubkeys(t *testing.T) {
require.NoError(t, err)
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig := params.MinimalSpecConfig().Copy()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -284,7 +284,7 @@ func TestProcessETH2GenesisLog_8DuplicatePubkeys(t *testing.T) {
func TestProcessETH2GenesisLog(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.GenesisDelay = 0
params.OverrideBeaconConfig(cfg)
hook := logTest.NewGlobal()
@@ -310,7 +310,7 @@ func TestProcessETH2GenesisLog(t *testing.T) {
web3Service.depositContractCaller, err = contracts.NewDepositContractCaller(testAcc.ContractAddr, testAcc.Backend)
require.NoError(t, err)
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig := params.MinimalSpecConfig().Copy()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
@@ -378,6 +378,7 @@ func TestProcessETH2GenesisLog(t *testing.T) {
}
func TestProcessETH2GenesisLog_CorrectNumOfDeposits(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
testAcc, err := mock.Setup()
require.NoError(t, err, "Unable to set up simulated backend")
@@ -406,8 +407,7 @@ func TestProcessETH2GenesisLog_CorrectNumOfDeposits(t *testing.T) {
web3Service.latestEth1Data.LastRequestedBlock = 0
web3Service.latestEth1Data.BlockHeight = testAcc.Backend.Blockchain().CurrentBlock().NumberU64()
web3Service.latestEth1Data.BlockTime = testAcc.Backend.Blockchain().CurrentBlock().Time()
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig := params.MinimalSpecConfig().Copy()
bConfig.MinGenesisTime = 0
bConfig.SecondsPerETH1Block = 10
params.OverrideBeaconConfig(bConfig)
@@ -476,6 +476,7 @@ func TestProcessETH2GenesisLog_CorrectNumOfDeposits(t *testing.T) {
}
func TestProcessETH2GenesisLog_LargePeriodOfNoLogs(t *testing.T) {
params.SetupTestConfigCleanup(t)
hook := logTest.NewGlobal()
testAcc, err := mock.Setup()
require.NoError(t, err, "Unable to set up simulated backend")
@@ -504,8 +505,7 @@ func TestProcessETH2GenesisLog_LargePeriodOfNoLogs(t *testing.T) {
web3Service.latestEth1Data.LastRequestedBlock = 0
web3Service.latestEth1Data.BlockHeight = testAcc.Backend.Blockchain().CurrentBlock().NumberU64()
web3Service.latestEth1Data.BlockTime = testAcc.Backend.Blockchain().CurrentBlock().Time()
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig := params.MinimalSpecConfig().Copy()
bConfig.SecondsPerETH1Block = 10
params.OverrideBeaconConfig(bConfig)
nConfig := params.BeaconNetworkConfig()
@@ -552,7 +552,7 @@ func TestProcessETH2GenesisLog_LargePeriodOfNoLogs(t *testing.T) {
// Set the genesis time 500 blocks ahead of the last
// deposit log.
bConfig = params.MinimalSpecConfig()
bConfig = params.MinimalSpecConfig().Copy()
bConfig.MinGenesisTime = wantedGenesisTime - 10
params.OverrideBeaconConfig(bConfig)
@@ -616,7 +616,7 @@ func newPowchainService(t *testing.T, eth1Backend *mock.TestAccount, beaconDB db
web3Service.eth1DataFetcher = &goodFetcher{backend: eth1Backend.Backend}
web3Service.httpLogger = &goodLogger{backend: eth1Backend.Backend}
params.SetupTestConfigCleanup(t)
bConfig := params.MinimalSpecConfig()
bConfig := params.MinimalSpecConfig().Copy()
bConfig.MinGenesisTime = 0
params.OverrideBeaconConfig(bConfig)
return web3Service

View File

@@ -252,7 +252,7 @@ func TestFollowBlock_OK(t *testing.T) {
// simulated backend sets eth1 block
// time as 10 seconds
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf := params.BeaconConfig().Copy()
conf.SecondsPerETH1Block = 10
params.OverrideBeaconConfig(conf)
@@ -340,7 +340,7 @@ func TestLogTillGenesis_OK(t *testing.T) {
}()
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.Eth1FollowDistance = 5
params.OverrideBeaconConfig(cfg)
@@ -506,7 +506,7 @@ func TestNewService_EarliestVotingBlock(t *testing.T) {
// simulated backend sets eth1 block
// time as 10 seconds
params.SetupTestConfigCleanup(t)
conf := params.BeaconConfig()
conf := params.BeaconConfig().Copy()
conf.SecondsPerETH1Block = 10
conf.Eth1FollowDistance = 50
params.OverrideBeaconConfig(conf)

View File

@@ -364,7 +364,7 @@ func TestWrapSignedContributionAndProofsArray(t *testing.T) {
func TestSetInitialPublishBlockPostRequest(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.BellatrixForkEpoch = params.BeaconConfig().AltairForkEpoch + 1
params.OverrideBeaconConfig(cfg)
@@ -470,7 +470,7 @@ func TestPreparePublishedBlock(t *testing.T) {
func TestSetInitialPublishBlindedBlockPostRequest(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.BellatrixForkEpoch = params.BeaconConfig().AltairForkEpoch + 1
params.OverrideBeaconConfig(cfg)

View File

@@ -16,7 +16,7 @@ import (
func TestGetSpec(t *testing.T) {
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.ConfigName = "ConfigName"
config.PresetBase = "PresetBase"
@@ -353,7 +353,7 @@ func TestGetDepositContract(t *testing.T) {
const chainId = 99
const address = "0x0000000000000000000000000000000000000009"
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.DepositChainID = chainId
config.DepositContractAddress = address
params.OverrideBeaconConfig(config)
@@ -372,7 +372,7 @@ func TestForkSchedule_Ok(t *testing.T) {
thirdForkVersion, thirdForkEpoch := []byte("Thir"), types.Epoch(300)
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.GenesisForkVersion = genesisForkVersion
// Create fork schedule adding keys in non-sorted order.
schedule := make(map[[4]byte]types.Epoch, 3)

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -703,7 +703,7 @@ func TestSubmitVoluntaryExit_InvalidExit(t *testing.T) {
func TestServer_SubmitAttestations_Ok(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
// Required for correct committee size calculation.
c.SlotsPerEpoch = 1
params.OverrideBeaconConfig(c)
@@ -809,7 +809,7 @@ func TestServer_SubmitAttestations_ValidAttestationSubmitted(t *testing.T) {
ctx := grpc.NewContextWithServerTransportStream(context.Background(), &runtime.ServerTransportStream{})
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
// Required for correct committee size calculation.
c.SlotsPerEpoch = 1
params.OverrideBeaconConfig(c)
@@ -909,7 +909,7 @@ func TestServer_SubmitAttestations_InvalidAttestationGRPCHeader(t *testing.T) {
ctx := grpc.NewContextWithServerTransportStream(context.Background(), &runtime.ServerTransportStream{})
params.SetupTestConfigCleanup(t)
c := params.BeaconConfig()
c := params.BeaconConfig().Copy()
// Required for correct committee size calculation.
c.SlotsPerEpoch = 1
params.OverrideBeaconConfig(c)

View File

@@ -22,7 +22,7 @@ import (
func TestGetGenesis(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
config := params.BeaconConfig()
config := params.BeaconConfig().Copy()
config.GenesisForkVersion = []byte("genesis")
params.OverrideBeaconConfig(config)
genesis := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)

View File

@@ -864,7 +864,7 @@ func TestProduceBlockV2(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
bc := params.BeaconConfig()
bc := params.BeaconConfig().Copy()
bc.AltairForkEpoch = types.Epoch(0)
params.OverrideBeaconConfig(bc)
@@ -1006,7 +1006,7 @@ func TestProduceBlockV2(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
bc := params.BeaconConfig()
bc := params.BeaconConfig().Copy()
bc.AltairForkEpoch = types.Epoch(0)
bc.BellatrixForkEpoch = types.Epoch(1)
params.OverrideBeaconConfig(bc)
@@ -1852,7 +1852,7 @@ func TestProduceBlindedBlock(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
bc := params.BeaconConfig()
bc := params.BeaconConfig().Copy()
bc.AltairForkEpoch = types.Epoch(0)
params.OverrideBeaconConfig(bc)
@@ -1995,7 +1995,7 @@ func TestProduceBlindedBlock(t *testing.T) {
ctx := context.Background()
params.SetupTestConfigCleanup(t)
bc := params.BeaconConfig()
bc := params.BeaconConfig().Copy()
bc.AltairForkEpoch = types.Epoch(0)
bc.BellatrixForkEpoch = types.Epoch(1)
params.OverrideBeaconConfig(bc)
@@ -2835,50 +2835,50 @@ func TestGetAggregateAttestation(t *testing.T) {
},
Signature: sig1,
}
root2_1 := bytesutil.PadTo([]byte("root2_1"), 32)
sig2_1 := bytesutil.PadTo([]byte("sig2_1"), fieldparams.BLSSignatureLength)
attSlot2_1 := &ethpbalpha.Attestation{
root21 := bytesutil.PadTo([]byte("root2_1"), 32)
sig21 := bytesutil.PadTo([]byte("sig2_1"), fieldparams.BLSSignatureLength)
attslot21 := &ethpbalpha.Attestation{
AggregationBits: []byte{0, 1, 1},
Data: &ethpbalpha.AttestationData{
Slot: 2,
CommitteeIndex: 2,
BeaconBlockRoot: root2_1,
BeaconBlockRoot: root21,
Source: &ethpbalpha.Checkpoint{
Epoch: 1,
Root: root2_1,
Root: root21,
},
Target: &ethpbalpha.Checkpoint{
Epoch: 1,
Root: root2_1,
Root: root21,
},
},
Signature: sig2_1,
Signature: sig21,
}
root2_2 := bytesutil.PadTo([]byte("root2_2"), 32)
sig2_2 := bytesutil.PadTo([]byte("sig2_2"), fieldparams.BLSSignatureLength)
attSlot2_2 := &ethpbalpha.Attestation{
root22 := bytesutil.PadTo([]byte("root2_2"), 32)
sig22 := bytesutil.PadTo([]byte("sig2_2"), fieldparams.BLSSignatureLength)
attslot22 := &ethpbalpha.Attestation{
AggregationBits: []byte{0, 1, 1, 1},
Data: &ethpbalpha.AttestationData{
Slot: 2,
CommitteeIndex: 3,
BeaconBlockRoot: root2_2,
BeaconBlockRoot: root22,
Source: &ethpbalpha.Checkpoint{
Epoch: 1,
Root: root2_2,
Root: root22,
},
Target: &ethpbalpha.Checkpoint{
Epoch: 1,
Root: root2_2,
Root: root22,
},
},
Signature: sig2_2,
Signature: sig22,
}
vs := &Server{
AttestationsPool: &mock.PoolMock{AggregatedAtts: []*ethpbalpha.Attestation{attSlot1, attSlot2_1, attSlot2_2}},
AttestationsPool: &mock.PoolMock{AggregatedAtts: []*ethpbalpha.Attestation{attSlot1, attslot21, attslot22}},
}
t.Run("OK", func(t *testing.T) {
reqRoot, err := attSlot2_2.Data.HashTreeRoot()
reqRoot, err := attslot22.Data.HashTreeRoot()
require.NoError(t, err)
req := &ethpbv1.AggregateAttestationRequest{
AttestationDataRoot: reqRoot[:],
@@ -2889,16 +2889,16 @@ func TestGetAggregateAttestation(t *testing.T) {
require.NotNil(t, att)
require.NotNil(t, att.Data)
assert.DeepEqual(t, bitfield.Bitlist{0, 1, 1, 1}, att.Data.AggregationBits)
assert.DeepEqual(t, sig2_2, att.Data.Signature)
assert.DeepEqual(t, sig22, att.Data.Signature)
assert.Equal(t, types.Slot(2), att.Data.Data.Slot)
assert.Equal(t, types.CommitteeIndex(3), att.Data.Data.Index)
assert.DeepEqual(t, root2_2, att.Data.Data.BeaconBlockRoot)
assert.DeepEqual(t, root22, att.Data.Data.BeaconBlockRoot)
require.NotNil(t, att.Data.Data.Source)
assert.Equal(t, types.Epoch(1), att.Data.Data.Source.Epoch)
assert.DeepEqual(t, root2_2, att.Data.Data.Source.Root)
assert.DeepEqual(t, root22, att.Data.Data.Source.Root)
require.NotNil(t, att.Data.Data.Target)
assert.Equal(t, types.Epoch(1), att.Data.Data.Target.Epoch)
assert.DeepEqual(t, root2_2, att.Data.Data.Target.Root)
assert.DeepEqual(t, root22, att.Data.Data.Target.Root)
})
t.Run("No matching attestation", func(t *testing.T) {

View File

@@ -740,7 +740,8 @@ func TestServer_StreamBlocks_ContextCanceled(t *testing.T) {
func TestServer_StreamBlocks_OnHeadUpdated(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.UseMainnetConfig()
params.OverrideBeaconConfig(params.MainnetConfig())
ctx := context.Background()
beaconState, privs := util.DeterministicGenesisState(t, 32)
b, err := util.GenerateFullBlock(beaconState, privs, util.DefaultBlockGenConfig(), 1)
@@ -778,7 +779,8 @@ func TestServer_StreamBlocks_OnHeadUpdated(t *testing.T) {
func TestServer_StreamBlocksVerified_OnHeadUpdated(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.UseMainnetConfig()
params.OverrideBeaconConfig(params.MainnetConfig())
db := dbTest.SetupDB(t)
ctx := context.Background()
beaconState, privs := util.DeterministicGenesisState(t, 32)

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -1028,6 +1028,7 @@ func TestServer_ListValidators_DefaultPageSize(t *testing.T) {
}
func TestServer_ListValidators_FromOldEpoch(t *testing.T) {
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
transition.SkipSlotCache.Disable()

View File

@@ -50,7 +50,6 @@ go_test(
"//beacon-chain/db/testing:go_default_library",
"//beacon-chain/forkchoice/protoarray:go_default_library",
"//beacon-chain/p2p/testing:go_default_library",
"//beacon-chain/state:go_default_library",
"//beacon-chain/state/stategen:go_default_library",
"//beacon-chain/state/stategen/mock:go_default_library",
"//config/fieldparams:go_default_library",

View File

@@ -7,7 +7,6 @@ import (
mock "github.com/prysmaticlabs/prysm/beacon-chain/blockchain/testing"
dbTest "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
"github.com/prysmaticlabs/prysm/beacon-chain/state"
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
mockstategen "github.com/prysmaticlabs/prysm/beacon-chain/state/stategen/mock"
types "github.com/prysmaticlabs/prysm/consensus-types/primitives"
@@ -83,10 +82,9 @@ func TestServer_GetBeaconState(t *testing.T) {
Slot: slot + 1,
},
}
state := state.BeaconState(st)
// since we are requesting a state at a skipped slot, use the same method as stategen
// to advance to the pre-state for the subsequent slot
state, err = stategen.ReplayProcessSlots(ctx, state, slot+1)
state, err := stategen.ReplayProcessSlots(ctx, st, slot+1)
require.NoError(t, err)
wanted, err = state.MarshalSSZ()
require.NoError(t, err)

View File

@@ -100,7 +100,7 @@ func TestSubmitAggregateAndProof_IsAggregatorAndNoAtts(t *testing.T) {
func TestSubmitAggregateAndProof_UnaggregateOk(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c := params.MinimalSpecConfig().Copy()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
@@ -135,7 +135,7 @@ func TestSubmitAggregateAndProof_UnaggregateOk(t *testing.T) {
func TestSubmitAggregateAndProof_AggregateOk(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c := params.MinimalSpecConfig().Copy()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
@@ -181,7 +181,7 @@ func TestSubmitAggregateAndProof_AggregateOk(t *testing.T) {
func TestSubmitAggregateAndProof_AggregateNotOk(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c := params.MinimalSpecConfig().Copy()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
@@ -293,7 +293,7 @@ func generateUnaggregatedAtt(state state.ReadOnlyBeaconState, index uint64, priv
func TestSubmitAggregateAndProof_PreferOwnAttestation(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c := params.MinimalSpecConfig().Copy()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)
@@ -349,7 +349,7 @@ func TestSubmitAggregateAndProof_PreferOwnAttestation(t *testing.T) {
func TestSubmitAggregateAndProof_SelectsMostBitsWhenOwnAttestationNotPresent(t *testing.T) {
params.SetupTestConfigCleanup(t)
c := params.MinimalSpecConfig()
c := params.MinimalSpecConfig().Copy()
c.TargetAggregatorsPerCommittee = 16
params.OverrideBeaconConfig(c)

View File

@@ -103,7 +103,7 @@ func TestGetDuties_OK(t *testing.T) {
func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg := params.MainnetConfig().Copy()
cfg.AltairForkEpoch = types.Epoch(0)
params.OverrideBeaconConfig(cfg)
@@ -205,7 +205,7 @@ func TestGetAltairDuties_SyncCommitteeOK(t *testing.T) {
func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg := params.MainnetConfig().Copy()
cfg.AltairForkEpoch = types.Epoch(0)
cfg.BellatrixForkEpoch = types.Epoch(1)
params.OverrideBeaconConfig(cfg)
@@ -311,7 +311,7 @@ func TestGetBellatrixDuties_SyncCommitteeOK(t *testing.T) {
func TestGetAltairDuties_UnknownPubkey(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg := params.MainnetConfig().Copy()
cfg.AltairForkEpoch = types.Epoch(0)
params.OverrideBeaconConfig(cfg)

View File

@@ -173,7 +173,7 @@ func TestGetAttestationData_SyncNotReady(t *testing.T) {
func TestGetAttestationData_Optimistic(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.BellatrixForkEpoch = 0
params.OverrideBeaconConfig(cfg)
@@ -214,7 +214,7 @@ func TestAttestationDataAtSlot_HandlesFarAwayJustifiedEpoch(t *testing.T) {
// Ensure HistoricalRootsLimit matches scenario
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig()
cfg := params.MainnetConfig().Copy()
cfg.HistoricalRootsLimit = 8192
params.OverrideBeaconConfig(cfg)

View File

@@ -27,81 +27,12 @@ func (vs *Server) StreamBlocksAltair(req *ethpb.StreamBlocksRequest, stream ethp
select {
case blockEvent := <-blocksChannel:
if req.VerifiedOnly {
if blockEvent.Type == statefeed.BlockProcessed {
data, ok := blockEvent.Data.(*statefeed.BlockProcessedData)
if !ok || data == nil {
continue
}
b := &ethpb.StreamBlocksResponse{}
switch data.SignedBlock.Version() {
case version.Phase0:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlock)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlock")
continue
}
b.Block = &ethpb.StreamBlocksResponse_Phase0Block{Phase0Block: phBlk}
case version.Altair:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlockAltair)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlockAltair")
continue
}
b.Block = &ethpb.StreamBlocksResponse_AltairBlock{AltairBlock: phBlk}
case version.Bellatrix:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlockBellatrix)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlockBellatrix")
continue
}
b.Block = &ethpb.StreamBlocksResponse_BellatrixBlock{BellatrixBlock: phBlk}
}
if err := stream.Send(b); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
if err := sendVerifiedBlocks(stream, blockEvent); err != nil {
return err
}
} else {
if blockEvent.Type == blockfeed.ReceivedBlock {
data, ok := blockEvent.Data.(*blockfeed.ReceivedBlockData)
if !ok {
// Got bad data over the stream.
continue
}
if data.SignedBlock == nil {
// One nil block shouldn't stop the stream.
continue
}
headState, err := vs.HeadFetcher.HeadState(vs.Ctx)
if err != nil {
log.WithError(err).WithField("blockSlot", data.SignedBlock.Block().Slot()).Error("Could not get head state")
continue
}
signed := data.SignedBlock
if err := blocks.VerifyBlockSignature(headState, signed.Block().ProposerIndex(), signed.Signature(), signed.Block().HashTreeRoot); err != nil {
log.WithError(err).WithField("blockSlot", data.SignedBlock.Block().Slot()).Error("Could not verify block signature")
continue
}
b := &ethpb.StreamBlocksResponse{}
switch data.SignedBlock.Version() {
case version.Phase0:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlock)
if !ok {
log.Warn("Mismatch between version and block type, was expecting *ethpb.SignedBeaconBlock")
continue
}
b.Block = &ethpb.StreamBlocksResponse_Phase0Block{Phase0Block: phBlk}
case version.Altair:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlockAltair)
if !ok {
log.Warn("Mismatch between version and block type, was expecting *v2.SignedBeaconBlockAltair")
continue
}
b.Block = &ethpb.StreamBlocksResponse_AltairBlock{AltairBlock: phBlk}
}
if err := stream.Send(b); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
if err := vs.sendBlocks(stream, blockEvent); err != nil {
return err
}
}
case <-blockSub.Err():
@@ -113,3 +44,86 @@ func (vs *Server) StreamBlocksAltair(req *ethpb.StreamBlocksRequest, stream ethp
}
}
}
func sendVerifiedBlocks(stream ethpb.BeaconNodeValidator_StreamBlocksAltairServer, blockEvent *feed.Event) error {
if blockEvent.Type != statefeed.BlockProcessed {
return nil
}
data, ok := blockEvent.Data.(*statefeed.BlockProcessedData)
if !ok || data == nil {
return nil
}
b := &ethpb.StreamBlocksResponse{}
switch data.SignedBlock.Version() {
case version.Phase0:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlock)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlock")
return nil
}
b.Block = &ethpb.StreamBlocksResponse_Phase0Block{Phase0Block: phBlk}
case version.Altair:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlockAltair)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlockAltair")
return nil
}
b.Block = &ethpb.StreamBlocksResponse_AltairBlock{AltairBlock: phBlk}
case version.Bellatrix:
phBlk, ok := data.SignedBlock.Proto().(*ethpb.SignedBeaconBlockBellatrix)
if !ok {
log.Warn("Mismatch between version and block type, was expecting SignedBeaconBlockBellatrix")
return nil
}
b.Block = &ethpb.StreamBlocksResponse_BellatrixBlock{BellatrixBlock: phBlk}
}
if err := stream.Send(b); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
return nil
}
func (vs *Server) sendBlocks(stream ethpb.BeaconNodeValidator_StreamBlocksAltairServer, blockEvent *feed.Event) error {
if blockEvent.Type != blockfeed.ReceivedBlock {
return nil
}
data, ok := blockEvent.Data.(*blockfeed.ReceivedBlockData)
if !ok {
// Got bad data over the stream.
return nil
}
if data.SignedBlock == nil {
// One nil block shouldn't stop the stream.
return nil
}
log := log.WithField("blockSlot", data.SignedBlock.Block().Slot())
headState, err := vs.HeadFetcher.HeadState(vs.Ctx)
if err != nil {
log.WithError(err).Error("Could not get head state")
return nil
}
signed := data.SignedBlock
if err := blocks.VerifyBlockSignature(headState, signed.Block().ProposerIndex(), signed.Signature(), signed.Block().HashTreeRoot); err != nil {
log.WithError(err).Error("Could not verify block signature")
return nil
}
b := &ethpb.StreamBlocksResponse{}
switch p := data.SignedBlock.Proto().(type) {
case *ethpb.SignedBeaconBlock:
b.Block = &ethpb.StreamBlocksResponse_Phase0Block{Phase0Block: p}
case *ethpb.SignedBeaconBlockAltair:
b.Block = &ethpb.StreamBlocksResponse_AltairBlock{AltairBlock: p}
case *ethpb.SignedBeaconBlockBellatrix:
b.Block = &ethpb.StreamBlocksResponse_BellatrixBlock{BellatrixBlock: p}
default:
log.Errorf("Unknown block type %T", p)
}
if err := stream.Send(b); err != nil {
return status.Errorf(codes.Unavailable, "Could not send over stream: %v", err)
}
return nil
}

View File

@@ -23,9 +23,10 @@ import (
)
func TestServer_activationEpochNotReached(t *testing.T) {
params.SetupTestConfigCleanup(t)
require.Equal(t, false, activationEpochNotReached(0))
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.TerminalBlockHash = common.BytesToHash(bytesutil.PadTo([]byte{0x01}, 32))
cfg.TerminalBlockHashActivationEpoch = 1
params.OverrideBeaconConfig(cfg)
@@ -112,7 +113,7 @@ func TestServer_getExecutionPayload(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.TerminalBlockHash = tt.terminalBlockHash
cfg.TerminalBlockHashActivationEpoch = tt.activationEpoch
params.OverrideBeaconConfig(cfg)
@@ -198,6 +199,7 @@ func TestServer_getExecutionPayload_UnexpectedFeeRecipient(t *testing.T) {
}
func TestServer_getTerminalBlockHashIfExists(t *testing.T) {
params.SetupTestConfigCleanup(t)
tests := []struct {
name string
paramsTerminalHash []byte
@@ -240,7 +242,7 @@ func TestServer_getTerminalBlockHashIfExists(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.TerminalTotalDifficulty = tt.paramsTd
cfg.TerminalBlockHash = common.BytesToHash(tt.paramsTerminalHash)
params.OverrideBeaconConfig(cfg)

View File

@@ -2585,7 +2585,7 @@ func setupGetBlock(bm *testing.B) (*Server, state.BeaconState, []bls.SecretKey)
ctx := context.Background()
params.SetupTestConfigCleanup(bm)
params.OverrideBeaconConfig(params.MainnetConfig())
params.OverrideBeaconConfig(params.MainnetConfig().Copy())
beaconState, privKeys := util.DeterministicGenesisState(bm, 64)
stateRoot, err := beaconState.HashTreeRoot(ctx)

View File

@@ -93,7 +93,7 @@ func TestWaitForActivation_ContextClosed(t *testing.T) {
func TestWaitForActivation_ValidatorOriginallyExists(t *testing.T) {
// This test breaks if it doesnt use mainnet config
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
params.OverrideBeaconConfig(params.MainnetConfig().Copy())
ctx := context.Background()
priv1, err := bls.RandKey()

View File

@@ -236,7 +236,7 @@ func TestValidatorStatus_Pending(t *testing.T) {
func TestValidatorStatus_Active(t *testing.T) {
// This test breaks if it doesnt use mainnet config
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
params.OverrideBeaconConfig(params.MainnetConfig().Copy())
ctx := context.Background()
pubKey := pubKey(1)
@@ -439,7 +439,7 @@ func TestValidatorStatus_Exited(t *testing.T) {
genesisRoot, err := block.Block.HashTreeRoot()
require.NoError(t, err, "Could not get signing root")
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
params.OverrideBeaconConfig(params.MainnetConfig().Copy())
state, err := util.NewBeaconState()
require.NoError(t, err)
require.NoError(t, state.SetSlot(slot))
@@ -603,12 +603,12 @@ func TestActivationStatus_OK(t *testing.T) {
}
func TestOptimisticStatus(t *testing.T) {
params.SetupTestConfigCleanup(t)
server := &Server{OptimisticModeFetcher: &mockChain.ChainService{}, TimeFetcher: &mockChain.ChainService{}}
err := server.optimisticStatus(context.Background())
require.NoError(t, err)
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.BellatrixForkEpoch = 2
params.OverrideBeaconConfig(cfg)

View File

@@ -37,7 +37,7 @@ func TestGetSyncMessageBlockRoot_OK(t *testing.T) {
func TestGetSyncMessageBlockRoot_Optimistic(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.BellatrixForkEpoch = 0
params.OverrideBeaconConfig(cfg)

View File

@@ -50,7 +50,7 @@ func TestGetState(t *testing.T) {
t.Run("genesis", func(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.BeaconConfig().Copy()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)

View File

@@ -4,7 +4,7 @@ import (
"math/big"
)
// MockGenesisTimeFetcher is a fake implementation of the powchain.ChainInfoFetcher
// MockPOWChainInfoFetcher is a fake implementation of the powchain.ChainInfoFetcher
type MockPOWChainInfoFetcher struct {
CurrEndpoint string
CurrError error
@@ -12,11 +12,11 @@ type MockPOWChainInfoFetcher struct {
Errors []error
}
func (m *MockPOWChainInfoFetcher) Eth2GenesisPowchainInfo() (uint64, *big.Int) {
func (*MockPOWChainInfoFetcher) Eth2GenesisPowchainInfo() (uint64, *big.Int) {
return uint64(0), &big.Int{}
}
func (m *MockPOWChainInfoFetcher) IsConnectedToETH1() bool {
func (*MockPOWChainInfoFetcher) IsConnectedToETH1() bool {
return true
}

View File

@@ -127,7 +127,7 @@ func TestService_pruneSlasherDataWithinSlidingWindow_ProposalsPruned(t *testing.
// Override beacon config to 1 slot per epoch for easier testing.
params2.SetupTestConfigCleanup(t)
config := params2.BeaconConfig()
config := params2.BeaconConfig().Copy()
config.SlotsPerEpoch = 1
params2.OverrideBeaconConfig(config)

View File

@@ -175,7 +175,6 @@ func (s *Service) waitForChainInitialization() {
stateChannel := make(chan *feed.Event, 1)
stateSub := s.serviceCfg.StateNotifier.StateFeed().Subscribe(stateChannel)
defer stateSub.Unsubscribe()
defer close(stateChannel)
for {
select {
case stateEvent := <-stateChannel:

View File

@@ -134,7 +134,7 @@ func (f *FieldTrie) RecomputeTrie(indices []uint64, elements interface{}) ([32]b
}
// We remove the duplicates here in order to prevent
// duplicated insertions into the trie.
newIndices := []uint64{}
var newIndices []uint64
indexExists := make(map[uint64]bool)
newRoots := make([][32]byte, 0, len(fieldRoots)/iNumOfElems)
for i, idx := range indices {

View File

@@ -374,7 +374,7 @@ func handleBalanceSlice(val, indices []uint64, convertAll bool) ([][32]byte, err
if err != nil {
return nil, err
}
roots := [][32]byte{}
var roots [][32]byte
for _, idx := range indices {
// We split the indexes into their relevant groups. Balances
// are compressed according to 4 values -> 1 chunk.

View File

@@ -10,7 +10,7 @@ var _ fssz.HashRoot = (HistoricalRoots)([][32]byte{})
var _ fssz.Marshaler = (*HistoricalRoots)(nil)
var _ fssz.Unmarshaler = (*HistoricalRoots)(nil)
// Byte32 represents a 32 bytes HistoricalRoots object in Ethereum beacon chain consensus.
// HistoricalRoots represents a 32 bytes HistoricalRoots object in Ethereum beacon chain consensus.
type HistoricalRoots [][32]byte
// HashTreeRoot returns calculated hash root.

View File

@@ -6,7 +6,7 @@ import (
func init() {
// Override network name so that hardcoded genesis files are not loaded.
cfg := params.BeaconConfig()
cfg.ConfigName = "test"
params.OverrideBeaconConfig(cfg)
if err := params.SetActive(params.MainnetTestConfig()); err != nil {
panic(err)
}
}

View File

@@ -23,7 +23,7 @@ func NewMockService() *MockStateManager {
}
}
// StateByRootIfCachedNoCopy
// StateByRootIfCachedNoCopy --
func (_ *MockStateManager) StateByRootIfCachedNoCopy(_ [32]byte) state.BeaconState {
panic("implement me")
}

View File

@@ -113,7 +113,7 @@ func TestReplayBlocks_LowerSlotBlock(t *testing.T) {
func TestReplayBlocks_ThroughForkBoundary(t *testing.T) {
params.SetupTestConfigCleanup(t)
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 1
bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = 1
params.OverrideBeaconConfig(bCfg)
@@ -141,7 +141,7 @@ func TestReplayBlocks_ThroughForkBoundary(t *testing.T) {
func TestReplayBlocks_ThroughBellatrixForkBoundary(t *testing.T) {
params.SetupTestConfigCleanup(t)
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 1
bCfg.ForkVersionSchedule[bytesutil.ToBytes4(bCfg.AltairForkVersion)] = 1
bCfg.BellatrixForkEpoch = 2

View File

@@ -62,7 +62,7 @@ func TestService_CheckForNextEpochFork(t *testing.T) {
Genesis: time.Now().Add(-4 * oneEpoch()),
ValidatorsRoot: [32]byte{'A'},
}
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 5
params.OverrideBeaconConfig(bCfg)
params.BeaconConfig().InitializeForkSchedule()
@@ -105,7 +105,7 @@ func TestService_CheckForNextEpochFork(t *testing.T) {
Genesis: time.Now().Add(-4 * oneEpoch()),
ValidatorsRoot: [32]byte{'A'},
}
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 3
bCfg.BellatrixForkEpoch = 5
params.OverrideBeaconConfig(bCfg)
@@ -207,7 +207,7 @@ func TestService_CheckForPreviousEpochFork(t *testing.T) {
Genesis: time.Now().Add(-4 * oneEpoch()),
ValidatorsRoot: [32]byte{'A'},
}
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 3
params.OverrideBeaconConfig(bCfg)
params.BeaconConfig().InitializeForkSchedule()
@@ -281,7 +281,7 @@ func TestService_CheckForPreviousEpochFork(t *testing.T) {
Genesis: time.Now().Add(-4 * oneEpoch()),
ValidatorsRoot: [32]byte{'A'},
}
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 1
bCfg.BellatrixForkEpoch = 3
params.OverrideBeaconConfig(bCfg)

View File

@@ -13,6 +13,7 @@ import (
db "github.com/prysmaticlabs/prysm/beacon-chain/db/testing"
p2ptest "github.com/prysmaticlabs/prysm/beacon-chain/p2p/testing"
p2ptypes "github.com/prysmaticlabs/prysm/beacon-chain/p2p/types"
"github.com/prysmaticlabs/prysm/config/params"
types "github.com/prysmaticlabs/prysm/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
@@ -20,6 +21,11 @@ import (
)
func TestGoodByeRPCHandler_Disconnects_With_Peer(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig().Copy()
cfg.SecondsPerSlot = 1
params.OverrideBeaconConfig(cfg)
p1 := p2ptest.NewTestP2P(t)
p2 := p2ptest.NewTestP2P(t)
p1.Connect(p2)

View File

@@ -141,7 +141,7 @@ func TestMetadataRPCHandler_SendsMetadata(t *testing.T) {
func TestMetadataRPCHandler_SendsMetadataAltair(t *testing.T) {
params.SetupTestConfigCleanup(t)
bCfg := params.BeaconConfig()
bCfg := params.BeaconConfig().Copy()
bCfg.AltairForkEpoch = 5
params.OverrideBeaconConfig(bCfg)
params.BeaconConfig().InitializeForkSchedule()

View File

@@ -115,6 +115,11 @@ func TestSubscribe_UnsubscribeTopic(t *testing.T) {
}
func TestSubscribe_ReceivesAttesterSlashing(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig().Copy()
cfg.SecondsPerSlot = 1
params.OverrideBeaconConfig(cfg)
p2pService := p2ptest.NewTestP2P(t)
ctx := context.Background()
d := db.SetupDB(t)
@@ -138,8 +143,6 @@ func TestSubscribe_ReceivesAttesterSlashing(t *testing.T) {
topic := "/eth2/%x/attester_slashing"
var wg sync.WaitGroup
wg.Add(1)
params.SetupTestConfigCleanup(t)
params.OverrideBeaconConfig(params.MainnetConfig())
var err error
p2pService.Digest, err = r.currentForkDigest()
require.NoError(t, err)
@@ -437,6 +440,11 @@ func Test_wrapAndReportValidation(t *testing.T) {
}
func TestFilterSubnetPeers(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetConfig().Copy()
cfg.SecondsPerSlot = 1
params.OverrideBeaconConfig(cfg)
gFlags := new(flags.GlobalFlags)
gFlags.MinimumPeersPerSubnet = 4
flags.Init(gFlags)
@@ -504,6 +512,11 @@ func TestFilterSubnetPeers(t *testing.T) {
}
func TestSubscribeWithSyncSubnets_StaticOK(t *testing.T) {
params.SetupTestConfigCleanup(t)
cfg := params.MainnetTestConfig().Copy()
cfg.SecondsPerSlot = 1
params.OverrideBeaconConfig(cfg)
p := p2ptest.NewTestP2P(t)
ctx, cancel := context.WithCancel(context.Background())
currSlot := types.Slot(100)
@@ -530,11 +543,12 @@ func TestSubscribeWithSyncSubnets_StaticOK(t *testing.T) {
}
func TestSubscribeWithSyncSubnets_DynamicOK(t *testing.T) {
p := p2ptest.NewTestP2P(t)
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
cfg := params.MainnetConfig().Copy()
cfg.SecondsPerSlot = 1
params.OverrideBeaconConfig(cfg)
p := p2ptest.NewTestP2P(t)
ctx, cancel := context.WithCancel(context.Background())
currSlot := types.Slot(100)
r := Service{
@@ -611,9 +625,9 @@ func TestSubscribeWithSyncSubnets_StaticSwitchFork(t *testing.T) {
}
func TestSubscribeWithSyncSubnets_DynamicSwitchFork(t *testing.T) {
p := p2ptest.NewTestP2P(t)
params.SetupTestConfigCleanup(t)
cfg := params.BeaconConfig()
p := p2ptest.NewTestP2P(t)
cfg := params.BeaconConfig().Copy()
cfg.AltairForkEpoch = 1
cfg.SecondsPerSlot = 1
cfg.SlotsPerEpoch = 4

View File

@@ -168,7 +168,7 @@ func (s *Service) validateBeaconBlockPubSub(ctx context.Context, pid peer.ID, ms
}
s.pendingQueueLock.Unlock()
err := errors.Errorf("unknown parent for block with slot %d and parent root %#x", blk.Block().Slot(), blk.Block().ParentRoot())
log.WithError(err).WithFields(getBlockFields(blk)).Debug("Could not process early block")
log.WithError(err).WithFields(getBlockFields(blk)).Debug("Could not identify parent for block")
return pubsub.ValidationIgnore, err
}

View File

@@ -25,7 +25,6 @@ import (
"github.com/prysmaticlabs/prysm/beacon-chain/state/stategen"
mockSync "github.com/prysmaticlabs/prysm/beacon-chain/sync/initial-sync/testing"
lruwrpr "github.com/prysmaticlabs/prysm/cache/lru"
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/config/params"
types "github.com/prysmaticlabs/prysm/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/consensus-types/wrapper"
@@ -46,7 +45,7 @@ func TestValidateBeaconBlockPubSub_InvalidSignature(t *testing.T) {
db := dbtest.SetupDB(t)
p := p2ptest.NewTestP2P(t)
ctx := context.Background()
beaconState, _ := util.DeterministicGenesisState(t, 100)
beaconState, privKeys := util.DeterministicGenesisState(t, 100)
parentBlock := util.NewBeaconBlock()
wsb, err := wrapper.WrappedSignedBeaconBlock(parentBlock)
require.NoError(t, err)
@@ -63,14 +62,18 @@ func TestValidateBeaconBlockPubSub_InvalidSignature(t *testing.T) {
msg.Block.ParentRoot = bRoot[:]
msg.Block.Slot = 1
msg.Block.ProposerIndex = proposerIdx
msg.Signature = bytesutil.PadTo([]byte("fake"), fieldparams.BLSSignatureLength)
badPrivKeyIdx := proposerIdx + 1 // We generate a valid signature from a wrong private key which fails to verify
msg.Signature, err = signing.ComputeDomainAndSign(beaconState, 0, msg.Block, params.BeaconConfig().DomainBeaconProposer, privKeys[badPrivKeyIdx])
require.NoError(t, err)
stateGen := stategen.New(db)
chainService := &mock.ChainService{Genesis: time.Unix(time.Now().Unix()-int64(params.BeaconConfig().SecondsPerSlot), 0),
FinalizedCheckPoint: &ethpb.Checkpoint{
Epoch: 0,
Root: make([]byte, 32),
}}
},
DB: db,
}
r := &Service{
cfg: &config{
beaconDB: db,
@@ -88,6 +91,9 @@ func TestValidateBeaconBlockPubSub_InvalidSignature(t *testing.T) {
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -95,7 +101,7 @@ func TestValidateBeaconBlockPubSub_InvalidSignature(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
assert.NotNil(t, err)
require.ErrorIs(t, err, signing.ErrSigFailedToVerify)
result := res == pubsub.ValidationReject
assert.Equal(t, true, result)
}
@@ -130,6 +136,9 @@ func TestValidateBeaconBlockPubSub_BlockAlreadyPresentInDB(t *testing.T) {
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -137,9 +146,8 @@ func TestValidateBeaconBlockPubSub_BlockAlreadyPresentInDB(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
assert.NoError(t, err)
assert.Equal(t, res, pubsub.ValidationIgnore, "block present in DB should be ignored")
}
func TestValidateBeaconBlockPubSub_CanRecoverStateSummary(t *testing.T) {
@@ -516,12 +524,11 @@ func TestValidateBeaconBlockPubSub_Syncing(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
assert.NoError(t, err)
assert.Equal(t, res, pubsub.ValidationIgnore, "block is ignored until fully synced")
}
func TestValidateBeaconBlockPubSub_AcceptBlocksFromNearFuture(t *testing.T) {
func TestValidateBeaconBlockPubSub_IgnoreAndQueueBlocksFromNearFuture(t *testing.T) {
db := dbtest.SetupDB(t)
p := p2ptest.NewTestP2P(t)
ctx := context.Background()
@@ -583,9 +590,8 @@ func TestValidateBeaconBlockPubSub_AcceptBlocksFromNearFuture(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationIgnore
assert.Equal(t, true, result)
require.ErrorContains(t, "early block, with current slot", err)
assert.Equal(t, res, pubsub.ValidationIgnore, "early block should be ignored and queued")
// check if the block is inserted in the Queue
assert.Equal(t, true, len(r.pendingBlocksInCache(msg.Block.Slot)) == 1)
@@ -600,7 +606,7 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromFuture(t *testing.T) {
sk, err := bls.SecretKeyFromBytes(b32[:])
require.NoError(t, err)
msg := util.NewBeaconBlock()
msg.Block.Slot = 3
msg.Block.Slot = 10
msg.Block.ParentRoot = util.Random32Bytes(t)
msg.Signature = sk.Sign([]byte("data")).Marshal()
@@ -624,6 +630,9 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromFuture(t *testing.T) {
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -631,9 +640,8 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromFuture(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
assert.NoError(t, err)
assert.Equal(t, res, pubsub.ValidationIgnore, "block from the future should be ignored")
}
func TestValidateBeaconBlockPubSub_RejectBlocksFromThePast(t *testing.T) {
@@ -672,6 +680,9 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromThePast(t *testing.T) {
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -679,9 +690,8 @@ func TestValidateBeaconBlockPubSub_RejectBlocksFromThePast(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
require.ErrorContains(t, "greater or equal to block slot", err)
assert.Equal(t, res, pubsub.ValidationIgnore, "block from the past should be ignored")
}
func TestValidateBeaconBlockPubSub_SeenProposerSlot(t *testing.T) {
@@ -731,6 +741,9 @@ func TestValidateBeaconBlockPubSub_SeenProposerSlot(t *testing.T) {
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -740,9 +753,8 @@ func TestValidateBeaconBlockPubSub_SeenProposerSlot(t *testing.T) {
r.setSeenBlockIndexSlot(msg.Block.Slot, msg.Block.ProposerIndex)
time.Sleep(10 * time.Millisecond) // Wait for cached value to pass through buffers.
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
assert.NoError(t, err)
assert.Equal(t, res, pubsub.ValidationIgnore, "seen proposer block should be ignored")
}
func TestValidateBeaconBlockPubSub_FilterByFinalizedEpoch(t *testing.T) {
@@ -932,6 +944,9 @@ func TestValidateBeaconBlockPubSub_InvalidParentBlock(t *testing.T) {
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -939,9 +954,8 @@ func TestValidateBeaconBlockPubSub_InvalidParentBlock(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
require.ErrorContains(t, "unknown parent for block", err)
assert.Equal(t, res, pubsub.ValidationIgnore, "block with invalid parent should be ignored")
require.NoError(t, copied.SetSlot(2))
proposerIdx, err = helpers.BeaconProposerIndex(ctx, copied)
@@ -961,21 +975,27 @@ func TestValidateBeaconBlockPubSub_InvalidParentBlock(t *testing.T) {
Topic: &topic,
},
}
chainService = &mock.ChainService{Genesis: time.Unix(time.Now().Unix()-int64(2*params.BeaconConfig().SecondsPerSlot), 0),
State: beaconState,
FinalizedCheckPoint: &ethpb.Checkpoint{
Epoch: 0,
}}
r.cfg.chain = chainService
res, err = r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result = res == pubsub.ValidationAccept
require.ErrorContains(t, "unknown parent for block", err)
// Expect block with bad parent to fail too
assert.Equal(t, false, result)
assert.Equal(t, res, pubsub.ValidationIgnore, "block with invalid parent should be ignored")
}
func TestValidateBeaconBlockPubSub_RejectEvilBlocksFromFuture(t *testing.T) {
func TestValidateBeaconBlockPubSub_RejectBlocksFromBadParent(t *testing.T) {
db := dbtest.SetupDB(t)
p := p2ptest.NewTestP2P(t)
ctx := context.Background()
beaconState, privKeys := util.DeterministicGenesisState(t, 100)
parentBlock := util.NewBeaconBlock()
parentBlock.Block.ParentRoot = bytesutil.PadTo([]byte("foo"), 32)
wsb, err := wrapper.WrappedSignedBeaconBlock(parentBlock)
require.NoError(t, err)
require.NoError(t, db.SaveBlock(ctx, wsb))
@@ -1031,11 +1051,15 @@ func TestValidateBeaconBlockPubSub_RejectEvilBlocksFromFuture(t *testing.T) {
slotToPendingBlocks: gcache.New(time.Second, 2*time.Second),
seenPendingBlocks: make(map[[32]byte]bool),
}
r.setBadBlock(ctx, bytesutil.ToBytes32(msg.Block.ParentRoot))
buf := new(bytes.Buffer)
_, err = p.Encoding().EncodeGossip(buf, msg)
require.NoError(t, err)
topic := p2p.GossipTypeMapping[reflect.TypeOf(msg)]
digest, err := r.currentForkDigest()
assert.NoError(t, err)
topic = r.addDigestToTopic(topic, digest)
m := &pubsub.Message{
Message: &pubsubpb.Message{
Data: buf.Bytes(),
@@ -1043,9 +1067,8 @@ func TestValidateBeaconBlockPubSub_RejectEvilBlocksFromFuture(t *testing.T) {
},
}
res, err := r.validateBeaconBlockPubSub(ctx, "", m)
_ = err
result := res == pubsub.ValidationAccept
assert.Equal(t, false, result)
assert.ErrorContains(t, "invalid parent", err)
assert.Equal(t, res, pubsub.ValidationReject)
}
func TestService_setBadBlock_DoesntSetWithContextErr(t *testing.T) {

View File

@@ -28,6 +28,7 @@ go_library(
"//io/logs:go_default_library",
"//monitoring/journald:go_default_library",
"//runtime/debug:go_default_library",
"//runtime/fdlimits:go_default_library",
"//runtime/maxprocs:go_default_library",
"//runtime/tos:go_default_library",
"//runtime/version:go_default_library",

View File

@@ -24,6 +24,7 @@ import (
"github.com/prysmaticlabs/prysm/io/logs"
"github.com/prysmaticlabs/prysm/monitoring/journald"
"github.com/prysmaticlabs/prysm/runtime/debug"
"github.com/prysmaticlabs/prysm/runtime/fdlimits"
_ "github.com/prysmaticlabs/prysm/runtime/maxprocs"
"github.com/prysmaticlabs/prysm/runtime/tos"
"github.com/prysmaticlabs/prysm/runtime/version"
@@ -193,6 +194,9 @@ func main() {
if err := debug.Setup(ctx); err != nil {
return err
}
if err := fdlimits.SetMaxFdLimits(); err != nil {
return err
}
return cmd.ValidateNoArgs(ctx)
}

View File

@@ -42,39 +42,53 @@ func InitWithReset(c *Flags) func() {
// ConfigureBeaconChain sets the global config based
// on what flags are enabled for the beacon-chain client.
func ConfigureBeaconChain(ctx *cli.Context) {
cfg := newConfig(ctx)
func ConfigureBeaconChain(ctx *cli.Context) error {
cfg, err := newConfig(ctx)
if err != nil {
return err
}
if ctx.IsSet(RPCMaxPageSizeFlag.Name) {
cfg.MaxRPCPageSize = ctx.Int(RPCMaxPageSizeFlag.Name)
log.Warnf("Starting beacon chain with max RPC page size of %d", cfg.MaxRPCPageSize)
}
Init(cfg)
return nil
}
// ConfigureValidator sets the global config based
// on what flags are enabled for the validator client.
func ConfigureValidator(ctx *cli.Context) {
cfg := newConfig(ctx)
func ConfigureValidator(ctx *cli.Context) error {
cfg, err := newConfig(ctx)
if err != nil {
return err
}
Init(cfg)
return nil
}
func newConfig(ctx *cli.Context) *Flags {
func newConfig(ctx *cli.Context) (*Flags, error) {
cfg := Get()
if ctx.Bool(MinimalConfigFlag.Name) {
log.Warn("Using minimal config")
cfg.MinimalConfig = true
params.UseMinimalConfig()
if err := params.SetActive(params.MinimalSpecConfig().Copy()); err != nil {
return nil, err
}
}
if ctx.Bool(E2EConfigFlag.Name) {
log.Warn("Using end-to-end testing config")
switch fieldparams.Preset {
case "mainnet":
params.UseE2EMainnetConfig()
if err := params.SetActive(params.E2EMainnetTestConfig().Copy()); err != nil {
return nil, err
}
case "minimal":
params.UseE2EConfig()
if err := params.SetActive(params.E2ETestConfig().Copy()); err != nil {
return nil, err
}
default:
log.Fatalf("Unrecognized preset being used: %s", fieldparams.Preset)
}
}
return cfg
return cfg, nil
}

View File

@@ -6,6 +6,7 @@ import (
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
"github.com/urfave/cli/v2"
)
@@ -37,7 +38,7 @@ func TestConfigureBeaconConfig(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool(MinimalConfigFlag.Name, true, "test")
context := cli.NewContext(&app, set, nil)
ConfigureBeaconChain(context)
require.NoError(t, ConfigureBeaconChain(context))
c := Get()
assert.Equal(t, true, c.MinimalConfig)
}

View File

@@ -39,7 +39,9 @@ var Commands = &cli.Command{
if err := tos.VerifyTosAcceptedOrPrompt(cliCtx); err != nil {
return err
}
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
return nil
},
Action: func(cliCtx *cli.Context) error {
@@ -76,7 +78,9 @@ var Commands = &cli.Command{
if err := tos.VerifyTosAcceptedOrPrompt(cliCtx); err != nil {
return err
}
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
return nil
},
Action: func(cliCtx *cli.Context) error {
@@ -110,7 +114,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := accounts.BackupAccountsCli(cliCtx); err != nil {
log.Fatalf("Could not backup accounts: %v", err)
}
@@ -138,7 +144,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := accounts.ImportAccountsCli(cliCtx); err != nil {
log.Fatalf("Could not import accounts: %v", err)
}
@@ -172,7 +180,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := accounts.ExitAccountsCli(cliCtx, os.Stdin); err != nil {
log.Fatalf("Could not perform voluntary exit: %v", err)
}

View File

@@ -33,7 +33,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := exportSlashingProtectionJSON(cliCtx); err != nil {
logrus.Fatalf("Could not export slashing protection file: %v", err)
}
@@ -58,7 +60,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
err := importSlashingProtectionJSON(cliCtx)
if err != nil {
logrus.Fatalf("Could not import slashing protection cli: %v", err)

View File

@@ -45,7 +45,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if _, err := accounts.CreateAndSaveWalletCli(cliCtx); err != nil {
log.Fatalf("Could not create a wallet: %v", err)
}
@@ -75,7 +77,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := accounts.EditWalletConfigurationCli(cliCtx); err != nil {
log.Fatalf("Could not edit wallet configuration: %v", err)
}
@@ -104,7 +108,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
if err := accounts.RecoverWalletCli(cliCtx); err != nil {
log.Fatalf("Could not recover wallet: %v", err)
}

View File

@@ -33,7 +33,9 @@ var Commands = &cli.Command{
return tos.VerifyTosAcceptedOrPrompt(cliCtx)
},
Action: func(cliCtx *cli.Context) error {
features.ConfigureValidator(cliCtx)
if err := features.ConfigureValidator(cliCtx); err != nil {
return err
}
walletDirPath := cliCtx.String(flags.WalletDirFlag.Name)
if walletDirPath == "" {
log.Fatal("--wallet-dir not specified")

View File

@@ -27,6 +27,7 @@ go_test(
embed = [":go_default_library"],
deps = [
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
],
)

View File

@@ -110,30 +110,39 @@ func InitWithReset(c *Flags) func() {
}
// configureTestnet sets the config according to specified testnet flag
func configureTestnet(ctx *cli.Context) {
func configureTestnet(ctx *cli.Context) error {
if ctx.Bool(PraterTestnet.Name) {
log.Warn("Running on the Prater Testnet")
params.UsePraterConfig()
if err := params.SetActive(params.PraterConfig().Copy()); err != nil {
return err
}
params.UsePraterNetworkConfig()
} else if ctx.Bool(RopstenTestnet.Name) {
log.Warn("Running on the Ropsten Beacon Chain Testnet")
params.UseRopstenConfig()
if err := params.SetActive(params.RopstenConfig().Copy()); err != nil {
return err
}
params.UseRopstenNetworkConfig()
} else {
log.Warn("Running on Ethereum Consensus Mainnet")
params.UseMainnetConfig()
if err := params.SetActive(params.MainnetConfig().Copy()); err != nil {
return err
}
}
return nil
}
// ConfigureBeaconChain sets the global config based
// on what flags are enabled for the beacon-chain client.
func ConfigureBeaconChain(ctx *cli.Context) {
func ConfigureBeaconChain(ctx *cli.Context) error {
complainOnDeprecatedFlags(ctx)
cfg := &Flags{}
if ctx.Bool(devModeFlag.Name) {
enableDevModeFlags(ctx)
}
configureTestnet(ctx)
if err := configureTestnet(ctx); err != nil {
return err
}
if ctx.Bool(writeSSZStateTransitionsFlag.Name) {
logEnabled(writeSSZStateTransitionsFlag)
@@ -190,14 +199,17 @@ func ConfigureBeaconChain(ctx *cli.Context) {
cfg.EnableBatchGossipAggregation = true
}
Init(cfg)
return nil
}
// ConfigureValidator sets the global config based
// on what flags are enabled for the validator client.
func ConfigureValidator(ctx *cli.Context) {
func ConfigureValidator(ctx *cli.Context) error {
complainOnDeprecatedFlags(ctx)
cfg := &Flags{}
configureTestnet(ctx)
if err := configureTestnet(ctx); err != nil {
return err
}
if ctx.Bool(enableExternalSlasherProtectionFlag.Name) {
log.Fatal(
"Remote slashing protection has currently been disabled in Prysm due to safety concerns. " +
@@ -226,6 +238,7 @@ func ConfigureValidator(ctx *cli.Context) {
}
cfg.KeystoreImportDebounceInterval = ctx.Duration(dynamicKeyReloadDebounceInterval.Name)
Init(cfg)
return nil
}
// enableDevModeFlags switches development mode features on.

View File

@@ -5,6 +5,7 @@ import (
"testing"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
"github.com/urfave/cli/v2"
)
@@ -45,7 +46,7 @@ func TestConfigureBeaconConfig(t *testing.T) {
set := flag.NewFlagSet("test", 0)
set.Bool(enablePeerScorer.Name, true, "test")
context := cli.NewContext(&app, set, nil)
ConfigureBeaconChain(context)
require.NoError(t, ConfigureBeaconChain(context))
c := Get()
assert.Equal(t, true, c.EnablePeerScorer)
}

View File

@@ -19,7 +19,7 @@ go_test(
deps = [
":go_default_library",
"//config/params:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
],
)
@@ -30,9 +30,10 @@ go_test(
"minimal_test.go",
],
eth_network = "minimal",
tags = ["minimal"],
deps = [
":go_default_library",
"//config/params:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",
],
)

View File

@@ -5,18 +5,18 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
)
func testFieldParametersMatchConfig(t *testing.T) {
assert.Equal(t, uint64(params.BeaconConfig().SlotsPerHistoricalRoot), uint64(fieldparams.BlockRootsLength))
assert.Equal(t, uint64(params.BeaconConfig().SlotsPerHistoricalRoot), uint64(fieldparams.StateRootsLength))
assert.Equal(t, params.BeaconConfig().HistoricalRootsLimit, uint64(fieldparams.HistoricalRootsLength))
assert.Equal(t, uint64(params.BeaconConfig().EpochsPerHistoricalVector), uint64(fieldparams.RandaoMixesLength))
assert.Equal(t, params.BeaconConfig().ValidatorRegistryLimit, uint64(fieldparams.ValidatorRegistryLimit))
assert.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod))), uint64(fieldparams.Eth1DataVotesLength))
assert.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().MaxAttestations)), uint64(fieldparams.PreviousEpochAttestationsLength))
assert.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().MaxAttestations)), uint64(fieldparams.CurrentEpochAttestationsLength))
assert.Equal(t, uint64(params.BeaconConfig().EpochsPerSlashingsVector), uint64(fieldparams.SlashingsLength))
assert.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(fieldparams.SyncCommitteeLength))
require.Equal(t, uint64(params.BeaconConfig().SlotsPerHistoricalRoot), uint64(fieldparams.BlockRootsLength))
require.Equal(t, uint64(params.BeaconConfig().SlotsPerHistoricalRoot), uint64(fieldparams.StateRootsLength))
require.Equal(t, params.BeaconConfig().HistoricalRootsLimit, uint64(fieldparams.HistoricalRootsLength))
require.Equal(t, uint64(params.BeaconConfig().EpochsPerHistoricalVector), uint64(fieldparams.RandaoMixesLength))
require.Equal(t, params.BeaconConfig().ValidatorRegistryLimit, uint64(fieldparams.ValidatorRegistryLimit))
require.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(uint64(params.BeaconConfig().EpochsPerEth1VotingPeriod))), uint64(fieldparams.Eth1DataVotesLength))
require.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().MaxAttestations)), uint64(fieldparams.PreviousEpochAttestationsLength))
require.Equal(t, uint64(params.BeaconConfig().SlotsPerEpoch.Mul(params.BeaconConfig().MaxAttestations)), uint64(fieldparams.CurrentEpochAttestationsLength))
require.Equal(t, uint64(params.BeaconConfig().EpochsPerSlashingsVector), uint64(fieldparams.SlashingsLength))
require.Equal(t, params.BeaconConfig().SyncCommitteeSize, uint64(fieldparams.SyncCommitteeLength))
}

View File

@@ -8,11 +8,17 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
)
func TestFieldParametersValues(t *testing.T) {
params.UseMainnetConfig()
assert.Equal(t, "mainnet", fieldparams.Preset)
min, err := params.ByName(params.MainnetName)
require.NoError(t, err)
undo, err := params.SetActiveWithUndo(min)
require.NoError(t, err)
defer func() {
require.NoError(t, undo())
}()
require.Equal(t, "mainnet", fieldparams.Preset)
testFieldParametersMatchConfig(t)
}

View File

@@ -8,11 +8,13 @@ import (
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/config/params"
"github.com/prysmaticlabs/prysm/testing/assert"
"github.com/prysmaticlabs/prysm/testing/require"
)
func TestFieldParametersValues(t *testing.T) {
params.UseMinimalConfig()
assert.Equal(t, "minimal", fieldparams.Preset)
params.SetupTestConfigCleanup(t)
min := params.MinimalSpecConfig().Copy()
params.OverrideBeaconConfig(min)
require.Equal(t, "minimal", fieldparams.Preset)
testFieldParametersMatchConfig(t)
}

View File

@@ -6,12 +6,14 @@ go_library(
"config.go",
"config_utils_develop.go", # keep
"config_utils_prod.go",
"configset.go",
"init.go",
"interop.go",
"io_config.go",
"loader.go",
"mainnet_config.go",
"minimal_config.go",
"network_config.go",
"registry.go",
"testnet_e2e_config.go",
"testnet_prater_config.go",
"testnet_ropsten_config.go",
@@ -40,6 +42,7 @@ go_test(
srcs = [
"checktags_test.go",
"config_test.go",
"configset_test.go",
"loader_test.go",
"testnet_config_test.go",
"testnet_prater_config_test.go",
@@ -51,10 +54,11 @@ go_test(
"@eth2_networks//:configs",
"testdata/e2e_config.yaml",
],
embed = [":go_default_library"],
gotags = ["develop"],
race = "on",
deps = [
":go_default_library",
"//encoding/bytesutil:go_default_library",
"//io/file:go_default_library",
"//testing/assert:go_default_library",
"//testing/require:go_default_library",

View File

@@ -34,6 +34,7 @@ func TestConfig_OverrideBeaconConfigTestTeardown(t *testing.T) {
}
func TestConfig_DataRace(t *testing.T) {
params.SetupTestConfigCleanup(t)
for i := 0; i < 10; i++ {
go func() {
cfg := params.BeaconConfig()

View File

@@ -9,14 +9,13 @@ import (
"github.com/mohae/deepcopy"
)
var beaconConfig = MainnetConfig()
var beaconConfigLock sync.RWMutex
var cfgrw sync.RWMutex
// BeaconConfig retrieves beacon chain config.
func BeaconConfig() *BeaconChainConfig {
beaconConfigLock.RLock()
defer beaconConfigLock.RUnlock()
return beaconConfig
cfgrw.RLock()
defer cfgrw.RUnlock()
return configs.getActive()
}
// OverrideBeaconConfig by replacing the config. The preferred pattern is to
@@ -24,18 +23,18 @@ func BeaconConfig() *BeaconChainConfig {
// OverrideBeaconConfig(c). Any subsequent calls to params.BeaconConfig() will
// return this new configuration.
func OverrideBeaconConfig(c *BeaconChainConfig) {
beaconConfigLock.Lock()
defer beaconConfigLock.Unlock()
beaconConfig = c
cfgrw.Lock()
defer cfgrw.Unlock()
configs.active = c
}
// Copy returns a copy of the config object.
func (b *BeaconChainConfig) Copy() *BeaconChainConfig {
beaconConfigLock.RLock()
defer beaconConfigLock.RUnlock()
cfgrw.RLock()
defer cfgrw.RUnlock()
config, ok := deepcopy.Copy(*b).(BeaconChainConfig)
if !ok {
config = *beaconConfig
panic("somehow deepcopy produced a BeaconChainConfig that is not of the same type as the original")
}
return &config
}

View File

@@ -7,11 +7,9 @@ import (
"github.com/mohae/deepcopy"
)
var beaconConfig = MainnetConfig()
// BeaconConfig retrieves beacon chain config.
func BeaconConfig() *BeaconChainConfig {
return beaconConfig
return configs.getActive()
}
// OverrideBeaconConfig by replacing the config. The preferred pattern is to
@@ -19,14 +17,14 @@ func BeaconConfig() *BeaconChainConfig {
// OverrideBeaconConfig(c). Any subsequent calls to params.BeaconConfig() will
// return this new configuration.
func OverrideBeaconConfig(c *BeaconChainConfig) {
beaconConfig = c
configs.active = c
}
// Copy returns a copy of the config object.
func (b *BeaconChainConfig) Copy() *BeaconChainConfig {
config, ok := deepcopy.Copy(*b).(BeaconChainConfig)
if !ok {
config = *beaconConfig
panic("somehow deepcopy produced a BeaconChainConfig that is not of the same type as the original")
}
return &config
}

171
config/params/configset.go Normal file
View File

@@ -0,0 +1,171 @@
package params
import (
"github.com/pkg/errors"
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
)
var configs *configset
// All returns a slice of every BeaconChainConfig contained in the configset.
func All() []*BeaconChainConfig {
return configs.all()
}
// ByName returns the BeaconChainConfig with the matching `ConfigName` field.
// The runtime ensures that each config name uniquely refers to a single BeaconChainConfig.
func ByName(name string) (*BeaconChainConfig, error) {
return configs.byName(name)
}
// ByVersion returns the BeaconChainConfig that has the given version in its ForkVersionSchedule.
// The configset ensures that each fork version schedule entry uniquely points to a single BeaconChainConfig.
func ByVersion(version [fieldparams.VersionLength]byte) (*BeaconChainConfig, error) {
return configs.byVersion(version)
}
// SetActive sets the given config as active (the config that will be returned by GetActive).
// SetActive will always overwrite any config with the same ConfigName before setting the updated value to active.
func SetActive(c *BeaconChainConfig) error {
return configs.setActive(c)
}
// SetActiveWithUndo attempts to set the active config, and if successful,
// returns a callback function that can be used to revert the configset back to its previous state.
func SetActiveWithUndo(c *BeaconChainConfig) (func() error, error) {
return configs.setActiveWithUndo(c)
}
type configset struct {
active *BeaconChainConfig
versionToName map[[fieldparams.VersionLength]byte]string
nameToConfig map[string]*BeaconChainConfig
}
func newConfigset(configs ...*BeaconChainConfig) *configset {
r := &configset{
versionToName: make(map[[fieldparams.VersionLength]byte]string),
nameToConfig: make(map[string]*BeaconChainConfig),
}
for _, c := range configs {
if err := r.add(c); err != nil {
panic(err)
}
}
return r
}
var errCannotNullifyActive = errors.New("cannot set a config marked as active to nil")
var errCollisionFork = errors.New("configset cannot add config with conflicting fork version schedule")
var errCollisionName = errors.New("config with conflicting name already exists")
var errConfigNotFound = errors.New("unable to find requested BeaconChainConfig")
var errReplaceNilConfig = errors.New("replace called with a nil value")
func (r *configset) add(c *BeaconChainConfig) error {
name := c.ConfigName
if _, exists := r.nameToConfig[name]; exists {
return errors.Wrapf(errCollisionName, "ConfigName=%s", name)
}
c.InitializeForkSchedule()
for v := range c.ForkVersionSchedule {
if n, exists := r.versionToName[v]; exists {
return errors.Wrapf(errCollisionFork, "config name=%s conflicts with existing config named=%s", name, n)
}
r.versionToName[v] = name
}
r.nameToConfig[name] = c
return nil
}
func (r *configset) delete(name string) {
c, exists := r.nameToConfig[name]
if !exists {
return
}
for v := range c.ForkVersionSchedule {
delete(r.versionToName, v)
}
delete(r.nameToConfig, name)
}
func (r *configset) replace(cfg *BeaconChainConfig) error {
if cfg == nil {
return errReplaceNilConfig
}
name := cfg.ConfigName
r.delete(name)
if err := r.add(cfg); err != nil {
return err
}
if r.active != nil && r.active.ConfigName == name {
r.active = cfg
}
return nil
}
func (r *configset) replaceWithUndo(cfg *BeaconChainConfig) (func() error, error) {
name := cfg.ConfigName
prev := r.nameToConfig[name]
if err := r.replace(cfg); err != nil {
return nil, err
}
return func() error {
if prev == nil {
if r.active.ConfigName == name {
return errors.Wrapf(errCannotNullifyActive, "active config name=%s", name)
}
r.delete(name)
return nil
}
return r.replace(prev)
}, nil
}
func (r *configset) getActive() *BeaconChainConfig {
return r.active
}
func (r *configset) setActive(c *BeaconChainConfig) error {
if err := r.replace(c); err != nil {
return err
}
r.active = c
return nil
}
func (r *configset) setActiveWithUndo(c *BeaconChainConfig) (func() error, error) {
active := r.active
r.active = c
undo, err := r.replaceWithUndo(c)
if err != nil {
return nil, err
}
return func() error {
r.active = active
return undo()
}, nil
}
func (r *configset) byName(name string) (*BeaconChainConfig, error) {
c, ok := r.nameToConfig[name]
if !ok {
return nil, errors.Wrapf(errConfigNotFound, "name=%s is not a known BeaconChainConfig name", name)
}
return c, nil
}
func (r *configset) byVersion(version [fieldparams.VersionLength]byte) (*BeaconChainConfig, error) {
name, ok := r.versionToName[version]
if !ok {
return nil, errors.Wrapf(errConfigNotFound, "version=%#x not found in any known fork choice schedule", version)
}
return r.byName(name)
}
func (r *configset) all() []*BeaconChainConfig {
all := make([]*BeaconChainConfig, 0)
for _, c := range r.nameToConfig {
all = append(all, c)
}
return all
}

View File

@@ -0,0 +1,203 @@
package params
import (
"testing"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
"github.com/prysmaticlabs/prysm/testing/require"
)
func TestConfigset_Add(t *testing.T) {
r := newConfigset()
name := "devnet"
cfg := testConfig(name)
require.NoError(t, r.add(cfg))
c, err := r.byName(name)
require.NoError(t, err)
compareConfigs(t, cfg, c)
require.ErrorIs(t, r.add(cfg), errCollisionName)
cfg.ConfigName = "test"
require.ErrorIs(t, r.add(cfg), errCollisionFork)
}
func TestConfigsetReplaceMainnet(t *testing.T) {
r := newConfigset()
mainnet := MainnetConfig().Copy()
require.NoError(t, r.setActive(mainnet))
FillTestVersions(mainnet, 128)
require.NoError(t, r.replace(mainnet))
}
func TestConfigset_Replace(t *testing.T) {
r := newConfigset()
mainnet := MainnetConfig().Copy()
require.NoError(t, r.add(mainnet))
require.NoError(t, r.setActive(mainnet))
require.ErrorIs(t, r.add(mainnet), errCollisionName)
c, err := r.byName(MainnetName)
require.NoError(t, err)
fail := c.Copy()
fail.ConfigName = "test"
require.ErrorIs(t, r.replace(fail), errCollisionFork)
o := c.Copy()
FillTestVersions(o, 128)
o.ConfigName = MainnetName
require.NoError(t, r.replace(o))
// mainnet is replaced, we shouldn't be able to find its fork version anymore
_, err = r.byVersion(bytesutil.ToBytes4(mainnet.GenesisForkVersion))
require.ErrorIs(t, err, errConfigNotFound)
undo := o.Copy()
FillTestVersions(undo, 127)
undoFunc, err := r.replaceWithUndo(undo)
require.NoError(t, err)
u, err := r.byName(undo.ConfigName)
require.NoError(t, err)
require.Equal(t, undo, u)
u, err = r.byVersion(bytesutil.ToBytes4(undo.GenesisForkVersion))
require.NoError(t, err)
require.Equal(t, undo, u)
_, err = r.byVersion(bytesutil.ToBytes4(o.GenesisForkVersion))
require.ErrorIs(t, err, errConfigNotFound)
require.NoError(t, undoFunc())
// replaced config restored by undoFunc, lookup should now succeed
_, err = r.byVersion(bytesutil.ToBytes4(o.GenesisForkVersion))
require.NoError(t, err)
}
func testConfig(name string) *BeaconChainConfig {
c := MainnetConfig().Copy()
FillTestVersions(c, 127)
c.ConfigName = name
return c
}
func compareConfigs(t *testing.T, expected, actual *BeaconChainConfig) {
require.DeepEqual(t, expected.GenesisEpoch, actual.GenesisEpoch)
require.DeepEqual(t, expected.FarFutureEpoch, actual.FarFutureEpoch)
require.DeepEqual(t, expected.FarFutureSlot, actual.FarFutureSlot)
require.DeepEqual(t, expected.BaseRewardsPerEpoch, actual.BaseRewardsPerEpoch)
require.DeepEqual(t, expected.DepositContractTreeDepth, actual.DepositContractTreeDepth)
require.DeepEqual(t, expected.JustificationBitsLength, actual.JustificationBitsLength)
require.DeepEqual(t, expected.PresetBase, actual.PresetBase)
require.DeepEqual(t, expected.ConfigName, actual.ConfigName)
require.DeepEqual(t, expected.TargetCommitteeSize, actual.TargetCommitteeSize)
require.DeepEqual(t, expected.MaxValidatorsPerCommittee, actual.MaxValidatorsPerCommittee)
require.DeepEqual(t, expected.MaxCommitteesPerSlot, actual.MaxCommitteesPerSlot)
require.DeepEqual(t, expected.MinPerEpochChurnLimit, actual.MinPerEpochChurnLimit)
require.DeepEqual(t, expected.ChurnLimitQuotient, actual.ChurnLimitQuotient)
require.DeepEqual(t, expected.ShuffleRoundCount, actual.ShuffleRoundCount)
require.DeepEqual(t, expected.MinGenesisActiveValidatorCount, actual.MinGenesisActiveValidatorCount)
require.DeepEqual(t, expected.MinGenesisTime, actual.MinGenesisTime)
require.DeepEqual(t, expected.TargetAggregatorsPerCommittee, actual.TargetAggregatorsPerCommittee)
require.DeepEqual(t, expected.HysteresisQuotient, actual.HysteresisQuotient)
require.DeepEqual(t, expected.HysteresisDownwardMultiplier, actual.HysteresisDownwardMultiplier)
require.DeepEqual(t, expected.HysteresisUpwardMultiplier, actual.HysteresisUpwardMultiplier)
require.DeepEqual(t, expected.MinDepositAmount, actual.MinDepositAmount)
require.DeepEqual(t, expected.MaxEffectiveBalance, actual.MaxEffectiveBalance)
require.DeepEqual(t, expected.EjectionBalance, actual.EjectionBalance)
require.DeepEqual(t, expected.EffectiveBalanceIncrement, actual.EffectiveBalanceIncrement)
require.DeepEqual(t, expected.BLSWithdrawalPrefixByte, actual.BLSWithdrawalPrefixByte)
require.DeepEqual(t, expected.ZeroHash, actual.ZeroHash)
require.DeepEqual(t, expected.GenesisDelay, actual.GenesisDelay)
require.DeepEqual(t, expected.MinAttestationInclusionDelay, actual.MinAttestationInclusionDelay)
require.DeepEqual(t, expected.SecondsPerSlot, actual.SecondsPerSlot)
require.DeepEqual(t, expected.SlotsPerEpoch, actual.SlotsPerEpoch)
require.DeepEqual(t, expected.SqrRootSlotsPerEpoch, actual.SqrRootSlotsPerEpoch)
require.DeepEqual(t, expected.MinSeedLookahead, actual.MinSeedLookahead)
require.DeepEqual(t, expected.MaxSeedLookahead, actual.MaxSeedLookahead)
require.DeepEqual(t, expected.EpochsPerEth1VotingPeriod, actual.EpochsPerEth1VotingPeriod)
require.DeepEqual(t, expected.SlotsPerHistoricalRoot, actual.SlotsPerHistoricalRoot)
require.DeepEqual(t, expected.MinValidatorWithdrawabilityDelay, actual.MinValidatorWithdrawabilityDelay)
require.DeepEqual(t, expected.ShardCommitteePeriod, actual.ShardCommitteePeriod)
require.DeepEqual(t, expected.MinEpochsToInactivityPenalty, actual.MinEpochsToInactivityPenalty)
require.DeepEqual(t, expected.Eth1FollowDistance, actual.Eth1FollowDistance)
require.DeepEqual(t, expected.SafeSlotsToUpdateJustified, actual.SafeSlotsToUpdateJustified)
require.DeepEqual(t, expected.SafeSlotsToImportOptimistically, actual.SafeSlotsToImportOptimistically)
require.DeepEqual(t, expected.SecondsPerETH1Block, actual.SecondsPerETH1Block)
require.DeepEqual(t, expected.ProposerScoreBoost, actual.ProposerScoreBoost)
require.DeepEqual(t, expected.IntervalsPerSlot, actual.IntervalsPerSlot)
require.DeepEqual(t, expected.DepositChainID, actual.DepositChainID)
require.DeepEqual(t, expected.DepositNetworkID, actual.DepositNetworkID)
require.DeepEqual(t, expected.DepositContractAddress, actual.DepositContractAddress)
require.DeepEqual(t, expected.RandomSubnetsPerValidator, actual.RandomSubnetsPerValidator)
require.DeepEqual(t, expected.EpochsPerRandomSubnetSubscription, actual.EpochsPerRandomSubnetSubscription)
require.DeepEqual(t, expected.EpochsPerHistoricalVector, actual.EpochsPerHistoricalVector)
require.DeepEqual(t, expected.EpochsPerSlashingsVector, actual.EpochsPerSlashingsVector)
require.DeepEqual(t, expected.HistoricalRootsLimit, actual.HistoricalRootsLimit)
require.DeepEqual(t, expected.ValidatorRegistryLimit, actual.ValidatorRegistryLimit)
require.DeepEqual(t, expected.BaseRewardFactor, actual.BaseRewardFactor)
require.DeepEqual(t, expected.WhistleBlowerRewardQuotient, actual.WhistleBlowerRewardQuotient)
require.DeepEqual(t, expected.ProposerRewardQuotient, actual.ProposerRewardQuotient)
require.DeepEqual(t, expected.InactivityPenaltyQuotient, actual.InactivityPenaltyQuotient)
require.DeepEqual(t, expected.MinSlashingPenaltyQuotient, actual.MinSlashingPenaltyQuotient)
require.DeepEqual(t, expected.ProportionalSlashingMultiplier, actual.ProportionalSlashingMultiplier)
require.DeepEqual(t, expected.MaxProposerSlashings, actual.MaxProposerSlashings)
require.DeepEqual(t, expected.MaxAttesterSlashings, actual.MaxAttesterSlashings)
require.DeepEqual(t, expected.MaxAttestations, actual.MaxAttestations)
require.DeepEqual(t, expected.MaxDeposits, actual.MaxDeposits)
require.DeepEqual(t, expected.MaxVoluntaryExits, actual.MaxVoluntaryExits)
require.DeepEqual(t, expected.DomainBeaconProposer, actual.DomainBeaconProposer)
require.DeepEqual(t, expected.DomainRandao, actual.DomainRandao)
require.DeepEqual(t, expected.DomainBeaconAttester, actual.DomainBeaconAttester)
require.DeepEqual(t, expected.DomainDeposit, actual.DomainDeposit)
require.DeepEqual(t, expected.DomainVoluntaryExit, actual.DomainVoluntaryExit)
require.DeepEqual(t, expected.DomainSelectionProof, actual.DomainSelectionProof)
require.DeepEqual(t, expected.DomainAggregateAndProof, actual.DomainAggregateAndProof)
require.DeepEqual(t, expected.DomainSyncCommittee, actual.DomainSyncCommittee)
require.DeepEqual(t, expected.DomainSyncCommitteeSelectionProof, actual.DomainSyncCommitteeSelectionProof)
require.DeepEqual(t, expected.DomainContributionAndProof, actual.DomainContributionAndProof)
require.DeepEqual(t, expected.GweiPerEth, actual.GweiPerEth)
require.DeepEqual(t, expected.BLSSecretKeyLength, actual.BLSSecretKeyLength)
require.DeepEqual(t, expected.BLSPubkeyLength, actual.BLSPubkeyLength)
require.DeepEqual(t, expected.DefaultBufferSize, actual.DefaultBufferSize)
require.DeepEqual(t, expected.ValidatorPrivkeyFileName, actual.ValidatorPrivkeyFileName)
require.DeepEqual(t, expected.WithdrawalPrivkeyFileName, actual.WithdrawalPrivkeyFileName)
require.DeepEqual(t, expected.RPCSyncCheck, actual.RPCSyncCheck)
require.DeepEqual(t, expected.EmptySignature, actual.EmptySignature)
require.DeepEqual(t, expected.DefaultPageSize, actual.DefaultPageSize)
require.DeepEqual(t, expected.MaxPeersToSync, actual.MaxPeersToSync)
require.DeepEqual(t, expected.SlotsPerArchivedPoint, actual.SlotsPerArchivedPoint)
require.DeepEqual(t, expected.GenesisCountdownInterval, actual.GenesisCountdownInterval)
require.DeepEqual(t, expected.BeaconStateFieldCount, actual.BeaconStateFieldCount)
require.DeepEqual(t, expected.BeaconStateAltairFieldCount, actual.BeaconStateAltairFieldCount)
require.DeepEqual(t, expected.BeaconStateBellatrixFieldCount, actual.BeaconStateBellatrixFieldCount)
require.DeepEqual(t, expected.WeakSubjectivityPeriod, actual.WeakSubjectivityPeriod)
require.DeepEqual(t, expected.PruneSlasherStoragePeriod, actual.PruneSlasherStoragePeriod)
require.DeepEqual(t, expected.SlashingProtectionPruningEpochs, actual.SlashingProtectionPruningEpochs)
require.DeepEqual(t, expected.GenesisForkVersion, actual.GenesisForkVersion)
require.DeepEqual(t, expected.AltairForkVersion, actual.AltairForkVersion)
require.DeepEqual(t, expected.AltairForkEpoch, actual.AltairForkEpoch)
require.DeepEqual(t, expected.BellatrixForkVersion, actual.BellatrixForkVersion)
require.DeepEqual(t, expected.BellatrixForkEpoch, actual.BellatrixForkEpoch)
require.DeepEqual(t, expected.ShardingForkVersion, actual.ShardingForkVersion)
require.DeepEqual(t, expected.ShardingForkEpoch, actual.ShardingForkEpoch)
require.DeepEqual(t, expected.ForkVersionSchedule, actual.ForkVersionSchedule)
require.DeepEqual(t, expected.SafetyDecay, actual.SafetyDecay)
require.DeepEqual(t, expected.TimelySourceFlagIndex, actual.TimelySourceFlagIndex)
require.DeepEqual(t, expected.TimelyTargetFlagIndex, actual.TimelyTargetFlagIndex)
require.DeepEqual(t, expected.TimelyHeadFlagIndex, actual.TimelyHeadFlagIndex)
require.DeepEqual(t, expected.TimelySourceWeight, actual.TimelySourceWeight)
require.DeepEqual(t, expected.TimelyTargetWeight, actual.TimelyTargetWeight)
require.DeepEqual(t, expected.TimelyHeadWeight, actual.TimelyHeadWeight)
require.DeepEqual(t, expected.SyncRewardWeight, actual.SyncRewardWeight)
require.DeepEqual(t, expected.WeightDenominator, actual.WeightDenominator)
require.DeepEqual(t, expected.ProposerWeight, actual.ProposerWeight)
require.DeepEqual(t, expected.TargetAggregatorsPerSyncSubcommittee, actual.TargetAggregatorsPerSyncSubcommittee)
require.DeepEqual(t, expected.SyncCommitteeSubnetCount, actual.SyncCommitteeSubnetCount)
require.DeepEqual(t, expected.SyncCommitteeSize, actual.SyncCommitteeSize)
require.DeepEqual(t, expected.InactivityScoreBias, actual.InactivityScoreBias)
require.DeepEqual(t, expected.InactivityScoreRecoveryRate, actual.InactivityScoreRecoveryRate)
require.DeepEqual(t, expected.EpochsPerSyncCommitteePeriod, actual.EpochsPerSyncCommitteePeriod)
require.DeepEqual(t, expected.InactivityPenaltyQuotientAltair, actual.InactivityPenaltyQuotientAltair)
require.DeepEqual(t, expected.MinSlashingPenaltyQuotientAltair, actual.MinSlashingPenaltyQuotientAltair)
require.DeepEqual(t, expected.ProportionalSlashingMultiplierAltair, actual.ProportionalSlashingMultiplierAltair)
require.DeepEqual(t, expected.MinSlashingPenaltyQuotientBellatrix, actual.MinSlashingPenaltyQuotientBellatrix)
require.DeepEqual(t, expected.ProportionalSlashingMultiplierBellatrix, actual.ProportionalSlashingMultiplierBellatrix)
require.DeepEqual(t, expected.InactivityPenaltyQuotientBellatrix, actual.InactivityPenaltyQuotientBellatrix)
require.DeepEqual(t, expected.MinSyncCommitteeParticipants, actual.MinSyncCommitteeParticipants)
require.DeepEqual(t, expected.TerminalBlockHash, actual.TerminalBlockHash)
require.DeepEqual(t, expected.TerminalBlockHashActivationEpoch, actual.TerminalBlockHashActivationEpoch)
require.DeepEqual(t, expected.TerminalTotalDifficulty, actual.TerminalTotalDifficulty)
require.DeepEqual(t, expected.DefaultFeeRecipient, actual.DefaultFeeRecipient)
}

26
config/params/init.go Normal file
View File

@@ -0,0 +1,26 @@
package params
func init() {
defaults := []*BeaconChainConfig{
MainnetConfig(),
PraterConfig(),
MinimalSpecConfig(),
E2ETestConfig(),
E2EMainnetTestConfig(),
InteropConfig(),
RopstenConfig(),
}
configs = newConfigset(defaults...)
// ensure that main net is always present and active by default
if err := SetActive(MainnetConfig()); err != nil {
panic(err)
}
// make sure mainnet is present and active
m, err := ByName(MainnetName)
if err != nil {
panic(err)
}
if configs.getActive() != m {
panic("mainnet should always be the active config at init() time")
}
}

16
config/params/interop.go Normal file
View File

@@ -0,0 +1,16 @@
package params
// InteropConfig provides a generic config suitable for interop testing.
func InteropConfig() *BeaconChainConfig {
c := MainnetConfig().Copy()
// Prysm constants.
c.ConfigName = InteropName
c.GenesisForkVersion = []byte{0, 0, 0, 235}
c.AltairForkVersion = []byte{1, 0, 0, 235}
c.BellatrixForkVersion = []byte{2, 0, 0, 235}
c.ShardingForkVersion = []byte{3, 0, 0, 235}
c.InitializeForkSchedule()
return c
}

View File

@@ -6,6 +6,7 @@ import (
"os"
"strings"
"github.com/pkg/errors"
types "github.com/prysmaticlabs/prysm/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/math"
log "github.com/sirupsen/logrus"
@@ -24,12 +25,10 @@ func isMinimal(lines []string) bool {
return false
}
// LoadChainConfigFile load, convert hex values into valid param yaml format,
// unmarshal , and apply beacon chain config file.
func LoadChainConfigFile(chainConfigFileName string, conf *BeaconChainConfig) {
yamlFile, err := os.ReadFile(chainConfigFileName) // #nosec G304
func UnmarshalConfigFile(path string, conf *BeaconChainConfig) (*BeaconChainConfig, error) {
yamlFile, err := os.ReadFile(path) // #nosec G304
if err != nil {
log.WithError(err).Fatal("Failed to read chain config file.")
return nil, errors.Wrap(err, "Failed to read chain config file.")
}
// To track if config name is defined inside config file.
hasConfigName := false
@@ -59,19 +58,28 @@ func LoadChainConfigFile(chainConfigFileName string, conf *BeaconChainConfig) {
yamlFile = []byte(strings.Join(lines, "\n"))
if err := yaml.UnmarshalStrict(yamlFile, conf); err != nil {
if _, ok := err.(*yaml.TypeError); !ok {
log.WithError(err).Fatal("Failed to parse chain config yaml file.")
return nil, errors.Wrap(err, "Failed to parse chain config yaml file.")
} else {
log.WithError(err).Error("There were some issues parsing the config from a yaml file")
}
}
if !hasConfigName {
conf.ConfigName = "devnet"
conf.ConfigName = DevnetName
}
// recompute SqrRootSlotsPerEpoch constant to handle non-standard values of SlotsPerEpoch
conf.SqrRootSlotsPerEpoch = types.Slot(math.IntegerSquareRoot(uint64(conf.SlotsPerEpoch)))
log.Debugf("Config file values: %+v", conf)
conf.InitializeForkSchedule()
OverrideBeaconConfig(conf)
return conf, nil
}
// LoadChainConfigFile load, convert hex values into valid param yaml format,
// unmarshal , and apply beacon chain config file.
func LoadChainConfigFile(path string, conf *BeaconChainConfig) error {
c, err := UnmarshalConfigFile(path, conf)
if err != nil {
return err
}
return SetActive(c)
}
// ReplaceHexStringWithYAMLFormat will replace hex strings that the yaml parser will understand.

View File

@@ -1,6 +1,8 @@
package params_test
import (
"bytes"
"io"
"os"
"path"
"path/filepath"
@@ -109,36 +111,49 @@ func TestLoadConfigFile(t *testing.T) {
}
t.Run("mainnet", func(t *testing.T) {
mn := params.MainnetConfig().Copy()
mainnetPresetsFiles := presetsFilePath(t, "mainnet")
var err error
for _, fp := range mainnetPresetsFiles {
params.LoadChainConfigFile(fp, nil)
mn, err = params.UnmarshalConfigFile(fp, mn)
require.NoError(t, err)
}
// configs loaded from file get the name 'devnet' unless they specify a specific name in the yaml itself.
// since these are partial patches for presets, they do not have the config name
mn.ConfigName = params.MainnetName
mainnetConfigFile := configFilePath(t, "mainnet")
params.LoadChainConfigFile(mainnetConfigFile, nil)
mnf, err := params.UnmarshalConfigFile(mainnetConfigFile, nil)
require.NoError(t, err)
fields := fieldsFromYamls(t, append(mainnetPresetsFiles, mainnetConfigFile))
assertVals("mainnet", fields, params.MainnetConfig(), params.BeaconConfig())
assertVals("mainnet", fields, mn, mnf)
})
t.Run("minimal", func(t *testing.T) {
min := params.MinimalSpecConfig().Copy()
minimalPresetsFiles := presetsFilePath(t, "minimal")
var err error
for _, fp := range minimalPresetsFiles {
params.LoadChainConfigFile(fp, nil)
min, err = params.UnmarshalConfigFile(fp, min)
require.NoError(t, err)
}
// configs loaded from file get the name 'devnet' unless they specify a specific name in the yaml itself.
// since these are partial patches for presets, they do not have the config name
min.ConfigName = params.MinimalName
minimalConfigFile := configFilePath(t, "minimal")
params.LoadChainConfigFile(minimalConfigFile, nil)
minf, err := params.UnmarshalConfigFile(minimalConfigFile, nil)
require.NoError(t, err)
fields := fieldsFromYamls(t, append(minimalPresetsFiles, minimalConfigFile))
assertVals("minimal", fields, params.MinimalSpecConfig(), params.BeaconConfig())
assertVals("minimal", fields, min, minf)
})
t.Run("e2e", func(t *testing.T) {
minimalPresetsFiles := presetsFilePath(t, "minimal")
for _, fp := range minimalPresetsFiles {
params.LoadChainConfigFile(fp, nil)
}
e2e, err := params.ByName(params.EndToEndName)
require.NoError(t, err)
configFile := "testdata/e2e_config.yaml"
params.LoadChainConfigFile(configFile, nil)
fields := fieldsFromYamls(t, append(minimalPresetsFiles, configFile))
assertVals("e2e", fields, params.E2ETestConfig(), params.BeaconConfig())
e2ef, err := params.UnmarshalConfigFile(configFile, nil)
require.NoError(t, err)
fields := fieldsFromYamls(t, []string{configFile})
assertVals("e2e", fields, e2e, e2ef)
})
}
@@ -146,21 +161,34 @@ func TestLoadConfigFile_OverwriteCorrectly(t *testing.T) {
file, err := os.CreateTemp("", "")
require.NoError(t, err)
// Set current config to minimal config
params.OverrideBeaconConfig(params.MinimalSpecConfig())
cfg := params.MinimalSpecConfig().Copy()
params.FillTestVersions(cfg, 128)
_, err = io.Copy(file, bytes.NewBuffer(params.ConfigToYaml(cfg)))
require.NoError(t, err)
// set active config to mainnet, so that we can confirm LoadChainConfigFile overrides it
mainnet, err := params.ByName(params.MainnetName)
require.NoError(t, err)
undo, err := params.SetActiveWithUndo(mainnet)
require.NoError(t, err)
defer func() {
err := undo()
require.NoError(t, err)
}()
// load empty config file, so that it defaults to mainnet values
params.LoadChainConfigFile(file.Name(), nil)
if params.BeaconConfig().MinGenesisTime != params.MainnetConfig().MinGenesisTime {
t.Errorf("Expected MinGenesisTime to be set to mainnet value: %d found: %d",
params.MainnetConfig().MinGenesisTime,
require.NoError(t, params.LoadChainConfigFile(file.Name(), nil))
if params.BeaconConfig().MinGenesisTime != cfg.MinGenesisTime {
t.Errorf("Expected MinGenesisTime to be set to value written to config: %d found: %d",
cfg.MinGenesisTime,
params.BeaconConfig().MinGenesisTime)
}
if params.BeaconConfig().SlotsPerEpoch != params.MainnetConfig().SlotsPerEpoch {
t.Errorf("Expected SlotsPerEpoch to be set to mainnet value: %d found: %d",
params.MainnetConfig().SlotsPerEpoch,
if params.BeaconConfig().SlotsPerEpoch != cfg.SlotsPerEpoch {
t.Errorf("Expected SlotsPerEpoch to be set to value written to config: %d found: %d",
cfg.SlotsPerEpoch,
params.BeaconConfig().SlotsPerEpoch)
}
require.Equal(t, "devnet", params.BeaconConfig().ConfigName)
require.Equal(t, params.MinimalName, params.BeaconConfig().ConfigName)
}
func Test_replaceHexStringWithYAMLFormat(t *testing.T) {
@@ -241,7 +269,7 @@ func TestConfigParityYaml(t *testing.T) {
yamlObj := params.ConfigToYaml(testCfg)
assert.NoError(t, file.WriteFile(yamlDir, yamlObj))
params.LoadChainConfigFile(yamlDir, params.E2ETestConfig().Copy())
require.NoError(t, params.LoadChainConfigFile(yamlDir, params.E2ETestConfig().Copy()))
assert.DeepEqual(t, params.BeaconConfig(), testCfg)
}

View File

@@ -4,6 +4,7 @@ import (
"math"
"time"
fieldparams "github.com/prysmaticlabs/prysm/config/fieldparams"
"github.com/prysmaticlabs/prysm/encoding/bytesutil"
)
@@ -15,11 +16,6 @@ func MainnetConfig() *BeaconChainConfig {
return mainnetBeaconConfig
}
// UseMainnetConfig for beacon chain services.
func UseMainnetConfig() {
beaconConfig = MainnetConfig()
}
const (
// Genesis Fork Epoch for the mainnet config.
genesisForkEpoch = 0
@@ -247,3 +243,32 @@ var mainnetBeaconConfig = &BeaconChainConfig{
TerminalBlockHash: [32]byte{},
TerminalTotalDifficulty: "115792089237316195423570985008687907853269984665640564039457584007913129638912",
}
// MainnetTestConfig provides a version of the mainnet config that has a different name
// and a different fork choice schedule. This can be used in cases where we want to use config values
// that are consistent with mainnet, but won't conflict or cause the hard-coded genesis to be loaded.
func MainnetTestConfig() *BeaconChainConfig {
mn := MainnetConfig().Copy()
mn.ConfigName = MainnetTestName
FillTestVersions(mn, 128)
return mn
}
// FillTestVersions replaces the byte in the last position of each fork version
// so that
func FillTestVersions(c *BeaconChainConfig, b byte) {
c.GenesisForkVersion = make([]byte, fieldparams.VersionLength)
c.AltairForkVersion = make([]byte, fieldparams.VersionLength)
c.BellatrixForkVersion = make([]byte, fieldparams.VersionLength)
c.ShardingForkVersion = make([]byte, fieldparams.VersionLength)
c.GenesisForkVersion[fieldparams.VersionLength-1] = b
c.AltairForkVersion[fieldparams.VersionLength-1] = b
c.BellatrixForkVersion[fieldparams.VersionLength-1] = b
c.ShardingForkVersion[fieldparams.VersionLength-1] = b
c.GenesisForkVersion[0] = 0
c.AltairForkVersion[0] = 1
c.BellatrixForkVersion[0] = 2
c.ShardingForkVersion[0] = 3
}

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