public async Task ChainNoAttestations() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); // On receiving a block of `GENESIS_SLOT + 1` slot BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1); await AddBlockToStore(testServiceProvider, store, block1); // On receiving a block of next epoch BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2); await AddBlockToStore(testServiceProvider, store, block2); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 expectedRoot = cryptographyService.SigningRoot(block2); headRoot.ShouldBe(expectedRoot); }
public void IsValidGenesisStateFalseNotEnoughValidators() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; BeaconNode.GenesisChainStart beaconChain = testServiceProvider.GetService <BeaconNode.GenesisChainStart>(); int depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount - 1; IList <DepositData> deposits = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: true); IDepositStore depositStore = testServiceProvider.GetService <IDepositStore>(); foreach (DepositData deposit in deposits) { depositStore.Place(deposit); } Bytes32 eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x12, 32).ToArray()); ulong eth1Timestamp = miscellaneousParameters.MinimumGenesisTime; // Act BeaconState state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp); // Assert IsValidGenesisState(testServiceProvider, state, false); }
private async Task RunOnAttestation(IServiceProvider testServiceProvider, BeaconState state, IStore store, Attestation attestation, bool expectValid) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); if (!expectValid) { Should.Throw <Exception>(async() => { await forkChoice.OnAttestationAsync(store, attestation); }); return; } BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); IndexedAttestation indexedAttestation = beaconStateAccessor.GetIndexedAttestation(state, attestation); await forkChoice.OnAttestationAsync(store, attestation); IEnumerable <ValidatorIndex> attestingIndices = beaconStateAccessor.GetAttestingIndices(state, attestation.Data, attestation.AggregationBits); ValidatorIndex firstAttestingIndex = attestingIndices.First(); LatestMessage latestMessage = (await store.GetLatestMessageAsync(firstAttestingIndex, true)) !; latestMessage.Epoch.ShouldBe(attestation.Data.Target.Epoch); latestMessage.Root.ShouldBe(attestation.Data.BeaconBlockRoot); }
public CryptographyService(ChainConstants chainConstants, IOptionsMonitor<MiscellaneousParameters> miscellaneousParameterOptions, IOptionsMonitor<TimeParameters> timeParameterOptions, IOptionsMonitor<StateListLengths> stateListLengthOptions, IOptionsMonitor<MaxOperationsPerBlock> maxOperationsPerBlockOptions) { _chainConstants = chainConstants; _miscellaneousParameterOptions = miscellaneousParameterOptions; _timeParameterOptions = timeParameterOptions; _stateListLengthOptions = stateListLengthOptions; _maxOperationsPerBlockOptions = maxOperationsPerBlockOptions; MiscellaneousParameters miscellaneousParameters = miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = timeParameterOptions.CurrentValue; StateListLengths stateListLengths = stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = maxOperationsPerBlockOptions.CurrentValue; Nethermind.Ssz.Ssz.Init( chainConstants.DepositContractTreeDepth, chainConstants.JustificationBitsLength, miscellaneousParameters.MaximumValidatorsPerCommittee, timeParameters.SlotsPerEpoch, timeParameters.SlotsPerEth1VotingPeriod, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, stateListLengths.HistoricalRootsLimit, stateListLengths.ValidatorRegistryLimit, maxOperationsPerBlock.MaximumProposerSlashings, maxOperationsPerBlock.MaximumAttesterSlashings, maxOperationsPerBlock.MaximumAttestations, maxOperationsPerBlock.MaximumDeposits, maxOperationsPerBlock.MaximumVoluntaryExits); }
public void TestInitializeBeaconStateFromEth1() { bool useBls = true; // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useBls, useStore: true); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; int depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount; (IList <Deposit> deposits, Root depositRoot) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: useBls); Bytes32 eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x12, 32).ToArray()); ulong eth1Timestamp = miscellaneousParameters.MinimumGenesisTime; BeaconNode.GenesisChainStart beaconChain = testServiceProvider.GetService <BeaconNode.GenesisChainStart>(); // Act //# initialize beacon_state BeaconState state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp, deposits); // Assert state.GenesisTime.ShouldBe(eth1Timestamp - eth1Timestamp % timeParameters.MinimumGenesisDelay + 2 * timeParameters.MinimumGenesisDelay); state.Validators.Count.ShouldBe(depositCount); state.Eth1Data.DepositRoot.ShouldBe(depositRoot); state.Eth1Data.DepositCount.ShouldBe((ulong)depositCount); state.Eth1Data.BlockHash.ShouldBe(eth1BlockHash); }
public async Task GenesisHead() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.ConfigureNethermindCore2(); string debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 stateRoot = cryptographyService.HashTreeRoot(state); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 expectedRoot = cryptographyService.SigningRoot(genesisBlock); headRoot.ShouldBe(expectedRoot); }
private void AddAttestationToStore(IServiceProvider testServiceProvider, IStore store, Attestation attestation) { TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); if (!store.TryGetBlock(attestation.Data.BeaconBlockRoot, out BeaconBlock? parentBlock)) { throw new InvalidDataException("Cannot retrieve parent block"); } Hash32 parentSigningRoot = parentBlock !.SigningRoot(miscellaneousParameters, maxOperationsPerBlock); if (!store.TryGetBlockState(parentSigningRoot, out BeaconState? preState)) { throw new InvalidDataException("Cannot retrieve pre state"); } ulong blockTime = preState !.GenesisTime + (ulong)parentBlock !.Slot * timeParameters.SecondsPerSlot; ulong nextEpochTime = blockTime + (ulong)timeParameters.SlotsPerEpoch * timeParameters.SecondsPerSlot; if (store.Time < blockTime) { forkChoice.OnTick(store, blockTime); } forkChoice.OnAttestation(store, attestation); }
private static IEnumerable <SszElement> GetValues(BeaconState item, MiscellaneousParameters miscellaneousParameters, TimeParameters timeParameters, StateListLengths stateListLengths, MaxOperationsPerBlock maxOperationsPerBlock) { //# Versioning yield return(item.GenesisTime.ToSszBasicElement()); yield return(item.Slot.ToSszBasicElement()); yield return(item.Fork.ToSszContainer()); //# History yield return(item.LatestBlockHeader.ToSszContainer()); yield return(item.BlockRoots.ToSszVector()); yield return(item.StateRoots.ToSszVector()); yield return(item.HistoricalRoots.ToSszList(stateListLengths.HistoricalRootsLimit)); //# Eth1 yield return(item.Eth1Data.ToSszContainer()); yield return(new SszList(item.Eth1DataVotes.Select(x => x.ToSszContainer()), (ulong)timeParameters.SlotsPerEth1VotingPeriod)); yield return(item.Eth1DepositIndex.ToSszBasicElement()); //# Registry yield return(new SszList(item.Validators.Select(x => x.ToSszContainer()), stateListLengths.ValidatorRegistryLimit)); yield return(item.Balances.ToSszBasicList(stateListLengths.ValidatorRegistryLimit)); //# Randomness //yield return item.StartShard.ToSszBasicElement(); yield return(item.RandaoMixes.ToSszVector()); //# Slashings //Per-epoch sums of slashed effective balances yield return(item.Slashings.ToSszBasicVector()); //# Attestations yield return(item.PreviousEpochAttestations.ToSszList(maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch, miscellaneousParameters)); yield return(item.CurrentEpochAttestations.ToSszList(maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch, miscellaneousParameters)); //# Crosslinks //# Previous epoch snapshot //yield return item.PreviousCrosslinks.ToSszVector(); //yield return item.CurrentCrosslinks.ToSszVector(); //# Finality // Bit set for every recent justified epoch yield return(item.JustificationBits.ToSszBitvector()); yield return(item.PreviousJustifiedCheckpoint.ToSszContainer()); yield return(item.CurrentJustifiedCheckpoint.ToSszContainer()); yield return(item.FinalizedCheckpoint.ToSszContainer()); }
/// <summary> /// Return the validator churn limit for the current epoch. /// </summary> public ulong GetValidatorChurnLimit(BeaconState state) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; Epoch currentEpoch = GetCurrentEpoch(state); IList <ValidatorIndex> activeValidatorIndices = GetActiveValidatorIndices(state, currentEpoch); ulong churnLimit = (ulong)activeValidatorIndices.Count / miscellaneousParameters.ChurnLimitQuotient; return(Math.Max(churnLimit, miscellaneousParameters.MinimumPerEpochChurnLimit)); }
public Hash32 HashTreeRoot(BeaconBlock beaconBlock) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; return beaconBlock.HashTreeRoot(maxOperationsPerBlock.MaximumProposerSlashings, maxOperationsPerBlock.MaximumAttesterSlashings, maxOperationsPerBlock.MaximumAttestations, maxOperationsPerBlock.MaximumDeposits, maxOperationsPerBlock.MaximumVoluntaryExits, miscellaneousParameters.MaximumValidatorsPerCommittee); }
private static IEnumerable <SszElement> GetValues(PendingAttestation item, MiscellaneousParameters miscellaneousParameters) { yield return(item.AggregationBits.ToSszBitlist(miscellaneousParameters.MaximumValidatorsPerCommittee)); yield return(item.Data.ToSszContainer()); yield return(item.InclusionDelay.ToSszBasicElement()); yield return(item.ProposerIndex.ToSszBasicElement()); }
private static IEnumerable <SszElement> GetValues(Attestation item, MiscellaneousParameters miscellaneousParameters) { yield return(item.AggregationBits.ToSszBitlist(miscellaneousParameters.MaximumValidatorsPerCommittee)); yield return(item.Data.ToSszContainer()); yield return(item.CustodyBits.ToSszBitlist(miscellaneousParameters.MaximumValidatorsPerCommittee)); yield return(item.Signature.ToSszBasicVector()); }
public static void SignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block, ValidatorIndex proposerIndex) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; SignatureDomains signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); BeaconChainUtility beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>(); BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); if (state.Slot > block.Slot) { throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Slot of block must be equal or less that state slot {state.Slot}"); } Epoch blockEpoch = beaconChainUtility.ComputeEpochAtSlot(block.Slot); if (proposerIndex == ValidatorIndex.None) { if (block.Slot == state.Slot) { proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state); } else { Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot); if (stateEpoch + 1 > blockEpoch) { Console.WriteLine("WARNING: Block slot far away, and no proposer index manually given." + " Signing block is slow due to transition for proposer index calculation."); } // use stub state to get proposer index of future slot BeaconState stubState = BeaconState.Clone(state); beaconStateTransition.ProcessSlots(stubState, block.Slot); proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState); } } byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray(); byte[] privateKey = privateKeys[(int)(ulong)proposerIndex]; Domain randaoDomain = beaconStateAccessor.GetDomain(state, signatureDomains.Randao, blockEpoch); Hash32 randaoRevealHash = blockEpoch.HashTreeRoot(); BlsSignature randaoReveal = TestSecurity.BlsSign(randaoRevealHash, privateKey, randaoDomain); block.Body.SetRandaoReveal(randaoReveal); Domain signatureDomain = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, blockEpoch); Hash32 signingRoot = cryptographyService.SigningRoot(block); BlsSignature signature = TestSecurity.BlsSign(signingRoot, privateKey, signatureDomain); block.SetSignature(signature); }
public Hash32 SigningRoot(BeaconBlock beaconBlock) { // TODO: Signing root version of Nethermind SSZ; or are removed in later version of spec, so maybe just wait until then MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; return beaconBlock.SigningRoot(maxOperationsPerBlock.MaximumProposerSlashings, maxOperationsPerBlock.MaximumAttesterSlashings, maxOperationsPerBlock.MaximumAttestations, maxOperationsPerBlock.MaximumDeposits, maxOperationsPerBlock.MaximumVoluntaryExits, miscellaneousParameters.MaximumValidatorsPerCommittee); }
public Hash32 HashTreeRoot(BeaconState beaconState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; ulong maximumAttestationsPerEpoch = maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch; return(beaconState.HashTreeRoot(stateListLengths.HistoricalRootsLimit, timeParameters.SlotsPerEth1VotingPeriod, stateListLengths.ValidatorRegistryLimit, maximumAttestationsPerEpoch, miscellaneousParameters.MaximumValidatorsPerCommittee)); }
public async Task ShorterChainButHeavierWeight() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); BeaconState genesisState = BeaconState.Clone(state); // build longer tree Hash32 longRoot = default; BeaconState longState = BeaconState.Clone(genesisState); for (int i = 0; i < 3; i++) { BeaconBlock longBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, longState, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, longState, longBlock); await AddBlockToStore(testServiceProvider, store, longBlock); if (i == 2) { longRoot = cryptographyService.SigningRoot(longBlock); } } // build short tree BeaconState shortState = BeaconState.Clone(genesisState); BeaconBlock shortBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, shortState, signed: true); shortBlock.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, shortState, shortBlock, ValidatorIndex.None); TestState.StateTransitionAndSignBlock(testServiceProvider, shortState, shortBlock); await AddBlockToStore(testServiceProvider, store, shortBlock); Attestation shortAttestation = TestAttestation.GetValidAttestation(testServiceProvider, shortState, shortBlock.Slot, CommitteeIndex.None, signed: true); await AddAttestationToStore(testServiceProvider, store, shortAttestation); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 expectedRoot = cryptographyService.SigningRoot(shortBlock); headRoot.ShouldBe(expectedRoot); headRoot.ShouldNotBe(longRoot); }
public void IsValidGenesisStateFalseInvalidTimestamp() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; // Act BeaconState state = CreateValidBeaconState(testServiceProvider, eth1TimestampOverride: (miscellaneousParameters.MinimumGenesisTime - 3 * timeParameters.MinimumGenesisDelay)); // Assert IsValidGenesisState(testServiceProvider, state, false); }
public Hash32 HashTreeRoot(BeaconBlockBody beaconBlockBody) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; return beaconBlockBody.HashTreeRoot(maxOperationsPerBlock.MaximumProposerSlashings, maxOperationsPerBlock.MaximumAttesterSlashings, maxOperationsPerBlock.MaximumAttestations, maxOperationsPerBlock.MaximumDeposits, maxOperationsPerBlock.MaximumVoluntaryExits, miscellaneousParameters.MaximumValidatorsPerCommittee); // TODO: Get this working and switch over block body, beacon block, and state // Merkle.Ize(out UInt256 root, beaconBlockBody); // Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1)); // return new Hash32(bytes); }
public Hash32 HashTreeRoot(BeaconState beaconState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; ulong maximumAttestationsPerEpoch = maxOperationsPerBlock.MaximumAttestations * (ulong) timeParameters.SlotsPerEpoch; return beaconState.HashTreeRoot(stateListLengths.HistoricalRootsLimit, timeParameters.SlotsPerEth1VotingPeriod, stateListLengths.ValidatorRegistryLimit, maximumAttestationsPerEpoch, miscellaneousParameters.MaximumValidatorsPerCommittee); // Merkle.Ize(out UInt256 root, beaconState); // Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1)); // return new Hash32(bytes); }
/// <summary> /// State transition via the provided ``block`` /// then package the block with the state root and signature. /// </summary> public static void StateTransitionAndSignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); beaconStateTransition.StateTransition(state, block, validateStateRoot: false); Hash32 stateRoot = state.HashTreeRoot(miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock); block.SetStateRoot(stateRoot); TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); }
private static IEnumerable <SszElement> GetValues(BeaconBlock item, MiscellaneousParameters miscellaneousParameters, MaxOperationsPerBlock maxOperationsPerBlock, bool forSigning) { yield return(item.Slot.ToSszBasicElement()); yield return(item.ParentRoot.ToSszBasicVector()); yield return(item.StateRoot.ToSszBasicVector()); yield return(item.Body.ToSszContainer(miscellaneousParameters, maxOperationsPerBlock)); if (!forSigning) { //signature: BLSSignature yield return(item.Signature.ToSszBasicVector()); } }
public static BeaconState CreateValidBeaconState(IServiceProvider testServiceProvider, ulong?eth1TimestampOverride = null) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; BeaconNode.GenesisChainStart beaconChain = testServiceProvider.GetService <BeaconNode.GenesisChainStart>(); int depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount; (IList <Deposit> deposits, _) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: true); Bytes32 eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x12, 32).ToArray()); ulong eth1Timestamp = eth1TimestampOverride ?? miscellaneousParameters.MinimumGenesisTime; BeaconState state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp, deposits); return(state); }
public async Task SplitTieBreakerNoAttestations() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); BeaconState genesisState = BeaconState.Clone(state); // block at slot 1 BeaconState block1State = BeaconState.Clone(genesisState); BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block1State, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, block1State, block1); await AddBlockToStore(testServiceProvider, store, block1); Hash32 block1Root = cryptographyService.SigningRoot(block1); // build short tree BeaconState block2State = BeaconState.Clone(genesisState); BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block2State, signed: true); block2.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, block2State, block2, ValidatorIndex.None); TestState.StateTransitionAndSignBlock(testServiceProvider, block2State, block2); await AddBlockToStore(testServiceProvider, store, block2); Hash32 block2Root = cryptographyService.SigningRoot(block2); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Console.WriteLine("block1 {0}", block1Root); Console.WriteLine("block2 {0}", block2Root); Hash32 highestRoot = block1Root.CompareTo(block2Root) > 0 ? block1Root : block2Root; Console.WriteLine("highest {0}", highestRoot); headRoot.ShouldBe(highestRoot); }
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); }
public IStore GetGenesisStore(BeaconState genesisState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; Hash32 stateRoot = _cryptographyService.HashTreeRoot(genesisState); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 root = _cryptographyService.SigningRoot(genesisBlock); Checkpoint justifiedCheckpoint = new Checkpoint(_initialValueOptions.CurrentValue.GenesisEpoch, root); Checkpoint finalizedCheckpoint = new Checkpoint(_initialValueOptions.CurrentValue.GenesisEpoch, root); if (_logger.IsInfo()) { Log.CreateGenesisStore(_logger, genesisBlock, genesisState, justifiedCheckpoint, root, null); } Dictionary <Hash32, BeaconBlock> blocks = new Dictionary <Hash32, BeaconBlock> { [root] = genesisBlock }; Dictionary <Hash32, BeaconState> blockStates = new Dictionary <Hash32, BeaconState> { [root] = BeaconState.Clone(genesisState) }; Dictionary <Checkpoint, BeaconState> checkpointStates = new Dictionary <Checkpoint, BeaconState> { [justifiedCheckpoint] = BeaconState.Clone(genesisState) }; IStore store = _storeProvider.CreateStore( genesisState.GenesisTime, genesisState.GenesisTime, justifiedCheckpoint, finalizedCheckpoint, justifiedCheckpoint, blocks, blockStates, checkpointStates, new Dictionary <ValidatorIndex, LatestMessage>() ); return(store); }
public static BeaconBlock BuildEmptyBlock(IServiceProvider testServiceProvider, BeaconState state, Slot slot, bool signed) { //if (slot) is none MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); Eth1Data eth1Data = new Eth1Data(state.Eth1DepositIndex, Hash32.Zero); BeaconBlockHeader previousBlockHeader = BeaconBlockHeader.Clone(state.LatestBlockHeader); if (previousBlockHeader.StateRoot == Hash32.Zero) { Hash32 stateRoot = cryptographyService.HashTreeRoot(state); previousBlockHeader.SetStateRoot(stateRoot); } Hash32 previousBlockSigningRoot = previousBlockHeader.SigningRoot(); BeaconBlock emptyBlock = new BeaconBlock(slot, previousBlockSigningRoot, Hash32.Zero, new BeaconBlockBody( BlsSignature.Empty, eth1Data, new Bytes32(), Array.Empty <ProposerSlashing>(), Array.Empty <AttesterSlashing>(), Array.Empty <Attestation>(), Array.Empty <Deposit>(), Array.Empty <VoluntaryExit>() ), BlsSignature.Empty); if (signed) { SignBlock(testServiceProvider, state, emptyBlock, ValidatorIndex.None); } return(emptyBlock); }
/// <summary> /// State transition via the provided ``block`` /// then package the block with the state root and signature. /// </summary> public static SignedBeaconBlock StateTransitionAndSignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); SignedBeaconBlock preSigningBlock = new SignedBeaconBlock(block, BlsSignature.Zero); beaconStateTransition.StateTransition(state, preSigningBlock, validateResult: false); Root stateRoot = cryptographyService.HashTreeRoot(state); block.SetStateRoot(stateRoot); SignedBeaconBlock signedBlock = TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); return(signedBlock); }
private static IEnumerable <SszElement> GetValues(BeaconBlockBody item, MiscellaneousParameters miscellaneousParameters, MaxOperationsPerBlock maxOperationsPerBlock) { yield return(item.RandaoReveal.ToSszBasicVector()); yield return(item.Eth1Data.ToSszContainer()); yield return(item.Graffiti.ToSszBasicVector()); // Operations yield return(item.ProposerSlashings.ToSszList(maxOperationsPerBlock.MaximumProposerSlashings)); yield return(item.AttesterSlashings.ToSszList(maxOperationsPerBlock.MaximumAttesterSlashings, miscellaneousParameters)); yield return(item.Attestations.ToSszList(maxOperationsPerBlock.MaximumAttestations, miscellaneousParameters)); yield return(item.Deposits.ToSszList(maxOperationsPerBlock.MaximumDeposits)); yield return(item.VoluntaryExits.ToSszList(maxOperationsPerBlock.MaximumVoluntaryExits)); //yield return item.Transfers.ToSszList(MAX_TRANSFERS); }
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); }
/// <summary> /// Check if ``indexed_attestation`` has valid indices and signature. /// </summary> public bool IsValidIndexedAttestation(BeaconState state, IndexedAttestation indexedAttestation, Domain domain) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; IReadOnlyList<ValidatorIndex> attestingIndices = indexedAttestation.AttestingIndices; // Verify max number of indices if ((ulong) attestingIndices.Count > miscellaneousParameters.MaximumValidatorsPerCommittee) { if (_logger.IsWarn()) Log.InvalidIndexedAttestationTooMany(_logger, indexedAttestation.Data.Index, indexedAttestation.Data.Slot, attestingIndices.Count, miscellaneousParameters.MaximumValidatorsPerCommittee, null); return false; } // Verify indices are sorted if (attestingIndices.Count() > 1) { for (int index = 0; index < attestingIndices.Count() - 1; index++) { if (!(attestingIndices[index] < attestingIndices[index + 1])) { if (_logger.IsWarn()) Log.InvalidIndexedAttestationNotSorted(_logger, indexedAttestation.Data.Index, indexedAttestation.Data.Slot, 0, index, null); return false; } } } // Verify aggregate signature IEnumerable<BlsPublicKey> publicKeys = attestingIndices.Select(x => state.Validators[(int) (ulong) x].PublicKey); BlsPublicKey aggregatePublicKey = _cryptographyService.BlsAggregatePublicKeys(publicKeys); Hash32 messageHash = _cryptographyService.HashTreeRoot(indexedAttestation.Data); BlsSignature signature = indexedAttestation.Signature; bool isValid = _cryptographyService.BlsVerify(aggregatePublicKey, messageHash, signature, domain); if (!isValid) { if (_logger.IsWarn()) Log.InvalidIndexedAttestationSignature(_logger, indexedAttestation.Data.Index, indexedAttestation.Data.Slot, null); return false; } return true; }