Esempio n. 1
0
        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);
        }
Esempio n. 2
0
        public void ActivationQueueSorting()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            ChainConstants      chainConstants      = testServiceProvider.GetService <ChainConstants>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            int   mockActivations = 10;
            Epoch currentEpoch    = beaconStateAccessor.GetCurrentEpoch(state);

            for (int index = 0; index < mockActivations; index++)
            {
                MockDeposit(testServiceProvider, state, index);
                state.Validators[index].SetEligible(currentEpoch + Epoch.One);
            }

            // give the last priority over the others
            state.Validators[mockActivations - 1].SetEligible(currentEpoch);

            // make sure we are hitting the churn
            int churnLimit = (int)beaconStateAccessor.GetValidatorChurnLimit(state);

            mockActivations.ShouldBeGreaterThan(churnLimit);

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

            // Assert

            //# the first got in as second
            state.Validators[0].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            //# the prioritized got in as first
            state.Validators[mockActivations - 1].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            //# the second last is at the end of the queue, and did not make the churn,
            //#  hence is not assigned an activation_epoch yet.
            state.Validators[mockActivations - 2].ActivationEpoch.ShouldBe(chainConstants.FarFutureEpoch);
            //# the one at churn_limit - 1 did not make it, it was out-prioritized
            state.Validators[churnLimit - 1].ActivationEpoch.ShouldBe(chainConstants.FarFutureEpoch);
            //# but the the one in front of the above did
            state.Validators[churnLimit - 2].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
        }
 public QuickStartMockEth1GenesisProvider(ILogger <QuickStartMockEth1GenesisProvider> logger,
                                          ChainConstants chainConstants,
                                          IOptionsMonitor <GweiValues> gweiValueOptions,
                                          IOptionsMonitor <InitialValues> initialValueOptions,
                                          IOptionsMonitor <TimeParameters> timeParameterOptions,
                                          IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                                          IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                                          ICryptographyService cryptographyService,
                                          BeaconChainUtility beaconChainUtility)
 {
     _logger                     = logger;
     _chainConstants             = chainConstants;
     _gweiValueOptions           = gweiValueOptions;
     _initialValueOptions        = initialValueOptions;
     _timeParameterOptions       = timeParameterOptions;
     _signatureDomainOptions     = signatureDomainOptions;
     _quickStartParameterOptions = quickStartParameterOptions;
     _cryptographyService        = cryptographyService;
     _beaconChainUtility         = beaconChainUtility;
 }
Esempio n. 4
0
        public void Ejection()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            GweiValues     gweiValues     = testServiceProvider.GetService <IOptions <GweiValues> >().Value;
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            BeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            int index = 0;

            Epoch     currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);
            Validator validator    = state.Validators[index];
            bool      isActive     = beaconChainUtility.IsActiveValidator(validator, currentEpoch);

            isActive.ShouldBeTrue();
            validator.ExitEpoch.ShouldBe(chainConstants.FarFutureEpoch);

            // Mock an ejection
            state.Validators[index].SetEffectiveBalance(gweiValues.EjectionBalance);

            for (ulong count = (ulong)0; count < (ulong)timeParameters.MaximumSeedLookahead + 1; count++)
            {
                TestState.NextEpoch(testServiceProvider, state);
            }

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

            // Assert
            Epoch     epochAfter     = beaconStateAccessor.GetCurrentEpoch(state);
            Validator validatorAfter = state.Validators[index];
            bool      isActiveAfter  = beaconChainUtility.IsActiveValidator(validatorAfter, epochAfter);

            isActiveAfter.ShouldBeFalse();
            validatorAfter.ExitEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
        }
Esempio n. 5
0
        public static (IList <Deposit>, Root) PrepareGenesisDeposits(IServiceProvider testServiceProvider, int genesisValidatorCount, Gwei amount, bool signed)
        {
            ChainConstants          chainConstants          = testServiceProvider.GetService <ChainConstants>();
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            InitialValues           initialValues           = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor   beaconStateAccessor   = testServiceProvider.GetService <BeaconStateAccessor>();
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            BlsPublicKey[] publicKeys;
            if (signed)
            {
                publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();
            }
            else
            {
                publicKeys = privateKeys.Select(x => new BlsPublicKey(x)).ToArray();
            }
            List <DepositData> depositDataList = new List <DepositData>();
            List <Deposit>     genesisDeposits = new List <Deposit>();
            Root root = Root.Zero;

            for (int validatorIndex = 0; validatorIndex < genesisValidatorCount; validatorIndex++)
            {
                BlsPublicKey publicKey  = publicKeys[validatorIndex];
                byte[]       privateKey = privateKeys[validatorIndex];
                // insecurely use pubkey as withdrawal key if no credentials provided
                byte[] withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                Bytes32 withdrawalCredentials = new Bytes32(withdrawalCredentialBytes);
                (Deposit deposit, Root depositRoot) = BuildDeposit(testServiceProvider, null, depositDataList, publicKey, privateKey, amount, withdrawalCredentials, signed);
                root = depositRoot;
                genesisDeposits.Add(deposit);
            }
            return(genesisDeposits, root);
        }
Esempio n. 6
0
        private void MockDeposit(IServiceProvider testServiceProvider, BeaconState state, int index)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            GweiValues     gweiValues     = testServiceProvider.GetService <IOptions <GweiValues> >().Value;

            BeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            Validator validator    = state.Validators[index];
            Epoch     currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);
            bool      isActive     = beaconChainUtility.IsActiveValidator(validator, currentEpoch);

            isActive.ShouldBeTrue();

            validator.SetEligible(chainConstants.FarFutureEpoch);
            validator.SetActive(chainConstants.FarFutureEpoch);
            validator.SetEffectiveBalance(gweiValues.MaximumEffectiveBalance);

            bool isActiveAfter = beaconChainUtility.IsActiveValidator(validator, currentEpoch);

            isActiveAfter.ShouldBeFalse();
        }
Esempio n. 7
0
        public static Validator BuildMockValidator(ChainConstants chainConstants, InitialValues initialValues, GweiValues gweiValues, TimeParameters timeParameters, ulong validatorIndex, Gwei balance)
        {
            var publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();
            var publicKey  = publicKeys[validatorIndex];
            // insecurely use pubkey as withdrawal key if no credentials provided
            var withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());

            withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
            var withdrawalCredentials = new Bytes32(withdrawalCredentialBytes);

            var validator = new Validator(
                publicKey,
                withdrawalCredentials,
                Gwei.Min(balance - balance % gweiValues.EffectiveBalanceIncrement, gweiValues.MaximumEffectiveBalance),
                false,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch);

            return(validator);
        }
Esempio n. 8
0
 public Genesis(ILogger <Genesis> logger,
                ChainConstants chainConstants,
                IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions,
                IOptionsMonitor <GweiValues> gweiValueOptions,
                IOptionsMonitor <InitialValues> initialValueOptions,
                IOptionsMonitor <TimeParameters> timeParameterOptions,
                IOptionsMonitor <StateListLengths> stateListLengthOptions,
                IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions,
                BeaconStateAccessor beaconStateAccessor,
                BeaconStateTransition beaconStateTransition)
 {
     _logger = logger;
     _beaconStateAccessor           = beaconStateAccessor;
     _beaconStateTransition         = beaconStateTransition;
     _chainConstants                = chainConstants;
     _miscellaneousParameterOptions = miscellaneousParameterOptions;
     _gweiValueOptions              = gweiValueOptions;
     _initialValueOptions           = initialValueOptions;
     _timeParameterOptions          = timeParameterOptions;
     _stateListLengthOptions        = stateListLengthOptions;
     _maxOperationsPerBlockOptions  = maxOperationsPerBlockOptions;
 }
Esempio n. 9
0
 public QuickStart(ILogger <QuickStart> logger,
                   ChainConstants chainConstants,
                   IOptionsMonitor <GweiValues> gweiValueOptions,
                   IOptionsMonitor <InitialValues> initialValueOptions,
                   IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                   IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                   ICryptographyService cryptographyService,
                   BeaconChainUtility beaconChainUtility,
                   Genesis beaconChain,
                   ForkChoice forkChoice)
 {
     _logger                     = logger;
     _chainConstants             = chainConstants;
     _gweiValueOptions           = gweiValueOptions;
     _initialValueOptions        = initialValueOptions;
     _signatureDomainOptions     = signatureDomainOptions;
     _quickStartParameterOptions = quickStartParameterOptions;
     _cryptographyService        = cryptographyService;
     _beaconChainUtility         = beaconChainUtility;
     _beaconChain                = beaconChain;
     _forkChoice                 = forkChoice;
 }
        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;

            BLSParameters blsParameters = new BLSParameters();

            _bls = BLS.Create(blsParameters);

            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 void TestInitializeBeaconStateFromEth1()
        {
            bool useBls = true;

            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useBls, useStore: true);

            ChainConstants          chainConstants          = testServiceProvider.GetService <ChainConstants>();
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value;

            int depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount;

            IList <DepositData> deposits     = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: useBls);
            IDepositStore       depositStore = testServiceProvider.GetService <IDepositStore>();

            foreach (DepositData depositData in deposits)
            {
                depositStore.Place(depositData);
            }

            Bytes32 eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x12, 32).ToArray());
            ulong   eth1Timestamp = miscellaneousParameters.MinimumGenesisTime;

            BeaconNode.GenesisChainStart beaconChain = testServiceProvider.GetService <BeaconNode.GenesisChainStart>();

            // Act
            //# initialize beacon_state
            BeaconState state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp);

            // Assert
            state.GenesisTime.ShouldBe(eth1Timestamp - eth1Timestamp % timeParameters.MinimumGenesisDelay + 2 * timeParameters.MinimumGenesisDelay);
            state.Validators.Count.ShouldBe(depositCount);
            state.Eth1Data.DepositRoot.ShouldBe(depositStore.DepositData.Root);
            state.Eth1Data.DepositCount.ShouldBe((ulong)depositCount);
            state.Eth1Data.BlockHash.ShouldBe(eth1BlockHash);
        }
        private static IList <Attestation> PrepareStateWithFullAttestations(IServiceProvider testServiceProvider, BeaconState state)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>();

            var   attestations = new List <Attestation>();
            ulong maxSlot      = timeParameters.SlotsPerEpoch + timeParameters.MinimumAttestationInclusionDelay;

            for (Slot slot = Slot.Zero; slot < maxSlot; slot += new Slot(1))
            {
                // create an attestation for each slot in epoch
                if (slot < timeParameters.SlotsPerEpoch)
                {
                    Attestation attestation = TestAttestation.GetValidAttestation(testServiceProvider, state, Slot.None, CommitteeIndex.None, signed: true);
                    attestations.Add(attestation);
                }

                // fill each created slot in state after inclusion delay
                if (slot >= timeParameters.MinimumAttestationInclusionDelay)
                {
                    Slot        index = slot - timeParameters.MinimumAttestationInclusionDelay;
                    Attestation includeAttestation = attestations[(int)(ulong)index];
                    TestAttestation.AddAttestationsToState(testServiceProvider, state, new[] { includeAttestation }, state.Slot);
                }

                TestState.NextSlot(testServiceProvider, state);
            }

            Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);

            stateEpoch.ShouldBe(chainConstants.GenesisEpoch + Epoch.One);

            state.PreviousEpochAttestations.Count.ShouldBe((int)timeParameters.SlotsPerEpoch);

            return(attestations);
        }
Esempio n. 13
0
        public void BasicActivation()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            BeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            int index = 0;

            MockDeposit(testServiceProvider, state, index);

            for (ulong count = (ulong)0; count < (ulong)timeParameters.MaximumSeedLookahead + 1; count++)
            {
                TestState.NextEpoch(testServiceProvider, state);
            }

            // eligibility must be finalized
            Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);

            state.SetFinalizedCheckpoint(new Checkpoint(currentEpoch + new Epoch(2), Root.Zero));

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

            // Assert
            Validator validator = state.Validators[index];

            validator.ActivationEligibilityEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            validator.ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            bool isActive = beaconChainUtility.IsActiveValidator(validator, currentEpoch + timeParameters.MaximumSeedLookahead + Epoch.One);

            isActive.ShouldBeTrue();
        }
Esempio n. 14
0
        public async Task OnAttestationPastEpoch()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            InitialValues  initialValues  = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            IForkChoice    forkChoice     = testServiceProvider.GetService <IForkChoice>();

            // Initialization
            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // move time forward 2 epochs
            ulong time = store.Time + 2 * timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch;
            await forkChoice.OnTickAsync(store, time);

            // create and store block from 3 epochs ago
            BeaconBlock       block       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
            SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
            await forkChoice.OnBlockAsync(store, signedBlock);

            // create attestation for past block
            Attestation attestation = TestAttestation.GetValidAttestation(testServiceProvider, state, state.Slot, CommitteeIndex.None, signed: true);

            attestation.Data.Target.Epoch.ShouldBe(chainConstants.GenesisEpoch);

            IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>();
            Slot  currentSlot  = ((ForkChoice)forkChoice).GetCurrentSlot(store);
            Epoch currentEpoch = beaconChainUtility.ComputeEpochAtSlot(currentSlot);

            currentEpoch.ShouldBe((Epoch)(chainConstants.GenesisEpoch + 2UL));

            await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : false);
        }
        public void GenesisEpochNoAttestationsNoPenalties()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            ChainConstants      chainConstants     = testServiceProvider.GetService <ChainConstants>();
            IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>();

            BeaconState preState = BeaconState.Clone(state);

            Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);

            stateEpoch.ShouldBe(chainConstants.GenesisEpoch);

            // Act
            RunProcessRewardsAndPenalties(testServiceProvider, state);

            // Assert
            for (int index = 0; index < preState.Validators.Count; index++)
            {
                state.Balances[index].ShouldBe(preState.Balances[index], $"Balance {index}");
            }
        }
Esempio n. 16
0
 public DepositStore(ICryptographyService crypto, ChainConstants chainConstants)
 {
     _crypto         = crypto;
     _chainConstants = chainConstants;
 }
        //    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);
            }
        }
Esempio n. 18
0
        public async Task GenesisWithEmptyParametersTimeShouldReject()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();

            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions =
                testServiceProvider.GetService <IOptionsMonitor <MiscellaneousParameters> >();
            IOptionsMonitor <GweiValues> gweiValueOptions =
                testServiceProvider.GetService <IOptionsMonitor <GweiValues> >();
            IOptionsMonitor <InitialValues> initialValueOptions =
                testServiceProvider.GetService <IOptionsMonitor <InitialValues> >();
            IOptionsMonitor <TimeParameters> timeParameterOptions =
                testServiceProvider.GetService <IOptionsMonitor <TimeParameters> >();
            IOptionsMonitor <StateListLengths> stateListLengthOptions =
                testServiceProvider.GetService <IOptionsMonitor <StateListLengths> >();
            IOptionsMonitor <RewardsAndPenalties> rewardsAndPenaltiesOptions =
                testServiceProvider.GetService <IOptionsMonitor <RewardsAndPenalties> >();
            IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions =
                testServiceProvider.GetService <IOptionsMonitor <MaxOperationsPerBlock> >();
            IOptionsMonitor <ForkChoiceConfiguration> forkChoiceConfigurationOptions =
                testServiceProvider.GetService <IOptionsMonitor <ForkChoiceConfiguration> >();
            IOptionsMonitor <SignatureDomains> signatureDomainOptions =
                testServiceProvider.GetService <IOptionsMonitor <SignatureDomains> >();
            IOptionsMonitor <InMemoryConfiguration> inMemoryConfigurationOptions =
                testServiceProvider.GetService <IOptionsMonitor <InMemoryConfiguration> >();

            miscellaneousParameterOptions.CurrentValue.MinimumGenesisActiveValidatorCount = 2;

            LoggerFactory loggerFactory = new LoggerFactory(new[]
            {
                new ConsoleLoggerProvider(Core2.Configuration.Static.OptionsMonitor <ConsoleLoggerOptions>())
            });

            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            IDepositStore        depositStore        = new DepositStore(cryptographyService, chainConstants);

            BeaconChainUtility beaconChainUtility = new BeaconChainUtility(
                loggerFactory.CreateLogger <BeaconChainUtility>(),
                chainConstants, miscellaneousParameterOptions, initialValueOptions, gweiValueOptions,
                timeParameterOptions,
                cryptographyService);
            BeaconStateAccessor beaconStateAccessor = new BeaconStateAccessor(chainConstants,
                                                                              miscellaneousParameterOptions, timeParameterOptions, stateListLengthOptions, signatureDomainOptions,
                                                                              cryptographyService, beaconChainUtility);
            BeaconStateMutator beaconStateMutator = new BeaconStateMutator(chainConstants, timeParameterOptions,
                                                                           stateListLengthOptions, rewardsAndPenaltiesOptions,
                                                                           beaconChainUtility, beaconStateAccessor);
            BeaconStateTransition beaconStateTransition = new BeaconStateTransition(
                loggerFactory.CreateLogger <BeaconStateTransition>(),
                chainConstants, gweiValueOptions, timeParameterOptions, stateListLengthOptions,
                rewardsAndPenaltiesOptions, maxOperationsPerBlockOptions, signatureDomainOptions,
                cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateMutator, depositStore);
            SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree simpleLmdGhost =
                new SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree(
                    loggerFactory.CreateLogger <SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree>(),
                    chainConstants, beaconChainUtility, beaconStateAccessor);
            MemoryStore store = new MemoryStore(loggerFactory.CreateLogger <MemoryStore>(), inMemoryConfigurationOptions,
                                                new DataDirectory("data"), Substitute.For <IFileSystem>(), simpleLmdGhost, new StoreAccessor());
            ForkChoice forkChoice = new ForkChoice(loggerFactory.CreateLogger <ForkChoice>(),
                                                   chainConstants, miscellaneousParameterOptions, timeParameterOptions, maxOperationsPerBlockOptions,
                                                   forkChoiceConfigurationOptions, signatureDomainOptions,
                                                   cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateTransition);

            GenesisChainStart genesisChainStart = new GenesisChainStart(loggerFactory.CreateLogger <GenesisChainStart>(),
                                                                        chainConstants, miscellaneousParameterOptions, gweiValueOptions, initialValueOptions,
                                                                        timeParameterOptions, stateListLengthOptions,
                                                                        cryptographyService, store, beaconStateAccessor, beaconStateTransition, forkChoice, depositStore);

            // Act
            Bytes32 eth1BlockHash = Bytes32.Zero;
            ulong   eth1Timestamp = 106185600uL; // 1973-05-14
            bool    success       = await genesisChainStart.TryGenesisAsync(eth1BlockHash, eth1Timestamp);

            // Assert
            success.ShouldBeFalse();
        }