Ejemplo n.º 1
0
        public async Task OnAttestationPreviousEpoch()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            // Initialization
            IStore store = forkChoice.GetGenesisStore(state);
            ulong  time  = store.Time + timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch;
            await forkChoice.OnTickAsync(store, time);

            BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);

            // Store block in store
            await forkChoice.OnBlockAsync(store, block);

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

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

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

            currentEpoch.ShouldBe(initialValues.GenesisEpoch + Epoch.One);

            await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : true);
        }
        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 <Deposit> deposits, Root depositRoot) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: useBls);

            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, deposits);

            // Assert
            state.GenesisTime.ShouldBe(eth1Timestamp - eth1Timestamp % timeParameters.MinimumGenesisDelay + 2 * timeParameters.MinimumGenesisDelay);
            state.Validators.Count.ShouldBe(depositCount);
            state.Eth1Data.DepositRoot.ShouldBe(depositRoot);
            state.Eth1Data.DepositCount.ShouldBe((ulong)depositCount);
            state.Eth1Data.BlockHash.ShouldBe(eth1BlockHash);
        }
Ejemplo n.º 3
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);
            }

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

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

            validator.ActivationEligibilityEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            validator.ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
            Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);
            bool  isActive     = beaconChainUtility.IsActiveValidator(validator, currentEpoch);

            isActive.ShouldBeTrue();
        }
Ejemplo n.º 4
0
        /// <summary>
        ///     Return the committee assignment in the ``epoch`` for ``validator_index``.
        ///     ``assignment`` returned is a tuple of the following form:
        ///     * ``assignment[0]`` is the list of validators in the committee
        ///     * ``assignment[1]`` is the index to which the committee is assigned
        ///     * ``assignment[2]`` is the slot at which the committee is assigned
        ///     Return None if no assignment.
        /// </summary>
        public CommitteeAssignment GetCommitteeAssignment(BeaconState state, Epoch epoch, ValidatorIndex validatorIndex)
        {
            Epoch nextEpoch = _beaconStateAccessor.GetCurrentEpoch(state) + Epoch.One;

            if (epoch > nextEpoch)
            {
                throw new ArgumentOutOfRangeException(nameof(epoch), epoch,
                                                      $"Committee epoch cannot be greater than next epoch {nextEpoch}.");
            }

            TimeParameters timeParameters = _timeParameterOptions.CurrentValue;
            Slot           startSlot      = _beaconChainUtility.ComputeStartSlotOfEpoch(epoch);
            ulong          endSlot        = startSlot + timeParameters.SlotsPerEpoch;

            for (Slot slot = startSlot; slot < endSlot; slot += Slot.One)
            {
                ulong committeeCount = _beaconStateAccessor.GetCommitteeCountAtSlot(state, slot);
                for (CommitteeIndex index = CommitteeIndex.Zero;
                     index < new CommitteeIndex(committeeCount);
                     index += CommitteeIndex.One)
                {
                    IReadOnlyList <ValidatorIndex> committee =
                        _beaconStateAccessor.GetBeaconCommittee(state, slot, index);
                    if (committee.Contains(validatorIndex))
                    {
                        CommitteeAssignment committeeAssignment = new CommitteeAssignment(committee, index, slot);
                        return(committeeAssignment);
                    }
                }
            }

            return(CommitteeAssignment.None);
        }
Ejemplo n.º 5
0
        public void InvalidSignature()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            TimeParameters      timeParameters      = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            // move state forward PERSISTENT_COMMITTEE_PERIOD epochs to allow for exit
            ulong move    = timeParameters.SlotsPerEpoch * (ulong)timeParameters.PersistentCommitteePeriod;
            ulong newSlot = state.Slot + move;

            state.SetSlot((Slot)newSlot);

            Epoch          currentEpoch   = beaconStateAccessor.GetCurrentEpoch(state);
            ValidatorIndex validatorIndex = beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch)[0];
            Validator      validator      = state.Validators[(int)(ulong)validatorIndex];

            byte[] privateKey = TestKeys.PublicKeyToPrivateKey(validator.PublicKey, timeParameters);

            VoluntaryExit       voluntaryExit       = TestVoluntaryExit.BuildVoluntaryExit(testServiceProvider, currentEpoch, validatorIndex);
            SignedVoluntaryExit signedVoluntaryExit = new SignedVoluntaryExit(voluntaryExit, BlsSignature.Zero);

            RunVoluntaryExitProcessing(testServiceProvider, state, signedVoluntaryExit, expectValid: false);
        }
Ejemplo n.º 6
0
        private void AddAttestationToStore(IServiceProvider testServiceProvider, IStore store, Attestation attestation)
        {
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;
            ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>();

            if (!store.TryGetBlock(attestation.Data.BeaconBlockRoot, out BeaconBlock? parentBlock))
            {
                throw new InvalidDataException("Cannot retrieve parent block");
            }

            Hash32 parentSigningRoot = parentBlock !.SigningRoot(miscellaneousParameters, maxOperationsPerBlock);

            if (!store.TryGetBlockState(parentSigningRoot, out BeaconState? preState))
            {
                throw new InvalidDataException("Cannot retrieve pre state");
            }

            ulong blockTime     = preState !.GenesisTime + (ulong)parentBlock !.Slot * timeParameters.SecondsPerSlot;
            ulong nextEpochTime = blockTime + (ulong)timeParameters.SlotsPerEpoch * timeParameters.SecondsPerSlot;

            if (store.Time < blockTime)
            {
                forkChoice.OnTick(store, blockTime);
            }

            forkChoice.OnAttestation(store, attestation);
        }
Ejemplo n.º 7
0
        /// <inheritdoc/>
        public IWaveform Create(IBindingContext context)
        {
            IIntegrationMethod method = null;
            TimeParameters     tp     = null;

            context?.TryGetState(out method);
            context?.TryGetSimulationParameterSet(out tp);
            double step = 1.0;

            if (!RiseTime.Given || !FallTime.Given)
            {
                if (tp is SpiceMethod sm)
                {
                    step = sm.InitialStep;
                }
                else if (tp != null)
                {
                    step = tp.StopTime / 50.0;
                }
            }
            return(new Instance(method,
                                InitialValue,
                                PulsedValue,
                                Delay,
                                RiseTime.Given ? RiseTime.Value : step,
                                FallTime.Given ? FallTime.Value : step,
                                PulseWidth,
                                Period));
        }
        public void Eth1VoteReset()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            //  skip ahead to the end of the voting period
            state.SetSlot((Slot)(timeParameters.SlotsPerEth1VotingPeriod - 1UL));

            // add a vote for each skipped slot.
            for (Slot index = Slot.Zero; index < state.Slot + new Slot(1); index += new Slot(1))
            {
                ulong    eth1DepositIndex = state.Eth1DepositIndex;
                Root     depositRoot      = new Root(Enumerable.Repeat((byte)0xaa, 32).ToArray());
                Bytes32  blockHash        = new Bytes32(Enumerable.Repeat((byte)0xbb, 32).ToArray());
                Eth1Data eth1Data         = new Eth1Data(depositRoot, eth1DepositIndex, blockHash);
                state.AddEth1DataVote(eth1Data);
            }

            // Act
            RunProcessFinalUpdates(testServiceProvider, state);

            // Assert
            state.Eth1DataVotes.Count.ShouldBe(0);
        }
Ejemplo n.º 9
0
        public static byte[] PublicKeyToPrivateKey(BlsPublicKey publicKey, TimeParameters timeParameters)
        {
            EnsureKeys(timeParameters);
            var privateKey = _testKeys[publicKey];

            return(privateKey);
        }
Ejemplo n.º 10
0
        public static AttesterSlashing GetValidAttesterSlashing(IServiceProvider testServiceProvider, BeaconState state, bool signed1, bool signed2)
        {
            TimeParameters      timeParameters      = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            Attestation attestation1 = TestAttestation.GetValidAttestation(testServiceProvider, state, Slot.None, CommitteeIndex.None, signed1);

            Hash32      targetRoot2  = new Hash32(Enumerable.Repeat((byte)0x01, 32).ToArray());
            Attestation attestation2 = new Attestation(
                attestation1.AggregationBits,
                new AttestationData(attestation1.Data.Slot,
                                    attestation1.Data.Index,
                                    attestation1.Data.BeaconBlockRoot,
                                    attestation1.Data.Source,
                                    new Checkpoint(
                                        attestation1.Data.Target.Epoch,
                                        targetRoot2
                                        )),
                BlsSignature.Empty
                );

            if (signed2)
            {
                TestAttestation.SignAttestation(testServiceProvider, state, attestation2);
            }

            IndexedAttestation indexedAttestation1 = beaconStateAccessor.GetIndexedAttestation(state, attestation1);
            IndexedAttestation indexedAttestation2 = beaconStateAccessor.GetIndexedAttestation(state, attestation2);

            AttesterSlashing attesterSlashing = new AttesterSlashing(indexedAttestation1, indexedAttestation2);

            return(attesterSlashing);
        }
Ejemplo n.º 11
0
        //    Run ``process_voluntary_exit``, yielding:
        //  - pre-state('pre')
        //  - voluntary_exit('voluntary_exit')
        //  - post-state('post').
        //If ``valid == False``, run expecting ``AssertionError``
        private void RunVoluntaryExitProcessing(IServiceProvider testServiceProvider, BeaconState state, VoluntaryExit voluntaryExit, bool expectValid)
        {
            TimeParameters        timeParameters        = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

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

            // Act
            if (!expectValid)
            {
                Should.Throw <Exception>(() =>
                {
                    beaconStateTransition.ProcessVoluntaryExit(state, voluntaryExit);
                });
                return;
            }

            ValidatorIndex validatorIndex = voluntaryExit.ValidatorIndex;

            Epoch preExitEpoch = state.Validators[(int)(ulong)validatorIndex].ExitEpoch;

            beaconStateTransition.ProcessVoluntaryExit(state, voluntaryExit);

            // Assert
            preExitEpoch.ShouldBe(chainConstants.FarFutureEpoch);

            Epoch postExitEpoch = state.Validators[(int)(ulong)validatorIndex].ExitEpoch;

            postExitEpoch.ShouldBeLessThan(chainConstants.FarFutureEpoch);
        }
Ejemplo n.º 12
0
        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);
        }
Ejemplo n.º 13
0
        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);
        }
Ejemplo n.º 14
0
        public async Task TestValidators80DutiesForEpochZeroHaveExactlyOneProposerPerSlot()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            testServiceCollection.AddSingleton <IEth1DataProvider>(Substitute.For <IEth1DataProvider>());
            testServiceCollection.AddSingleton <IOperationPool>(Substitute.For <IOperationPool>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            ForkChoice      forkChoice = testServiceProvider.GetService <ForkChoice>();

            // Get genesis store initialise MemoryStoreProvider with the state
            _ = forkChoice.GetGenesisStore(state);

            TimeParameters timeParameters     = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            int            numberOfValidators = state.Validators.Count;

            Console.WriteLine("Number of validators: {0}", numberOfValidators);
            BlsPublicKey[] publicKeys  = TestKeys.PublicKeys(timeParameters).ToArray();
            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            for (int index = 0; index < numberOfValidators; index++)
            {
                Console.WriteLine("[{0}] priv:{1} pub:{2}", index, "0x" + BitConverter.ToString(privateKeys[index]).Replace("-", ""), publicKeys[index]);
            }

            // Act
            Epoch targetEpoch = new Epoch(0);
            IEnumerable <BlsPublicKey> validatorPublicKeys = publicKeys.Take(numberOfValidators);
            IBeaconNodeApi             beaconNode          = testServiceProvider.GetService <IBeaconNodeApi>();

            beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade));

            int validatorDutyIndex = 0;
            List <ValidatorDuty> validatorDuties = new List <ValidatorDuty>();

            await foreach (ValidatorDuty validatorDuty in beaconNode.ValidatorDutiesAsync(validatorPublicKeys, targetEpoch, CancellationToken.None))
            {
                validatorDuties.Add(validatorDuty);
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  validatorDutyIndex, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
                validatorDutyIndex++;
            }

            // Assert
            Dictionary <Slot, IGrouping <Slot, ValidatorDuty> > groupsByProposalSlot = validatorDuties
                                                                                       .GroupBy(x => x.BlockProposalSlot)
                                                                                       .ToDictionary(x => x.Key, x => x);

            groupsByProposalSlot[new Slot(0)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(1)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(2)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(3)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(4)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(5)].Count().ShouldBe(1);
            //groupsByProposalSlot[new Slot(6)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(7)].Count().ShouldBe(1);
            //groupsByProposalSlot[Slot.None].Count().ShouldBe(numberOfValidators - 7);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Prepare the state for the deposit, and create a deposit for the given validator, depositing the given amount.
        /// </summary>
        public static Deposit PrepareStateAndDeposit(IServiceProvider testServiceProvider, BeaconState state, ValidatorIndex validatorIndex, Gwei amount, Bytes32 withdrawalCredentials, bool signed)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            InitialValues  initialValues  = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

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

            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            BlsPublicKey[] publicKeys  = TestKeys.PublicKeys(timeParameters).ToArray();
            byte[]         privateKey  = privateKeys[(int)(ulong)validatorIndex];
            BlsPublicKey   publicKey   = publicKeys[(int)(ulong)validatorIndex];

            if (withdrawalCredentials == Bytes32.Zero)
            {
                // insecurely use pubkey as withdrawal key if no credentials provided
                byte[] withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                withdrawalCredentials        = new Bytes32(withdrawalCredentialBytes);
            }

            List <DepositData> depositDataList = new List <DepositData>();

            (Deposit deposit, Root depositRoot) = BuildDeposit(testServiceProvider, state, depositDataList, publicKey, privateKey, amount, withdrawalCredentials, signed);

            state.SetEth1DepositIndex(0);
            state.Eth1Data.SetDepositRoot(depositRoot);
            state.Eth1Data.SetDepositCount((ulong)depositDataList.Count);

            return(deposit);
        }
Ejemplo n.º 16
0
        private void CheckHistoricalSlots(IStore store, IReadOnlyList <Hash32> historicalBlockRoots, Slot fromSlot, Slot startSlot, ValidatorIndex validatorIndex,
                                          ref Slot attestationSlot, ref CommitteeIndex attestationCommitteeIndex, ref Slot blockProposalSlot)
        {
            TimeParameters timeParameters = _timeParameterOptions.CurrentValue;
            Slot           previousSlot   = fromSlot;

            while (true)
            {
                previousSlot -= Slot.One;
                int    index        = (int)(previousSlot % timeParameters.SlotsPerHistoricalRoot);
                Hash32 previousRoot = historicalBlockRoots[index];
                if (!store.TryGetBlockState(previousRoot, out BeaconState? previousState))
                {
                    throw new Exception($"Historical state {previousRoot} for slot {previousSlot} not found.");
                }

                CheckStateDuty(previousState !, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex,
                               ref blockProposalSlot);

                if (previousSlot <= startSlot || (attestationSlot != Slot.None && blockProposalSlot != Slot.None))
                {
                    break;
                }
            }
        }
Ejemplo n.º 17
0
        // [DataRow(42uL, "0xab48aa2cc6f4a0bb63b5d67be54ac3aed10326dda304c5aeb9e942b40d6e7610478377680ab90e092ef1895e62786008", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x8aea7d8eb22063bcfe882e2b7efc0b3713e1a48dd8343bed523b1ab4546114be84d00f896d33c605d1f67456e8e2ed93", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x89db41a6183c2fe47cf54d1e00c3cfaae53df634a32cccd5cf0c0a73e95ee0450fc3d060bb6878780fbf5f30d9e29aac", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0xb783a70a1cf9f53e7d2ddf386bea81a947e5360c5f1e0bf004fceedb2073e4dd180ef3d2d91bee7b1c5a88d1afd11c49", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x8fe55d12257709ae842f8594f9a0a40de3d38dabdf82b21a60baac927e52ed00c5fd42f4c905410eacdaf8f8a9952490", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x95906ec0660892c205634e21ad540cbe0b6f7729d101d5c4639b864dea09be7f42a4252c675d46dd90a2661b3a94e8ca", 0uL, 5uL, 1uL, null)]
        public async Task ValidatorDutyAtSpecificTimeDuplicateProposal(ulong targetTime, string publicKey, ulong epoch, ulong attestationSlot, ulong attestationShard, ulong?blockProposalSlot)
        {
            // NOTE: Current algorithm for GetBeaconProposerIndex() someimtes allocates multiple proposal slots in an epoch, e.g. above index 23 gets slot 2 and 6
            // It could be an error in the algorithm (need to check; domain type could be wrong), or due to the pre-shard algorithm.
            // The algorithm before shards were removed was different, so maybe ignore for now, implement phase 1 (with shards), and worry about it then.
            // This test for now will simply detect if things unintentionally change.

            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            IForkChoice     forkChoice = testServiceProvider.GetService <IForkChoice>();
            // Get genesis store initialise MemoryStoreProvider with the state
            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // Move forward time
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            for (ulong timeSinceGenesis = 1; timeSinceGenesis <= targetTime; timeSinceGenesis++)
            {
                ulong time = state.GenesisTime + timeSinceGenesis;
                await forkChoice.OnTickAsync(store, time);

                if (timeSinceGenesis % timeParameters.SecondsPerSlot == 0)
                {
                    BeaconBlock       block       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
                    SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
                    await forkChoice.OnBlockAsync(store, signedBlock);
                }
            }

            Console.WriteLine("");
            Console.WriteLine("***** State advanced to slot {0}, time {1}, ready to start tests *****", state.Slot, store.Time);
            Console.WriteLine("");

            // Act
            ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>();
            BlsPublicKey         validatorPublicKey   = new BlsPublicKey(publicKey);
            Epoch targetEpoch = new Epoch(epoch);

            ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch);

            Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}",
                              validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);

            // Assert
            validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey);

            Slot  expectedBlockProposalSlot = blockProposalSlot.HasValue ? new Slot(blockProposalSlot.Value) : Slot.None;
            Slot  expectedAttestationSlot   = new Slot(attestationSlot);
            Shard expectedAttestationShard  = new Shard(attestationShard);

            validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot);
            validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot);
            validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard);
        }
Ejemplo n.º 18
0
        public void ProposerIndexForFirstTwoEpochsMustBeValid()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            ForkChoice      forkChoice = testServiceProvider.GetService <ForkChoice>();
            // Get genesis store initialise MemoryStoreProvider with the state
            IStore store = forkChoice.GetGenesisStore(state);

            // Move forward time
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
            TimeParameters      timeParameters      = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            ulong          time                  = state.GenesisTime + 1;
            ulong          nextSlotTime          = state.GenesisTime;
            ValidatorIndex maximumValidatorIndex = new ValidatorIndex((ulong)state.Validators.Count - 1);

            ValidatorIndex validatorIndex0 = beaconStateAccessor.GetBeaconProposerIndex(state);

            Console.WriteLine("Slot {0}, time {1} = proposer index {2}", state.Slot, time, validatorIndex0);
            validatorIndex0.ShouldBeLessThanOrEqualTo(maximumValidatorIndex);

            List <ValidatorIndex> proposerIndexes = new List <ValidatorIndex>();

            proposerIndexes.Add(validatorIndex0);

            for (int slotIndex = 1; slotIndex <= 16; slotIndex++)
            {
                // Slot 1
                nextSlotTime = nextSlotTime + timeParameters.SecondsPerSlot;
                while (time < nextSlotTime)
                {
                    forkChoice.OnTick(store, time);
                    time++;
                }

                forkChoice.OnTick(store, time);
                time++;
                BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);
                TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
                forkChoice.OnBlock(store, block);
                forkChoice.OnTick(store, time);
                time++;

                ValidatorIndex validatorIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                Console.WriteLine("Slot {0}, time {1} = proposer index {2}", state.Slot, time, validatorIndex);
                validatorIndex.ShouldBeLessThanOrEqualTo(maximumValidatorIndex);
                proposerIndexes.Add(validatorIndex);
            }

            for (var slotIndex = 0; slotIndex < proposerIndexes.Count; slotIndex++)
            {
                ValidatorIndex proposerIndex = proposerIndexes[slotIndex];
                Validator      proposer      = state.Validators[(int)(ulong)proposerIndex];
                Console.WriteLine("Slot {0} = proposer index {1}, public key {2}", slotIndex, proposerIndex, proposer.PublicKey);
            }
        }
Ejemplo n.º 19
0
        public static BeaconState PrepareTestState(IServiceProvider testServiceProvider)
        {
            TimeParameters timeParameters     = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            ulong          numberOfValidators = (ulong)timeParameters.SlotsPerEpoch * 10;
            BeaconState    state = TestGenesis.CreateGenesisState(testServiceProvider, numberOfValidators);

            return(state);
        }
Ejemplo n.º 20
0
        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);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Transition to the start slot of the next epoch
        /// </summary>
        public static void NextEpoch(IServiceProvider testServiceProvider, BeaconState state)
        {
            TimeParameters        timeParameters        = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            Slot slot = (Slot)(state.Slot + timeParameters.SlotsPerEpoch - state.Slot % timeParameters.SlotsPerEpoch);

            beaconStateTransition.ProcessSlots(state, slot);
        }
Ejemplo n.º 22
0
        public ulong GetAttestationTime(BeaconChainInformation beaconChainInformation, Slot slot)
        {
            TimeParameters timeParameters  = _timeParameterOptions.CurrentValue;
            ulong          startTimeOfSlot = beaconChainInformation.GenesisTime + timeParameters.SecondsPerSlot * slot;

            // Attest 1/3 way through slot
            ulong attestationTime = startTimeOfSlot + (_timeParameterOptions.CurrentValue.SecondsPerSlot / 3);

            return(attestationTime);
        }
Ejemplo n.º 23
0
        public static void SignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block, ValidatorIndex proposerIndex)
        {
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;
            SignatureDomains        signatureDomains        = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;

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

            if (state.Slot > block.Slot)
            {
                throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Slot of block must be equal or less that state slot {state.Slot}");
            }

            Epoch blockEpoch = beaconChainUtility.ComputeEpochAtSlot(block.Slot);

            if (proposerIndex == ValidatorIndex.None)
            {
                if (block.Slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (stateEpoch + 1 > blockEpoch)
                    {
                        Console.WriteLine("WARNING: Block slot far away, and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.");
                    }
                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, block.Slot);
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState);
                }
            }

            byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            byte[]   privateKey  = privateKeys[(int)(ulong)proposerIndex];

            Domain       randaoDomain     = beaconStateAccessor.GetDomain(state, signatureDomains.Randao, blockEpoch);
            Hash32       randaoRevealHash = blockEpoch.HashTreeRoot();
            BlsSignature randaoReveal     = TestSecurity.BlsSign(randaoRevealHash, privateKey, randaoDomain);

            block.Body.SetRandaoReveal(randaoReveal);

            Domain       signatureDomain = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, blockEpoch);
            Hash32       signingRoot     = cryptographyService.SigningRoot(block);
            BlsSignature signature       = TestSecurity.BlsSign(signingRoot, privateKey, signatureDomain);

            block.SetSignature(signature);
        }
        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));
        }
Ejemplo n.º 25
0
        public static SignedBeaconBlock SignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block, ValidatorIndex?optionalProposerIndex)
        {
            TimeParameters   timeParameters   = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            SignatureDomains signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;

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

            if (state.Slot > block.Slot)
            {
                throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Slot of block must be equal or less that state slot {state.Slot}");
            }

            Epoch          blockEpoch = beaconChainUtility.ComputeEpochAtSlot(block.Slot);
            ValidatorIndex proposerIndex;

            if (optionalProposerIndex.HasValue)
            {
                proposerIndex = optionalProposerIndex.Value;
            }
            else
            {
                if (block.Slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (stateEpoch + 1 > blockEpoch)
                    {
                        Console.WriteLine("WARNING: Block slot far away, and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.");
                    }
                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, block.Slot);
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState);
                }
            }

            byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            byte[]   privateKey  = privateKeys[(int)(ulong)proposerIndex];

            Root         blockHashTreeRoot = cryptographyService.HashTreeRoot(block);
            Domain       proposerDomain    = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, blockEpoch);
            Root         signingRoot       = beaconChainUtility.ComputeSigningRoot(blockHashTreeRoot, proposerDomain);
            BlsSignature signature         = TestSecurity.BlsSign(signingRoot, privateKey);

            return(new SignedBeaconBlock(block, signature));
        }
Ejemplo n.º 26
0
        public async Task TestValidators80DutiesForEpochOneHaveExactlyOneProposerPerSlot()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            testServiceCollection.AddSingleton <IEth1DataProvider>(Substitute.For <IEth1DataProvider>());
            testServiceCollection.AddSingleton <IOperationPool>(Substitute.For <IOperationPool>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            ForkChoice      forkChoice = testServiceProvider.GetService <ForkChoice>();

            // Get genesis store initialise MemoryStoreProvider with the state
            _ = forkChoice.GetGenesisStore(state);

            TimeParameters timeParameters     = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            int            numberOfValidators = state.Validators.Count;

            Console.WriteLine("Number of validators: {0}", numberOfValidators);
            BlsPublicKey[] publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();

            // Act
            Epoch          targetEpoch         = new Epoch(1);
            var            validatorPublicKeys = publicKeys.Take(numberOfValidators);
            IBeaconNodeApi beaconNode          = testServiceProvider.GetService <IBeaconNodeApi>();

            beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade));
            var validatorDuties = await beaconNode.ValidatorDutiesAsync(validatorPublicKeys, targetEpoch);

            for (var index = 0; index < validatorDuties.Count; index++)
            {
                ValidatorDuty validatorDuty = validatorDuties[index];
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  index, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
            }

            // Assert
            Dictionary <Slot, IGrouping <Slot, ValidatorDuty> > groupsByProposalSlot = validatorDuties
                                                                                       .GroupBy(x => x.BlockProposalSlot)
                                                                                       .ToDictionary(x => x.Key, x => x);

            groupsByProposalSlot[new Slot(8)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(9)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(10)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(11)].Count().ShouldBe(1);
            //groupsByProposalSlot[new Slot(12)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(13)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(14)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(15)].Count().ShouldBe(1);
            //groupsByProposalSlot[Slot.None].Count().ShouldBe(numberOfValidators - 8);
        }
Ejemplo n.º 27
0
        public async Task ShouldNotRequestIfHeadBehind()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            INetworkPeering    mockNetworkPeering    = Substitute.For <INetworkPeering>();

            testServiceCollection.AddSingleton <INetworkPeering>(mockNetworkPeering);
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

            BeaconState state      = TestState.PrepareTestState(testServiceProvider);
            IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>();
            // Get genesis store initialise MemoryStoreProvider with the state
            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // Move forward time
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            ulong          targetTime     = 2 * 6; // slot 2

            for (ulong timeSinceGenesis = 1; timeSinceGenesis <= targetTime; timeSinceGenesis++)
            {
                ulong time = state.GenesisTime + timeSinceGenesis;
                await forkChoice.OnTickAsync(store, time);

                if (timeSinceGenesis % timeParameters.SecondsPerSlot == 0)
                {
                    BeaconBlock       block       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
                    SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
                    await forkChoice.OnBlockAsync(store, signedBlock);
                }
            }

            // Act
            PeeringStatus peeringStatus = new PeeringStatus(
                new ForkVersion(new byte[4] {
                0, 0, 0, 0
            }),
                Root.Zero,
                Epoch.Zero,
                new Root(Enumerable.Repeat((byte)0x56, 32).ToArray()),
                new Slot(1));
            ISynchronizationManager synchronizationManager = testServiceProvider.GetService <ISynchronizationManager>();
            await synchronizationManager.OnStatusResponseReceived("peer", peeringStatus);

            // Assert
            await mockNetworkPeering.DidNotReceive()
            .RequestBlocksAsync("peer", Arg.Any <Root>(), Arg.Any <Slot>(), Arg.Any <Slot>());

            await mockNetworkPeering.DidNotReceive().DisconnectPeerAsync("peer");
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Processes to the next epoch transition, up to, but not including, the sub-transition named ``process_name``
        /// </summary>
        public static void RunEpochProcessingTo(IServiceProvider testServiceProvider, BeaconState state, TestProcessStep step)
        {
            TimeParameters        timeParameters        = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            Slot slot = (Slot)(state.Slot + (timeParameters.SlotsPerEpoch - state.Slot % timeParameters.SlotsPerEpoch) - 1UL);

            // transition state to slot before epoch state transition
            beaconStateTransition.ProcessSlots(state, slot);

            // start transitioning, do one slot update before the epoch itself.
            beaconStateTransition.ProcessSlot(state);

            // process components of epoch transition before final-updates
            if (step == TestProcessStep.ProcessJustificationAndFinalization)
            {
                return;
            }
            // Note: only run when present. Later phases introduce more to the epoch-processing.
            beaconStateTransition.ProcessJustificationAndFinalization(state);

            if (step == TestProcessStep.ProcessRewardsAndPenalties)
            {
                return;
            }

            beaconStateTransition.ProcessRewardsAndPenalties(state);

            if (step == TestProcessStep.ProcessRegistryUpdates)
            {
                return;
            }

            beaconStateTransition.ProcessRegistryUpdates(state);

            if (step == TestProcessStep.ProcessSlashings)
            {
                return;
            }

            beaconStateTransition.ProcessSlashings(state);

            if (step == TestProcessStep.ProcessFinalUpdates)
            {
                return;
            }

            beaconStateTransition.ProcessFinalUpdates(state);
        }
Ejemplo n.º 29
0
        public void GenesisEpochFullAttestationsNoRewards()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            InitialValues  initialValues  = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

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

            var attestations = new List <Attestation>();

            for (Slot slot = Slot.Zero; slot < timeParameters.SlotsPerEpoch - new Slot(1); slot += new Slot(1))
            {
                // create an attestation for each slot
                if (slot < timeParameters.SlotsPerEpoch)
                {
                    Attestation attestation = TestAttestation.GetValidAttestation(testServiceProvider, state, slot, 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);
            }

            // ensure has not cross the epoch boundary
            Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);

            stateEpoch.ShouldBe(initialValues.GenesisEpoch);

            BeaconState preState = BeaconState.Clone(state);

            // Act
            RunProcessRewardsAndPenalties(testServiceProvider, state);

            // Assert
            for (int index = 0; index < preState.Validators.Count; index++)
            {
                state.Balances[index].ShouldBe(preState.Balances[index], $"Balance {index}");
            }
        }
Ejemplo n.º 30
0
        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);
        }