private static IEnumerable <SszElement> GetValues(DepositData item, bool forSigning)
        {
            yield return(new SszBasicVector(item.PublicKey.AsSpan()));

            yield return(new SszBasicVector(item.WithdrawalCredentials.AsSpan()));

            yield return(new SszBasicElement((ulong)item.Amount));

            if (!forSigning)
            {
                yield return(item.Signature.ToSszBasicVector());
            }
        }
Exemple #2
0
        private DepositData BuildAndSignDepositData(ulong validatorIndex, Gwei amount, SignatureDomains signatureDomains)
        {
            InitialValues initialValues = _initialValueOptions.CurrentValue;

            byte[] privateKey = GeneratePrivateKey(validatorIndex);

            // Public Key
            BLSParameters blsParameters = new BLSParameters
            {
                PrivateKey = privateKey
            };

            using BLS bls = BLS.Create(blsParameters);
            byte[] publicKeyBytes = new byte[BlsPublicKey.Length];
            bls.TryExportBlsPublicKey(publicKeyBytes, out int publicKeyBytesWritten);
            BlsPublicKey publicKey = new BlsPublicKey(publicKeyBytes);

            // Withdrawal Credentials
            Bytes32 withdrawalCredentials = _crypto.Hash(publicKey.AsSpan());

            withdrawalCredentials.Unwrap()[0] = initialValues.BlsWithdrawalPrefix;

            // Build deposit data
            DepositData depositData = new DepositData(publicKey, withdrawalCredentials, amount, BlsSignature.Zero);

            // Sign deposit data
            Domain         domain         = _beaconChainUtility.ComputeDomain(signatureDomains.Deposit);
            DepositMessage depositMessage = new DepositMessage(
                depositData.PublicKey,
                depositData.WithdrawalCredentials,
                depositData.Amount);

            Root depositMessageRoot     = _crypto.HashTreeRoot(depositMessage);
            Root depositDataSigningRoot = _beaconChainUtility.ComputeSigningRoot(depositMessageRoot, domain);

            byte[] signatureBytes = new byte[96];
            bls.TrySignData(depositDataSigningRoot.AsSpan(), signatureBytes, out int bytesWritten);

            BlsSignature depositDataSignature = new BlsSignature(signatureBytes);

            depositData.SetSignature(depositDataSignature);

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                LogDebug.QuickStartAddValidator(_logger, validatorIndex, publicKey.ToString().Substring(0, 12),
                                                null);
            }

            return(depositData);
        }
        public static DepositData DecodeDepositData(Span <byte> span)
        {
            if (span.Length != DepositData.SszLength)
            {
                ThrowSourceLength <DepositData>(span.Length, DepositData.SszLength);
            }
            int         offset    = 0;
            DepositData container = new DepositData();

            container.PublicKey             = DecodeBlsPublicKey(span, ref offset);
            container.WithdrawalCredentials = DecodeSha256(span, ref offset);
            container.Amount    = DecodeGwei(span, ref offset);
            container.Signature = DecodeBlsSignature(span, ref offset);
            return(container);
        }
Exemple #4
0
        public Deposit Place(DepositData depositData)
        {
            Ref <DepositData> depositDataRef = depositData.OrRoot;
            Root    leaf      = _crypto.HashTreeRoot(depositDataRef);
            Bytes32 leafBytes = Bytes32.Wrap(leaf.Bytes);

            DepositData.Insert(leafBytes);

            var proof = DepositData.GetProof(DepositData.Count - 1);

            Deposit deposit = new Deposit(proof, depositDataRef);

            Deposits.Add(deposit);
            return(deposit);
        }
        public static DepositData DecodeDepositData(Span <byte> span)
        {
            if (span.Length != Ssz.DepositDataLength)
            {
                ThrowSourceLength <DepositData>(span.Length, Ssz.DepositDataLength);
            }
            int          offset                = 0;
            BlsPublicKey publicKey             = DecodeBlsPublicKey(span, ref offset);
            Hash32       withdrawalCredentials = DecodeSha256(span, ref offset);
            Gwei         amount                = DecodeGwei(span, ref offset);
            BlsSignature signature             = DecodeBlsSignature(span, ref offset);
            DepositData  container             = new DepositData(publicKey, withdrawalCredentials, amount, signature);

            return(container);
        }
Exemple #6
0
        public static Deposit?DecodeDeposit(Span <byte> span)
        {
            if (span.Length != Ssz.DepositLength())
            {
                ThrowSourceLength <Deposit>(span.Length, Ssz.DepositLength());
            }
            if (span.SequenceEqual(NullDeposit()))
            {
                return(null);
            }
            Hash32[]    proof   = DecodeHashes(span.Slice(0, Ssz.DepositLengthOfProof()));
            DepositData data    = DecodeDepositData(span.Slice(Ssz.DepositLengthOfProof()));
            Deposit     deposit = new Deposit(proof, data);

            return(deposit);
        }
Exemple #7
0
        public void Deposit_data_there_and_back()
        {
            DepositData container = new DepositData(
                TestKey1,
                Sha256.Bytes32OfAnEmptyString,
                Gwei.One,
                TestSig1);
            Span <byte> encoded = new byte[Ssz.DepositDataLength];

            Ssz.Encode(encoded, container);
            DepositData decoded = Ssz.DecodeDepositData(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
        public void Deposit_data_there_and_back()
        {
            DepositData container = new DepositData();

            container.PublicKey             = BlsPublicKey.TestKey1;
            container.WithdrawalCredentials = Sha256.OfAnEmptyString;
            container.Amount    = Gwei.One;
            container.Signature = BlsSignature.TestSig1;
            Span <byte> encoded = new byte[DepositData.SszLength];

            Ssz.Encode(encoded, container);
            DepositData decoded = Ssz.DecodeDepositData(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #9
0
        public void Can_merkleize_deposit_data()
        {
            // arrange
            DepositData depositData = new DepositData(
                new BlsPublicKey(Enumerable.Repeat((byte)0x12, BlsPublicKey.Length).ToArray()),
                new Bytes32(Enumerable.Repeat((byte)0x34, Bytes32.Length).ToArray()),
                new Gwei(5),
                new BlsSignature(Enumerable.Repeat((byte)0x67, BlsSignature.Length).ToArray())
                );

            // act
            Merkle.Ize(out UInt256 root, depositData);
            Span <byte> bytes = MemoryMarshal.Cast <UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1));

            // assert
            byte[] expected = HashUtility.Hash(
                HashUtility.Hash(
                    HashUtility.Hash( // public key
                        Enumerable.Repeat((byte)0x12, 32).ToArray(),
                        HashUtility.Chunk(Enumerable.Repeat((byte)0x12, 16).ToArray())
                        ),
                    Enumerable.Repeat((byte)0x34, Bytes32.Length).ToArray()  // withdrawal credentials
                    ),
                HashUtility.Hash(
                    HashUtility.Chunk(new byte[] { 0x05 }), // amount
                    HashUtility.Hash(                       // signature
                        HashUtility.Hash(
                            Enumerable.Repeat((byte)0x67, 32).ToArray(),
                            Enumerable.Repeat((byte)0x67, 32).ToArray()
                            ),
                        HashUtility.Hash(
                            Enumerable.Repeat((byte)0x67, 32).ToArray(),
                            Enumerable.Repeat((byte)0x00, 32).ToArray()
                            )
                        )
                    )
                );

            TestContext.WriteLine("root: {0:x}", root);
            TestContext.WriteLine("bytes: {0}", bytes.ToHexString(true));
            TestContext.WriteLine("expected: {0}", expected.ToHexString(true));

            bytes.ToArray().ShouldBe(expected);
        }
Exemple #10
0
        public void Deposit_there_and_back()
        {
            DepositData data = new DepositData(
                TestKey1,
                Sha256.Bytes32OfAnEmptyString,
                Gwei.One,
                TestSig1);

            Bytes32[] proof = Enumerable.Repeat(Bytes32.Zero, Ssz.DepositContractTreeDepth + 1).ToArray();
            proof[7] = Sha256.Bytes32OfAnEmptyString;
            Deposit container = new Deposit(proof, data);

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

            Ssz.Encode(encoded, container);
            Deposit?decoded = Ssz.DecodeDeposit(encoded);

            Assert.AreEqual(container, decoded);

            Merkle.Ize(out UInt256 root, container);
        }
Exemple #11
0
        public ValueTask <ResultWrapper <DepositData[]> > deposit_getAll()
        {
            ResultWrapper <DepositData[]> result;

            if (_depositContract == null)
            {
                result = ResultWrapper <DepositData[]> .Fail("Deposit contract address not specified.", ErrorCodes.InternalError);

                return(new ValueTask <ResultWrapper <DepositData[]> >(result));
            }

            var logFilter = new LogFilter(
                1,
                new BlockParameter(0L),
                BlockParameter.Latest,
                new AddressFilter(_depositContract.ContractAddress),
                new TopicsFilter(new SpecificTopic(_depositContract.DepositEventHash)));

            var logs = _logFinder.FindLogs(logFilter);
            List <DepositData> allData = new List <DepositData>();

            foreach (FilterLog filterLog in logs)
            {
                DepositData depositData = new DepositData();
                depositData.LogIndex              = filterLog.LogIndex;
                depositData.TxIndex               = filterLog.TransactionIndex;
                depositData.BlockNumber           = filterLog.BlockNumber;
                depositData.Amount                = filterLog.Data.Slice(352, 8);
                depositData.PubKey                = filterLog.Data.Slice(192, 48);
                depositData.WithdrawalCredentials = filterLog.Data.Slice(288, 32);
                depositData.BlsSignature          = filterLog.Data.Slice(416, 96);
                allData.Add(depositData);
            }

            // foreach log

            result = ResultWrapper <DepositData[]> .Success(allData.ToArray());

            return(new ValueTask <ResultWrapper <DepositData[]> >(result));
        }
Exemple #12
0
        public static void SignDepositData(IServiceProvider testServiceProvider, DepositData depositData, byte[] privateKey, BeaconState?state)
        {
            var signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;

            Domain domain;

            if (state == null)
            {
                // Genesis
                var beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>();
                domain = beaconChainUtility.ComputeDomain(signatureDomains.Deposit);
            }
            else
            {
                var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
                domain = beaconStateAccessor.GetDomain(state, signatureDomains.Deposit, Epoch.None);
            }

            var signature = TestSecurity.BlsSign(depositData.SigningRoot(), privateKey, domain);

            depositData.SetSignature(signature);
        }
Exemple #13
0
        public static IList <DepositData> PrepareGenesisDeposits(IServiceProvider testServiceProvider, int genesisValidatorCount, Gwei amount, bool signed)
        {
            ChainConstants          chainConstants          = testServiceProvider.GetService <ChainConstants>();
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            InitialValues           initialValues           = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

            IBeaconChainUtility   beaconChainUtility    = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor   beaconStateAccessor   = testServiceProvider.GetService <BeaconStateAccessor>();
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            BlsPublicKey[] publicKeys;
            if (signed)
            {
                publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();
            }
            else
            {
                publicKeys = privateKeys.Select(x => new BlsPublicKey(x)).ToArray();
            }
            List <DepositData> depositDataList = new List <DepositData>();

            for (int validatorIndex = 0; validatorIndex < genesisValidatorCount; validatorIndex++)
            {
                BlsPublicKey publicKey  = publicKeys[validatorIndex];
                byte[]       privateKey = privateKeys[validatorIndex];
                // insecurely use pubkey as withdrawal key if no credentials provided
                byte[] withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                Bytes32     withdrawalCredentials = new Bytes32(withdrawalCredentialBytes);
                DepositData depositData           =
                    BuildDeposit(testServiceProvider, null, publicKey, privateKey, amount, withdrawalCredentials, signed);
                depositDataList.Add(depositData);
            }

            return(depositDataList);
        }
Exemple #14
0
        public static void Deposit(DepositData depositData)
        {
            if (depositData.Amount < 0.01m ||
                depositData.Percent < 0 ||
                depositData.Period <= 0)
            {
                return;
            }

            List <DepositResultRow> rows = new List <DepositResultRow>();
            decimal startAmount          = depositData.Amount;
            decimal percentAmount        = 0;

            for (int i = 1; i <= depositData.Period; i++)
            {
                decimal percent = startAmount * depositData.Percent / 1200;
                percentAmount += percent;
                DepositResultRow row = new DepositResultRow
                {
                    Period        = i,
                    StartAmount   = startAmount,
                    Percent       = percent,
                    PercentAmount = percentAmount,
                    EndAmount     = depositData.IsMontlyСapitalization
                                ? startAmount + percent
                                : i < depositData.Period ? startAmount : startAmount + percentAmount
                };
                rows.Add(row);

                if (depositData.IsMontlyСapitalization)
                {
                    startAmount += percent;
                }
            }

            depositData.Result = rows;
        }
Exemple #15
0
        public static DepositData BuildDeposit(IServiceProvider testServiceProvider, BeaconState?state, BlsPublicKey publicKey, byte[] privateKey, Gwei amount, Bytes32 withdrawalCredentials, bool signed)
        {
            // ChainConstants chainConstants = testServiceProvider.GetService<ChainConstants>();
            // IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService<IBeaconChainUtility>();
            // ICryptographyService cryptographyService = testServiceProvider.GetService<ICryptographyService>();

            DepositData depositData = BuildDepositData(testServiceProvider, publicKey, privateKey, amount, withdrawalCredentials, state, signed);

            // int index = depositDataList.Count;
            // depositDataList.Add(depositData);
            // Root root = cryptographyService.HashTreeRoot(depositDataList);
            // IEnumerable<Bytes32> allLeaves = depositDataList.Select(x => new Bytes32(cryptographyService.HashTreeRoot(x).AsSpan()));
            // IList<IList<Bytes32>> tree = TestSecurity.CalculateMerkleTreeFromLeaves(allLeaves);
            // IList<Bytes32> merkleProof = TestSecurity.GetMerkleProof(tree, index, 32);
            // List<Bytes32> proof = new List<Bytes32>(merkleProof);
            // Span<byte> indexBytes = new Span<byte>(new byte[32]);
            // BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1);
            // if (!BitConverter.IsLittleEndian)
            // {
            //     indexBytes.Slice(0, 8).Reverse();
            // }
            //
            // Bytes32 indexHash = new Bytes32(indexBytes);
            // proof.Add(indexHash);
            // Bytes32 leaf = new Bytes32(cryptographyService.HashTreeRoot(depositData).AsSpan());
            // bool checkValid = beaconChainUtility.IsValidMerkleBranch(leaf, proof, chainConstants.DepositContractTreeDepth + 1, (ulong)index, root);
            // if (!checkValid)
            // {
            //     throw new Exception($"Invalid Merkle branch for deposit for validator public key {depositData.PublicKey}");
            // }
            //
            // Deposit deposit = new Deposit(proof, depositData);
            // return (deposit, root);

            return(depositData);
        }
Exemple #16
0
        public void Can_merkleize_deposit_data_list()
        {
            // arrange
            DepositData depositData1 = new DepositData(
                new BlsPublicKey(Enumerable.Repeat((byte)0x12, BlsPublicKey.Length).ToArray()),
                new Bytes32(Enumerable.Repeat((byte)0x34, Bytes32.Length).ToArray()),
                new Gwei(5),
                new BlsSignature(Enumerable.Repeat((byte)0x67, BlsSignature.Length).ToArray())
                );
            DepositData depositData2 = new DepositData(
                new BlsPublicKey(Enumerable.Repeat((byte)0x9a, BlsPublicKey.Length).ToArray()),
                new Bytes32(Enumerable.Repeat((byte)0xbc, Bytes32.Length).ToArray()),
                new Gwei(0xd),
                new BlsSignature(Enumerable.Repeat((byte)0xef, BlsSignature.Length).ToArray())
                );
            List <DepositData> depositDataList = new List <DepositData> {
                depositData1, depositData2
            };

            // act
            Merkle.Ize(out UInt256 root, depositDataList);
            Span <byte> bytes = MemoryMarshal.Cast <UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1));

            Merkle.Ize(out UInt256 root0, depositDataList[0]);
Exemple #17
0
        public void QuickStartGenesis()
        {
            var quickStartParameters = _quickStartParameterOptions.CurrentValue;

            _logger.LogWarning(0, "Mocked quick start with genesis time {GenesisTime} and {ValidatorCount} validators.",
                               quickStartParameters.GenesisTime, quickStartParameters.ValidatorCount);

            var miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue;
            var gweiValues            = _gweiValueOptions.CurrentValue;
            var initialValues         = _initialValueOptions.CurrentValue;
            var timeParameters        = _timeParameterOptions.CurrentValue;
            var stateListLengths      = _stateListLengthOptions.CurrentValue;
            var maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue;
            var signatureDomains      = _signatureDomainOptions.CurrentValue;

            // Fixed amount
            var amount = gweiValues.MaximumEffectiveBalance;

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

            for (var validatorIndex = 0uL; validatorIndex < quickStartParameters.ValidatorCount; validatorIndex++)
            {
                var privateKey = GeneratePrivateKey(validatorIndex);

                // Public Key
                var blsParameters = new BLSParameters()
                {
                    PrivateKey = privateKey
                };
                using var bls = BLS.Create(blsParameters);
                var publicKeyBytes = new Span <byte>(new byte[BlsPublicKey.Length]);
                bls.TryExportBLSPublicKey(publicKeyBytes, out var publicKeybytesWritten);
                var publicKey = new BlsPublicKey(publicKeyBytes);

                // Withdrawal Credentials
                var withdrawalCredentialBytes = _cryptographyService.Hash(publicKey.AsSpan()).AsSpan().ToArray();
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                var withdrawalCredentials = new Hash32(withdrawalCredentialBytes);

                // Build deposit data
                var depositData = new DepositData(publicKey, withdrawalCredentials, amount);

                // Sign deposit data
                var depositDataSigningRoot = depositData.SigningRoot();
                var domain      = _beaconChainUtility.ComputeDomain(signatureDomains.Deposit);
                var destination = new Span <byte>(new byte[96]);
                bls.TrySignHash(depositDataSigningRoot.AsSpan(), destination, out var bytesWritten, domain.AsSpan());
                var depositDataSignature = new BlsSignature(destination);
                depositData.SetSignature(depositDataSignature);

                // Deposit

                // TODO: This seems a very inefficient way (copied from tests) as it recalculates the merkle tree each time
                // (you only need to add one node)

                // TODO: Add some tests around quick start, then improve

                var index = depositDataList.Count;
                depositDataList.Add(depositData);
                var root        = depositDataList.HashTreeRoot((ulong)1 << _chainConstants.DepositContractTreeDepth);
                var allLeaves   = depositDataList.Select(x => x.HashTreeRoot());
                var tree        = CalculateMerkleTreeFromLeaves(allLeaves);
                var merkleProof = GetMerkleProof(tree, index, 32);
                var proof       = new List <Hash32>(merkleProof);
                var indexBytes  = new Span <byte>(new byte[32]);
                BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1);
                if (!BitConverter.IsLittleEndian)
                {
                    indexBytes.Slice(0, 8).Reverse();
                }
                var indexHash = new Hash32(indexBytes);
                proof.Add(indexHash);
                var leaf = depositData.HashTreeRoot();
                _beaconChainUtility.IsValidMerkleBranch(leaf, proof, _chainConstants.DepositContractTreeDepth + 1, (ulong)index, root);
                var deposit = new Deposit(proof, depositData);

                _logger.LogDebug("Quick start adding deposit for mocked validator {ValidatorIndex} with public key {PublicKey}.",
                                 validatorIndex, publicKey);

                deposits.Add(deposit);
            }

            var genesisState = _beaconChain.InitializeBeaconStateFromEth1(quickStartParameters.Eth1BlockHash, quickStartParameters.Eth1Timestamp, deposits);

            // We use the state directly, and don't test IsValid
            genesisState.SetGenesisTime(quickStartParameters.GenesisTime);
            var store = _forkChoice.GetGenesisStore(genesisState);

            _logger.LogDebug("Quick start genesis store created with genesis time {GenesisTime}.", store.GenesisTime);
        }
 public Root HashTreeRoot(DepositData depositData)
 {
     throw new NotImplementedException();
 }
Exemple #19
0
        public void QuickStartGenesis()
        {
            QuickStartParameters quickStartParameters = _quickStartParameterOptions.CurrentValue;

            if (_logger.IsWarn())
            {
                Log.MockedQuickStart(_logger, quickStartParameters.GenesisTime, quickStartParameters.ValidatorCount, null);
            }

            GweiValues       gweiValues       = _gweiValueOptions.CurrentValue;
            InitialValues    initialValues    = _initialValueOptions.CurrentValue;
            SignatureDomains signatureDomains = _signatureDomainOptions.CurrentValue;

            // Fixed amount
            Gwei amount = gweiValues.MaximumEffectiveBalance;

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

            for (ulong validatorIndex = 0uL; validatorIndex < quickStartParameters.ValidatorCount; validatorIndex++)
            {
                byte[] privateKey = GeneratePrivateKey(validatorIndex);

                // Public Key
                BLSParameters blsParameters = new BLSParameters()
                {
                    PrivateKey = privateKey
                };
                using BLS bls = BLS.Create(blsParameters);
                byte[] publicKeyBytes = new byte[BlsPublicKey.Length];
                bls.TryExportBLSPublicKey(publicKeyBytes, out int publicKeyBytesWritten);
                BlsPublicKey publicKey = new BlsPublicKey(publicKeyBytes);

                // Withdrawal Credentials
                byte[] withdrawalCredentialBytes = _cryptographyService.Hash(publicKey.AsSpan()).AsSpan().ToArray();
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                Hash32 withdrawalCredentials = new Hash32(withdrawalCredentialBytes);

                // Build deposit data
                DepositData depositData = new DepositData(publicKey, withdrawalCredentials, amount);

                // Sign deposit data
                Hash32 depositDataSigningRoot = _cryptographyService.SigningRoot(depositData);
                Domain domain      = _beaconChainUtility.ComputeDomain(signatureDomains.Deposit);
                byte[] destination = new byte[96];
                bls.TrySignHash(depositDataSigningRoot.AsSpan(), destination, out int bytesWritten, domain.AsSpan());
                BlsSignature depositDataSignature = new BlsSignature(destination);
                depositData.SetSignature(depositDataSignature);

                // Deposit

                // TODO: This seems a very inefficient way (copied from tests) as it recalculates the merkle tree each time
                // (you only need to add one node)

                // TODO: Add some tests around quick start, then improve

                int index = depositDataList.Count;
                depositDataList.Add(depositData);
                //int depositDataLength = (ulong) 1 << _chainConstants.DepositContractTreeDepth;
                Hash32 root = _cryptographyService.HashTreeRoot(depositDataList);
                IEnumerable <Hash32>    allLeaves = depositDataList.Select(x => _cryptographyService.HashTreeRoot(x));
                IList <IList <Hash32> > tree      = CalculateMerkleTreeFromLeaves(allLeaves);


                IList <Hash32> merkleProof = GetMerkleProof(tree, index, 32);
                List <Hash32>  proof       = new List <Hash32>(merkleProof);
                Span <byte>    indexBytes  = new Span <byte>(new byte[32]);
                BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1);
                if (!BitConverter.IsLittleEndian)
                {
                    indexBytes.Slice(0, 8).Reverse();
                }

                Hash32 indexHash = new Hash32(indexBytes);
                proof.Add(indexHash);
                Hash32 leaf = _cryptographyService.HashTreeRoot(depositData);
                _beaconChainUtility.IsValidMerkleBranch(leaf, proof, _chainConstants.DepositContractTreeDepth + 1, (ulong)index, root);
                Deposit deposit = new Deposit(proof, depositData);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    LogDebug.QuickStartAddValidator(_logger, validatorIndex, publicKey.ToString().Substring(0, 12),
                                                    null);
                }

                deposits.Add(deposit);
            }

            BeaconState genesisState = _beaconChain.InitializeBeaconStateFromEth1(quickStartParameters.Eth1BlockHash, quickStartParameters.Eth1Timestamp, deposits);

            // We use the state directly, and don't test IsValid
            genesisState.SetGenesisTime(quickStartParameters.GenesisTime);
            IStore store = _forkChoice.GetGenesisStore(genesisState);

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                LogDebug.QuickStartStoreCreated(_logger, store.GenesisTime, null);
            }
        }
 public Hash32 SigningRoot(DepositData depositData)
 {
     return depositData.SigningRoot();
 }
 /// <summary>
 /// <see cref="IBankingService"/>
 /// </summary>
 public PaymentResponse Deposit(DepositData paymentData)
 {
     _inputValidator.Validate(paymentData);
     return(_bank.Deposit(paymentData));
 }
 public static SszContainer ToSszContainer(this DepositData item)
 {
     return(new SszContainer(GetValues(item, false)));
 }
 public Hash32 HashTreeRoot(DepositData depositData)
 {
     Merkle.Ize(out UInt256 root, depositData);
     Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1));
     return new Hash32(bytes);
 }
        public static Hash32 HashTreeRoot(this DepositData item)
        {
            var tree = new SszTree(item.ToSszContainer());

            return(new Hash32(tree.HashTreeRoot()));
        }
        public static Hash32 SigningRoot(this DepositData item)
        {
            var tree = new SszTree(new SszContainer(GetValues(item, true)));

            return(new Hash32(tree.HashTreeRoot()));
        }
Exemple #26
0
        public SszBeaconBlockBodyBenchmark()
        {
            AttestationData data = new AttestationData(
                new Slot(1),
                new CommitteeIndex(4),
                Sha256.RootOfAnEmptyString,
                new Checkpoint(new Epoch(2), Sha256.RootOfAnEmptyString),
                new Checkpoint(new Epoch(3), Sha256.RootOfAnEmptyString));

            Attestation attestation = new Attestation(
                new BitArray(new byte[5]),
                data,
                TestSig1
                );

            DepositData depositData = new DepositData(
                TestKey1,
                Sha256.Bytes32OfAnEmptyString,
                new Gwei(7),
                TestSig1);

            Deposit deposit = new Deposit(
                new Bytes32[Ssz.DepositContractTreeDepth + 1],
                depositData);

            IndexedAttestation indexedAttestation1 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            IndexedAttestation indexedAttestation2 = new IndexedAttestation(
                new ValidatorIndex[8],
                data,
                TestSig1);

            AttesterSlashing slashing = new AttesterSlashing(indexedAttestation1, indexedAttestation2);

            Eth1Data eth1Data = new Eth1Data(
                Sha256.RootOfAnEmptyString,
                9,
                Sha256.Bytes32OfAnEmptyString);

            Attestation[] attestations = new Attestation[3];
            attestations[1] = attestation;

            Deposit[] deposits = new Deposit[3];
            deposits[2] = deposit;

            Bytes32 graffiti = new Bytes32(new byte[32]);

            AttesterSlashing[] attesterSlashings = new AttesterSlashing[3];
            attesterSlashings[0] = slashing;

            ProposerSlashing[] proposerSlashings = new ProposerSlashing[10];

            BlsSignature randaoReveal = TestSig1;

            SignedVoluntaryExit[] signedVoluntaryExits = new SignedVoluntaryExit[11];

            _body = new BeaconBlockBody(randaoReveal,
                                        eth1Data,
                                        graffiti,
                                        proposerSlashings,
                                        attesterSlashings,
                                        attestations,
                                        deposits,
                                        signedVoluntaryExits);

            _encoded = new byte[Ssz.BeaconBlockBodyLength(_body)];
        }
Exemple #27
0
 public Hash32 SigningRoot(DepositData depositData)
 {
     throw new NotImplementedException();
 }
 public Root HashTreeRoot(DepositData depositData)
 {
     return(depositData.HashTreeRoot());
 }
        public void Beacon_block_body_more_detailed()
        {
            BeaconBlockBody body = new BeaconBlockBody();

            AttestationData data = new AttestationData();

            data.Slot            = new Slot(1);
            data.Source          = new Checkpoint(new Epoch(2), Sha256.OfAnEmptyString);
            data.Target          = new Checkpoint(new Epoch(3), Sha256.OfAnEmptyString);
            data.CommitteeIndex  = new CommitteeIndex(4);
            data.BeaconBlockRoot = Sha256.OfAnEmptyString;

            Attestation attestation = new Attestation();

            attestation.Data            = data;
            attestation.Signature       = BlsSignature.TestSig1;
            attestation.AggregationBits = new byte[5];

            DepositData depositData = new DepositData();

            depositData.Amount                = new Gwei(7);
            depositData.Signature             = BlsSignature.TestSig1;
            depositData.PublicKey             = BlsPublicKey.TestKey1;
            depositData.WithdrawalCredentials = Sha256.OfAnEmptyString;

            Deposit deposit = new Deposit();

            deposit.Data  = depositData;
            deposit.Proof = new Hash32[Deposit.ContractTreeDepth + 1];

            IndexedAttestation indexedAttestation1 = new IndexedAttestation();

            indexedAttestation1.Data             = data;
            indexedAttestation1.Signature        = BlsSignature.TestSig1;
            indexedAttestation1.AttestingIndices = new ValidatorIndex[8];

            IndexedAttestation indexedAttestation2 = new IndexedAttestation();

            indexedAttestation2.Data             = data;
            indexedAttestation2.Signature        = BlsSignature.TestSig1;
            indexedAttestation2.AttestingIndices = new ValidatorIndex[8];

            AttesterSlashing slashing = new AttesterSlashing();

            slashing.Attestation1 = indexedAttestation1;
            slashing.Attestation2 = indexedAttestation2;

            Eth1Data eth1Data = new Eth1Data();

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

            body.Attestations    = new Attestation[3];
            body.Attestations[1] = attestation;

            body.Deposits    = new Deposit[3];
            body.Deposits[2] = deposit;

            body.Graffiti             = new byte[32];
            body.AttesterSlashings    = new AttesterSlashing[3];
            body.AttesterSlashings[0] = slashing;
            body.Eth1Data             = eth1Data;
            body.ProposerSlashings    = new ProposerSlashing[10];
            body.RandaoReversal       = BlsSignature.TestSig1;
            body.VoluntaryExits       = new VoluntaryExit[11];

            byte[] encoded = new byte[BeaconBlockBody.SszLength(body)];
            Ssz.Encode(encoded, body);
        }
Exemple #30
0
 public DepositResponse()
 {
     this.Data = new DepositData();
 }