Example #1
0
        private static Eth1Data DecodeEth1Data(ReadOnlySpan <byte> span, ref int offset)
        {
            Eth1Data eth1Data = DecodeEth1Data(span.Slice(offset, Ssz.Eth1DataLength));

            offset += Ssz.Eth1DataLength;
            return(eth1Data);
        }
Example #2
0
        public void Beacon_block_body_there_and_back()
        {
            Eth1Data eth1Data = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                1,
                Sha256.Bytes32OfAnEmptyString);

            Deposit         zeroDeposit = new Deposit(Enumerable.Repeat(Bytes32.Zero, Ssz.DepositContractTreeDepth + 1), DepositData.Zero);
            BeaconBlockBody container   = new BeaconBlockBody(
                TestSig1,
                eth1Data,
                new Bytes32(new byte[32]),
                Enumerable.Repeat(ProposerSlashing.Zero, 2).ToArray(),
                Enumerable.Repeat(AttesterSlashing.Zero, 3).ToArray(),
                Enumerable.Repeat(Attestation.Zero, 4).ToArray(),
                Enumerable.Repeat(zeroDeposit, 5).ToArray(),
                Enumerable.Repeat(SignedVoluntaryExit.Zero, 6).ToArray()
                );

            Span <byte> encoded = new byte[Ssz.BeaconBlockBodyLength(container)];

            Ssz.Encode(encoded, container);
            BeaconBlockBody decoded = Ssz.DecodeBeaconBlockBody(encoded);

            AssertBeaconBlockBodyEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
        public void Beacon_block_body_there_and_back()
        {
            Eth1Data eth1Data = new Eth1Data(
                Sha256.OfAnEmptyString,
                1,
                Sha256.OfAnEmptyString);

            BeaconBlockBody container = new BeaconBlockBody(
                SszTest.TestSig1,
                eth1Data,
                new Bytes32(new byte[32]),
                new ProposerSlashing[2],
                new AttesterSlashing[3],
                new Attestation[4],
                new Deposit[5],
                new VoluntaryExit[6]
                );

            Span <byte> encoded = new byte[Ssz.BeaconBlockBodyLength(container)];

            Ssz.Encode(encoded, container);
            BeaconBlockBody decoded = Ssz.DecodeBeaconBlockBody(encoded);

            AssertBeaconBlockBodyEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Example #4
0
        public void Beacon_block_body_there_and_back()
        {
            Eth1Data eth1Data = new Eth1Data();

            eth1Data.BlockHash    = Sha256.OfAnEmptyString;
            eth1Data.DepositCount = 1;
            eth1Data.DepositRoot  = Sha256.OfAnEmptyString;

            BeaconBlockBody container = new BeaconBlockBody();

            container.RandaoReversal    = BlsSignature.TestSig1;
            container.Eth1Data          = eth1Data;
            container.Graffiti          = new byte[32];
            container.ProposerSlashings = new ProposerSlashing[2];
            container.AttesterSlashings = new AttesterSlashing[3];
            container.Attestations      = new Attestation[4];
            container.Deposits          = new Deposit[5];
            container.VoluntaryExits    = new VoluntaryExit[6];

            Span <byte> encoded = new byte[BeaconBlockBody.SszLength(container)];

            Ssz.Encode(encoded, container);
            BeaconBlockBody decoded = Ssz.DecodeBeaconBlockBody(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Example #5
0
        public void Eth1VoteReset()
        {
            // Arrange
            var testServiceProvider = TestSystem.BuildTestServiceProvider();
            var state = TestState.PrepareTestState(testServiceProvider);

            var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            //  skip ahead to the end of the voting period
            state.SetSlot((Slot)(timeParameters.SlotsPerEth1VotingPeriod - 1UL));

            // add a vote for each skipped slot.
            for (var index = Slot.Zero; index < state.Slot + new Slot(1); index += new Slot(1))
            {
                var eth1DepositIndex = state.Eth1DepositIndex;
                var depositRoot      = new Hash32(Enumerable.Repeat((byte)0xaa, 32).ToArray());
                var blockHash        = new Hash32(Enumerable.Repeat((byte)0xbb, 32).ToArray());
                var eth1Data         = new Eth1Data(depositRoot, eth1DepositIndex, blockHash);
                state.AddEth1DataVote(eth1Data);
            }

            // Act
            RunProcessFinalUpdates(testServiceProvider, state);

            // Assert
            state.Eth1DataVotes.Count.ShouldBe(0);
        }
Example #6
0
        private static Eth1Data DecodeEth1Data(Span <byte> span, ref int offset)
        {
            Eth1Data eth1Data = DecodeEth1Data(span.Slice(offset, Eth1Data.SszLength));

            offset += Eth1Data.SszLength;
            return(eth1Data);
        }
        public void Eth1VoteNoReset()
        {
            // Arrange
            IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider();
            BeaconState      state = TestState.PrepareTestState(testServiceProvider);

            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            timeParameters.SlotsPerEth1VotingPeriod.ShouldBeGreaterThan(timeParameters.SlotsPerEpoch);

            // skip ahead to the end of the epoch
            state.SetSlot((Slot)(timeParameters.SlotsPerEpoch - 1UL));

            // add a vote for each skipped slot.
            for (Slot index = Slot.Zero; index < state.Slot + new Slot(1); index += new Slot(1))
            {
                ulong    eth1DepositIndex = state.Eth1DepositIndex;
                Root     depositRoot      = new Root(Enumerable.Repeat((byte)0xaa, 32).ToArray());
                Bytes32  blockHash        = new Bytes32(Enumerable.Repeat((byte)0xbb, 32).ToArray());
                Eth1Data eth1Data         = new Eth1Data(depositRoot, eth1DepositIndex, blockHash);
                state.AddEth1DataVote(eth1Data);
            }

            // Act
            RunProcessFinalUpdates(testServiceProvider, state);

            // Assert
            state.Eth1DataVotes.Count.ShouldBe((int)(ulong)timeParameters.SlotsPerEpoch);
        }
Example #8
0
        private static IEnumerable <SszElement> GetValues(Eth1Data item)
        {
            yield return(item.DepositRoot.ToSszBasicVector());

            yield return(item.DepositCount.ToSszBasicElement());

            yield return(item.BlockHash.ToSszBasicVector());
        }
Example #9
0
        public BeaconState InitializeBeaconStateFromEth1(Bytes32 eth1BlockHash, ulong eth1Timestamp,
                                                         IList <Deposit> deposits)
        {
            if (_logger.IsInfo())
            {
                Log.InitializeBeaconState(_logger, eth1BlockHash, eth1Timestamp, deposits.Count, null);
            }

            InitialValues    initialValues    = _initialValueOptions.CurrentValue;
            GweiValues       gweiValues       = _gweiValueOptions.CurrentValue;
            TimeParameters   timeParameters   = _timeParameterOptions.CurrentValue;
            StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue;

            Fork fork = new Fork(initialValues.GenesisForkVersion, initialValues.GenesisForkVersion,
                                 _chainConstants.GenesisEpoch);

            ulong genesisTime = eth1Timestamp - (eth1Timestamp % timeParameters.MinimumGenesisDelay)
                                + (2 * timeParameters.MinimumGenesisDelay);
            Eth1Data eth1Data = new Eth1Data(Root.Zero, (ulong)deposits.Count, eth1BlockHash);

            Root emptyBlockBodyRoot             = _cryptographyService.HashTreeRoot(BeaconBlockBody.Zero);
            BeaconBlockHeader latestBlockHeader = new BeaconBlockHeader(emptyBlockBodyRoot);

            Bytes32[] randaoMixes = Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector)
                                    .ToArray();

            BeaconState state = new BeaconState(genesisTime, fork, eth1Data, latestBlockHeader, randaoMixes,
                                                timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector,
                                                stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength);

            // Process deposits
            List <DepositData> depositDataList = new List <DepositData>();

            foreach (Deposit deposit in deposits)
            {
                depositDataList.Add(deposit.Data);
                Root depositRoot = _cryptographyService.HashTreeRoot(depositDataList);
                state.Eth1Data.SetDepositRoot(depositRoot);
                _beaconStateTransition.ProcessDeposit(state, deposit);
            }

            // Process activations
            for (int validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++)
            {
                Validator validator        = state.Validators[validatorIndex];
                Gwei      balance          = state.Balances[validatorIndex];
                Gwei      effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement),
                                                      gweiValues.MaximumEffectiveBalance);
                validator.SetEffectiveBalance(effectiveBalance);
                if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance)
                {
                    validator.SetEligible(_chainConstants.GenesisEpoch);
                    validator.SetActive(_chainConstants.GenesisEpoch);
                }
            }

            return(state);
        }
Example #10
0
        private static void TestEth1DataSsz(byte[] serialized, UInt256 expectedMerkleRoot, string testCaseDir)
        {
            Eth1Data container = Nethermind.Ssz.Ssz.DecodeEth1Data(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);
        }
Example #11
0
        public static void Encode(Span <byte> span, Eth1Data container)
        {
            if (span.Length != Ssz.Eth1DataLength)
            {
                ThrowTargetLength <Eth1Data>(span.Length, Ssz.Eth1DataLength);
            }
            int offset = 0;

            Encode(span, container.DepositRoot, ref offset);
            Encode(span, container.DepositCount, ref offset);
            Encode(span, container.BlockHash, ref offset);
        }
        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 IAsyncEnumerable <Eth1Data> GetEth1DataDescendingAsync(ulong maximumTimestampInclusive,
                                                                            ulong minimumTimestampInclusive, [EnumeratorCancellation] CancellationToken cancellationToken)
        {
            Root head = await _forkChoice.GetHeadAsync(_store);

            BeaconState state = await _store.GetBlockStateAsync(head);

            Epoch    currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state !);
            Eth1Data eth1Data     = GetEth1DataStub(state !, currentEpoch);

            yield return(eth1Data);
        }
Example #14
0
        public static Eth1Data DecodeEth1Data(Span <byte> span)
        {
            if (span.Length != Ssz.Eth1DataLength)
            {
                ThrowSourceLength <Eth1Data>(span.Length, Ssz.Eth1DataLength);
            }
            Hash32   depositRoot  = DecodeSha256(span.Slice(0, Ssz.Hash32Length));
            ulong    depositCount = DecodeULong(span.Slice(Ssz.Hash32Length, sizeof(ulong)));
            Hash32   blockHash    = DecodeSha256(span.Slice(Ssz.Hash32Length + sizeof(ulong), Ssz.Hash32Length));
            Eth1Data container    = new Eth1Data(depositRoot, depositCount, blockHash);

            return(container);
        }
Example #15
0
        public static Eth1Data DecodeEth1Data(Span <byte> span)
        {
            if (span.Length != Eth1Data.SszLength)
            {
                ThrowSourceLength <Eth1Data>(span.Length, Eth1Data.SszLength);
            }
            Eth1Data container = new Eth1Data();

            container.DepositRoot  = DecodeSha256(span.Slice(0, Hash32.SszLength));
            container.DepositCount = DecodeULong(span.Slice(Hash32.SszLength, sizeof(ulong)));
            container.BlockHash    = DecodeSha256(span.Slice(Hash32.SszLength + sizeof(ulong), Hash32.SszLength));
            return(container);
        }
Example #16
0
        public static Eth1Data DecodeEth1Data(ReadOnlySpan <byte> span)
        {
            if (span.Length != Ssz.Eth1DataLength)
            {
                ThrowSourceLength <Eth1Data>(span.Length, Ssz.Eth1DataLength);
            }
            Root     depositRoot  = DecodeRoot(span.Slice(0, Ssz.RootLength));
            ulong    depositCount = DecodeULong(span.Slice(Ssz.RootLength, sizeof(ulong)));
            Bytes32  blockHash    = DecodeBytes32(span.Slice(Ssz.RootLength + sizeof(ulong), Ssz.Bytes32Length));
            Eth1Data container    = new Eth1Data(depositRoot, depositCount, blockHash);

            return(container);
        }
Example #17
0
        public async Task SignedBeaconBlock_RoundTripEmpty()
        {
            // Arrange
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.ConfigureNethermindCore2();

            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);

            SignedBeaconBlock signedBeaconBlock = new SignedBeaconBlock(
                beaconBlock,
                new BlsSignature(Enumerable.Repeat((byte)0x0e, 96).ToArray())
                );

            // Act - round trip to string
            await using MemoryStream outputMemoryStream = new MemoryStream();
            await JsonSerializer.SerializeAsync(outputMemoryStream, signedBeaconBlock, options);

            string jsonString = Encoding.UTF8.GetString(outputMemoryStream.ToArray());

            Console.WriteLine(jsonString);

            // Assert - Round trip

            await using MemoryStream inputMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            SignedBeaconBlock roundTripSignedBeaconBlock = await JsonSerializer.DeserializeAsync <SignedBeaconBlock>(inputMemoryStream, options);

            roundTripSignedBeaconBlock.Message.Body.Eth1Data.BlockHash.AsSpan()[1].ShouldBe((byte)0x34);
        }
Example #18
0
        public void EmptyBeaconBlockEncode()
        {
            // Arrange
            Eth1Data eth1Data = new Eth1Data(
                new Root(Enumerable.Repeat((byte)0x12, 32).ToArray()),
                64,
                new Bytes32(Enumerable.Repeat((byte)0x34, 32).ToArray()));
            BeaconBlockBody beaconBlockBody = new BeaconBlockBody(
                new BlsSignature(Enumerable.Repeat((byte)0x56, 96).ToArray()),
                eth1Data,
                new Bytes32(Enumerable.Repeat((byte)0x78, 32).ToArray()),
                new ProposerSlashing[0],
                new AttesterSlashing [0],
                new Attestation[0],
                new Deposit[0],
                new SignedVoluntaryExit[0]
                );
            BeaconBlock beaconBlock = new BeaconBlock(
                Slot.One,
                new Root(Enumerable.Repeat((byte)0x9a, 32).ToArray()),
                new Root(Enumerable.Repeat((byte)0xbc, 32).ToArray()),
                beaconBlockBody
                );

            // Act
            Span <byte> encoded = new byte[Ssz.BeaconBlockLength(beaconBlock)];

            Ssz.Encode(encoded, beaconBlock);

            // Assert
            string expectedHex =
                // static
                "0100000000000000" +
                "9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a9a" +
                "bcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbcbc" +
                "4c000000" + // body dynamic offset 8+32+32+4 = 76 = 0x4c
                // dynamic
                // - body - static
                "565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656565656" +
                "1212121212121212121212121212121212121212121212121212121212121212" +
                "4000000000000000" +
                "3434343434343434343434343434343434343434343434343434343434343434" +
                "7878787878787878787878787878787878787878787878787878787878787878" +
                "dc000000" + // proposer dynamic offset 96+(32+8+32)+32 + 5*4 = 220 = 0xdc
                "dc000000" + // attester slashings & all remaining offsets are the same, as they are empty
                "dc000000" +
                "dc000000" +
                "dc000000"; // body - dynamic part is empty

            encoded.ToHexString().ShouldBe(expectedHex);
        }
Example #19
0
        public async Task <Eth1Data> GetEth1DataAsync(ulong distance)
        {
            if (!_storeProvider.TryGetStore(out IStore? store))
            {
                throw new Exception("Store not available.");
            }

            Hash32 head = await _forkChoice.GetHeadAsync(store !);

            BeaconState state        = await store !.GetBlockStateAsync(head);
            Epoch       currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state !);
            Eth1Data    eth1Data     = GetEth1DataStub(state !, currentEpoch);

            return(eth1Data);
        }
Example #20
0
        public void Eth1_data_there_and_back()
        {
            Eth1Data container = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                1,
                Sha256.Bytes32OfAnEmptyString);
            Span <byte> encoded = new byte[Ssz.Eth1DataLength];

            Ssz.Encode(encoded, container);
            Eth1Data decoded = Ssz.DecodeEth1Data(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Example #21
0
        public static void Ize(out UInt256 root, Eth1Data container)
        {
            if (container == null)
            {
                root = RootOfNull;
                return;
            }

            Merkleizer merkleizer = new Merkleizer(2);

            merkleizer.Feed(container.DepositRoot);
            merkleizer.Feed(container.DepositCount);
            merkleizer.Feed(container.BlockHash);
            merkleizer.CalculateRoot(out root);
        }
Example #22
0
        public void Eth1_data_there_and_back()
        {
            Eth1Data container = new Eth1Data();

            container.BlockHash    = Sha256.OfAnEmptyString;
            container.DepositCount = 1;
            container.DepositRoot  = Sha256.OfAnEmptyString;
            Span <byte> encoded = new byte[Eth1Data.SszLength];

            Ssz.Encode(encoded, container);
            Eth1Data decoded = Ssz.DecodeEth1Data(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Example #23
0
        public Eth1Data GetEth1DataStub(BeaconState state, Epoch currentEpoch)
        {
            TimeParameters timeParameters = _timeParameterOptions.CurrentValue;

            uint        epochsPerPeriod   = timeParameters.SlotsPerEth1VotingPeriod / timeParameters.SlotsPerEpoch;
            ulong       votingPeriod      = (ulong)currentEpoch / epochsPerPeriod;
            Span <byte> votingPeriodBytes = stackalloc byte[32];

            BinaryPrimitives.WriteUInt64LittleEndian(votingPeriodBytes, votingPeriod);
            Hash32 depositRoot = _cryptographyService.Hash(votingPeriodBytes);

            ulong  depositCount = state.Eth1DepositIndex;
            Hash32 blockHash    = _cryptographyService.Hash(depositRoot.AsSpan());

            Eth1Data eth1Data = new Eth1Data(depositRoot, depositCount, blockHash);

            return(eth1Data);
        }
Example #24
0
        public void BasicEth1DataDecode()
        {
            // Arrange
            string hex =
                "1212121212121212121212121212121212121212121212121212121212121212" +
                "4000000000000000" +
                "3434343434343434343434343434343434343434343434343434343434343434";

            byte[] bytes = Bytes.FromHexString(hex);

            // Act
            Eth1Data eth1Data = Ssz.DecodeEth1Data(bytes);

            // Assert
            eth1Data.DepositRoot.AsSpan().ToArray().ShouldBe(Enumerable.Repeat((byte)0x12, 32).ToArray());
            eth1Data.DepositCount.ShouldBe(64uL);
            eth1Data.BlockHash.AsSpan().ToArray().ShouldBe(Enumerable.Repeat((byte)0x34, 32).ToArray());
        }
Example #25
0
        public static Eth1Data[] DecodeEth1Datas(Span <byte> span)
        {
            if (span.Length % Ssz.Eth1DataLength != 0)
            {
                ThrowInvalidSourceArrayLength <Eth1Data>(span.Length, Ssz.Eth1DataLength);
            }
            int count = span.Length / Ssz.Eth1DataLength;

            Eth1Data[] containers = new Eth1Data[count];
            int        offset     = 0;

            for (int i = 0; i < count; i++)
            {
                containers[i] = DecodeEth1Data(span, ref offset);
            }

            return(containers);
        }
Example #26
0
        public BeaconState InitializeBeaconStateFromEth1(Hash32 eth1BlockHash, ulong eth1Timestamp, IEnumerable <Deposit> deposits)
        {
            _logger.LogDebug(Event.InitializeBeaconState, "Initialise beacon state from ETH1 block {Eth1BlockHash}, time {Eth1Timestamp}, with {DepositCount} deposits.", eth1BlockHash, eth1Timestamp, deposits.Count());

            var gweiValues       = _gweiValueOptions.CurrentValue;
            var initialValues    = _initialValueOptions.CurrentValue;
            var timeParameters   = _timeParameterOptions.CurrentValue;
            var stateListLengths = _stateListLengthOptions.CurrentValue;

            var genesisTime = eth1Timestamp - (eth1Timestamp % _chainConstants.SecondsPerDay)
                              + (2 * _chainConstants.SecondsPerDay);
            var eth1Data          = new Eth1Data((ulong)deposits.Count(), eth1BlockHash);
            var emptyBlockBody    = new BeaconBlockBody();
            var latestBlockHeader = new BeaconBlockHeader(emptyBlockBody.HashTreeRoot(_miscellaneousParameterOptions.CurrentValue, _maxOperationsPerBlockOptions.CurrentValue));
            var state             = new BeaconState(genesisTime, 0, eth1Data, latestBlockHeader, timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, _chainConstants.JustificationBitsLength);

            // Process deposits
            var depositDataList = new List <DepositData>();

            foreach (var deposit in deposits)
            {
                depositDataList.Add(deposit.Data);
                var depositRoot = depositDataList.HashTreeRoot(_chainConstants.MaximumDepositContracts);
                state.Eth1Data.SetDepositRoot(depositRoot);
                _beaconStateTransition.ProcessDeposit(state, deposit);
            }

            // Process activations
            for (var validatorIndex = 0; validatorIndex < state.Validators.Count; validatorIndex++)
            {
                var validator        = state.Validators[validatorIndex];
                var balance          = state.Balances[validatorIndex];
                var effectiveBalance = Gwei.Min(balance - (balance % gweiValues.EffectiveBalanceIncrement), gweiValues.MaximumEffectiveBalance);
                validator.SetEffectiveBalance(effectiveBalance);
                if (validator.EffectiveBalance == gweiValues.MaximumEffectiveBalance)
                {
                    validator.SetEligible(initialValues.GenesisEpoch);
                    validator.SetActive(initialValues.GenesisEpoch);
                }
            }

            return(state);
        }
Example #27
0
        public static BeaconBlock BuildEmptyBlock(IServiceProvider testServiceProvider, BeaconState state, Slot slot, bool signed)
        {
            //if (slot) is none

            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            StateListLengths        stateListLengths        = testServiceProvider.GetService <IOptions <StateListLengths> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;
            ICryptographyService    cryptographyService     = testServiceProvider.GetService <ICryptographyService>();

            Eth1Data eth1Data = new Eth1Data(state.Eth1DepositIndex, Hash32.Zero);

            BeaconBlockHeader previousBlockHeader = BeaconBlockHeader.Clone(state.LatestBlockHeader);

            if (previousBlockHeader.StateRoot == Hash32.Zero)
            {
                Hash32 stateRoot = cryptographyService.HashTreeRoot(state);
                previousBlockHeader.SetStateRoot(stateRoot);
            }
            Hash32 previousBlockSigningRoot = previousBlockHeader.SigningRoot();

            BeaconBlock emptyBlock = new BeaconBlock(slot,
                                                     previousBlockSigningRoot,
                                                     Hash32.Zero,
                                                     new BeaconBlockBody(
                                                         BlsSignature.Empty,
                                                         eth1Data,
                                                         new Bytes32(),
                                                         Array.Empty <ProposerSlashing>(),
                                                         Array.Empty <AttesterSlashing>(),
                                                         Array.Empty <Attestation>(),
                                                         Array.Empty <Deposit>(),
                                                         Array.Empty <VoluntaryExit>()
                                                         ),
                                                     BlsSignature.Empty);

            if (signed)
            {
                SignBlock(testServiceProvider, state, emptyBlock, ValidatorIndex.None);
            }

            return(emptyBlock);
        }
Example #28
0
        public void Beacon_block_there_and_back()
        {
            Eth1Data eth1Data = new Eth1Data();

            eth1Data.BlockHash    = Sha256.OfAnEmptyString;
            eth1Data.DepositCount = 1;
            eth1Data.DepositRoot  = Sha256.OfAnEmptyString;

            BeaconBlockBody beaconBlockBody = new BeaconBlockBody();

            beaconBlockBody.RandaoReversal    = BlsSignature.TestSig1;
            beaconBlockBody.Eth1Data          = eth1Data;
            beaconBlockBody.Graffiti          = new byte[32];
            beaconBlockBody.ProposerSlashings = new ProposerSlashing[2];
            beaconBlockBody.AttesterSlashings = new AttesterSlashing[3];
            beaconBlockBody.Attestations      = new Attestation[4];
            beaconBlockBody.Deposits          = new Deposit[5];
            beaconBlockBody.VoluntaryExits    = new VoluntaryExit[6];

            BeaconBlock container = new BeaconBlock();

            container.Body       = beaconBlockBody;
            container.Signature  = BlsSignature.TestSig1;
            container.Slot       = new Slot(1);
            container.ParentRoot = Sha256.OfAnEmptyString;
            container.StateRoot  = Sha256.OfAnEmptyString;

            Span <byte> encoded = new byte[BeaconBlock.SszLength(container)];

            Ssz.Encode(encoded, container);
            BeaconBlock decoded = Ssz.DecodeBeaconBlock(encoded);

            Assert.AreEqual(container, decoded);

            Span <byte> encodedAgain = new byte[BeaconBlock.SszLength(container)];

            Ssz.Encode(encodedAgain, decoded);
            Assert.True(Bytes.AreEqual(encodedAgain, encoded));

            Merkle.Ize(out UInt256 root, container);
        }
Example #29
0
        public void BasicEth1DataEncode()
        {
            // Arrange
            Eth1Data eth1Data = new Eth1Data(
                new Root(Enumerable.Repeat((byte)0x12, 32).ToArray()),
                64,
                new Bytes32(Enumerable.Repeat((byte)0x34, 32).ToArray()));

            // Act
            Span <byte> encoded = new byte[Ssz.Eth1DataLength];

            Ssz.Encode(encoded, eth1Data);

            // Assert
            string expectedHex =
                "1212121212121212121212121212121212121212121212121212121212121212" +
                "4000000000000000" +
                "3434343434343434343434343434343434343434343434343434343434343434";

            encoded.ToHexString().ShouldBe(expectedHex);
        }
        public static BeaconBlockBody DecodeBeaconBlockBody(Span <byte> span)
        {
            // static part

            int          offset       = 0;
            BlsSignature randaoReveal = DecodeBlsSignature(span, ref offset);
            Eth1Data     eth1Data     = DecodeEth1Data(span, ref offset);
            Bytes32      graffiti     = new Bytes32(DecodeBytes32(span, ref offset));

            DecodeDynamicOffset(span, ref offset, out int dynamicOffset1);
            DecodeDynamicOffset(span, ref offset, out int dynamicOffset2);
            DecodeDynamicOffset(span, ref offset, out int dynamicOffset3);
            DecodeDynamicOffset(span, ref offset, out int dynamicOffset4);
            DecodeDynamicOffset(span, ref offset, out int dynamicOffset5);

            // var part

            int proposerSlashingsLength = dynamicOffset2 - dynamicOffset1;
            int attesterSlashingsLength = dynamicOffset3 - dynamicOffset2;
            int attestationsLength      = dynamicOffset4 - dynamicOffset3;
            int depositsLength          = dynamicOffset5 - dynamicOffset4;
            int voluntaryExitsLength    = span.Length - dynamicOffset5;

            ProposerSlashing[] proposerSlashings = DecodeProposerSlashings(span.Slice(dynamicOffset1, proposerSlashingsLength));
            AttesterSlashing[] attesterSlashings = DecodeAttesterSlashings(span.Slice(dynamicOffset2, attesterSlashingsLength));
            Attestation[]      attestations      = DecodeAttestations(span.Slice(dynamicOffset3, attestationsLength));
            Deposit[]          deposits          = DecodeDeposits(span.Slice(dynamicOffset4, depositsLength));
            VoluntaryExit[]    voluntaryExits    = DecodeVoluntaryExits(span.Slice(dynamicOffset5, voluntaryExitsLength));

            BeaconBlockBody container = new BeaconBlockBody(randaoReveal,
                                                            eth1Data,
                                                            graffiti,
                                                            proposerSlashings,
                                                            attesterSlashings,
                                                            attestations,
                                                            deposits,
                                                            voluntaryExits);

            return(container);
        }