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); }
public async Task ChainNoAttestations() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // On receiving a block of `GENESIS_SLOT + 1` slot BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock1 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1); await AddBlockToStore(testServiceProvider, store, signedBlock1); // On receiving a block of next epoch BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2); await AddBlockToStore(testServiceProvider, store, signedBlock2); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Root expectedRoot = cryptographyService.HashTreeRoot(block2); headRoot.ShouldBe(expectedRoot); }
public async Task <Gwei> GetLatestAttestingBalanceAsync(IStore store, Hash32 root) { // NOTE: This method should probably live in IStore, for various efficient implementations. Checkpoint justifiedCheckpoint = store.JustifiedCheckpoint; BeaconState state = (await store.GetCheckpointStateAsync(justifiedCheckpoint, true).ConfigureAwait(false)) !; Epoch currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); IList <ValidatorIndex> activeIndexes = _beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch); BeaconBlock rootBlock = await store.GetBlockAsync(root).ConfigureAwait(false); Slot rootSlot = rootBlock !.Slot; Gwei balance = Gwei.Zero; foreach (ValidatorIndex index in activeIndexes) { LatestMessage?latestMessage = await store.GetLatestMessageAsync(index, false); if (latestMessage != null) { Hash32 ancestor = await GetAncestorAsync(store, latestMessage.Root, rootSlot); if (ancestor == root) { Validator validator = state.Validators[(int)index]; balance += validator.EffectiveBalance; } } } return(balance); }
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 async Task GenesisHead() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.ConfigureNethermindCore2(); string debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 stateRoot = cryptographyService.HashTreeRoot(state); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 expectedRoot = cryptographyService.SigningRoot(genesisBlock); headRoot.ShouldBe(expectedRoot); }
public BlsSignature GetBlockSignature(BeaconBlock block, BlsPublicKey blsPublicKey) { var fork = _beaconChainInformation.Fork; var epoch = ComputeEpochAtSlot(block.Slot); ForkVersion forkVersion; if (epoch < fork.Epoch) { forkVersion = fork.PreviousVersion; } else { forkVersion = fork.CurrentVersion; } var domainType = _signatureDomainOptions.CurrentValue.BeaconProposer; var proposerDomain = ComputeDomain(domainType, forkVersion); /* * JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; * options.ConfigureNethermindCore2(); * string blockJson = System.Text.Json.JsonSerializer.Serialize(block, options); */ var blockRoot = _cryptographyService.HashTreeRoot(block); var signingRoot = ComputeSigningRoot(blockRoot, proposerDomain); var signature = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot); return(signature); }
public async Task ProcessProposalDutiesAsync(Slot slot, CancellationToken cancellationToken) { // If proposer, get block, sign block, return to node // Retry if not successful; need to queue this up to send immediately if connection issue. (or broadcast?) BlsPublicKey?blsPublicKey = _validatorState.GetProposalDutyForSlot(slot); if (!(blsPublicKey is null)) { if (_logger.IsInfo()) { Log.ProposalDutyFor(_logger, slot, blsPublicKey, null); } BlsSignature randaoReveal = GetEpochSignature(slot, blsPublicKey); if (_logger.IsDebug()) { LogDebug.RequestingBlock(_logger, slot, blsPublicKey.ToShortString(), randaoReveal.ToString().Substring(0, 10), null); } BeaconBlock unsignedBlock = await _beaconNodeApi.NewBlockAsync(slot, randaoReveal, cancellationToken).ConfigureAwait(false); BeaconBlock signedBlock = SignBlock(unsignedBlock, blsPublicKey); if (_logger.IsDebug()) { LogDebug.PublishingSignedBlock(_logger, slot, blsPublicKey.ToShortString(), randaoReveal.ToString().Substring(0, 10), signedBlock, signedBlock.Signature.ToString().Substring(0, 10), null); } bool nodeAccepted = await _beaconNodeApi.PublishBlockAsync(signedBlock, cancellationToken).ConfigureAwait(false); _validatorState.ClearProposalDutyForSlot(slot); } }
public async Task <bool> PublishBlockAsync(BeaconBlock signedBlock, CancellationToken cancellationToken) { if (!_storeProvider.TryGetStore(out IStore? retrievedStore)) { throw new Exception("Beacon chain is currently syncing or waiting for genesis."); } IStore store = retrievedStore !; bool acceptedLocally = false; try { await _forkChoice.OnBlockAsync(store, signedBlock).ConfigureAwait(false); // TODO: validate as per honest validator spec and return true/false acceptedLocally = true; } catch (Exception ex) { if (_logger.IsWarn()) { Log.BlockNotAcceptedLocally(_logger, signedBlock, ex); } } await _networkPeering.PublishBeaconBlockAsync(signedBlock).ConfigureAwait(false); return(acceptedLocally); }
public async Task <BeaconBlock> NewBlockAsync(Slot slot, BlsSignature randaoReveal) { if (slot == Slot.Zero) { throw new ArgumentException("Can't generate new block for slot 0, as it is the genesis block."); } if (!_storeProvider.TryGetStore(out IStore? retrievedStore)) { throw new Exception("Beacon chain is currently syncing or waiting for genesis."); } IStore store = retrievedStore !; Slot previousSlot = slot - Slot.One; Hash32 head = await _forkChoice.GetHeadAsync(store).ConfigureAwait(false); BeaconBlock headBlock = await store.GetBlockAsync(head).ConfigureAwait(false); BeaconBlock parentBlock; BeaconState parentState; Hash32 parentRoot; if (headBlock !.Slot > previousSlot) { // Requesting a block for a past slot? Hash32 ancestorSigningRoot = await _forkChoice.GetAncestorAsync(store, head, previousSlot); parentBlock = await store.GetBlockAsync(ancestorSigningRoot).ConfigureAwait(false); parentState = await store.GetBlockStateAsync(ancestorSigningRoot).ConfigureAwait(false); parentRoot = ancestorSigningRoot; }
public Task PublishBeaconBlockAsync(BeaconBlock beaconBlock) { // Validate signature before broadcasting return(Task.CompletedTask); //throw new NotImplementedException(); }
/// <summary> /// To address the bouncing attack, only update conflicting justified /// checkpoints in the fork choice if in the early slots of the epoch. /// Otherwise, delay incorporation of new justified checkpoint until next epoch boundary. /// See https://ethresear.ch/t/prevention-of-bouncing-attack-on-ffg/6114 for more detailed analysis and discussion. /// </summary> public async Task <bool> ShouldUpdateJustifiedCheckpointAsync(IStore store, Checkpoint newJustifiedCheckpoint) { Slot currentSlot = GetCurrentSlot(store); Slot slotsSinceEpochStart = ComputeSlotsSinceEpochStart(currentSlot); if (slotsSinceEpochStart < _forkChoiceConfigurationOptions.CurrentValue.SafeSlotsToUpdateJustified) { return(true); } BeaconBlock newJustifiedBlock = await store.GetBlockAsync(newJustifiedCheckpoint.Root).ConfigureAwait(false); Slot justifiedCheckpointEpochStartSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(store.JustifiedCheckpoint.Epoch); if (newJustifiedBlock.Slot <= justifiedCheckpointEpochStartSlot) { return(false); } BeaconBlock justifiedCheckPointBlock = await store.GetBlockAsync(store.JustifiedCheckpoint.Root).ConfigureAwait(false); Hash32 ancestorOfNewCheckpointAtOldCheckpointSlot = await GetAncestorAsync(store, newJustifiedCheckpoint.Root, justifiedCheckPointBlock.Slot).ConfigureAwait(false); // i.e. new checkpoint is descendant of old checkpoint return(ancestorOfNewCheckpointAtOldCheckpointSlot == store.JustifiedCheckpoint.Root); }
public async Task GenesisHead() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.ConfigureNethermindCore2(); string debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>(); ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Root stateRoot = cryptographyService.HashTreeRoot(state); BeaconBlock genesisBlock = new BeaconBlock(Slot.Zero, Root.Zero, stateRoot, BeaconBlockBody.Zero); Root expectedRoot = cryptographyService.HashTreeRoot(genesisBlock); headRoot.ShouldBe(expectedRoot); }
public async Task GenesisHead() { // Arrange var testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); var state = TestState.PrepareTestState(testServiceProvider); var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; var stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; var maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.AddCortexContainerConverters(); var debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization var forkChoice = testServiceProvider.GetService <ForkChoice>(); var store = forkChoice.GetGenesisStore(state); // Act var headRoot = await forkChoice.GetHeadAsync(store); // Assert var stateRoot = state.HashTreeRoot(miscellaneousParameters, timeParameters, stateListLengths, maxOperationsPerBlock); var genesisBlock = new BeaconBlock(stateRoot); var expectedRoot = genesisBlock.SigningRoot(miscellaneousParameters, maxOperationsPerBlock); headRoot.ShouldBe(expectedRoot); }
public async Task <ApiResponse <BeaconBlock> > NewBlockAsync(Slot slot, BlsSignature randaoReveal, CancellationToken cancellationToken) { string baseUri = "validator/block"; Dictionary <string, string> queryParameters = new Dictionary <string, string> { ["slot"] = slot.ToString(), ["randao_reveal"] = randaoReveal.ToString() }; string uri = QueryHelpers.AddQueryString(baseUri, queryParameters); using HttpResponseMessage httpResponse = await _httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); int statusCode = (int)httpResponse.StatusCode; if (statusCode == (int)StatusCode.InvalidRequest || statusCode == (int)StatusCode.CurrentlySyncing) { return(ApiResponse.Create <BeaconBlock>((StatusCode)statusCode)); } httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299 await using Stream contentStream = await httpResponse.Content.ReadAsStreamAsync(); BeaconBlock content = await JsonSerializer.DeserializeAsync <BeaconBlock>(contentStream, _jsonSerializerOptions, cancellationToken); return(ApiResponse.Create((StatusCode)statusCode, content)); }
public async Task <ApiResponse <Syncing> > GetSyncingAsync(CancellationToken cancellationToken) { try { Slot currentSlot = Slot.Zero; if (_store.IsInitialized) { Root head = await _forkChoice.GetHeadAsync(_store).ConfigureAwait(false); BeaconBlock block = (await _store.GetSignedBlockAsync(head).ConfigureAwait(false)).Message; currentSlot = block.Slot; } Slot highestSlot = Slot.Max(currentSlot, _networkPeering.HighestPeerSlot); Slot startingSlot = _networkPeering.SyncStartingSlot; bool isSyncing = highestSlot > currentSlot; Syncing syncing = new Syncing(isSyncing, new SyncingStatus(startingSlot, currentSlot, highestSlot)); return(ApiResponse.Create(StatusCode.Success, syncing)); } catch (Exception ex) { if (_logger.IsWarn()) { Log.ApiErrorGetSyncing(_logger, ex); } throw; } }
public async Task <BeaconBlock> NewBlockAsync(Slot slot, BlsSignature randaoReveal, CancellationToken cancellationToken) { if (slot == Slot.Zero) { throw new ArgumentException("Can't generate new block for slot 0, as it is the genesis block."); } Slot previousSlot = slot - Slot.One; Root head = await _forkChoice.GetHeadAsync(_store).ConfigureAwait(false); BeaconBlock headBeaconBlock = (await _store.GetSignedBlockAsync(head).ConfigureAwait(false)).Message; BeaconState parentState; Root parentRoot; if (headBeaconBlock !.Slot > previousSlot) { // Requesting a block for a past slot? Root ancestorRoot = await _forkChoice.GetAncestorAsync(_store, head, previousSlot).ConfigureAwait(false); parentState = await _store.GetBlockStateAsync(ancestorRoot).ConfigureAwait(false); parentRoot = ancestorRoot; }
// [DataRow(42uL, "0xab48aa2cc6f4a0bb63b5d67be54ac3aed10326dda304c5aeb9e942b40d6e7610478377680ab90e092ef1895e62786008", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x8aea7d8eb22063bcfe882e2b7efc0b3713e1a48dd8343bed523b1ab4546114be84d00f896d33c605d1f67456e8e2ed93", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x89db41a6183c2fe47cf54d1e00c3cfaae53df634a32cccd5cf0c0a73e95ee0450fc3d060bb6878780fbf5f30d9e29aac", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0xb783a70a1cf9f53e7d2ddf386bea81a947e5360c5f1e0bf004fceedb2073e4dd180ef3d2d91bee7b1c5a88d1afd11c49", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x8fe55d12257709ae842f8594f9a0a40de3d38dabdf82b21a60baac927e52ed00c5fd42f4c905410eacdaf8f8a9952490", 0uL, 5uL, 1uL, null)] // [DataRow(42uL, "0x95906ec0660892c205634e21ad540cbe0b6f7729d101d5c4639b864dea09be7f42a4252c675d46dd90a2661b3a94e8ca", 0uL, 5uL, 1uL, null)] public async Task ValidatorDutyAtSpecificTimeDuplicateProposal(ulong targetTime, string publicKey, ulong epoch, ulong attestationSlot, ulong attestationShard, ulong?blockProposalSlot) { // NOTE: Current algorithm for GetBeaconProposerIndex() someimtes allocates multiple proposal slots in an epoch, e.g. above index 23 gets slot 2 and 6 // It could be an error in the algorithm (need to check; domain type could be wrong), or due to the pre-shard algorithm. // The algorithm before shards were removed was different, so maybe ignore for now, implement phase 1 (with shards), and worry about it then. // This test for now will simply detect if things unintentionally change. // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // Move forward time TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; for (ulong timeSinceGenesis = 1; timeSinceGenesis <= targetTime; timeSinceGenesis++) { ulong time = state.GenesisTime + timeSinceGenesis; await forkChoice.OnTickAsync(store, time); if (timeSinceGenesis % timeParameters.SecondsPerSlot == 0) { BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await forkChoice.OnBlockAsync(store, signedBlock); } } Console.WriteLine(""); Console.WriteLine("***** State advanced to slot {0}, time {1}, ready to start tests *****", state.Slot, store.Time); Console.WriteLine(""); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); // Assert validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey); Slot expectedBlockProposalSlot = blockProposalSlot.HasValue ? new Slot(blockProposalSlot.Value) : Slot.None; Slot expectedAttestationSlot = new Slot(attestationSlot); Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard); }
public void ProposerIndexForFirstTwoEpochsMustBeValid() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state IStore store = forkChoice.GetGenesisStore(state); // Move forward time BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; ulong time = state.GenesisTime + 1; ulong nextSlotTime = state.GenesisTime; ValidatorIndex maximumValidatorIndex = new ValidatorIndex((ulong)state.Validators.Count - 1); ValidatorIndex validatorIndex0 = beaconStateAccessor.GetBeaconProposerIndex(state); Console.WriteLine("Slot {0}, time {1} = proposer index {2}", state.Slot, time, validatorIndex0); validatorIndex0.ShouldBeLessThanOrEqualTo(maximumValidatorIndex); List <ValidatorIndex> proposerIndexes = new List <ValidatorIndex>(); proposerIndexes.Add(validatorIndex0); for (int slotIndex = 1; slotIndex <= 16; slotIndex++) { // Slot 1 nextSlotTime = nextSlotTime + timeParameters.SecondsPerSlot; while (time < nextSlotTime) { forkChoice.OnTick(store, time); time++; } forkChoice.OnTick(store, time); time++; BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); forkChoice.OnBlock(store, block); forkChoice.OnTick(store, time); time++; ValidatorIndex validatorIndex = beaconStateAccessor.GetBeaconProposerIndex(state); Console.WriteLine("Slot {0}, time {1} = proposer index {2}", state.Slot, time, validatorIndex); validatorIndex.ShouldBeLessThanOrEqualTo(maximumValidatorIndex); proposerIndexes.Add(validatorIndex); } for (var slotIndex = 0; slotIndex < proposerIndexes.Count; slotIndex++) { ValidatorIndex proposerIndex = proposerIndexes[slotIndex]; Validator proposer = state.Validators[(int)(ulong)proposerIndex]; Console.WriteLine("Slot {0} = proposer index {1}, public key {2}", slotIndex, proposerIndex, proposer.PublicKey); } }
public void ProcessBlock(BeaconState state, BeaconBlock block) { _logger.LogInformation(Event.ProcessBlock, "Process block {BeaconBlock} for state {BeaconState}", block, state); ProcessBlockHeader(state, block); ProcessRandao(state, block.Body); ProcessEth1Data(state, block.Body); ProcessOperations(state, block.Body); }
private void AssertBeaconBlockEqual(BeaconBlock expected, BeaconBlock actual) { actual.Slot.ShouldBe(expected.Slot); actual.ParentRoot.ShouldBe(expected.ParentRoot); actual.StateRoot.ShouldBe(expected.StateRoot); AssertBeaconBlockBodyEqual(expected.Body, actual.Body); }
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); }
public static void Encode(Span <byte> span, BeaconBlock container) { if (span.Length != Ssz.BeaconBlockLength(container)) { ThrowTargetLength <BeaconBlock>(span.Length, Ssz.BeaconBlockLength(container)); } int offset = 0; Encode(span, container, ref offset); }
public static void Ize(out UInt256 root, BeaconBlock container) { Merkleizer merkleizer = new Merkleizer(2); merkleizer.Feed(container.Slot); merkleizer.Feed(container.ParentRoot); merkleizer.Feed(container.StateRoot); merkleizer.Feed(container.Body); merkleizer.CalculateRoot(out root); }
public void SuccessBlockHeader() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); RunBlockHeaderProcessing(testServiceProvider, state, block, expectValid: true); }
public void InvalidSlotBlockHeader() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); BeaconBlock block = TestBlock.BuildEmptyBlock(testServiceProvider, state, state.Slot + new Slot(2), BlsSignature.Zero); RunBlockHeaderProcessing(testServiceProvider, state, block, expectValid: false); }
private static IEnumerable <SszElement> GetValues(BeaconBlock item, ulong maximumProposerSlashings, ulong maximumAttesterSlashings, ulong maximumAttestations, ulong maximumDeposits, ulong maximumVoluntaryExits, ulong maximumValidatorsPerCommittee) { yield return(item.Slot.ToSszBasicElement()); yield return(item.ParentRoot.ToSszBasicVector()); yield return(item.StateRoot.ToSszBasicVector()); yield return(item.Body.ToSszContainer(maximumProposerSlashings, maximumAttesterSlashings, maximumAttestations, maximumDeposits, maximumVoluntaryExits, maximumValidatorsPerCommittee)); }
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); }
private static void TestBeaconBlockSsz(byte[] serialized, UInt256 expectedMerkleRoot, string testCaseDir) { BeaconBlock container = Nethermind.Ssz.Ssz.DecodeBeaconBlock(serialized); byte[] again = new byte[serialized.Length]; Nethermind.Ssz.Ssz.Encode(again, container); Assert.AreEqual(serialized.ToHexString(), again.ToHexString(), testCaseDir); Merkle.Ize(out UInt256 root, container); Assert.AreEqual(expectedMerkleRoot, root); }
public void CheckEmptyBlockRootAfterDeserializing() { // Arrange Eth1Data eth1Data = new Eth1Data( new Root(Enumerable.Repeat((byte)0x12, 32).ToArray()), 64, new Bytes32(Enumerable.Repeat((byte)0x34, 32).ToArray())); BlsSignature randaoReveal = new BlsSignature(Enumerable.Repeat((byte)0xfe, 96).ToArray()); BeaconBlockBody beaconBlockBody = new BeaconBlockBody( randaoReveal, eth1Data, new Bytes32(new byte[32]), new ProposerSlashing[0], new AttesterSlashing [0], new Attestation[0], new Deposit[0], new SignedVoluntaryExit[0] ); BeaconBlock beaconBlock = new BeaconBlock( new Slot(1), new Root(Enumerable.Repeat((byte)0x78, 32).ToArray()), new Root(Enumerable.Repeat((byte)0x9a, 32).ToArray()), beaconBlockBody); Merkle.Ize(out UInt256 blockRoot256, beaconBlock); Span <byte> blockRootSpan = MemoryMarshal.Cast <UInt256, byte>(MemoryMarshal.CreateSpan(ref blockRoot256, 1)); Root blockRoot = new Root(blockRootSpan); SignedBeaconBlock signedBeaconBlock = new SignedBeaconBlock( beaconBlock, new BlsSignature(Enumerable.Repeat((byte)0x0e, 96).ToArray()) ); // Act Span <byte> encoded = new byte[Ssz.SignedBeaconBlockLength(signedBeaconBlock)]; Ssz.Encode(encoded, signedBeaconBlock); SignedBeaconBlock decoded = Ssz.DecodeSignedBeaconBlock(encoded); // Assert Merkle.Ize(out UInt256 decodedBlockRoot256, decoded.Message); Span <byte> decodedBlockRootSpan = MemoryMarshal.Cast <UInt256, byte>(MemoryMarshal.CreateSpan(ref decodedBlockRoot256, 1)); Root decodedBlockRoot = new Root(decodedBlockRootSpan); decodedBlockRoot.ShouldBe(blockRoot); }
public async Task ShorterChainButHeavierWeight() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); BeaconState genesisState = BeaconState.Clone(state); // build longer tree Root longRoot = Root.Zero; BeaconState longState = BeaconState.Clone(genesisState); for (int i = 0; i < 3; i++) { BeaconBlock longBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, longState, BlsSignature.Zero); SignedBeaconBlock signedLongBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, longState, longBlock); await AddBlockToStore(testServiceProvider, store, signedLongBlock); if (i == 2) { longRoot = cryptographyService.HashTreeRoot(longBlock); } } // build short tree BeaconState shortState = BeaconState.Clone(genesisState); BeaconBlock shortBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, shortState, BlsSignature.Zero); shortBlock.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, shortState, shortBlock, ValidatorIndex.None); SignedBeaconBlock signedShortBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, shortState, shortBlock); await AddBlockToStore(testServiceProvider, store, signedShortBlock); Attestation shortAttestation = TestAttestation.GetValidAttestation(testServiceProvider, shortState, shortBlock.Slot, CommitteeIndex.None, signed: true); await AddAttestationToStore(testServiceProvider, store, shortAttestation); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Root expectedRoot = cryptographyService.HashTreeRoot(shortBlock); headRoot.ShouldBe(expectedRoot); headRoot.ShouldNotBe(longRoot); }