public async Task ShouldGetStatusWhenSyncComplete()
        {
            // Arrange
            Slot            starting           = Slot.One;
            Slot            current            = new Slot(11);
            Slot            highest            = new Slot(11);
            INetworkPeering mockNetworkPeering = Substitute.For <INetworkPeering>();

            mockNetworkPeering.HighestPeerSlot.Returns(highest);
            mockNetworkPeering.SyncStartingSlot.Returns(starting);
            IStore            mockStore   = Substitute.For <IStore>();
            Root              root        = new Root(Enumerable.Repeat((byte)0x12, 32).ToArray());
            Checkpoint        checkpoint  = new Checkpoint(Epoch.Zero, root);
            SignedBeaconBlock signedBlock =
                new SignedBeaconBlock(new BeaconBlock(current, Root.Zero, Root.Zero, BeaconBlockBody.Zero),
                                      BlsSignature.Zero);
            BeaconState state = TestState.Create(slot: current, finalizedCheckpoint: checkpoint);

            mockStore.GetHeadAsync().Returns(root);
            mockStore.GetSignedBlockAsync(root).Returns(signedBlock);
            mockStore.GetBlockStateAsync(root).Returns(state);
            mockStore.IsInitialized.Returns(true);
            mockStore.JustifiedCheckpoint.Returns(checkpoint);

            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton(mockNetworkPeering);
            testServiceCollection.AddSingleton(mockStore);
            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            testServiceCollection.AddSingleton <IEth1DataProvider>(Substitute.For <IEth1DataProvider>());
            testServiceCollection.AddSingleton <IOperationPool>(Substitute.For <IOperationPool>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

            // Act
            IBeaconNodeApi beaconNode = testServiceProvider.GetService <IBeaconNodeApi>();

            beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade));

            ApiResponse <Syncing> syncingResponse = await beaconNode.GetSyncingAsync(CancellationToken.None);

            Syncing syncing = syncingResponse.Content;

            // Assert
            syncing.IsSyncing.ShouldBeFalse();
            syncing.SyncStatus !.StartingSlot.ShouldBe(Slot.One);
            syncing.SyncStatus.CurrentSlot.ShouldBe(new Slot(11));
            syncing.SyncStatus.HighestSlot.ShouldBe(new Slot(11));
        }
Exemple #2
0
        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 = 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);
        }
Exemple #3
0
        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);
        }
Exemple #4
0
        public void BasicGetCommitteeAssignment(ulong index, ulong slot, ulong committeeIndex)
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state = TestState.PrepareTestState(testServiceProvider);

            // Act
            ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>();
            ValidatorIndex       validatorIndex       = new ValidatorIndex(index);
            CommitteeAssignment  committeeAssignment  = validatorAssignments.GetCommitteeAssignment(state, Epoch.Zero, validatorIndex);

            // Assert
            Console.WriteLine("Validator [{0}] {1} in slot {2} committee {3}",
                              validatorIndex, state.Validators[(int)validatorIndex].PublicKey, committeeAssignment.Slot, committeeAssignment.CommitteeIndex);

            Slot           expectedSlot           = new Slot(slot);
            CommitteeIndex expectedCommitteeIndex = new CommitteeIndex(committeeIndex);

            committeeAssignment.Slot.ShouldBe(expectedSlot);
            committeeAssignment.CommitteeIndex.ShouldBe(expectedCommitteeIndex);
        }
Exemple #5
0
        // [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() sometimes 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.

            // The implementation of GetValidatorDuties will always return the first assigned slot in an epoch.
            // This means it is consistent whether run before or after the first slot.

            // 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 = (Slot?)blockProposalSlot;
            Slot  expectedAttestationSlot   = new Slot(attestationSlot);
            Shard expectedAttestationShard  = new Shard(attestationShard);

            validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot);
            validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot);
            validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard);
        }
Exemple #6
0
        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}");
            }
        }
Exemple #7
0
        public async Task BasicNewBlock()
        {
            // Arrange
            int numberOfValidators = 64;
            int genesisTime        = 1578009600;
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            IConfigurationRoot configuration         = new ConfigurationBuilder()
                                                       .AddInMemoryCollection(new Dictionary <string, string>
            {
                ["QuickStart:ValidatorCount"] = $"{numberOfValidators}",
                ["QuickStart:GenesisTime"]    = $"{genesisTime}"
            })
                                                       .Build();

            testServiceCollection.AddBeaconNodeQuickStart(configuration);
            testServiceCollection.AddBeaconNodeEth1Bridge(configuration);
            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

            Eth1BridgeWorker eth1BridgeWorker =
                testServiceProvider.GetServices <IHostedService>().OfType <Eth1BridgeWorker>().First();
            await eth1BridgeWorker.ExecuteEth1GenesisAsync(CancellationToken.None);

            IBeaconNodeApi     beaconNode   = testServiceProvider.GetService <IBeaconNodeApi>();
            ApiResponse <Fork> forkResponse = await beaconNode.GetNodeForkAsync(CancellationToken.None);

            Fork fork = forkResponse.Content;

            fork.CurrentVersion.ShouldBe(new ForkVersion(new byte[4] {
                0x00, 0x00, 0x00, 0x01
            }));

            // Act
            BlockProducer blockProducer = testServiceProvider.GetService <BlockProducer>();
            Slot          targetSlot    = new Slot(1);

            // With QuickStart64, proposer for Slot 1 is validator index 29, 0xa98ed496...
            QuickStartMockEth1GenesisProvider quickStartMockEth1GenesisProvider = (QuickStartMockEth1GenesisProvider)testServiceProvider.GetService <IEth1GenesisProvider>();

            byte[]       privateKey   = quickStartMockEth1GenesisProvider.GeneratePrivateKey(29);
            BlsSignature randaoReveal = GetEpochSignature(testServiceProvider, privateKey, fork.CurrentVersion, targetSlot);

            // value for quickstart 20/64, fork 0, slot 1
            randaoReveal.ToString().StartsWith("0x932f8730");
            BeaconBlock newBlock = await blockProducer.NewBlockAsync(targetSlot, randaoReveal, CancellationToken.None);

            // Assert
            newBlock.Slot.ShouldBe(targetSlot);
            newBlock.Body.RandaoReveal.ShouldBe(randaoReveal);

            newBlock.ParentRoot.ToString().ShouldStartWith("0x4d4e9a16");

            newBlock.Body.Eth1Data.DepositCount.ShouldBe((ulong)numberOfValidators);

            newBlock.Body.Eth1Data.DepositRoot.ToString().ShouldStartWith("0x66687aad");

            newBlock.StateRoot.ToString().ShouldStartWith("0x0138b69f");

            newBlock.Body.Attestations.Count.ShouldBe(0);
            newBlock.Body.Deposits.Count.ShouldBe(0);
        }
        public async Task TestValidators80DutiesForEpochZeroHaveExactlyOneProposerPerSlot()
        {
            // 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);

            TimeParameters timeParameters     = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            int            numberOfValidators = state.Validators.Count;

            Console.WriteLine("Number of validators: {0}", numberOfValidators);
            BlsPublicKey[] publicKeys  = TestKeys.PublicKeys(timeParameters).ToArray();
            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            for (int index = 0; index < numberOfValidators; index++)
            {
                Console.WriteLine("[{0}] priv:{1} pub:{2}", index, "0x" + BitConverter.ToString(privateKeys[index]).Replace("-", ""), publicKeys[index]);
            }

            // Act
            Epoch          targetEpoch         = new Epoch(0);
            var            validatorPublicKeys = publicKeys.Take(numberOfValidators).ToList();
            IBeaconNodeApi beaconNode          = testServiceProvider.GetService <IBeaconNodeApi>();

            beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade));

            int validatorDutyIndex = 0;
            List <ValidatorDuty> validatorDuties = new List <ValidatorDuty>();
            var validatorDutiesResponse          =
                await beaconNode.ValidatorDutiesAsync(validatorPublicKeys, targetEpoch, CancellationToken.None);

            foreach (ValidatorDuty validatorDuty in validatorDutiesResponse.Content)
            {
                validatorDuties.Add(validatorDuty);
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  validatorDutyIndex, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
                validatorDutyIndex++;
            }

            Console.WriteLine();
            Console.WriteLine("** ValidatorDuty summary");
            foreach (ValidatorDuty validatorDuty in validatorDuties)
            {
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  validatorDutyIndex, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
            }

            // Assert
            Dictionary <Slot, IGrouping <Slot, ValidatorDuty> > groupsByProposalSlot = validatorDuties
                                                                                       .Where(x => x.BlockProposalSlot.HasValue)
                                                                                       .GroupBy(x => x.BlockProposalSlot !.Value)
                                                                                       .ToDictionary(x => x.Key, x => x);

            groupsByProposalSlot[new Slot(0)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(1)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(2)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(3)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(4)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(5)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(6)].Count().ShouldBe(1);
            //groupsByProposalSlot[new Slot(7)].Count().ShouldBe(1);
            validatorDuties.Count(x => !x.BlockProposalSlot.HasValue).ShouldBe(numberOfValidators - 7);
        }
        public async Task QuickStart64DutiesForEpochZeroHaveExactlyOneProposerPerSlot()
        {
            // Arrange
            int numberOfValidators = 64;
            int genesisTime        = 1578009600;
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            IConfigurationRoot configuration         = new ConfigurationBuilder()
                                                       .AddInMemoryCollection(new Dictionary <string, string>
            {
                ["QuickStart:ValidatorCount"] = $"{numberOfValidators}",
                ["QuickStart:GenesisTime"]    = $"{genesisTime}"
            })
                                                       .Build();

            testServiceCollection.AddBeaconNodeEth1Bridge(configuration);
            testServiceCollection.AddBeaconNodeQuickStart(configuration);
            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

            Eth1BridgeWorker eth1BridgeWorker =
                testServiceProvider.GetServices <IHostedService>().OfType <Eth1BridgeWorker>().First();
            await eth1BridgeWorker.ExecuteEth1GenesisAsync(CancellationToken.None);

            IStore      store = testServiceProvider.GetService <IStore>();
            BeaconState state = await store !.GetBlockStateAsync(store.FinalizedCheckpoint.Root);

            // Act
            Epoch          targetEpoch         = new Epoch(0);
            var            validatorPublicKeys = state !.Validators.Select(x => x.PublicKey).ToList();
            IBeaconNodeApi beaconNode          = testServiceProvider.GetService <IBeaconNodeApi>();

            beaconNode.ShouldBeOfType(typeof(BeaconNodeFacade));

            int validatorDutyIndex = 0;
            List <ValidatorDuty> validatorDuties = new List <ValidatorDuty>();
            var validatorDutiesResponse          =
                await beaconNode.ValidatorDutiesAsync(validatorPublicKeys, targetEpoch, CancellationToken.None);

            foreach (ValidatorDuty validatorDuty in validatorDutiesResponse.Content)
            {
                validatorDuties.Add(validatorDuty);
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  validatorDutyIndex, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
                validatorDutyIndex++;
            }

            Console.WriteLine();
            Console.WriteLine("** ValidatorDuty summary");
            foreach (ValidatorDuty validatorDuty in validatorDuties)
            {
                Console.WriteLine("Index [{0}], Epoch {1}, Validator {2}, : attestation slot {3}, shard {4}, proposal slot {5}",
                                  validatorDutyIndex, targetEpoch, validatorDuty.ValidatorPublicKey, validatorDuty.AttestationSlot,
                                  (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
            }

            // Assert
            Dictionary <Slot, IGrouping <Slot, ValidatorDuty> > groupsByProposalSlot = validatorDuties
                                                                                       .Where(x => x.BlockProposalSlot.HasValue)
                                                                                       .GroupBy(x => x.BlockProposalSlot !.Value)
                                                                                       .ToDictionary(x => x.Key, x => x);

            groupsByProposalSlot[new Slot(0)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(1)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(2)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(3)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(4)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(5)].Count().ShouldBe(1);
            groupsByProposalSlot[new Slot(6)].Count().ShouldBe(1);
            //groupsByProposalSlot[new Slot(7)].Count().ShouldBe(1);
            //groupsByProposalSlot[Slot.None].Count().ShouldBe(numberOfValidators - 8);
        }
        public async Task BasicNewBlock()
        {
            // Arrange
            int numberOfValidators = 64;
            int genesisTime        = 1578009600;
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            IConfigurationRoot configuration         = new ConfigurationBuilder()
                                                       .AddInMemoryCollection(new Dictionary <string, string>
            {
                ["QuickStart:ValidatorCount"] = $"{numberOfValidators}",
                ["QuickStart:GenesisTime"]    = $"{genesisTime}"
            })
                                                       .Build();

            testServiceCollection.AddBeaconNodeQuickStart(configuration);
            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

            QuickStart quickStart = (QuickStart)testServiceProvider.GetService <INodeStart>();
            await quickStart.InitializeNodeAsync();

            IBeaconNodeApi beaconNode = testServiceProvider.GetService <IBeaconNodeApi>();

            Core2.Containers.Fork fork = await beaconNode.GetNodeForkAsync(CancellationToken.None);

            fork.CurrentVersion.ShouldBe(new ForkVersion());

            // Act
            BlockProducer blockProducer = testServiceProvider.GetService <BlockProducer>();
            Slot          targetSlot    = new Slot(1);

            // With QuickStart64, proposer for Slot 1 is validator index 20, 0xa1c76af1...
            byte[]       privateKey   = quickStart.GeneratePrivateKey(20);
            BlsSignature randaoReveal = GetEpochSignature(testServiceProvider, privateKey, fork.CurrentVersion, targetSlot);

            // value for quickstart 20/64, fork 0, slot 1
            randaoReveal.ToString().ShouldBe("0xa3426b6391a29c88f2280428d5fdae9e20f4c75a8d38d0714e3aa5b9e55594dbd555c4bc685191e83d39158c3be9744d06adc34b21d2885998a206e3b3fd435eab424cf1c01b8fd562deb411348a601e83d7332d8774d1fd3bf8b88d7a33c67c");
            BeaconBlock newBlock = await blockProducer.NewBlockAsync(targetSlot, randaoReveal);

            // Assert
            newBlock.Slot.ShouldBe(targetSlot);
            newBlock.Body.RandaoReveal.ShouldBe(randaoReveal);

            Hash32 expectedParentRoot = new Hash32("0x91b06cbcd6dc97b89dc8b95e0b01a497932683b182e6c722ddfa10cd005b2180");

            newBlock.ParentRoot.ShouldBe(expectedParentRoot);

            newBlock.Body.Eth1Data.DepositCount.ShouldBe((ulong)numberOfValidators);

            Hash32 expectedEth1DataDepositRoot = new Hash32("0x66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925");

            newBlock.Body.Eth1Data.DepositRoot.ShouldBe(expectedEth1DataDepositRoot);

            Hash32 expectedStateRoot = new Hash32("0xe05ccf6347cac0b0dab0ad0d5c941fe7c7e2ed4c69550ed9a628bc9d62914242");

            newBlock.StateRoot.ShouldBe(expectedStateRoot);

            newBlock.Signature.ShouldBe(new BlsSignature(new byte[96])); // signature should be empty

            newBlock.Body.Attestations.Count.ShouldBe(0);
            newBlock.Body.Deposits.Count.ShouldBe(0);
        }
Exemple #11
0
        public async Task 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)
                {
                    await forkChoice.OnTickAsync(store, time);

                    time++;
                }

                await forkChoice.OnTickAsync(store, time);

                time++;
                BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true);
                TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
                await forkChoice.OnBlockAsync(store, block);

                await forkChoice.OnTickAsync(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 (int 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);
            }
        }