示例#1
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);
        }
示例#2
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;

            IBeaconChainUtility beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
            IDepositStore       depositStore        = testServiceProvider.GetService <IDepositStore>();

            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);
            }

            DepositData depositData = BuildDeposit(testServiceProvider, state, publicKey, privateKey, amount, withdrawalCredentials, signed);
            Deposit     deposit     = depositStore.Place(depositData);

            state.SetEth1DepositIndex(0);
            state.Eth1Data.SetDepositRoot(depositStore.DepositData.Root);
            state.Eth1Data.SetDepositCount((ulong)depositStore.Deposits.Count);

            return(deposit);
        }
示例#3
0
        public static void SignDepositData(IServiceProvider testServiceProvider, DepositData depositData, byte[] privateKey, BeaconState?state)
        {
            SignatureDomains     signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            IBeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();

            Domain domain;

            if (state == null)
            {
                // Genesis
                domain = beaconChainUtility.ComputeDomain(signatureDomains.Deposit);
            }
            else
            {
                BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
                domain = beaconStateAccessor.GetDomain(state, signatureDomains.Deposit, Epoch.None);
            }

            DepositMessage depositMessage     = new DepositMessage(depositData.PublicKey, depositData.WithdrawalCredentials, depositData.Amount);
            Root           depositMessageRoot = cryptographyService.HashTreeRoot(depositMessage);
            Root           signingRoot        = beaconChainUtility.ComputeSigningRoot(depositMessageRoot, domain);
            BlsSignature   signature          = TestSecurity.BlsSign(signingRoot, privateKey);

            depositData.SetSignature(signature);
        }
示例#4
0
 public ForkChoice(
     ILogger <ForkChoice> logger,
     ChainConstants chainConstants,
     IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions,
     IOptionsMonitor <TimeParameters> timeParameterOptions,
     IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions,
     IOptionsMonitor <ForkChoiceConfiguration> forkChoiceConfigurationOptions,
     IOptionsMonitor <SignatureDomains> signatureDomainOptions,
     ICryptographyService cryptographyService,
     IBeaconChainUtility beaconChainUtility,
     BeaconStateAccessor beaconStateAccessor,
     BeaconStateTransition beaconStateTransition)
 {
     _logger         = logger;
     _chainConstants = chainConstants;
     _miscellaneousParameterOptions  = miscellaneousParameterOptions;
     _timeParameterOptions           = timeParameterOptions;
     _maxOperationsPerBlockOptions   = maxOperationsPerBlockOptions;
     _forkChoiceConfigurationOptions = forkChoiceConfigurationOptions;
     _signatureDomainOptions         = signatureDomainOptions;
     _cryptographyService            = cryptographyService;
     _beaconChainUtility             = beaconChainUtility;
     _beaconStateAccessor            = beaconStateAccessor;
     _beaconStateTransition          = beaconStateTransition;
 }
 public SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree(
     ILogger <SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree> logger,
     ChainConstants chainConstants,
     IBeaconChainUtility beaconChainUtility,
     BeaconStateAccessor beaconStateAccessor)
 {
     _logger              = logger;
     _chainConstants      = chainConstants;
     _beaconChainUtility  = beaconChainUtility;
     _beaconStateAccessor = beaconStateAccessor;
 }
示例#6
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>();
            IBeaconChainUtility   beaconChainUtility    = testServiceProvider.GetService <IBeaconChainUtility>();
            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));
        }
示例#7
0
        public static BlsSignature GetAttestationSignature(IServiceProvider testServiceProvider, BeaconState state, AttestationData attestationData, byte[] privateKey)
        {
            SignatureDomains    signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            IBeaconChainUtility beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            Root         attestationDataRoot = attestationData.HashTreeRoot();
            Domain       domain      = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconAttester, attestationData.Target.Epoch);
            Root         signingRoot = beaconChainUtility.ComputeSigningRoot(attestationDataRoot, domain);
            BlsSignature signature   = TestSecurity.BlsSign(signingRoot, privateKey);

            return(signature);
        }
示例#8
0
        public static SignedBeaconBlockHeader SignBlockHeader(IServiceProvider testServiceProvider, BeaconState state, BeaconBlockHeader header, byte[] privateKey)
        {
            SignatureDomains     signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            IBeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor  beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();

            Root         headerRoot  = cryptographyService.HashTreeRoot(header);
            Domain       domain      = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, Epoch.None);
            Root         signingRoot = beaconChainUtility.ComputeSigningRoot(headerRoot, domain);
            BlsSignature signature   = TestSecurity.BlsSign(signingRoot, privateKey);

            return(new SignedBeaconBlockHeader(header, signature));
        }
示例#9
0
        public static SignedVoluntaryExit SignVoluntaryExit(IServiceProvider testServiceProvider, BeaconState state, VoluntaryExit voluntaryExit, byte[] privateKey)
        {
            var signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>();
            var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();

            var voluntaryExitRoot = cryptographyService.HashTreeRoot(voluntaryExit);
            var domain            = beaconStateAccessor.GetDomain(state, signatureDomains.VoluntaryExit, voluntaryExit.Epoch);
            var signingRoot       = beaconChainUtility.ComputeSigningRoot(voluntaryExitRoot, domain);
            var signature         = TestSecurity.BlsSign(signingRoot, privateKey);

            return(new SignedVoluntaryExit(voluntaryExit, signature));
        }
        public void GenesisEpochFullAttestationsNoRewards()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

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

            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(chainConstants.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}");
            }
        }
 public SynchronizationManager(
     ILogger <SynchronizationManager> logger,
     IBeaconChainUtility beaconChainUtility,
     BeaconStateAccessor beaconStateAccessor,
     IForkChoice forkChoice,
     IStore store,
     INetworkPeering networkPeering)
 {
     _logger              = logger;
     _beaconChainUtility  = beaconChainUtility;
     _beaconStateAccessor = beaconStateAccessor;
     _forkChoice          = forkChoice;
     _store          = store;
     _networkPeering = networkPeering;
 }
示例#12
0
 public BeaconStateMutator(
     ChainConstants chainConstants,
     IOptionsMonitor <TimeParameters> timeParameterOptions,
     IOptionsMonitor <StateListLengths> stateListLengthOptions,
     IOptionsMonitor <RewardsAndPenalties> rewardsAndPenaltiesOptions,
     IBeaconChainUtility beaconChainUtility,
     BeaconStateAccessor beaconStateAccessor)
 {
     _beaconChainUtility         = beaconChainUtility;
     _beaconStateAccessor        = beaconStateAccessor;
     _chainConstants             = chainConstants;
     _timeParameterOptions       = timeParameterOptions;
     _stateListLengthOptions     = stateListLengthOptions;
     _rewardsAndPenaltiesOptions = rewardsAndPenaltiesOptions;
 }
示例#13
0
 public AttestationProducer(ILogger <AttestationProducer> logger,
                            ICryptographyService cryptographyService,
                            IBeaconChainUtility beaconChainUtility,
                            BeaconStateAccessor beaconStateAccessor,
                            BeaconStateTransition beaconStateTransition,
                            IForkChoice forkChoice,
                            IStore store)
 {
     _logger = logger;
     _cryptographyService   = cryptographyService;
     _beaconChainUtility    = beaconChainUtility;
     _beaconStateAccessor   = beaconStateAccessor;
     _beaconStateTransition = beaconStateTransition;
     _forkChoice            = forkChoice;
     _store = store;
 }
示例#14
0
 public BeaconStateAccessor(
     ChainConstants chainConstants,
     IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions,
     IOptionsMonitor <TimeParameters> timeParameterOptions,
     IOptionsMonitor <StateListLengths> stateListLengthOptions,
     IOptionsMonitor <SignatureDomains> signatureDomainOptions,
     ICryptographyService cryptographyService,
     IBeaconChainUtility beaconChainUtility)
 {
     _chainConstants                = chainConstants;
     _cryptographyService           = cryptographyService;
     _beaconChainUtility            = beaconChainUtility;
     _miscellaneousParameterOptions = miscellaneousParameterOptions;
     _timeParameterOptions          = timeParameterOptions;
     _stateListLengthOptions        = stateListLengthOptions;
     _signatureDomainOptions        = signatureDomainOptions;
 }
示例#15
0
 public ValidatorAssignments(ILogger <ValidatorAssignments> logger,
                             IOptionsMonitor <TimeParameters> timeParameterOptions,
                             IBeaconChainUtility beaconChainUtility,
                             BeaconStateAccessor beaconStateAccessor,
                             BeaconStateTransition beaconStateTransition,
                             IForkChoice forkChoice,
                             IStore store,
                             ValidatorAssignmentsCache validatorAssignmentsCache)
 {
     _logger = logger;
     _timeParameterOptions  = timeParameterOptions;
     _beaconChainUtility    = beaconChainUtility;
     _beaconStateAccessor   = beaconStateAccessor;
     _beaconStateTransition = beaconStateTransition;
     _forkChoice            = forkChoice;
     _store = store;
     _validatorAssignmentsCache = validatorAssignmentsCache;
 }
        public void Ejection()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

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

            int index = 0;

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

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

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

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

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

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

            isActiveAfter.ShouldBeFalse();
            validatorAfter.ExitEpoch.ShouldNotBe(chainConstants.FarFutureEpoch);
        }
        private void MockDeposit(IServiceProvider testServiceProvider, BeaconState state, int index)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            GweiValues     gweiValues     = testServiceProvider.GetService <IOptions <GweiValues> >().Value;

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

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

            isActive.ShouldBeTrue();

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

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

            isActiveAfter.ShouldBeFalse();
        }
示例#18
0
 public QuickStartMockEth1GenesisProvider(ILogger <QuickStartMockEth1GenesisProvider> logger,
                                          ChainConstants chainConstants,
                                          IOptionsMonitor <GweiValues> gweiValueOptions,
                                          IOptionsMonitor <InitialValues> initialValueOptions,
                                          IOptionsMonitor <TimeParameters> timeParameterOptions,
                                          IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                                          IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                                          ICryptographyService crypto,
                                          IBeaconChainUtility beaconChainUtility,
                                          IDepositStore depositStore)
 {
     _logger                     = logger;
     _chainConstants             = chainConstants;
     _gweiValueOptions           = gweiValueOptions;
     _initialValueOptions        = initialValueOptions;
     _timeParameterOptions       = timeParameterOptions;
     _signatureDomainOptions     = signatureDomainOptions;
     _quickStartParameterOptions = quickStartParameterOptions;
     _crypto                     = crypto;
     _beaconChainUtility         = beaconChainUtility;
     _depositStore               = depositStore;
 }
示例#19
0
        public static IList <DepositData> PrepareGenesisDeposits(IServiceProvider testServiceProvider, int genesisValidatorCount, Gwei amount, bool signed)
        {
            ChainConstants          chainConstants          = testServiceProvider.GetService <ChainConstants>();
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            InitialValues           initialValues           = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

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

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

            for (int validatorIndex = 0; validatorIndex < genesisValidatorCount; validatorIndex++)
            {
                BlsPublicKey publicKey  = publicKeys[validatorIndex];
                byte[]       privateKey = privateKeys[validatorIndex];
                // insecurely use pubkey as withdrawal key if no credentials provided
                byte[] withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                Bytes32     withdrawalCredentials = new Bytes32(withdrawalCredentialBytes);
                DepositData depositData           =
                    BuildDeposit(testServiceProvider, null, publicKey, privateKey, amount, withdrawalCredentials, signed);
                depositDataList.Add(depositData);
            }

            return(depositDataList);
        }
        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;

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

            int index = 0;

            MockDeposit(testServiceProvider, state, index);

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

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

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

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

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

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

            isActive.ShouldBeTrue();
        }
        private static IList <Attestation> PrepareStateWithFullAttestations(IServiceProvider testServiceProvider, BeaconState state)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

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

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

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

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

                TestState.NextSlot(testServiceProvider, state);
            }

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

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

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

            return(attestations);
        }
示例#22
0
        public async Task OnAttestationPastEpoch()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true);
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

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

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

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

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

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

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

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

            await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : false);
        }
示例#23
0
        private BlsSignature GetEpochSignature(IServiceProvider testServiceProvider, byte[] privateKey, ForkVersion forkVersion, Slot slot)
        {
            SignatureDomains    signatureDomains   = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>();
            var domain = beaconChainUtility.ComputeDomain(signatureDomains.Randao, forkVersion);

            var epoch = beaconChainUtility.ComputeEpochAtSlot(slot);

            var epochRoot        = epoch.HashTreeRoot();
            var epochSigningRoot = beaconChainUtility.ComputeSigningRoot(epochRoot, domain);

            BLSParameters parameters = new BLSParameters()
            {
                PrivateKey = privateKey
            };
            BLS bls         = BLS.Create(parameters);
            var destination = new Span <byte>(new byte[96]);

            bls.TrySignData(epochSigningRoot.AsSpan(), destination, out var bytesWritten);

            var signature = new BlsSignature(destination.ToArray());

            return(signature);
        }
        public void GenesisEpochNoAttestationsNoPenalties()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

            BeaconState preState = BeaconState.Clone(state);

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

            stateEpoch.ShouldBe(chainConstants.GenesisEpoch);

            // Act
            RunProcessRewardsAndPenalties(testServiceProvider, state);

            // Assert
            for (int index = 0; index < preState.Validators.Count; index++)
            {
                state.Balances[index].ShouldBe(preState.Balances[index], $"Balance {index}");
            }
        }
示例#25
0
        public void EffectiveBalanceHysteresis()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            //# Prepare state up to the final-updates.
            //# Then overwrite the balances, we only want to focus to be on the hysteresis based changes.
            TestProcessUtility.RunEpochProcessingTo(testServiceProvider, state, TestProcessStep.ProcessFinalUpdates);

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

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

            // Set some edge cases for balances
            Gwei maximum       = gweiValues.MaximumEffectiveBalance;
            Gwei minimum       = gweiValues.EjectionBalance;
            Gwei increment     = gweiValues.EffectiveBalanceIncrement;
            Gwei halfIncrement = increment / 2;

            EffectiveBalanceCase[] testCases = new[] {
                new EffectiveBalanceCase(maximum, maximum, maximum, "as-is"),
                new EffectiveBalanceCase(maximum, (Gwei)(maximum - 1), maximum - increment, "round down, step lower"),
                new EffectiveBalanceCase(maximum, (Gwei)(maximum + 1), maximum, "round down"),
                new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment), maximum - increment, "exactly 1 step lower"),
                new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment - 1), maximum - (increment * 2), "just 1 over 1 step lower"),
                new EffectiveBalanceCase(maximum, (Gwei)(maximum - increment + 1), maximum - increment, "close to 1 step lower"),
                new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 3)), minimum, "bigger balance, but not high enough"),
                new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 3) + 1), minimum + increment, "bigger balance, high enough, but small step"),
                new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4) - 1), minimum + increment, "bigger balance, high enough, close to double step"),
                new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4)), minimum + (increment * 2), "exact two step balance increment"),
                new EffectiveBalanceCase(minimum, (Gwei)(minimum + (halfIncrement * 4) + 1), minimum + (increment * 2), "over two steps, round down"),
            };

            Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state);

            for (int index = 0; index < testCases.Length; index++)
            {
                Validator validator = state.Validators[index];
                bool      isActive  = beaconChainUtility.IsActiveValidator(validator, currentEpoch);
                isActive.ShouldBeTrue();

                EffectiveBalanceCase testCase = testCases[index];
                validator.SetEffectiveBalance(testCase.PreEffective);
                ValidatorIndex validatorIndex = new ValidatorIndex((ulong)index);
                state.SetBalance(validatorIndex, testCase.Balance);
            }

            // Act
            beaconStateTransition.ProcessFinalUpdates(state);

            // Assert
            for (int index = 0; index < testCases.Length; index++)
            {
                EffectiveBalanceCase testCase  = testCases[index];
                Validator            validator = state.Validators[index];
                validator.EffectiveBalance.ShouldBe(testCase.PostEffective, testCase.Name);
            }
        }
示例#26
0
        public static BeaconBlock BuildEmptyBlock(IServiceProvider testServiceProvider, BeaconState state, Slot slot, BlsSignature randaoReveal)
        {
            //if (slot) is none

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

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

            Eth1Data eth1Data = new Eth1Data(Root.Zero, state.Eth1DepositIndex, Bytes32.Zero);

            Root stateRoot = !state.LatestBlockHeader.StateRoot.Equals(Root.Zero)
                ? state.LatestBlockHeader.StateRoot
                : cryptographyService.HashTreeRoot(state);
            BeaconBlockHeader previousBlockHeader = new BeaconBlockHeader(state.LatestBlockHeader.Slot,
                                                                          state.LatestBlockHeader.ParentRoot, stateRoot, state.LatestBlockHeader.BodyRoot);
            Root previousBlockHashTreeRoot = cryptographyService.HashTreeRoot(previousBlockHeader);

            if (randaoReveal.Equals(BlsSignature.Zero))
            {
                Epoch          blockEpoch = beaconChainUtility.ComputeEpochAtSlot(slot);
                ValidatorIndex proposerIndex;
                if (slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (blockEpoch > stateEpoch + 1)
                    {
                        Console.WriteLine("WARNING: Block slot (epoch {0}) far away from state (epoch {1}), and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.", blockEpoch, stateEpoch);
                    }

                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, 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);
                Root   epochHashTreeRoot = cryptographyService.HashTreeRoot(blockEpoch);
                Root   randaoSigningRoot = beaconChainUtility.ComputeSigningRoot(epochHashTreeRoot, randaoDomain);
                randaoReveal = TestSecurity.BlsSign(randaoSigningRoot, privateKey);
            }

            BeaconBlock emptyBlock = new BeaconBlock(slot,
                                                     previousBlockHashTreeRoot,
                                                     Root.Zero,
                                                     new BeaconBlockBody(
                                                         randaoReveal,
                                                         eth1Data,
                                                         new Bytes32(),
                                                         Array.Empty <ProposerSlashing>(),
                                                         Array.Empty <AttesterSlashing>(),
                                                         Array.Empty <Attestation>(),
                                                         Array.Empty <Deposit>(),
                                                         Array.Empty <SignedVoluntaryExit>()
                                                         ));

            return(emptyBlock);
        }
示例#27
0
        private static AttestationData BuildAttestationData(IServiceProvider testServiceProvider, BeaconState state, Slot slot, CommitteeIndex index)
        {
            IBeaconChainUtility beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            if (state.Slot > slot)
            {
                throw new ArgumentOutOfRangeException(nameof(slot), slot, $"Slot cannot be greater than state slot {state.Slot}.");
            }

            Root blockRoot;

            if (slot == state.Slot)
            {
                BeaconBlock nextBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
                blockRoot = nextBlock.ParentRoot;
            }
            else
            {
                blockRoot = beaconStateAccessor.GetBlockRootAtSlot(state, slot);
            }

            Root  epochBoundaryRoot;
            Epoch currentEpoch          = beaconStateAccessor.GetCurrentEpoch(state);
            Slot  currentEpochStartSlot = beaconChainUtility.ComputeStartSlotOfEpoch(currentEpoch);

            if (slot < currentEpochStartSlot)
            {
                Epoch previousEpoch = beaconStateAccessor.GetPreviousEpoch(state);
                epochBoundaryRoot = beaconStateAccessor.GetBlockRoot(state, previousEpoch);
            }
            else if (slot == currentEpochStartSlot)
            {
                epochBoundaryRoot = blockRoot;
            }
            else
            {
                epochBoundaryRoot = beaconStateAccessor.GetBlockRoot(state, currentEpoch);
            }

            Epoch sourceEpoch;
            Root  sourceRoot;

            if (slot < currentEpochStartSlot)
            {
                sourceEpoch = state.PreviousJustifiedCheckpoint.Epoch;
                sourceRoot  = state.PreviousJustifiedCheckpoint.Root;
            }
            else
            {
                sourceEpoch = state.CurrentJustifiedCheckpoint.Epoch;
                sourceRoot  = state.CurrentJustifiedCheckpoint.Root;
            }

            //Crosslink parentCrosslink;
            //if (epochOfSlot == currentEpoch)
            //{
            //    parentCrosslink = state.CurrentCrosslinks[(int)(ulong)shard];
            //}
            //else
            //{
            //    throw new NotImplementedException();
            //}

            Epoch           slotEpoch       = beaconChainUtility.ComputeEpochAtSlot(slot);
            AttestationData attestationData = new AttestationData(
                slot,
                index,
                blockRoot,
                new Checkpoint(sourceEpoch, sourceRoot),
                new Checkpoint(slotEpoch, epochBoundaryRoot));

            return(attestationData);
        }