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
            BeaconChainUtility   beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            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);
        }
Beispiel #2
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);
        }
Beispiel #3
0
        public static (Deposit, Root) BuildDeposit(IServiceProvider testServiceProvider, BeaconState?state, IList <DepositData> depositDataList, BlsPublicKey publicKey, byte[] privateKey, Gwei amount, Bytes32 withdrawalCredentials, bool signed)
        {
            ChainConstants       chainConstants      = testServiceProvider.GetService <ChainConstants>();
            BeaconChainUtility   beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();

            DepositData depositData = BuildDepositData(testServiceProvider, publicKey, privateKey, amount, withdrawalCredentials, state, signed);
            int         index       = depositDataList.Count;

            depositDataList.Add(depositData);
            Root root = cryptographyService.HashTreeRoot(depositDataList);
            IEnumerable <Bytes32>    allLeaves   = depositDataList.Select(x => new Bytes32(cryptographyService.HashTreeRoot(x).AsSpan()));
            IList <IList <Bytes32> > tree        = TestSecurity.CalculateMerkleTreeFromLeaves(allLeaves);
            IList <Bytes32>          merkleProof = TestSecurity.GetMerkleProof(tree, index, 32);
            List <Bytes32>           proof       = new List <Bytes32>(merkleProof);
            Span <byte> indexBytes = new Span <byte>(new byte[32]);

            BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1);
            if (!BitConverter.IsLittleEndian)
            {
                indexBytes.Slice(0, 8).Reverse();
            }
            Bytes32 indexHash = new Bytes32(indexBytes);

            proof.Add(indexHash);
            Bytes32 leaf       = new Bytes32(cryptographyService.HashTreeRoot(depositData).AsSpan());
            bool    checkValid = beaconChainUtility.IsValidMerkleBranch(leaf, proof, chainConstants.DepositContractTreeDepth + 1, (ulong)index, root);
            Deposit deposit    = new Deposit(proof, depositData);

            return(deposit, root);
        }
Beispiel #4
0
        public static void SignDepositData(IServiceProvider testServiceProvider, DepositData depositData, byte[] privateKey, BeaconState?state)
        {
            SignatureDomains     signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            BeaconChainUtility   beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            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);
        }
Beispiel #5
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();
        }
Beispiel #6
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);
        }
Beispiel #7
0
 public QuickStart(ILogger <QuickStart> logger,
                   ChainConstants chainConstants,
                   IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions,
                   IOptionsMonitor <GweiValues> gweiValueOptions,
                   IOptionsMonitor <InitialValues> initialValueOptions,
                   IOptionsMonitor <TimeParameters> timeParameterOptions,
                   IOptionsMonitor <StateListLengths> stateListLengthOptions,
                   IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions,
                   IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                   IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                   ICryptographyService cryptographyService,
                   BeaconChainUtility beaconChainUtility,
                   Genesis beaconChain,
                   ForkChoice forkChoice)
 {
     _logger         = logger;
     _chainConstants = chainConstants;
     _miscellaneousParameterOptions = miscellaneousParameterOptions;
     _gweiValueOptions             = gweiValueOptions;
     _initialValueOptions          = initialValueOptions;
     _timeParameterOptions         = timeParameterOptions;
     _stateListLengthOptions       = stateListLengthOptions;
     _maxOperationsPerBlockOptions = maxOperationsPerBlockOptions;
     _signatureDomainOptions       = signatureDomainOptions;
     _quickStartParameterOptions   = quickStartParameterOptions;
     _cryptographyService          = cryptographyService;
     _beaconChainUtility           = beaconChainUtility;
     _beaconChain = beaconChain;
     _forkChoice  = forkChoice;
 }
Beispiel #8
0
 public MemoryStore(ulong time,
                    ulong genesisTime,
                    Checkpoint justifiedCheckpoint,
                    Checkpoint finalizedCheckpoint,
                    Checkpoint bestJustifiedCheckpoint,
                    IDictionary <Hash32, BeaconBlock> blocks,
                    IDictionary <Hash32, BeaconState> blockStates,
                    IDictionary <Checkpoint, BeaconState> checkpointStates,
                    IDictionary <ValidatorIndex, LatestMessage> latestMessages,
                    ILogger <MemoryStore> logger,
                    IOptionsMonitor <TimeParameters> timeParameterOptions,
                    BeaconChainUtility beaconChainUtility)
 {
     Time                    = time;
     GenesisTime             = genesisTime;
     JustifiedCheckpoint     = justifiedCheckpoint;
     FinalizedCheckpoint     = finalizedCheckpoint;
     BestJustifiedCheckpoint = bestJustifiedCheckpoint;
     _blocks                 = new Dictionary <Hash32, BeaconBlock>(blocks);
     _blockStates            = new Dictionary <Hash32, BeaconState>(blockStates);
     _checkpointStates       = new Dictionary <Checkpoint, BeaconState>(checkpointStates);
     _latestMessages         = new Dictionary <ValidatorIndex, LatestMessage>(latestMessages);
     _logger                 = logger;
     _timeParameterOptions   = timeParameterOptions;
     _beaconChainUtility     = beaconChainUtility;
 }
Beispiel #9
0
        public async Task GenesisWithEmptyParametersTimeShouldReject()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();

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

            miscellaneousParameterOptions.CurrentValue.MinimumGenesisActiveValidatorCount = 2;

            LoggerFactory loggerFactory = new LoggerFactory(new[] {
                new ConsoleLoggerProvider(TestOptionsMonitor.Create(new ConsoleLoggerOptions()))
            });

            ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>();

            BeaconChainUtility beaconChainUtility = new BeaconChainUtility(loggerFactory.CreateLogger <BeaconChainUtility>(),
                                                                           miscellaneousParameterOptions, gweiValueOptions, timeParameterOptions,
                                                                           cryptographyService);
            BeaconStateAccessor beaconStateAccessor = new BeaconStateAccessor(miscellaneousParameterOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, signatureDomainOptions,
                                                                              cryptographyService, beaconChainUtility);
            BeaconStateMutator beaconStateMutator = new BeaconStateMutator(chainConstants, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions,
                                                                           beaconChainUtility, beaconStateAccessor);
            BeaconStateTransition beaconStateTransition = new BeaconStateTransition(loggerFactory.CreateLogger <BeaconStateTransition>(),
                                                                                    chainConstants, miscellaneousParameterOptions, gweiValueOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions, maxOperationsPerBlockOptions, signatureDomainOptions,
                                                                                    cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateMutator);

            BeaconNode.Genesis beaconChain = new BeaconNode.Genesis(loggerFactory.CreateLogger <BeaconNode.Genesis>(),
                                                                    chainConstants, miscellaneousParameterOptions,
                                                                    gweiValueOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, maxOperationsPerBlockOptions,
                                                                    cryptographyService, beaconStateAccessor, beaconStateTransition);
            MemoryStoreProvider storeProvider = new MemoryStoreProvider(loggerFactory, timeParameterOptions);
            ForkChoice          forkChoice    = new ForkChoice(loggerFactory.CreateLogger <ForkChoice>(),
                                                               miscellaneousParameterOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, maxOperationsPerBlockOptions, forkChoiceConfigurationOptions, signatureDomainOptions,
                                                               cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateTransition, storeProvider);
            ChainStart chainStart = new ChainStart(loggerFactory.CreateLogger <ChainStart>(), beaconChain, forkChoice);

            // Act
            Hash32 eth1BlockHash = Hash32.Zero;
            ulong  eth1Timestamp = 106185600uL; // 1973-05-14

            Deposit[] deposits = Array.Empty <Deposit>();
            bool      success  = await chainStart.TryGenesisAsync(eth1BlockHash, eth1Timestamp, deposits);

            // Assert
            success.ShouldBeFalse();
        }
Beispiel #10
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);
        }
Beispiel #11
0
 public SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree(
     ILogger <SimpleLatestMessageDrivenGreedyHeaviestObservedSubtree> logger,
     ChainConstants chainConstants,
     BeaconChainUtility beaconChainUtility,
     BeaconStateAccessor beaconStateAccessor)
 {
     _logger              = logger;
     _chainConstants      = chainConstants;
     _beaconChainUtility  = beaconChainUtility;
     _beaconStateAccessor = beaconStateAccessor;
 }
Beispiel #12
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));
        }
        public static BlsSignature GetAttestationSignature(IServiceProvider testServiceProvider, BeaconState state, AttestationData attestationData, byte[] privateKey)
        {
            SignatureDomains    signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            BeaconChainUtility  beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            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);
        }
        public static SignedBeaconBlockHeader SignBlockHeader(IServiceProvider testServiceProvider, BeaconState state, BeaconBlockHeader header, byte[] privateKey)
        {
            SignatureDomains     signatureDomains    = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            BeaconChainUtility   beaconChainUtility  = testServiceProvider.GetService <BeaconChainUtility>();
            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));
        }
        public static SignedVoluntaryExit SignVoluntaryExit(IServiceProvider testServiceProvider, BeaconState state, VoluntaryExit voluntaryExit, byte[] privateKey)
        {
            var signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>();
            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));
        }
Beispiel #16
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}");
            }
        }
Beispiel #17
0
        public async Task GenesisWithEmptyParametersTimeShouldReject()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();

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

            miscellaneousParameterOptions.CurrentValue.MinimumGenesisActiveValidatorCount = 2;

            var loggerFactory = new LoggerFactory(new[] {
                new ConsoleLoggerProvider(TestOptionsMonitor.Create(new ConsoleLoggerOptions()))
            });

            var cryptographyService = new CryptographyService();
            var beaconChainUtility  = new BeaconChainUtility(loggerFactory.CreateLogger <BeaconChainUtility>(),
                                                             miscellaneousParameterOptions, gweiValueOptions, timeParameterOptions,
                                                             cryptographyService);
            var beaconStateAccessor = new BeaconStateAccessor(miscellaneousParameterOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, signatureDomainOptions,
                                                              cryptographyService, beaconChainUtility);
            var beaconStateMutator = new BeaconStateMutator(chainConstants, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions,
                                                            beaconChainUtility, beaconStateAccessor);
            var beaconStateTransition = new BeaconStateTransition(loggerFactory.CreateLogger <BeaconStateTransition>(),
                                                                  chainConstants, miscellaneousParameterOptions, gweiValueOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, rewardsAndPenaltiesOptions, maxOperationsPerBlockOptions, signatureDomainOptions,
                                                                  cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateMutator);
            var beaconChain = new BeaconChain(loggerFactory.CreateLogger <BeaconChain>(),
                                              chainConstants, miscellaneousParameterOptions,
                                              gweiValueOptions, initialValueOptions, timeParameterOptions, stateListLengthOptions, maxOperationsPerBlockOptions,
                                              cryptographyService, beaconChainUtility, beaconStateAccessor, beaconStateMutator, beaconStateTransition);

            // Act
            var eth1BlockHash = Hash32.Zero;
            var eth1Timestamp = (ulong)106185600; // 1973-05-14
            var deposits      = Array.Empty <Deposit>();
            var success       = await beaconChain.TryGenesisAsync(eth1BlockHash, eth1Timestamp, deposits);

            // Assert
            success.ShouldBeFalse();
            beaconChain.State.ShouldBeNull();
        }
 public QuickStartMockEth1GenesisProvider(ILogger <QuickStartMockEth1GenesisProvider> logger,
                                          ChainConstants chainConstants,
                                          IOptionsMonitor <GweiValues> gweiValueOptions,
                                          IOptionsMonitor <InitialValues> initialValueOptions,
                                          IOptionsMonitor <TimeParameters> timeParameterOptions,
                                          IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                                          IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                                          ICryptographyService cryptographyService,
                                          BeaconChainUtility beaconChainUtility)
 {
     _logger                     = logger;
     _chainConstants             = chainConstants;
     _gweiValueOptions           = gweiValueOptions;
     _initialValueOptions        = initialValueOptions;
     _timeParameterOptions       = timeParameterOptions;
     _signatureDomainOptions     = signatureDomainOptions;
     _quickStartParameterOptions = quickStartParameterOptions;
     _cryptographyService        = cryptographyService;
     _beaconChainUtility         = beaconChainUtility;
 }
Beispiel #19
0
        public void Ejection()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

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

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

            int index = 0;

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

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

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

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

            // Act
            RunProcessRegistryUpdates(testServiceProvider, state);

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

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

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

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

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

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

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

            isActive.ShouldBeTrue();

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

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

            isActiveAfter.ShouldBeFalse();
        }
Beispiel #22
0
 public QuickStart(ILogger <QuickStart> logger,
                   ChainConstants chainConstants,
                   IOptionsMonitor <GweiValues> gweiValueOptions,
                   IOptionsMonitor <InitialValues> initialValueOptions,
                   IOptionsMonitor <SignatureDomains> signatureDomainOptions,
                   IOptionsMonitor <QuickStartParameters> quickStartParameterOptions,
                   ICryptographyService cryptographyService,
                   BeaconChainUtility beaconChainUtility,
                   Genesis beaconChain,
                   ForkChoice forkChoice)
 {
     _logger                     = logger;
     _chainConstants             = chainConstants;
     _gweiValueOptions           = gweiValueOptions;
     _initialValueOptions        = initialValueOptions;
     _signatureDomainOptions     = signatureDomainOptions;
     _quickStartParameterOptions = quickStartParameterOptions;
     _cryptographyService        = cryptographyService;
     _beaconChainUtility         = beaconChainUtility;
     _beaconChain                = beaconChain;
     _forkChoice                 = forkChoice;
 }
Beispiel #23
0
        private static IList <Attestation> PrepareStateWithFullAttestations(IServiceProvider testServiceProvider, BeaconState state)
        {
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            InitialValues  initialValues  = testServiceProvider.GetService <IOptions <InitialValues> >().Value;

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

            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(initialValues.GenesisEpoch + Epoch.One);

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

            return(attestations);
        }
        private BlsSignature GetEpochSignature(IServiceProvider testServiceProvider, byte[] privateKey, ForkVersion forkVersion, Slot slot)
        {
            SignatureDomains   signatureDomains   = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;
            BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>();
            var domain = beaconChainUtility.ComputeDomain(signatureDomains.Randao, forkVersion);

            var epoch = beaconChainUtility.ComputeEpochAtSlot(slot);

            var epochRoot = epoch.HashTreeRoot();

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

            bls.TrySignHash(epochRoot.AsSpan(), destination, out var bytesWritten, domain.AsSpan());

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

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

            BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>();
            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);
        }
Beispiel #26
0
        public void GenesisEpochNoAttestationsNoPenalties()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            InitialValues      initialValues      = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>();

            BeaconState preState = BeaconState.Clone(state);

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

            stateEpoch.ShouldBe(initialValues.GenesisEpoch);

            // Act
            RunProcessRewardsAndPenalties(testServiceProvider, state);

            // Assert
            for (int index = 0; index < preState.Validators.Count; index++)
            {
                state.Balances[index].ShouldBe(preState.Balances[index], $"Balance {index}");
            }
        }
Beispiel #27
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>();
            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            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);
        }
        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;

            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            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);
            }
        }
Beispiel #29
0
        public async Task GenesisWithEmptyParametersTimeShouldReject()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();

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

            miscellaneousParameterOptions.CurrentValue.MinimumGenesisActiveValidatorCount = 2;

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

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

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

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

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

            // Assert
            success.ShouldBeFalse();
        }
Beispiel #30
0
 public StoreProvider(ILoggerFactory loggerFactory, IOptionsMonitor <TimeParameters> timeParameterOptions, BeaconChainUtility beaconChainUtility)
 {
     _loggerFactory        = loggerFactory;
     _timeParameterOptions = timeParameterOptions;
     _beaconChainUtility   = beaconChainUtility;
 }