/// <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); }
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); }
private void GetInitialValueDependencies() { foreach (var pair in initialValueExpressions) { var variable = pair.Key; var expression = pair.Value; var symbols = expression.GetSubexpressionsRecursive(TokenType.Identifier); var variables = symbols.Select(token => Symbols.GetOrNull(token.Token.Value)).ToArray(); if (variables.Contains(null)) { //error } variables = variables.Distinct().ToArray(); if (variables.Length == 0) { var initialValue = EvaluateConstExpression(expression, variable.DataType, false); if (initialValue != null) { InitialValues.Set(variable, initialValue); } else { } } else { var depsList = initialDependencies.GetOrAddNew(variable); depsList.AddRange(variables); } } }
private object GetInitialValue(string attribute) { if (InitialValues != null && InitialValues.ContainsKey(attribute)) { return(InitialValues[attribute]); } return(null); }
public BeaconState InitializeBeaconStateFromEth1(Bytes32 eth1BlockHash, ulong eth1Timestamp, IList <Deposit> deposits) { if (_logger.IsInfo()) { Log.InitializeBeaconState(_logger, eth1BlockHash, eth1Timestamp, deposits.Count, null); } InitialValues initialValues = _initialValueOptions.CurrentValue; GweiValues gweiValues = _gweiValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; Fork fork = new Fork(initialValues.GenesisForkVersion, initialValues.GenesisForkVersion, _chainConstants.GenesisEpoch); ulong genesisTime = eth1Timestamp - (eth1Timestamp % timeParameters.MinimumGenesisDelay) + (2 * timeParameters.MinimumGenesisDelay); Eth1Data eth1Data = new Eth1Data(Root.Zero, (ulong)deposits.Count, eth1BlockHash); Root emptyBlockBodyRoot = _cryptographyService.HashTreeRoot(BeaconBlockBody.Zero); BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBodyRoot); Bytes32[] randaoMixes = Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector) .ToArray(); BeaconState state = new BeaconState(genesisTime, fork, eth1Data, latestBlockHeader, randaoMixes, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength); // Process deposits List <DepositData> depositDataList = new List <DepositData>(); foreach (Deposit deposit in deposits) { depositDataList.Add(deposit.Data); Root depositRoot = _cryptographyService.HashTreeRoot(depositDataList); state.Eth1Data.SetDepositRoot(depositRoot); _beaconStateTransition.ProcessDeposit(state, deposit); } // Process activations for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++) { Validator validator = state.Validators[validatorIndex]; Gwei balance = state.Balances[validatorIndex]; Gwei effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance); validator.SetEffectiveBalance(effectiveBalance); if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance) { validator.SetEligible(_chainConstants.GenesisEpoch); validator.SetActive(_chainConstants.GenesisEpoch); } } return(state); }
public static double CalculateTerminalVelocity(InitialValues initialValues) { //For the reference: https://www.grc.nasa.gov/WWW/K-12/airplane/termv.html var numerator = 2 * initialValues.Mass; var denominator = initialValues.DragCoefficient * initialValues.DensityOfTheMedium * initialValues.CrossSectionArea; return(Math.Sqrt(numerator / denominator)); }
public static double CalculateDragAtVelocity(double currentVelocity, InitialValues initialValues) { var drag = .5d * initialValues.DensityOfTheMedium * Math.Pow(currentVelocity, 2) * initialValues.CrossSectionArea * initialValues.DragCoefficient; return(drag); }
public object GetInitialValue(string name) { foreach (var prop in InitialValues.GetType().GetProperties()) { if (prop.CanRead && prop.Name == name) { return(prop.GetValue(InitialValues, null)); } } return(null); }
public bool HasChanges() { var dictCurrent = ObjectRef.ToStringDictionaryExcludingRefs(); if (!InitialValues.Any(q => dictCurrent[q.Key] == q.Value)) { return(false); } return(true); }
private void SetModel() { if (Entity != null && GenericManager != null) { GenericFormModel model = new GenericFormModel(string.Empty); foreach (var item in Entity.Attributes) { var type = GetTypeFromAttribute(item); var defaultValue = InitialValues != null && InitialValues.ContainsKey(item.LogicalName) ? InitialValues[item.LogicalName] : null; var attribute = new GenericFormInputModel() { Key = item.LogicalName, DisplayName = item.DisplayName, Description = item.Description, IsMandatory = item.IsMandatory, DefaultValue = defaultValue, Type = type, }; if (type == GenericFormInputModel.TypeValue.EntityReference) { var relatedEntity = Relationships.First(k => k.RelatedEntity == Entity.LogicalName && k.RelatedAttribute == attribute.Key); attribute.EntityReferenceSuggestionHandler = new EntityReferenceHandler(relatedEntity.MainEntity, GenericManager.RetrieveAllHandler, GenericManager.RetrieveHandler); } else if (type == GenericFormInputModel.TypeValue.OptionSet) { attribute.OptionSetValueOptions = item.Options.Select(k => new DD.Lab.Wpf.Models.Inputs.OptionSetValue() { DisplayName = k.DisplayName, Value = k.Value }).ToArray(); } else if (type == GenericFormInputModel.TypeValue.State) { var options = new List <DD.Lab.Wpf.Models.Inputs.OptionSetValue>(); options.Add(new DD.Lab.Wpf.Models.Inputs.OptionSetValue() { DisplayName = "Enabled", Value = 1 }); options.Add(new DD.Lab.Wpf.Models.Inputs.OptionSetValue() { DisplayName = "Disabled", Value = 0 }); attribute.OptionSetValueOptions = options.ToArray(); } model.Attributes.Add(attribute); } FormModel = model; } }
public void InitializeValues() { foreach (var prop in InitialValues.GetType().GetProperties()) { foreach (var customprop in Settings.GetAllProperties()) { if (customprop.Name.ToUpper() == prop.Name.ToUpper()) { //customprop.Value = prop.GetValue(InitialValues, null); customprop.Value = Conversions.ToString(prop.GetValue(RuntimeHelpers.GetObjectValue(this.InitialValues), null)); } } } }
private DepositData BuildAndSignDepositData(ulong validatorIndex, Gwei amount, SignatureDomains signatureDomains) { InitialValues initialValues = _initialValueOptions.CurrentValue; byte[] privateKey = GeneratePrivateKey(validatorIndex); // Public Key BLSParameters blsParameters = new BLSParameters { PrivateKey = privateKey }; using BLS bls = BLS.Create(blsParameters); byte[] publicKeyBytes = new byte[BlsPublicKey.Length]; bls.TryExportBlsPublicKey(publicKeyBytes, out int publicKeyBytesWritten); BlsPublicKey publicKey = new BlsPublicKey(publicKeyBytes); // Withdrawal Credentials Bytes32 withdrawalCredentials = _crypto.Hash(publicKey.AsSpan()); withdrawalCredentials.Unwrap()[0] = initialValues.BlsWithdrawalPrefix; // Build deposit data DepositData depositData = new DepositData(publicKey, withdrawalCredentials, amount, BlsSignature.Zero); // Sign deposit data Domain domain = _beaconChainUtility.ComputeDomain(signatureDomains.Deposit); DepositMessage depositMessage = new DepositMessage( depositData.PublicKey, depositData.WithdrawalCredentials, depositData.Amount); Root depositMessageRoot = _crypto.HashTreeRoot(depositMessage); Root depositDataSigningRoot = _beaconChainUtility.ComputeSigningRoot(depositMessageRoot, domain); byte[] signatureBytes = new byte[96]; bls.TrySignData(depositDataSigningRoot.AsSpan(), signatureBytes, out int bytesWritten); BlsSignature depositDataSignature = new BlsSignature(signatureBytes); depositData.SetSignature(depositDataSignature); if (_logger.IsEnabled(LogLevel.Debug)) { LogDebug.QuickStartAddValidator(_logger, validatorIndex, publicKey.ToString().Substring(0, 12), null); } return(depositData); }
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}"); } }
public Tuple <List <double[]>, List <double[]> > FormSchedule(ref InitialValues initVals, Action <string> action = null) { List <double[]> inFixValues = AH.CreateListOfArrays(_period, _inDimension, -1.0), outFixValues = AH.CreateListOfArrays(_period, _outDimension, -1.0), inSchedule = _inAlgorithm.GetSchedule(initVals.inTargets, inFixValues), outSchedule = _outAlgorithm.GetSchedule(initVals.outTargets, outFixValues); DiscreteSchedule reservoirSchedule = GetReservoirSchedule(inSchedule, outSchedule, initVals.startVolume, initVals.pumpsSchedule); int idx = reservoirSchedule.FirstIndexOfOutOfRange(initVals.minVolume, initVals.maxVolume); if (idx == -1) { return(new Tuple <List <double[]>, List <double[]> >(inSchedule, outSchedule)); } List <Tuple <List <double[]>, List <double[]> > > schedules; switch (initVals.algorithmType) { case AlgorithmType.GRAPH: schedules = GreedyRandomizeSearch(ref initVals, inSchedule, outSchedule, action); break; default: schedules = new List <Tuple <List <double[]>, List <double[]> > >() { DinamicProgramming(initVals, action) }; break; } action("Выбираем оптимальное на основе критериев"); if (schedules.Count() == 0) { return(null); } else if (schedules.Count() == 1) { return(schedules[0]); } else { List <double> criterias = GetCriteria(initVals.inTargets, initVals.outTargets, schedules); var best = schedules[criterias.IndexOf(criterias.Min())]; return(best); } }
/// <summary> /// Gets the available mobile connect version for the specified scope value. /// If versions aren't available then configured default versions will be used. /// </summary> /// <param name="scope">Scope value to retrieve supported version for</param> public string GetSupportedVersion(string scope) { if (_recognisedScopes.FirstOrDefault(x => string.Equals(x, scope, StringComparison.OrdinalIgnoreCase)) == null) { return(null); } string version; if (!InitialValues.TryGetValue(scope, out version)) { InitialValues.TryGetValue(MobileConnectConstants.MOBILECONNECT, out version); } return(Utils.MobileConnectVersions.CoerceVersion(version, scope)); }
public bool IsValidGenesisState(BeaconState state) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; InitialValues initialValues = _initialValueOptions.CurrentValue; if (state.GenesisTime < miscellaneousParameters.MinimumGenesisTime) { return(false); } var activeValidatorIndices = _beaconStateAccessor.GetActiveValidatorIndices(state, initialValues.GenesisEpoch); if (activeValidatorIndices.Count < miscellaneousParameters.MinimumGenesisActiveValidatorCount) { return(false); } return(true); }
private void InitializeStartingValues() { initialValues = new InitialValues { Gravity = (double)GravityBox.Value, DragCoefficient = 0.47, CrossSectionArea = Math.Pow((double)ProjectilesRadiusBox.Value, 2) * Math.PI, InitialVelocityX = (double)InitialVelocityVectorValueBox.Value * MathHelper.CosValueOfDegreeAngle((double)InitialVelocityVectorAngleBox.Value), InitialVelocityY = (double)InitialVelocityVectorValueBox.Value * MathHelper.SinValueOfDegreeAngle((double)InitialVelocityVectorAngleBox.Value), DensityOfTheMedium = (double)DensityOfTheMediumBox.Value, RadiusOfTheProjectile = (double)ProjectilesRadiusBox.Value, InitialVelocityVectorValue = (double)InitialVelocityVectorValueBox.Value, InitialVelocityVectorAngle = (double)InitialVelocityVectorAngleBox.Value, }; initialValues.Mass = initialValues.Density * (4 / 3 * Math.PI * Math.Pow(initialValues.RadiusOfTheProjectile, 2)); }
public GreedyNode(List <double[]> inSchedule, List <double[]> outSchedule, ReservoirBalanceAlgorithm algorithm, InitialValues initVals) { this.inSchedule = inSchedule; this.outSchedule = outSchedule; this.initVals = initVals; this.algorithm = algorithm; reservoirSchedule = algorithm.GetReservoirSchedule(inSchedule, outSchedule, initVals.startVolume, initVals.pumpsSchedule); crashIndex = reservoirSchedule.FirstIndexOfOutOfRange(initVals.minVolume, initVals.maxVolume); if (crashIndex != -1) { sign = reservoirSchedule[crashIndex] > initVals.maxVolume ? -1 : 1; } IsCalculated = false; IsFullExplored = false; }
public static BeaconState CreateGenesisState(IServiceProvider testServiceProvider, ulong numberOfValidators) { ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; InitialValues initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); var eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray()); var state = new BeaconState( 0, new Core2.Containers.Fork(new ForkVersion(new byte[ForkVersion.Length]), new ForkVersion(new byte[ForkVersion.Length]), Epoch.Zero), new Eth1Data(Root.Zero, numberOfValidators, eth1BlockHash), //numberOfValidators, new BeaconBlockHeader(cryptographyService.HashTreeRoot(BeaconBlockBody.Zero)), Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector).ToArray(), timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, chainConstants.JustificationBitsLength ); // We directly insert in the initial validators, // as it is much faster than creating and processing genesis deposits for every single test case. for (var index = (ulong)0; index < numberOfValidators; index++) { var validator = BuildMockValidator(chainConstants, initialValues, gweiValues, timeParameters, index, gweiValues.MaximumEffectiveBalance); state.AddValidatorWithBalance(validator, gweiValues.MaximumEffectiveBalance); state.IncreaseEth1DepositIndex(); } // Process genesis activations foreach (var validator in state.Validators) { if (validator.EffectiveBalance >= gweiValues.MaximumEffectiveBalance) { validator.SetEligible(chainConstants.GenesisEpoch); validator.SetActive(chainConstants.GenesisEpoch); } } return(state); }
public BeaconState InitializeBeaconStateFromEth1(Hash32 eth1BlockHash, ulong eth1Timestamp, IEnumerable <Deposit> deposits) { _logger.LogDebug(Event.InitializeBeaconState, "Initialise beacon state from ETH1 block {Eth1BlockHash}, time {Eth1Timestamp}, with {DepositCount} deposits.", eth1BlockHash, eth1Timestamp, deposits.Count()); GweiValues gweiValues = _gweiValueOptions.CurrentValue; InitialValues initialValues = _initialValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; ulong genesisTime = eth1Timestamp - (eth1Timestamp % _chainConstants.SecondsPerDay) + (2 * _chainConstants.SecondsPerDay); Eth1Data eth1Data = new Eth1Data((ulong)deposits.Count(), eth1BlockHash); BeaconBlockBody emptyBlockBody = new BeaconBlockBody(); BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBody.HashTreeRoot(_miscellaneousParameterOptions.CurrentValue, _maxOperationsPerBlockOptions.CurrentValue)); BeaconState state = new BeaconState(genesisTime, 0, eth1Data, latestBlockHeader, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength); // Process deposits var depositDataList = new List <DepositData>(); foreach (Deposit deposit in deposits) { depositDataList.Add(deposit.Data); Hash32 depositRoot = depositDataList.HashTreeRoot(_chainConstants.MaximumDepositContracts); state.Eth1Data.SetDepositRoot(depositRoot); _beaconStateTransition.ProcessDeposit(state, deposit); } // Process activations for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++) { Validator validator = state.Validators[validatorIndex]; Gwei balance = state.Balances[validatorIndex]; Gwei effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance); validator.SetEffectiveBalance(effectiveBalance); if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance) { validator.SetEligible(initialValues.GenesisEpoch); validator.SetActive(initialValues.GenesisEpoch); } } return(state); }
public void TestRemovedSetMonitorValues() { var monitor = TestMonitor; var valueToRemove = InitialValues.FirstOrDefault(); Assert.IsNotNull(valueToRemove); AssertStartup(monitor); AssertValueRemove(monitor, valueToRemove.Key); const int newKey = 5; const string newVal = "Value5"; const string newValChanged = "ValueChanged5"; AssertValueAdd(monitor, newKey, newVal); AssertValueChange(monitor, newKey, newValChanged); Assert.IsTrue(monitor.Stop()); }
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); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSpaStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseReactDevelopmentServer(npmScript: "start"); } }); using (var scope = app.ApplicationServices.CreateScope()) { FuelDbContext content = scope.ServiceProvider.GetRequiredService <FuelDbContext>(); InitialValues.Init(content); } }
public static Validator BuildMockValidator(ChainConstants chainConstants, InitialValues initialValues, GweiValues gweiValues, TimeParameters timeParameters, ulong validatorIndex, Gwei balance) { var publicKeys = TestKeys.PublicKeys(timeParameters).ToArray(); var publicKey = publicKeys[validatorIndex]; // insecurely use pubkey as withdrawal key if no credentials provided var withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan()); withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix; var withdrawalCredentials = new Bytes32(withdrawalCredentialBytes); var validator = new Validator( publicKey, withdrawalCredentials, Gwei.Min(balance - balance % gweiValues.EffectiveBalanceIncrement, gweiValues.MaximumEffectiveBalance), false, chainConstants.FarFutureEpoch, chainConstants.FarFutureEpoch, chainConstants.FarFutureEpoch, chainConstants.FarFutureEpoch); return(validator); }
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); }
public void TestSetMonitorRemovedValue() { var service = BuildTestSetMonitorService <TestSetMonitor>(); Assert.IsTrue(service.Start()); var removedItem = InitialValues.FirstOrDefault(); Assert.IsNotNull(removedItem); var itemToRemove = removedItem.Key; AssertRemovedValue(service, itemToRemove); const int newKey = 15; const string newInitValue = "Value15"; const string newChangedValue = "Changed15"; AssertAddedValue(service, newKey, newInitValue); AssertChangedValue(service, newKey, newChangedValue); Assert.IsTrue(service.Stop()); }
public async Task OnAttestationPastEpoch() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); InitialValues initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Initialization IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // move time forward 2 epochs ulong time = store.Time + 2 * timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch; await forkChoice.OnTickAsync(store, time); // create and store block from 3 epochs ago BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await forkChoice.OnBlockAsync(store, signedBlock); // create attestation for past block Attestation attestation = TestAttestation.GetValidAttestation(testServiceProvider, state, state.Slot, CommitteeIndex.None, signed: true); attestation.Data.Target.Epoch.ShouldBe(chainConstants.GenesisEpoch); IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>(); Slot currentSlot = ((ForkChoice)forkChoice).GetCurrentSlot(store); Epoch currentEpoch = beaconChainUtility.ComputeEpochAtSlot(currentSlot); currentEpoch.ShouldBe((Epoch)(chainConstants.GenesisEpoch + 2UL)); await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : false); }
public void GenesisEpochNoAttestationsNoPenalties() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); 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}"); } }
public void QuickStartGenesis() { QuickStartParameters quickStartParameters = _quickStartParameterOptions.CurrentValue; _logger.LogWarning(0, "Mocked quick start with genesis time {GenesisTime:n0} and {ValidatorCount} validators.", quickStartParameters.GenesisTime, quickStartParameters.ValidatorCount); GweiValues gweiValues = _gweiValueOptions.CurrentValue; InitialValues initialValues = _initialValueOptions.CurrentValue; SignatureDomains signatureDomains = _signatureDomainOptions.CurrentValue; // Fixed amount Gwei amount = gweiValues.MaximumEffectiveBalance; // Build deposits var depositDataList = new List <DepositData>(); var deposits = new List <Deposit>(); for (ulong validatorIndex = 0uL; validatorIndex < quickStartParameters.ValidatorCount; validatorIndex++) { var privateKey = GeneratePrivateKey(validatorIndex); // Public Key BLSParameters blsParameters = new BLSParameters() { PrivateKey = privateKey }; using BLS bls = BLS.Create(blsParameters); var publicKeyBytes = new byte[BlsPublicKey.Length]; bls.TryExportBLSPublicKey(publicKeyBytes, out int publicKeyBytesWritten); BlsPublicKey publicKey = new BlsPublicKey(publicKeyBytes); // Withdrawal Credentials var withdrawalCredentialBytes = _cryptographyService.Hash(publicKey.AsSpan()).AsSpan().ToArray(); withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix; Hash32 withdrawalCredentials = new Hash32(withdrawalCredentialBytes); // Build deposit data DepositData depositData = new DepositData(publicKey, withdrawalCredentials, amount); // Sign deposit data Hash32 depositDataSigningRoot = depositData.SigningRoot(); Domain domain = _beaconChainUtility.ComputeDomain(signatureDomains.Deposit); var destination = new byte[96]; bls.TrySignHash(depositDataSigningRoot.AsSpan(), destination, out int bytesWritten, domain.AsSpan()); BlsSignature depositDataSignature = new BlsSignature(destination); depositData.SetSignature(depositDataSignature); // Deposit // TODO: This seems a very inefficient way (copied from tests) as it recalculates the merkle tree each time // (you only need to add one node) // TODO: Add some tests around quick start, then improve int index = depositDataList.Count; depositDataList.Add(depositData); Hash32 root = depositDataList.HashTreeRoot((ulong)1 << _chainConstants.DepositContractTreeDepth); var allLeaves = depositDataList.Select(x => x.HashTreeRoot()); var tree = CalculateMerkleTreeFromLeaves(allLeaves); var merkleProof = GetMerkleProof(tree, index, 32); var proof = new List <Hash32>(merkleProof); var indexBytes = new Span <byte>(new byte[32]); BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1); if (!BitConverter.IsLittleEndian) { indexBytes.Slice(0, 8).Reverse(); } Hash32 indexHash = new Hash32(indexBytes); proof.Add(indexHash); Hash32 leaf = depositData.HashTreeRoot(); _beaconChainUtility.IsValidMerkleBranch(leaf, proof, _chainConstants.DepositContractTreeDepth + 1, (ulong)index, root); Deposit deposit = new Deposit(proof, depositData); if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Quick start adding deposit for mocked validator {ValidatorIndex} with public key {PublicKey}.", validatorIndex, publicKey.ToString().Substring(0, 12)); } deposits.Add(deposit); } BeaconState genesisState = _beaconChain.InitializeBeaconStateFromEth1(quickStartParameters.Eth1BlockHash, quickStartParameters.Eth1Timestamp, deposits); // We use the state directly, and don't test IsValid genesisState.SetGenesisTime(quickStartParameters.GenesisTime); IStore store = _forkChoice.GetGenesisStore(genesisState); _logger.LogDebug("Quick start genesis store created with genesis time {GenesisTime:n0}.", store.GenesisTime); }
/// <summary> /// Run ``on_attestation`` upon receiving a new ``attestation`` from either within a block or directly on the wire. /// An ``attestation`` that is asserted as invalid may be valid at a later time, /// consider scheduling it for later processing in such case. /// </summary> public async Task OnAttestationAsync(IStore store, Attestation attestation) { if (_logger.IsInfo()) { Log.OnAttestation(_logger, attestation, null); } InitialValues initialValues = _initialValueOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; Checkpoint target = attestation.Data.Target; // Attestations must be from the current or previous epoch Slot currentSlot = GetCurrentSlot(store); Epoch currentEpoch = _beaconChainUtility.ComputeEpochAtSlot(currentSlot); // Use GENESIS_EPOCH for previous when genesis to avoid underflow Epoch previousEpoch = currentEpoch > initialValues.GenesisEpoch ? currentEpoch - new Epoch(1) : initialValues.GenesisEpoch; if (target.Epoch != currentEpoch && target.Epoch != previousEpoch) { throw new ArgumentOutOfRangeException("attestation.Target.Epoch", target.Epoch, $"Attestation target epoch must be either the current epoch {currentEpoch} or previous epoch {previousEpoch}."); } // Cannot calculate the current shuffling if have not seen the target BeaconBlock targetBlock = await store.GetBlockAsync(target.Root).ConfigureAwait(false); // Attestations target be for a known block. If target block is unknown, delay consideration until the block is found BeaconState targetStoredState = await store.GetBlockStateAsync(target.Root).ConfigureAwait(false); // Attestations cannot be from future epochs. If they are, delay consideration until the epoch arrives BeaconState baseState = BeaconState.Clone(targetStoredState); Slot targetEpochStartSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(target.Epoch); ulong targetEpochStartSlotTime = baseState.GenesisTime + (ulong)targetEpochStartSlot * timeParameters.SecondsPerSlot; if (store.Time < targetEpochStartSlotTime) { throw new Exception($"Ättestation target state time {targetEpochStartSlotTime} should not be larger than the store time {store.Time})."); } // Attestations must be for a known block. If block is unknown, delay consideration until the block is found BeaconBlock attestationBlock = await store.GetBlockAsync(attestation.Data.BeaconBlockRoot).ConfigureAwait(false); // Attestations must not be for blocks in the future. If not, the attestation should not be considered if (attestationBlock.Slot > attestation.Data.Slot) { throw new Exception($"Attestation data root slot {attestationBlock.Slot} should not be larger than the attestation data slot {attestation.Data.Slot})."); } // Store target checkpoint state if not yet seen BeaconState?targetState = await store.GetCheckpointStateAsync(target, false).ConfigureAwait(false); if (targetState == null) { _beaconStateTransition.ProcessSlots(baseState, targetEpochStartSlot); await store.SetCheckpointStateAsync(target, baseState).ConfigureAwait(false); targetState = baseState; } // Attestations can only affect the fork choice of subsequent slots. // Delay consideration in the fork choice until their slot is in the past. ulong attestationDataSlotTime = targetState !.GenesisTime + ((ulong)attestation.Data.Slot + 1) * timeParameters.SecondsPerSlot; if (store.Time < attestationDataSlotTime) { throw new Exception($"Attestation data time {attestationDataSlotTime} should not be larger than the store time {store.Time})."); } // Get state at the `target` to validate attestation and calculate the committees IndexedAttestation indexedAttestation = _beaconStateAccessor.GetIndexedAttestation(targetState, attestation); Domain domain = _beaconStateAccessor.GetDomain(targetState, _signatureDomainOptions.CurrentValue.BeaconAttester, indexedAttestation.Data.Target.Epoch); bool isValid = _beaconChainUtility.IsValidIndexedAttestation(targetState, indexedAttestation, domain); if (!isValid) { throw new Exception($"Indexed attestation {indexedAttestation} is not valid."); } // Update latest messages IEnumerable <ValidatorIndex> attestingIndices = _beaconStateAccessor.GetAttestingIndices(targetState, attestation.Data, attestation.AggregationBits); foreach (ValidatorIndex index in attestingIndices) { LatestMessage?latestMessage = await store.GetLatestMessageAsync(index, false).ConfigureAwait(false); if (latestMessage == null || target.Epoch > latestMessage !.Epoch) { latestMessage = new LatestMessage(target.Epoch, attestation.Data.BeaconBlockRoot); await store.SetLatestMessageAsync(index, latestMessage).ConfigureAwait(false); } } }