public async Task ShouldRequestBlocksFromAheadFinalizedCheckpoint() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); INetworkPeering mockNetworkPeering = Substitute.For <INetworkPeering>(); testServiceCollection.AddSingleton <INetworkPeering>(mockNetworkPeering); 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); // Act PeeringStatus peeringStatus = new PeeringStatus( new ForkVersion(new byte[4] { 0, 0, 0, 0 }), new Root(Enumerable.Repeat((byte)0x34, 32).ToArray()), Epoch.One, new Root(Enumerable.Repeat((byte)0x56, 32).ToArray()), new Slot(2)); ISynchronizationManager synchronizationManager = testServiceProvider.GetService <ISynchronizationManager>(); await synchronizationManager.OnStatusResponseReceived("peer", peeringStatus); // Assert await mockNetworkPeering.Received(1) .RequestBlocksAsync("peer", Arg.Any <Root>(), Arg.Any <Slot>(), Arg.Any <Slot>()); await mockNetworkPeering.DidNotReceive().DisconnectPeerAsync("peer"); }
public GenesisChainStart(ILogger <GenesisChainStart> logger, ChainConstants chainConstants, IOptionsMonitor <MiscellaneousParameters> miscellaneousParameterOptions, IOptionsMonitor <GweiValues> gweiValueOptions, IOptionsMonitor <InitialValues> initialValueOptions, IOptionsMonitor <TimeParameters> timeParameterOptions, IOptionsMonitor <StateListLengths> stateListLengthOptions, ICryptographyService cryptographyService, IStore store, BeaconStateAccessor beaconStateAccessor, BeaconStateTransition beaconStateTransition, IForkChoice forkChoice, IDepositStore depositStore) { _logger = logger; _beaconStateAccessor = beaconStateAccessor; _beaconStateTransition = beaconStateTransition; _forkChoice = forkChoice; _depositStore = depositStore; _chainConstants = chainConstants; _miscellaneousParameterOptions = miscellaneousParameterOptions; _gweiValueOptions = gweiValueOptions; _initialValueOptions = initialValueOptions; _timeParameterOptions = timeParameterOptions; _stateListLengthOptions = stateListLengthOptions; _cryptographyService = cryptographyService; _store = store; }
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 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 ShouldReturnDefaultForkVersion() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>()); testServiceCollection.AddSingleton <IEth1DataProvider>(Substitute.For <IEth1DataProvider>()); testServiceCollection.AddSingleton <IOperationPool>(Substitute.For <IOperationPool>()); 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); // Act IBeaconNodeApi beaconNode = testServiceProvider.GetService <IBeaconNodeApi>(); beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade)); var forkResponse = await beaconNode.GetNodeForkAsync(CancellationToken.None); var fork = forkResponse.Content; // Assert fork.Epoch.ShouldBe(Epoch.Zero); fork.CurrentVersion.ShouldBe(new ForkVersion()); fork.PreviousVersion.ShouldBe(new ForkVersion()); }
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); }
// [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 RpcBeaconBlocksByRangeProcessor(ILogger <RpcBeaconBlocksByRangeProcessor> logger, INetworkPeering networkPeering, IForkChoice forkChoice, IStore store) : base(logger, MaximumQueue) { _logger = logger; _networkPeering = networkPeering; _forkChoice = forkChoice; _store = store; }
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); }
public QuickStartMockEth1DataProvider(IOptionsMonitor <TimeParameters> timeParameterOptions, ICryptographyService cryptographyService, BeaconStateAccessor beaconStateAccessor, IForkChoice forkChoice, IStore store) { _timeParameterOptions = timeParameterOptions; _cryptographyService = cryptographyService; _beaconStateAccessor = beaconStateAccessor; _forkChoice = forkChoice; _store = store; }
public async Task BasicValidatorDuty(string publicKey, ulong epoch, bool success, ulong?attestationSlot, ulong attestationShard, ulong?blockProposalSlot) { // 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); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); // failure expected if (!success) { Should.Throw <Exception>(async() => { 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); }); return; } 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 = (Slot?)blockProposalSlot; Slot? expectedAttestationSlot = (Slot?)attestationSlot; Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard); }
public async Task ShouldNotRequestIfHeadBehind() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); INetworkPeering mockNetworkPeering = Substitute.For <INetworkPeering>(); testServiceCollection.AddSingleton <INetworkPeering>(mockNetworkPeering); 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; ulong targetTime = 2 * 6; // slot 2 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); } } // Act PeeringStatus peeringStatus = new PeeringStatus( new ForkVersion(new byte[4] { 0, 0, 0, 0 }), Root.Zero, Epoch.Zero, new Root(Enumerable.Repeat((byte)0x56, 32).ToArray()), new Slot(1)); ISynchronizationManager synchronizationManager = testServiceProvider.GetService <ISynchronizationManager>(); await synchronizationManager.OnStatusResponseReceived("peer", peeringStatus); // Assert await mockNetworkPeering.DidNotReceive() .RequestBlocksAsync("peer", Arg.Any <Root>(), Arg.Any <Slot>(), Arg.Any <Slot>()); await mockNetworkPeering.DidNotReceive().DisconnectPeerAsync("peer"); }
public SynchronizationManager( ILogger <SynchronizationManager> logger, IBeaconChainUtility beaconChainUtility, BeaconStateAccessor beaconStateAccessor, IForkChoice forkChoice, IStore store, INetworkPeering networkPeering) { _logger = logger; _beaconChainUtility = beaconChainUtility; _beaconStateAccessor = beaconStateAccessor; _forkChoice = forkChoice; _store = store; _networkPeering = networkPeering; }
public async Task BasicOnTick() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // Act await RunOnTick(testServiceProvider, store, store.Time + 1, expectNewJustifiedCheckpoint : false); // Assert }
public ValidatorAssignments(ILogger <ValidatorAssignments> logger, IOptionsMonitor <TimeParameters> timeParameterOptions, BeaconChainUtility beaconChainUtility, BeaconStateAccessor beaconStateAccessor, BeaconStateTransition beaconStateTransition, IForkChoice forkChoice, IStore store) { _logger = logger; _timeParameterOptions = timeParameterOptions; _beaconChainUtility = beaconChainUtility; _beaconStateAccessor = beaconStateAccessor; _beaconStateTransition = beaconStateTransition; _forkChoice = forkChoice; _store = store; }
public AttestationProducer(ILogger <AttestationProducer> logger, ICryptographyService cryptographyService, BeaconChainUtility beaconChainUtility, BeaconStateAccessor beaconStateAccessor, BeaconStateTransition beaconStateTransition, IForkChoice forkChoice, IStore store) { _logger = logger; _cryptographyService = cryptographyService; _beaconChainUtility = beaconChainUtility; _beaconStateAccessor = beaconStateAccessor; _beaconStateTransition = beaconStateTransition; _forkChoice = forkChoice; _store = store; }
private async Task AddBlockToStore(IServiceProvider testServiceProvider, IStore store, SignedBeaconBlock signedBlock) { TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); BeaconState preState = await store.GetBlockStateAsync(signedBlock.Message.ParentRoot); ulong blockTime = preState !.GenesisTime + (ulong)signedBlock.Message.Slot * timeParameters.SecondsPerSlot; if (store.Time < blockTime) { await forkChoice.OnTickAsync(store, blockTime); } await forkChoice.OnBlockAsync(store, signedBlock); }
public async Task SplitTieBreakerNoAttestations() { // 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); // block at slot 1 BeaconState block1State = BeaconState.Clone(genesisState); BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block1State, BlsSignature.Zero); SignedBeaconBlock signedBlock1 = TestState.StateTransitionAndSignBlock(testServiceProvider, block1State, block1); await AddBlockToStore(testServiceProvider, store, signedBlock1); Root block1Root = cryptographyService.HashTreeRoot(block1); // build short tree BeaconState block2State = BeaconState.Clone(genesisState); BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block2State, BlsSignature.Zero); block2.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, block2State, block2, ValidatorIndex.None); SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, block2State, block2); await AddBlockToStore(testServiceProvider, store, signedBlock2); Root block2Root = cryptographyService.HashTreeRoot(block2); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Console.WriteLine("block1 {0}", block1Root); Console.WriteLine("block2 {0}", block2Root); Root highestRoot = block1Root.CompareTo(block2Root) > 0 ? block1Root : block2Root; Console.WriteLine("highest {0}", highestRoot); headRoot.ShouldBe(highestRoot); }
public void SetUp() { _mockLoggerOptionsMonitor = Substitute.For <IOptionsMonitor <ConsoleLoggerOptions> >(); _mockLoggerOptionsMonitor.CurrentValue.Returns(new ConsoleLoggerOptions() { Format = ConsoleLoggerFormat.Systemd, DisableColors = true, IncludeScopes = true, TimestampFormat = " HH':'mm':'sszz " }); _loggerFactory = new LoggerFactory(new [] { new ConsoleLoggerProvider(_mockLoggerOptionsMonitor) }); _mockMothra = new MockMothra(); // mockMothra.StartCalled += settings => // { // ThreadPool.QueueUserWorkItem(x => // { // Thread.Sleep(TimeSpan.FromMilliseconds(100)); // byte[] peerUtf8 = Encoding.UTF8.GetBytes("peer1"); // mockMothra.RaisePeerDiscovered(peerUtf8); // }); // }; _mockForkChoice = Substitute.For <IForkChoice>(); _mockSynchronizationManager = Substitute.For <ISynchronizationManager>(); _mockStore = Substitute.For <IStore>(); _mockStore.IsInitialized.Returns(true); _mockMothraConfigurationMonitor = Substitute.For <IOptionsMonitor <MothraConfiguration> >(); _mockMothraConfigurationMonitor.CurrentValue.Returns(new MothraConfiguration()); // TODO: Replace with MothraNetworkPeering and mockMothra. _mockNetworkPeering = Substitute.For <INetworkPeering>(); _dataDirectory = new DataDirectory("data"); _peerManager = new PeerManager(_loggerFactory.CreateLogger <PeerManager>()); _peerDiscoveredProcessor = new PeerDiscoveredProcessor( _loggerFactory.CreateLogger <PeerDiscoveredProcessor>(), _mockSynchronizationManager, _peerManager); _rpcPeeringStatusProcessor = new RpcPeeringStatusProcessor( _loggerFactory.CreateLogger <RpcPeeringStatusProcessor>(), _mockSynchronizationManager, _peerManager); _rpcBeaconBlocksByRangeProcessor = new RpcBeaconBlocksByRangeProcessor(_loggerFactory.CreateLogger <RpcBeaconBlocksByRangeProcessor>(), _mockNetworkPeering, _mockForkChoice, _mockStore); _signedBeaconBlockProcessor = new SignedBeaconBlockProcessor( _loggerFactory.CreateLogger <SignedBeaconBlockProcessor>(), _mockMothraConfigurationMonitor, Substitute.For <IFileSystem>(), _mockForkChoice, _mockStore, _dataDirectory, _peerManager); }
public BeaconNodeFacade( ILogger <BeaconNodeFacade> logger, IClientVersion clientVersion, IForkChoice forkChoice, IStore store, INetworkPeering networkPeering, ValidatorAssignments validatorAssignments, BlockProducer blockProducer) { _logger = logger; _clientVersion = clientVersion; _forkChoice = forkChoice; _store = store; _networkPeering = networkPeering; _validatorAssignments = validatorAssignments; _blockProducer = blockProducer; }
public BeaconNodeWorker(ILogger <BeaconNodeWorker> logger, IOptionsMonitor <TimeParameters> timeParameterOptions, IClock clock, IHostEnvironment environment, IClientVersion clientVersion, IStore store, DataDirectory dataDirectory, IForkChoice forkChoice, INodeStart nodeStart) { _logger = logger; _timeParameterOptions = timeParameterOptions; _clock = clock; _environment = environment; _clientVersion = clientVersion; _store = store; _dataDirectory = dataDirectory; _forkChoice = forkChoice; _nodeStart = nodeStart; }
public async Task BasicOnBlock() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Initialization IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); ulong time = 100uL; await forkChoice.OnTickAsync(store, time); store.Time.ShouldBe(time); // On receiving a block of `GENESIS_SLOT + 1` slot BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await RunOnBlock(testServiceProvider, store, signedBlock, expectValid : true); // On receiving a block of next epoch ulong time2 = time + timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch; await store.SetTimeAsync(time2); Slot slot2 = (Slot)(block.Slot + timeParameters.SlotsPerEpoch); BeaconBlock block2 = TestBlock.BuildEmptyBlock(testServiceProvider, state, slot2, BlsSignature.Zero); SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2); //var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; //options.AddCortexContainerConverters(); //var debugState = System.Text.Json.JsonSerializer.Serialize(state, options); await RunOnBlock(testServiceProvider, store, signedBlock2, expectValid : true); // Assert // TODO: add tests for justified_root and finalized_root }
private async Task RunOnTick(IServiceProvider testServiceProvider, IStore store, ulong time, bool expectNewJustifiedCheckpoint) { IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); Checkpoint previousJustifiedCheckpoint = store.JustifiedCheckpoint; await forkChoice.OnTickAsync(store, time); store.Time.ShouldBe(time); if (expectNewJustifiedCheckpoint) { store.JustifiedCheckpoint.ShouldBe(store.BestJustifiedCheckpoint); store.JustifiedCheckpoint.Epoch.ShouldBeGreaterThan(previousJustifiedCheckpoint.Epoch); store.JustifiedCheckpoint.Root.ShouldNotBe(previousJustifiedCheckpoint.Root); } else { store.JustifiedCheckpoint.ShouldBe(previousJustifiedCheckpoint); } }
private async Task RunOnBlock(IServiceProvider testServiceProvider, IStore store, SignedBeaconBlock signedBlock, bool expectValid) { ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); if (!expectValid) { Should.Throw <Exception>(async() => { await forkChoice.OnBlockAsync(store, signedBlock); }); return; } await forkChoice.OnBlockAsync(store, signedBlock); Root blockRoot = cryptographyService.HashTreeRoot(signedBlock.Message); BeaconBlock storedBlock = (await store.GetSignedBlockAsync(blockRoot)).Message; storedBlock.ShouldBe(signedBlock.Message); }
private async Task AddAttestationToStore(IServiceProvider testServiceProvider, IStore store, Attestation attestation) { TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); BeaconBlock parentBlock = (await store.GetSignedBlockAsync(attestation.Data.BeaconBlockRoot)).Message; Root parentRoot = cryptographyService.HashTreeRoot(parentBlock); BeaconState preState = await store.GetBlockStateAsync(parentRoot); ulong blockTime = preState.GenesisTime + (ulong)parentBlock.Slot * timeParameters.SecondsPerSlot; ulong nextEpochTime = blockTime + (ulong)timeParameters.SlotsPerEpoch * timeParameters.SecondsPerSlot; if (store.Time < blockTime) { await forkChoice.OnTickAsync(store, blockTime); } await forkChoice.OnAttestationAsync(store, attestation); }
public BlockProducer(ILogger <BlockProducer> logger, IOptionsMonitor <TimeParameters> timeParameterOptions, IOptionsMonitor <MaxOperationsPerBlock> maxOperationsPerBlockOptions, IOptionsMonitor <HonestValidatorConstants> honestValidatorConstantOptions, ICryptographyService cryptographyService, BeaconStateTransition beaconStateTransition, IForkChoice forkChoice, IStore store, IEth1DataProvider eth1DataProvider, IOperationPool operationPool) { _logger = logger; _timeParameterOptions = timeParameterOptions; _maxOperationsPerBlockOptions = maxOperationsPerBlockOptions; _honestValidatorConstantOptions = honestValidatorConstantOptions; _cryptographyService = cryptographyService; _beaconStateTransition = beaconStateTransition; _forkChoice = forkChoice; _store = store; _eth1DataProvider = eth1DataProvider; _operationPool = operationPool; }
public async Task UpdateJustifiedSingle() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; ulong secondsPerEpoch = timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch; Checkpoint checkpoint = new Checkpoint( store.JustifiedCheckpoint.Epoch + Epoch.One, new Root(Enumerable.Repeat((byte)0x55, 32).ToArray())); await store.SetBestJustifiedCheckpointAsync(checkpoint); // Act await RunOnTick(testServiceProvider, store, store.Time + secondsPerEpoch, expectNewJustifiedCheckpoint : true); // Assert }
public async Task ValidatorShouldBeActiveAfterTestGenesis(ulong index, bool shouldBeActive) { // NOTE: Test genesis has SlotsPerEpoch (8) * 10 = 80 validators. // 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); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); ValidatorIndex validatorIndex = new ValidatorIndex(index); bool validatorActive = validatorAssignments.CheckIfValidatorActive(state, validatorIndex); // Assert validatorActive.ShouldBe(shouldBeActive); }
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 async Task FutureEpochValidatorDuty() { // 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; ulong time = state.GenesisTime + 1; ulong nextSlotTime = state.GenesisTime + timeParameters.SecondsPerSlot; // half way through epoch 4 ulong futureEpoch = 4uL; ulong slots = futureEpoch * timeParameters.SlotsPerEpoch + timeParameters.SlotsPerEpoch / 2; for (ulong slot = 1; slot < slots; slot++) { while (time < nextSlotTime) { await forkChoice.OnTickAsync(store, time); time++; } await forkChoice.OnTickAsync(store, time); time++; // Hash32 head = await forkChoice.GetHeadAsync(store); // store.TryGetBlockState(head, out BeaconState headState); BeaconState headState = state; BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, headState, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, headState, block); await forkChoice.OnBlockAsync(store, signedBlock); nextSlotTime = nextSlotTime + timeParameters.SecondsPerSlot; } // halfway through slot ulong futureTime = nextSlotTime + timeParameters.SecondsPerSlot / 2; while (time < futureTime) { await forkChoice.OnTickAsync(store, time); time++; } Console.WriteLine(""); Console.WriteLine("***** State advanced to epoch {0}, slot {1}, time {2}, ready to start tests *****", futureEpoch, state.Slot, store.Time); Console.WriteLine(""); List <object?[]> data = FutureEpochValidatorDutyData().ToList(); for (int dataIndex = 0; dataIndex < data.Count; dataIndex++) { object?[] dataRow = data[dataIndex]; string publicKey = (string)dataRow[0] !; ulong epoch = (ulong)dataRow[1] !; bool success = (bool)dataRow[2] !; ulong? attestationSlot = (ulong?)dataRow[3] !; ulong attestationShard = (ulong)dataRow[4] !; ulong? blockProposalSlot = (ulong?)dataRow[5]; Console.WriteLine("** Test {0}, public key {1}, epoch {2}", dataIndex, publicKey, epoch); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); // failure expected if (!success) { Should.Throw <Exception>(async() => { 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); }, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); continue; } 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, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); Slot? expectedBlockProposalSlot = (Slot?)blockProposalSlot; Slot? expectedAttestationSlot = (Slot?)attestationSlot; Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard, $"Test {dataIndex}, public key {validatorPublicKey}, epoch {targetEpoch}"); } }