public void MaximumPenalties() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); int slashedCount = (state.Validators.Count / 3) + 1; Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state); Epoch outEpoch = currentEpoch + new Epoch((ulong)stateListLengths.EpochsPerSlashingsVector / 2); var slashedIndices = Enumerable.Range(0, slashedCount).ToList(); SlashValidators(testServiceProvider, state, slashedIndices, Enumerable.Repeat(outEpoch, slashedCount)); Gwei totalBalance = beaconStateAccessor.GetTotalActiveBalance(state); Gwei totalPenalties = state.Slashings.Aggregate(Gwei.Zero, (accumulator, x) => accumulator + x); (totalBalance / 3).ShouldBeLessThanOrEqualTo(totalPenalties); // Act RunProcessSlashings(testServiceProvider, state); // Assert foreach (int index in slashedIndices) { state.Balances[index].ShouldBe(Gwei.Zero, $"Incorrect balance {index}"); } }
/// <summary> /// Slash the validator with index ``slashed_index``. /// </summary> public void SlashValidator(BeaconState state, ValidatorIndex slashedIndex, ValidatorIndex?optionalWhistleblowerIndex) { RewardsAndPenalties rewardsAndPenalties = _rewardsAndPenaltiesOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; Epoch epoch = _beaconStateAccessor.GetCurrentEpoch(state); InitiateValidatorExit(state, slashedIndex); Validator validator = state.Validators[(int)slashedIndex]; validator.SetSlashed(); Epoch slashedWithdrawableEpoch = (Epoch)(epoch + stateListLengths.EpochsPerSlashingsVector); Epoch withdrawableEpoch = Epoch.Max(validator.WithdrawableEpoch, slashedWithdrawableEpoch); validator.SetWithdrawableEpoch(withdrawableEpoch); Epoch slashingsIndex = (Epoch)(epoch % stateListLengths.EpochsPerSlashingsVector); state.SetSlashings(slashingsIndex, validator.EffectiveBalance); Gwei slashingPenalty = validator.EffectiveBalance / rewardsAndPenalties.MinimumSlashingPenaltyQuotient; DecreaseBalance(state, slashedIndex, slashingPenalty); // Apply proposer and whistleblower rewards ValidatorIndex proposerIndex = _beaconStateAccessor.GetBeaconProposerIndex(state); ValidatorIndex whistleblowerIndex = optionalWhistleblowerIndex ?? proposerIndex; Gwei whistleblowerReward = validator.EffectiveBalance / rewardsAndPenalties.WhistleblowerRewardQuotient; Gwei proposerReward = whistleblowerReward / rewardsAndPenalties.ProposerRewardQuotient; IncreaseBalance(state, proposerIndex, proposerReward); IncreaseBalance(state, whistleblowerIndex, whistleblowerReward - proposerReward); }
public CryptographyService(ChainConstants chainConstants, IOptionsMonitor<MiscellaneousParameters> miscellaneousParameterOptions, IOptionsMonitor<TimeParameters> timeParameterOptions, IOptionsMonitor<StateListLengths> stateListLengthOptions, IOptionsMonitor<MaxOperationsPerBlock> maxOperationsPerBlockOptions) { _chainConstants = chainConstants; _miscellaneousParameterOptions = miscellaneousParameterOptions; _timeParameterOptions = timeParameterOptions; _stateListLengthOptions = stateListLengthOptions; _maxOperationsPerBlockOptions = maxOperationsPerBlockOptions; MiscellaneousParameters miscellaneousParameters = miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = timeParameterOptions.CurrentValue; StateListLengths stateListLengths = stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = maxOperationsPerBlockOptions.CurrentValue; Nethermind.Ssz.Ssz.Init( chainConstants.DepositContractTreeDepth, chainConstants.JustificationBitsLength, miscellaneousParameters.MaximumValidatorsPerCommittee, timeParameters.SlotsPerEpoch, timeParameters.SlotsPerEth1VotingPeriod, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, stateListLengths.HistoricalRootsLimit, stateListLengths.ValidatorRegistryLimit, maxOperationsPerBlock.MaximumProposerSlashings, maxOperationsPerBlock.MaximumAttesterSlashings, maxOperationsPerBlock.MaximumAttestations, maxOperationsPerBlock.MaximumDeposits, maxOperationsPerBlock.MaximumVoluntaryExits); }
public async Task GenesisHead() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.ConfigureNethermindCore2(); string debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 stateRoot = cryptographyService.HashTreeRoot(state); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 expectedRoot = cryptographyService.SigningRoot(genesisBlock); headRoot.ShouldBe(expectedRoot); }
public BeaconState InitializeBeaconStateFromEth1(Bytes32 eth1BlockHash, ulong eth1Timestamp, IList <Deposit> deposits) { if (_logger.IsInfo()) { Log.InitializeBeaconState(_logger, eth1BlockHash, eth1Timestamp, deposits.Count, null); } InitialValues initialValues = _initialValueOptions.CurrentValue; GweiValues gweiValues = _gweiValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; Fork fork = new Fork(initialValues.GenesisForkVersion, initialValues.GenesisForkVersion, _chainConstants.GenesisEpoch); ulong genesisTime = eth1Timestamp - (eth1Timestamp % timeParameters.MinimumGenesisDelay) + (2 * timeParameters.MinimumGenesisDelay); Eth1Data eth1Data = new Eth1Data(Root.Zero, (ulong)deposits.Count, eth1BlockHash); Root emptyBlockBodyRoot = _cryptographyService.HashTreeRoot(BeaconBlockBody.Zero); BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBodyRoot); Bytes32[] randaoMixes = Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector) .ToArray(); BeaconState state = new BeaconState(genesisTime, fork, eth1Data, latestBlockHeader, randaoMixes, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength); // Process deposits List <DepositData> depositDataList = new List <DepositData>(); foreach (Deposit deposit in deposits) { depositDataList.Add(deposit.Data); Root depositRoot = _cryptographyService.HashTreeRoot(depositDataList); state.Eth1Data.SetDepositRoot(depositRoot); _beaconStateTransition.ProcessDeposit(state, deposit); } // Process activations for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++) { Validator validator = state.Validators[validatorIndex]; Gwei balance = state.Balances[validatorIndex]; Gwei effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance); validator.SetEffectiveBalance(effectiveBalance); if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance) { validator.SetEligible(_chainConstants.GenesisEpoch); validator.SetActive(_chainConstants.GenesisEpoch); } } return(state); }
public Hash32 HashTreeRoot(BeaconState beaconState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; ulong maximumAttestationsPerEpoch = maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch; return(beaconState.HashTreeRoot(stateListLengths.HistoricalRootsLimit, timeParameters.SlotsPerEth1VotingPeriod, stateListLengths.ValidatorRegistryLimit, maximumAttestationsPerEpoch, miscellaneousParameters.MaximumValidatorsPerCommittee)); }
/// <summary> /// State transition via the provided ``block`` /// then package the block with the state root and signature. /// </summary> public static void StateTransitionAndSignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); beaconStateTransition.StateTransition(state, block, validateStateRoot: false); Hash32 stateRoot = state.HashTreeRoot(miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock); block.SetStateRoot(stateRoot); TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); }
public Hash32 HashTreeRoot(BeaconState beaconState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; ulong maximumAttestationsPerEpoch = maxOperationsPerBlock.MaximumAttestations * (ulong) timeParameters.SlotsPerEpoch; return beaconState.HashTreeRoot(stateListLengths.HistoricalRootsLimit, timeParameters.SlotsPerEth1VotingPeriod, stateListLengths.ValidatorRegistryLimit, maximumAttestationsPerEpoch, miscellaneousParameters.MaximumValidatorsPerCommittee); // Merkle.Ize(out UInt256 root, beaconState); // Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1)); // return new Hash32(bytes); }
public static BeaconState CreateGenesisState(IServiceProvider testServiceProvider, ulong numberOfValidators) { ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; InitialValues initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); var eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray()); var state = new BeaconState( 0, new Core2.Containers.Fork(new ForkVersion(new byte[ForkVersion.Length]), new ForkVersion(new byte[ForkVersion.Length]), Epoch.Zero), new Eth1Data(Root.Zero, numberOfValidators, eth1BlockHash), //numberOfValidators, new BeaconBlockHeader(cryptographyService.HashTreeRoot(BeaconBlockBody.Zero)), Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector).ToArray(), timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, chainConstants.JustificationBitsLength ); // We directly insert in the initial validators, // as it is much faster than creating and processing genesis deposits for every single test case. for (var index = (ulong)0; index < numberOfValidators; index++) { var validator = BuildMockValidator(chainConstants, initialValues, gweiValues, timeParameters, index, gweiValues.MaximumEffectiveBalance); state.AddValidatorWithBalance(validator, gweiValues.MaximumEffectiveBalance); state.IncreaseEth1DepositIndex(); } // Process genesis activations foreach (var validator in state.Validators) { if (validator.EffectiveBalance >= gweiValues.MaximumEffectiveBalance) { validator.SetEligible(chainConstants.GenesisEpoch); validator.SetActive(chainConstants.GenesisEpoch); } } return(state); }
public BeaconState InitializeBeaconStateFromEth1(Hash32 eth1BlockHash, ulong eth1Timestamp, IEnumerable <Deposit> deposits) { _logger.LogDebug(Event.InitializeBeaconState, "Initialise beacon state from ETH1 block {Eth1BlockHash}, time {Eth1Timestamp}, with {DepositCount} deposits.", eth1BlockHash, eth1Timestamp, deposits.Count()); GweiValues gweiValues = _gweiValueOptions.CurrentValue; InitialValues initialValues = _initialValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; ulong genesisTime = eth1Timestamp - (eth1Timestamp % _chainConstants.SecondsPerDay) + (2 * _chainConstants.SecondsPerDay); Eth1Data eth1Data = new Eth1Data((ulong)deposits.Count(), eth1BlockHash); BeaconBlockBody emptyBlockBody = new BeaconBlockBody(); BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBody.HashTreeRoot(_miscellaneousParameterOptions.CurrentValue, _maxOperationsPerBlockOptions.CurrentValue)); BeaconState state = new BeaconState(genesisTime, 0, eth1Data, latestBlockHeader, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength); // Process deposits var depositDataList = new List <DepositData>(); foreach (Deposit deposit in deposits) { depositDataList.Add(deposit.Data); Hash32 depositRoot = depositDataList.HashTreeRoot(_chainConstants.MaximumDepositContracts); state.Eth1Data.SetDepositRoot(depositRoot); _beaconStateTransition.ProcessDeposit(state, deposit); } // Process activations for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++) { Validator validator = state.Validators[validatorIndex]; Gwei balance = state.Balances[validatorIndex]; Gwei effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance); validator.SetEffectiveBalance(effectiveBalance); if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance) { validator.SetEligible(initialValues.GenesisEpoch); validator.SetActive(initialValues.GenesisEpoch); } } return(state); }
public static BeaconBlock BuildEmptyBlock(IServiceProvider testServiceProvider, BeaconState state, Slot slot, bool signed) { //if (slot) is none MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); Eth1Data eth1Data = new Eth1Data(state.Eth1DepositIndex, Hash32.Zero); BeaconBlockHeader previousBlockHeader = BeaconBlockHeader.Clone(state.LatestBlockHeader); if (previousBlockHeader.StateRoot == Hash32.Zero) { Hash32 stateRoot = cryptographyService.HashTreeRoot(state); previousBlockHeader.SetStateRoot(stateRoot); } Hash32 previousBlockSigningRoot = previousBlockHeader.SigningRoot(); BeaconBlock emptyBlock = new BeaconBlock(slot, previousBlockSigningRoot, Hash32.Zero, new BeaconBlockBody( BlsSignature.Empty, eth1Data, new Bytes32(), Array.Empty <ProposerSlashing>(), Array.Empty <AttesterSlashing>(), Array.Empty <Attestation>(), Array.Empty <Deposit>(), Array.Empty <VoluntaryExit>() ), BlsSignature.Empty); if (signed) { SignBlock(testServiceProvider, state, emptyBlock, ValidatorIndex.None); } return(emptyBlock); }
/// <summary> /// State transition via the provided ``block`` /// then package the block with the state root and signature. /// </summary> public static SignedBeaconBlock StateTransitionAndSignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); SignedBeaconBlock preSigningBlock = new SignedBeaconBlock(block, BlsSignature.Zero); beaconStateTransition.StateTransition(state, preSigningBlock, validateResult: false); Root stateRoot = cryptographyService.HashTreeRoot(state); block.SetStateRoot(stateRoot); SignedBeaconBlock signedBlock = TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); return(signedBlock); }
private void SlashValidators(IServiceProvider testServiceProvider, BeaconState state, IEnumerable <int> indices, IEnumerable <Epoch> outEpochs) { StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); BeaconStateMutator beaconStateMutator = testServiceProvider.GetService <BeaconStateMutator>(); Gwei totalSlashedBalance = Gwei.Zero; var items = indices.Zip(outEpochs, (index, outEpoch) => new { index, outEpoch }); foreach (var item in items) { Validator validator = state.Validators[item.index]; validator.SetSlashed(); beaconStateMutator.InitiateValidatorExit(state, new ValidatorIndex((ulong)item.index)); validator.SetWithdrawableEpoch(item.outEpoch); totalSlashedBalance += validator.EffectiveBalance; } Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state); Epoch slashingsIndex = (Epoch)(currentEpoch % stateListLengths.EpochsPerSlashingsVector); state.SetSlashings(slashingsIndex, totalSlashedBalance); }
private static void ValidateConfigShouldHaveValues(MiscellaneousParameters miscellaneousParameters, ForkChoiceConfiguration forkChoiceConfiguration, HonestValidatorConstants honestValidatorConstants, GweiValues gweiValues, InitialValues initialValues, TimeParameters timeParameters, StateListLengths stateListLengths, RewardsAndPenalties rewardsAndPenalties, MaxOperationsPerBlock maxOperationsPerBlock, SignatureDomains signatureDomains) { miscellaneousParameters.ChurnLimitQuotient.ShouldNotBe(0uL); miscellaneousParameters.MaximumCommitteesPerSlot.ShouldNotBe(0uL); miscellaneousParameters.MaximumValidatorsPerCommittee.ShouldNotBe(0uL); miscellaneousParameters.MinimumGenesisActiveValidatorCount.ShouldNotBe(0); miscellaneousParameters.MinimumGenesisTime.ShouldNotBe(0uL); miscellaneousParameters.MinimumPerEpochChurnLimit.ShouldNotBe(0uL); miscellaneousParameters.ShuffleRoundCount.ShouldNotBe(0); miscellaneousParameters.TargetCommitteeSize.ShouldNotBe(0uL); forkChoiceConfiguration.SafeSlotsToUpdateJustified.ShouldNotBe(Slot.Zero); honestValidatorConstants.EpochsPerRandomSubnetSubscription.ShouldNotBe(Epoch.Zero); honestValidatorConstants.Eth1FollowDistance.ShouldNotBe(0uL); honestValidatorConstants.RandomSubnetsPerValidator.ShouldNotBe(0uL); honestValidatorConstants.SecondsPerEth1Block.ShouldNotBe(0uL); honestValidatorConstants.TargetAggregatorsPerCommittee.ShouldNotBe(0uL); gweiValues.EffectiveBalanceIncrement.ShouldNotBe(Gwei.Zero); gweiValues.EjectionBalance.ShouldNotBe(Gwei.Zero); gweiValues.MaximumEffectiveBalance.ShouldNotBe(Gwei.Zero); // actually should be zero initialValues.BlsWithdrawalPrefix.ShouldBe((byte)0); initialValues.GenesisForkVersion.ShouldBe(new ForkVersion(new byte[] { 0x00, 0x00, 0x00, 0x01 })); timeParameters.MaximumSeedLookahead.ShouldNotBe(Epoch.Zero); timeParameters.MinimumAttestationInclusionDelay.ShouldNotBe(Slot.Zero); timeParameters.MinimumGenesisDelay.ShouldNotBe(0u); timeParameters.MinimumEpochsToInactivityPenalty.ShouldNotBe(Epoch.Zero); timeParameters.MinimumSeedLookahead.ShouldNotBe(Epoch.Zero); timeParameters.MinimumValidatorWithdrawabilityDelay.ShouldNotBe(Epoch.Zero); timeParameters.PersistentCommitteePeriod.ShouldNotBe(Epoch.Zero); timeParameters.SecondsPerSlot.ShouldNotBe(0U); timeParameters.SlotsPerEpoch.ShouldNotBe(0U); timeParameters.SlotsPerEth1VotingPeriod.ShouldNotBe(0U); timeParameters.SlotsPerHistoricalRoot.ShouldNotBe(0U); stateListLengths.EpochsPerHistoricalVector.ShouldNotBe(0U); stateListLengths.EpochsPerSlashingsVector.ShouldNotBe(0U); stateListLengths.HistoricalRootsLimit.ShouldNotBe(0uL); stateListLengths.ValidatorRegistryLimit.ShouldNotBe(0uL); rewardsAndPenalties.BaseRewardFactor.ShouldNotBe(0uL); rewardsAndPenalties.InactivityPenaltyQuotient.ShouldNotBe(0uL); rewardsAndPenalties.MinimumSlashingPenaltyQuotient.ShouldNotBe(0uL); rewardsAndPenalties.ProposerRewardQuotient.ShouldNotBe(0uL); rewardsAndPenalties.WhistleblowerRewardQuotient.ShouldNotBe(0uL); maxOperationsPerBlock.MaximumAttestations.ShouldNotBe(0uL); maxOperationsPerBlock.MaximumAttesterSlashings.ShouldNotBe(0uL); maxOperationsPerBlock.MaximumDeposits.ShouldNotBe(0uL); maxOperationsPerBlock.MaximumProposerSlashings.ShouldNotBe(0uL); maxOperationsPerBlock.MaximumVoluntaryExits.ShouldNotBe(0uL); // actually should be zero signatureDomains.BeaconProposer.ShouldBe(default);
public static Hash32 HashTreeRoot(this BeaconState item, MiscellaneousParameters miscellaneousParameters, TimeParameters timeParameters, StateListLengths stateListLengths, MaxOperationsPerBlock maxOperationsPerBlock) { var tree = new SszTree(item.ToSszContainer(miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock)); return(new Hash32(tree.HashTreeRoot())); }
public static SszContainer ToSszContainer(this BeaconState item, MiscellaneousParameters miscellaneousParameters, TimeParameters timeParameters, StateListLengths stateListLengths, MaxOperationsPerBlock maxOperationsPerBlock) { return(new SszContainer(GetValues(item, miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock))); }
// Run ``process_attester_slashing``, yielding: // - pre-state('pre') // - attester_slashing('attester_slashing') // - post-state('post'). //If ``valid == False``, run expecting ``AssertionError`` private void RunAttesterSlashingProcessing(IServiceProvider testServiceProvider, BeaconState state, AttesterSlashing attesterSlashing, bool expectValid) { ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; RewardsAndPenalties rewardsAndPenalties = testServiceProvider.GetService <IOptions <RewardsAndPenalties> >().Value; BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); if (!expectValid) { Should.Throw <Exception>(() => { beaconStateTransition.ProcessAttesterSlashing(state, attesterSlashing); }); return; } var slashedIndices = attesterSlashing.Attestation1.CustodyBit0Indices .Union(attesterSlashing.Attestation1.CustodyBit1Indices) .ToList(); ValidatorIndex proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state); Gwei preProposerBalance = TestState.GetBalance(state, proposerIndex); var preSlashings = slashedIndices.ToDictionary(x => x, x => TestState.GetBalance(state, x)); var preWithdrawableEpochs = slashedIndices.ToDictionary(x => x, x => state.Validators[(int)(ulong)x].WithdrawableEpoch); Gwei totalProposerRewards = preSlashings.Values.Aggregate(Gwei.Zero, (sum, x) => sum + x / rewardsAndPenalties.WhistleblowerRewardQuotient); // Process slashing beaconStateTransition.ProcessAttesterSlashing(state, attesterSlashing); foreach (ValidatorIndex slashedIndex in slashedIndices) { Console.WriteLine($"Checking index {slashedIndex}"); Epoch preWithdrawableEpoch = preWithdrawableEpochs[slashedIndex]; Validator slashedValidator = state.Validators[(int)(ulong)slashedIndex]; // Check Slashing slashedValidator.IsSlashed.ShouldBeTrue(); slashedValidator.ExitEpoch.ShouldBeLessThan(chainConstants.FarFutureEpoch); if (preWithdrawableEpoch < chainConstants.FarFutureEpoch) { ulong slashingsEpoch = beaconStateAccessor.GetCurrentEpoch(state) + stateListLengths.EpochsPerSlashingsVector; Epoch expectedWithdrawableEpoch = Epoch.Max(preWithdrawableEpoch, (Epoch)slashingsEpoch); slashedValidator.WithdrawableEpoch.ShouldBe(expectedWithdrawableEpoch); } else { slashedValidator.WithdrawableEpoch.ShouldBeLessThan(chainConstants.FarFutureEpoch); } Gwei preSlashing = preSlashings[slashedIndex]; Gwei slashedBalance = TestState.GetBalance(state, slashedIndex); slashedBalance.ShouldBeLessThan(preSlashing); } if (!slashedIndices.Contains(proposerIndex)) { // gained whistleblower reward Gwei expectedProposerBalance = preProposerBalance + totalProposerRewards; Gwei proposerBalance = TestState.GetBalance(state, proposerIndex); proposerBalance.ShouldBe(expectedProposerBalance); } else { // gained rewards for all slashings, which may include others. And only lost that of themselves. Gwei expectedProposerBalance = preProposerBalance + totalProposerRewards - (preSlashings[proposerIndex] / rewardsAndPenalties.MinimumSlashingPenaltyQuotient); Gwei proposerBalance = TestState.GetBalance(state, proposerIndex); proposerBalance.ShouldBe(expectedProposerBalance); } }
private static IEnumerable <SszElement> GetValues(BeaconState item, MiscellaneousParameters miscellaneousParameters, TimeParameters timeParameters, StateListLengths stateListLengths, MaxOperationsPerBlock maxOperationsPerBlock) { //# Versioning yield return(item.GenesisTime.ToSszBasicElement()); yield return(item.Slot.ToSszBasicElement()); yield return(item.Fork.ToSszContainer()); //# History yield return(item.LatestBlockHeader.ToSszContainer()); yield return(item.BlockRoots.ToSszVector()); yield return(item.StateRoots.ToSszVector()); yield return(item.HistoricalRoots.ToSszList(stateListLengths.HistoricalRootsLimit)); //# Eth1 yield return(item.Eth1Data.ToSszContainer()); yield return(new SszList(item.Eth1DataVotes.Select(x => x.ToSszContainer()), (ulong)timeParameters.SlotsPerEth1VotingPeriod)); yield return(item.Eth1DepositIndex.ToSszBasicElement()); //# Registry yield return(new SszList(item.Validators.Select(x => x.ToSszContainer()), stateListLengths.ValidatorRegistryLimit)); yield return(item.Balances.ToSszBasicList(stateListLengths.ValidatorRegistryLimit)); //# Randomness //yield return item.StartShard.ToSszBasicElement(); yield return(item.RandaoMixes.ToSszVector()); //# Slashings //Per-epoch sums of slashed effective balances yield return(item.Slashings.ToSszBasicVector()); //# Attestations yield return(item.PreviousEpochAttestations.ToSszList(maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch, miscellaneousParameters)); yield return(item.CurrentEpochAttestations.ToSszList(maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch, miscellaneousParameters)); //# Crosslinks //# Previous epoch snapshot //yield return item.PreviousCrosslinks.ToSszVector(); //yield return item.CurrentCrosslinks.ToSszVector(); //# Finality // Bit set for every recent justified epoch yield return(item.JustificationBits.ToSszBitvector()); yield return(item.PreviousJustifiedCheckpoint.ToSszContainer()); yield return(item.CurrentJustifiedCheckpoint.ToSszContainer()); yield return(item.FinalizedCheckpoint.ToSszContainer()); }