Example #1
0
        public void FullAttestations()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            var attestations = PrepareStateWithFullAttestations(testServiceProvider, state);

            BeaconState preState = BeaconState.Clone(state);

            // Act
            RunProcessRewardsAndPenalties(testServiceProvider, state);

            // Assert
            var pendingAttestations = attestations.Select(x => new PendingAttestation(x.AggregationBits, x.Data, Slot.None, ValidatorIndex.None));
            var attestingIndices    = beaconStateTransition.GetUnslashedAttestingIndices(state, pendingAttestations).ToList();

            attestingIndices.Count.ShouldBeGreaterThan(0);

            for (int index = 0; index < preState.Validators.Count; index++)
            {
                ValidatorIndex validatorIndex = new ValidatorIndex((ulong)index);
                if (attestingIndices.Contains(validatorIndex))
                {
                    state.Balances[index].ShouldBeGreaterThan(preState.Balances[index], $"Attesting balance {index}");
                }
                else
                {
                    state.Balances[index].ShouldBeLessThan(preState.Balances[index], $"Non-attesting balance {index}");
                }
            }
        }
Example #2
0
        public void MaximumPenalties()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            StateListLengths    stateListLengths    = testServiceProvider.GetService <IOptions <StateListLengths> >().Value;
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            int   slashedCount = (state.Validators.Count / 3) + 1;
            Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);
            Epoch outEpoch     = currentEpoch + new Epoch((ulong)stateListLengths.EpochsPerSlashingsVector / 2);

            var slashedIndices = Enumerable.Range(0, slashedCount).ToList();

            SlashValidators(testServiceProvider, state, slashedIndices, Enumerable.Repeat(outEpoch, slashedCount));

            Gwei totalBalance   = beaconStateAccessor.GetTotalActiveBalance(state);
            Gwei totalPenalties = state.Slashings.Aggregate(Gwei.Zero, (accumulator, x) => accumulator + x);

            (totalBalance / 3).ShouldBeLessThanOrEqualTo(totalPenalties);

            // Act
            RunProcessSlashings(testServiceProvider, state);

            // Assert
            foreach (int index in slashedIndices)
            {
                state.Balances[index].ShouldBe(Gwei.Zero, $"Incorrect balance {index}");
            }
        }
Example #3
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);
        }
        public void BasicActivation()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

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

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

            var index = 0;

            MockDeposit(testServiceProvider, state, index);

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

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

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

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

            isActive.ShouldBeTrue();
        }
Example #5
0
        public async Task ChainNoAttestations()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            // Initialization
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            ForkChoice           forkChoice          = testServiceProvider.GetService <ForkChoice>();
            IStore store = forkChoice.GetGenesisStore(state);

            // On receiving a block of `GENESIS_SLOT + 1` slot
            BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1);
            await AddBlockToStore(testServiceProvider, store, block1);

            // On receiving a block of next epoch
            BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2);
            await AddBlockToStore(testServiceProvider, store, block2);

            // Act
            Hash32 headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Hash32 expectedRoot = cryptographyService.SigningRoot(block2);

            headRoot.ShouldBe(expectedRoot);
        }
        public void OnAttestationPreviousEpoch()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            var state = TestState.PrepareTestState(testServiceProvider);

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

            // Initialization
            var store = forkChoice.GetGenesisStore(state);
            var time  = store.Time + timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch;

            forkChoice.OnTick(store, time);

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

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);

            // Store block in store
            forkChoice.OnBlock(store, block);

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

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

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

            currentEpoch.ShouldBe(initialValues.GenesisEpoch + new Epoch(1));

            RunOnAttestation(testServiceProvider, state, store, attestation, expectValid: true);
        }
        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);
        }
Example #8
0
        public async Task ChainNoAttestations()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            // On receiving a block of `GENESIS_SLOT + 1` slot
            BeaconBlock       block1       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
            SignedBeaconBlock signedBlock1 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1);

            await AddBlockToStore(testServiceProvider, store, signedBlock1);

            // On receiving a block of next epoch
            BeaconBlock       block2       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
            SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2);

            await AddBlockToStore(testServiceProvider, store, signedBlock2);

            // Act
            Root headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Root expectedRoot = cryptographyService.HashTreeRoot(block2);

            headRoot.ShouldBe(expectedRoot);
        }
        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);
        }
Example #10
0
        public async Task GenesisHead()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            var state = TestState.PrepareTestState(testServiceProvider);

            var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            var timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            var stateListLengths        = testServiceProvider.GetService <IOptions <StateListLengths> >().Value;
            var maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            var options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            options.AddCortexContainerConverters();
            var debugState = System.Text.Json.JsonSerializer.Serialize(state, options);

            // Initialization
            var forkChoice = testServiceProvider.GetService <ForkChoice>();
            var store      = forkChoice.GetGenesisStore(state);

            // Act
            var headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            var stateRoot    = state.HashTreeRoot(miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock);
            var genesisBlock = new BeaconBlock(stateRoot);
            var expectedRoot = genesisBlock.SigningRoot(miscellaneousParameters, maxOperationsPerBlock);

            headRoot.ShouldBe(expectedRoot);
        }
Example #11
0
        public void Eth1VoteReset()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            var 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 (var index = Slot.Zero; index < state.Slot + new Slot(1); index += new Slot(1))
            {
                var eth1DepositIndex = state.Eth1DepositIndex;
                var depositRoot      = new Hash32(Enumerable.Repeat((byte)0xaa, 32).ToArray());
                var blockHash        = new Hash32(Enumerable.Repeat((byte)0xbb, 32).ToArray());
                var eth1Data         = new Eth1Data(depositRoot, eth1DepositIndex, blockHash);
                state.AddEth1DataVote(eth1Data);
            }

            // Act
            RunProcessFinalUpdates(testServiceProvider, state);

            // Assert
            state.Eth1DataVotes.Count.ShouldBe(0);
        }
Example #12
0
        public async Task ChainNoAttestations()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            var state = TestState.PrepareTestState(testServiceProvider);

            var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            var maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            // Initialization
            var forkChoice = testServiceProvider.GetService <ForkChoice>();
            var store      = forkChoice.GetGenesisStore(state);

            // On receiving a block of `GENESIS_SLOT + 1` slot
            var block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1);
            AddBlockToStore(testServiceProvider, store, block1);

            // On receiving a block of next epoch
            var block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);

            TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2);
            AddBlockToStore(testServiceProvider, store, block2);

            // Act
            var headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            var expectedRoot = block2.SigningRoot(miscellaneousParameters, maxOperationsPerBlock);

            headRoot.ShouldBe(expectedRoot);
        }
Example #13
0
        public async Task OnAttestationCurrentEpoch()
        {
            // 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 * 2;
            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);

            await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : true);
        }
Example #14
0
        public async Task GenesisHead()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            };

            options.ConfigureNethermindCore2();
            string debugState = System.Text.Json.JsonSerializer.Serialize(state, options);

            // Initialization
            IBeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            IForkChoice          forkChoice          = testServiceProvider.GetService <IForkChoice>();

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

            // Act
            Root headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Root stateRoot = cryptographyService.HashTreeRoot(state);

            BeaconBlock genesisBlock = new BeaconBlock(Slot.Zero, Root.Zero, stateRoot, BeaconBlockBody.Zero);
            Root        expectedRoot = cryptographyService.HashTreeRoot(genesisBlock);

            headRoot.ShouldBe(expectedRoot);
        }
        public void IsValidGenesisStateFalseNotEnoughValidators()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);

            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value;

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

            int depositCount                 = miscellaneousParameters.MinimumGenesisActiveValidatorCount - 1;
            IList <DepositData> deposits     = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: true);
            IDepositStore       depositStore = testServiceProvider.GetService <IDepositStore>();

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

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

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

            // Assert
            IsValidGenesisState(testServiceProvider, state, false);
        }
Example #16
0
        public void FinalizeOn234(ulong epochValue, bool sufficientSupport)
        {
            // Arrange
            var epoch = new Epoch(epochValue);
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            epoch.ShouldBeGreaterThan(new Epoch(4));

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

            // Skip ahead to just before epoch
            var slot = new Slot((ulong)timeParameters.SlotsPerEpoch * (ulong)epoch - 1);

            state.SetSlot(slot);

            // 43210 -- epochs ago
            // 3210x -- justification bitfield indices
            // 11*0. -- justification bitfield contents, . = this epoch, * is being justified now
            // checkpoints for the epochs ago:
            var checkpoints = TestCheckpoint.GetCheckpoints(epoch).ToArray();

            PutCheckpointsInBlockRoots(beaconChainUtility, timeParameters, state, checkpoints[0..3]);
        public void Eth1VoteNoReset()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            timeParameters.SlotsPerEth1VotingPeriod.ShouldBeGreaterThan(timeParameters.SlotsPerEpoch);

            // skip ahead to the end of the epoch
            state.SetSlot((Slot)(timeParameters.SlotsPerEpoch - 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((int)(ulong)timeParameters.SlotsPerEpoch);
        }
Example #18
0
        public void TestInitializeBeaconStateFromEth1()
        {
            var useBls = true;

            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider(useBls);

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

            var depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount;

            (var deposits, var depositRoot) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: useBls);

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

            var beaconChain = testServiceProvider.GetService <BeaconNode.Genesis>();

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

            // Assert
            state.GenesisTime.ShouldBe(eth1Timestamp - eth1Timestamp % chainConstants.SecondsPerDay + 2 * chainConstants.SecondsPerDay);
            state.Validators.Count.ShouldBe(depositCount);
            state.Eth1Data.DepositRoot.ShouldBe(depositRoot);
            state.Eth1Data.DepositCount.ShouldBe((ulong)depositCount);
            state.Eth1Data.BlockHash.ShouldBe(eth1BlockHash);
        }
Example #19
0
        public void InvalidSignatureBlockHeader()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            var block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: false);

            RunBlockHeaderProcessing(testServiceProvider, state, block, expectValid: false);
        }
        public void InvalidSlotBlockHeader()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            BeaconBlock block = TestBlock.BuildEmptyBlock(testServiceProvider, state, state.Slot + new Slot(2), BlsSignature.Zero);

            RunBlockHeaderProcessing(testServiceProvider, state, block, expectValid: false);
        }
Example #21
0
        public void InvalidSignature1()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            var proposerSlashing = TestProposerSlashing.GetValidProposerSlashing(testServiceProvider, state, signed1: false, signed2: true);

            RunProposerSlashingProcessing(testServiceProvider, state, proposerSlashing, expectValid: false);
        }
        public void SuccessDouble()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            var attesterSlashing = TestAttesterSlashing.GetValidAttesterSlashing(testServiceProvider, state, signed1: true, signed2: true);

            RunAttesterSlashingProcessing(testServiceProvider, state, attesterSlashing, expectValid: true);
        }
        public void SuccessBlockHeader()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);

            RunBlockHeaderProcessing(testServiceProvider, state, block, expectValid: true);
        }
        public void InvalidSignature1()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            AttesterSlashing attesterSlashing = TestAttesterSlashing.GetValidAttesterSlashing(testServiceProvider, state, signed1: false, signed2: true);

            RunAttesterSlashingProcessing(testServiceProvider, state, attesterSlashing, expectValid: false);
        }
        public void IsValidGenesisStateTrue()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();

            // Act
            var state = CreateValidBeaconState(testServiceProvider);

            // Assert
            IsValidGenesisState(testServiceProvider, state, true);
        }
Example #26
0
        public async Task ShorterChainButHeavierWeight()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            // Initialization
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();
            ForkChoice           forkChoice          = testServiceProvider.GetService <ForkChoice>();
            IStore      store        = forkChoice.GetGenesisStore(state);
            BeaconState genesisState = BeaconState.Clone(state);

            // build longer tree
            Hash32      longRoot  = default;
            BeaconState longState = BeaconState.Clone(genesisState);

            for (int i = 0; i < 3; i++)
            {
                BeaconBlock longBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, longState, signed: true);
                TestState.StateTransitionAndSignBlock(testServiceProvider, longState, longBlock);
                await AddBlockToStore(testServiceProvider, store, longBlock);

                if (i == 2)
                {
                    longRoot = cryptographyService.SigningRoot(longBlock);
                }
            }

            // build short tree
            BeaconState shortState = BeaconState.Clone(genesisState);
            BeaconBlock shortBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, shortState, signed: true);

            shortBlock.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray()));
            TestBlock.SignBlock(testServiceProvider, shortState, shortBlock, ValidatorIndex.None);
            TestState.StateTransitionAndSignBlock(testServiceProvider, shortState, shortBlock);
            await AddBlockToStore(testServiceProvider, store, shortBlock);

            Attestation shortAttestation = TestAttestation.GetValidAttestation(testServiceProvider, shortState, shortBlock.Slot, CommitteeIndex.None, signed: true);

            await AddAttestationToStore(testServiceProvider, store, shortAttestation);

            // Act
            Hash32 headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Hash32 expectedRoot = cryptographyService.SigningRoot(shortBlock);

            headRoot.ShouldBe(expectedRoot);
            headRoot.ShouldNotBe(longRoot);
        }
Example #27
0
        public async Task ShorterChainButHeavierWeight()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            BeaconState genesisState = BeaconState.Clone(state);

            // build longer tree
            Root        longRoot  = Root.Zero;
            BeaconState longState = BeaconState.Clone(genesisState);

            for (int i = 0; i < 3; i++)
            {
                BeaconBlock       longBlock       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, longState, BlsSignature.Zero);
                SignedBeaconBlock signedLongBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, longState, longBlock);
                await AddBlockToStore(testServiceProvider, store, signedLongBlock);

                if (i == 2)
                {
                    longRoot = cryptographyService.HashTreeRoot(longBlock);
                }
            }

            // build short tree
            BeaconState shortState = BeaconState.Clone(genesisState);
            BeaconBlock shortBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, shortState, BlsSignature.Zero);

            shortBlock.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray()));
            TestBlock.SignBlock(testServiceProvider, shortState, shortBlock, ValidatorIndex.None);
            SignedBeaconBlock signedShortBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, shortState, shortBlock);

            await AddBlockToStore(testServiceProvider, store, signedShortBlock);

            Attestation shortAttestation = TestAttestation.GetValidAttestation(testServiceProvider, shortState, shortBlock.Slot, CommitteeIndex.None, signed: true);

            await AddAttestationToStore(testServiceProvider, store, shortAttestation);

            // Act
            Root headRoot = await forkChoice.GetHeadAsync(store);

            // Assert
            Root expectedRoot = cryptographyService.HashTreeRoot(shortBlock);

            headRoot.ShouldBe(expectedRoot);
            headRoot.ShouldNotBe(longRoot);
        }
Example #28
0
        public void BasicOnTick()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            var state = TestState.PrepareTestState(testServiceProvider);

            var forkChoice = testServiceProvider.GetService <ForkChoice>();
            var store      = forkChoice.GetGenesisStore(state);

            // Act
            RunOnTick(testServiceProvider, store, store.Time + 1, expectNewJustifiedCheckpoint: false);

            // Assert
        }
        public void IsValidGenesisStateFalseInvalidTimestamp()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();

            var chainConstants          = testServiceProvider.GetService <ChainConstants>();
            var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;

            // Act
            var state = CreateValidBeaconState(testServiceProvider, eth1TimestampOverride: (miscellaneousParameters.MinimumGenesisTime - 3 * chainConstants.SecondsPerDay));

            // Assert
            IsValidGenesisState(testServiceProvider, state, false);
        }
Example #30
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}");
            }
        }