Exemplo n.º 1
0
        /// <summary>
        /// Prepare the state for the deposit, and create a deposit for the given validator, depositing the given amount.
        /// </summary>
        public static Deposit PrepareStateAndDeposit(IServiceProvider testServiceProvider, BeaconState state, ValidatorIndex validatorIndex, Gwei amount, Bytes32 withdrawalCredentials, bool signed)
        {
            ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>();
            InitialValues  initialValues  = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            IBeaconChainUtility beaconChainUtility  = testServiceProvider.GetService <IBeaconChainUtility>();
            BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();
            IDepositStore       depositStore        = testServiceProvider.GetService <IDepositStore>();

            byte[][]       privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            BlsPublicKey[] publicKeys  = TestKeys.PublicKeys(timeParameters).ToArray();
            byte[]         privateKey  = privateKeys[(int)(ulong)validatorIndex];
            BlsPublicKey   publicKey   = publicKeys[(int)(ulong)validatorIndex];

            if (withdrawalCredentials == Bytes32.Zero)
            {
                // insecurely use pubkey as withdrawal key if no credentials provided
                byte[] withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                withdrawalCredentials        = new Bytes32(withdrawalCredentialBytes);
            }

            DepositData depositData = BuildDeposit(testServiceProvider, state, publicKey, privateKey, amount, withdrawalCredentials, signed);
            Deposit     deposit     = depositStore.Place(depositData);

            state.SetEth1DepositIndex(0);
            state.Eth1Data.SetDepositRoot(depositStore.DepositData.Root);
            state.Eth1Data.SetDepositCount((ulong)depositStore.Deposits.Count);

            return(deposit);
        }
Exemplo n.º 2
0
        public static void SignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block, ValidatorIndex proposerIndex)
        {
            MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            TimeParameters          timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            MaxOperationsPerBlock   maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;
            SignatureDomains        signatureDomains        = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;

            ICryptographyService  cryptographyService   = testServiceProvider.GetService <ICryptographyService>();
            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor   beaconStateAccessor   = testServiceProvider.GetService <BeaconStateAccessor>();
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            if (state.Slot > block.Slot)
            {
                throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Slot of block must be equal or less that state slot {state.Slot}");
            }

            Epoch blockEpoch = beaconChainUtility.ComputeEpochAtSlot(block.Slot);

            if (proposerIndex == ValidatorIndex.None)
            {
                if (block.Slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (stateEpoch + 1 > blockEpoch)
                    {
                        Console.WriteLine("WARNING: Block slot far away, and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.");
                    }
                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, block.Slot);
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState);
                }
            }

            byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            byte[]   privateKey  = privateKeys[(int)(ulong)proposerIndex];

            Domain       randaoDomain     = beaconStateAccessor.GetDomain(state, signatureDomains.Randao, blockEpoch);
            Hash32       randaoRevealHash = blockEpoch.HashTreeRoot();
            BlsSignature randaoReveal     = TestSecurity.BlsSign(randaoRevealHash, privateKey, randaoDomain);

            block.Body.SetRandaoReveal(randaoReveal);

            Domain       signatureDomain = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, blockEpoch);
            Hash32       signingRoot     = cryptographyService.SigningRoot(block);
            BlsSignature signature       = TestSecurity.BlsSign(signingRoot, privateKey, signatureDomain);

            block.SetSignature(signature);
        }
Exemplo n.º 3
0
        public static SignedBeaconBlock SignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block, ValidatorIndex?optionalProposerIndex)
        {
            TimeParameters   timeParameters   = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            SignatureDomains signatureDomains = testServiceProvider.GetService <IOptions <SignatureDomains> >().Value;

            ICryptographyService  cryptographyService   = testServiceProvider.GetService <ICryptographyService>();
            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor   beaconStateAccessor   = testServiceProvider.GetService <BeaconStateAccessor>();
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

            if (state.Slot > block.Slot)
            {
                throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Slot of block must be equal or less that state slot {state.Slot}");
            }

            Epoch          blockEpoch = beaconChainUtility.ComputeEpochAtSlot(block.Slot);
            ValidatorIndex proposerIndex;

            if (optionalProposerIndex.HasValue)
            {
                proposerIndex = optionalProposerIndex.Value;
            }
            else
            {
                if (block.Slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (stateEpoch + 1 > blockEpoch)
                    {
                        Console.WriteLine("WARNING: Block slot far away, and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.");
                    }
                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, block.Slot);
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState);
                }
            }

            byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
            byte[]   privateKey  = privateKeys[(int)(ulong)proposerIndex];

            Root         blockHashTreeRoot = cryptographyService.HashTreeRoot(block);
            Domain       proposerDomain    = beaconStateAccessor.GetDomain(state, signatureDomains.BeaconProposer, blockEpoch);
            Root         signingRoot       = beaconChainUtility.ComputeSigningRoot(blockHashTreeRoot, proposerDomain);
            BlsSignature signature         = TestSecurity.BlsSign(signingRoot, privateKey);

            return(new SignedBeaconBlock(block, signature));
        }
Exemplo n.º 4
0
        public static BlsSignature SignAggregateAttestation(IServiceProvider testServiceProvider, BeaconState state, AttestationData attestationData, IEnumerable <ValidatorIndex> participants)
        {
            var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            var privateKeys = TestKeys.PrivateKeys(timeParameters).ToList();
            var signatures  = new List <BlsSignature>();

            foreach (var validatorIndex in participants)
            {
                var privateKey = privateKeys[(int)(ulong)validatorIndex];
                var signature  = GetAttestationSignature(testServiceProvider, state, attestationData, privateKey);
                signatures.Add(signature);
            }

            return(TestSecurity.BlsAggregateSignatures(signatures));
        }
Exemplo n.º 5
0
        public static ProposerSlashing GetValidProposerSlashing(IServiceProvider testServiceProvider, BeaconState state, bool signed1, bool signed2)
        {
            var timeParameters      = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>();

            var currentEpoch   = beaconStateAccessor.GetCurrentEpoch(state);
            var validatorIndex = beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch).Last();
            var validator      = state.Validators[(int)(ulong)validatorIndex];
            var privateKey     = TestKeys.PublicKeyToPrivateKey(validator.PublicKey, timeParameters);
            var slot           = state.Slot;

            var header1 = new BeaconBlockHeader(
                slot,
                new Root(Enumerable.Repeat((byte)0x33, 32).ToArray()),
                new Root(Enumerable.Repeat((byte)0x44, 32).ToArray()),
                new Root(Enumerable.Repeat((byte)0x45, 32).ToArray())
                );

            var header2 = new BeaconBlockHeader(
                slot,
                new Root(Enumerable.Repeat((byte)0x99, 32).ToArray()),
                new Root(Enumerable.Repeat((byte)0x44, 32).ToArray()),
                new Root(Enumerable.Repeat((byte)0x45, 32).ToArray())
                );

            SignedBeaconBlockHeader signedHeader1 = new SignedBeaconBlockHeader(header1, BlsSignature.Zero);

            if (signed1)
            {
                signedHeader1 = TestBlockHeader.SignBlockHeader(testServiceProvider, state, header1, privateKey);
            }

            SignedBeaconBlockHeader signedHeader2 = new SignedBeaconBlockHeader(header2, BlsSignature.Zero);

            if (signed2)
            {
                signedHeader2 = TestBlockHeader.SignBlockHeader(testServiceProvider, state, header2, privateKey);
            }

            var proposerSlashing = new ProposerSlashing(validatorIndex, signedHeader1, signedHeader2);

            return(proposerSlashing);
        }
Exemplo n.º 6
0
        public static (IEnumerable <Deposit>, Hash32) PrepareGenesisDeposits(IServiceProvider testServiceProvider, int genesisValidatorCount, Gwei amount, bool signed)
        {
            var chainConstants          = testServiceProvider.GetService <ChainConstants>();
            var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value;
            var initialValues           = testServiceProvider.GetService <IOptions <InitialValues> >().Value;
            var timeParameters          = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;
            var maxOperationsPerBlock   = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value;

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

            var privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();

            BlsPublicKey[] publicKeys;
            if (signed)
            {
                publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();
            }
            else
            {
                publicKeys = privateKeys.Select(x => new BlsPublicKey(x)).ToArray();
            }
            var depositDataList = new List <DepositData>();
            var genesisDeposits = new List <Deposit>();
            var root            = Hash32.Zero;

            for (var validatorIndex = 0; validatorIndex < genesisValidatorCount; validatorIndex++)
            {
                var publicKey  = publicKeys[validatorIndex];
                var privateKey = privateKeys[validatorIndex];
                // insecurely use pubkey as withdrawal key if no credentials provided
                var withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());
                withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
                var withdrawalCredentials = new Hash32(withdrawalCredentialBytes);
                (var deposit, var depositRoot) = BuildDeposit(testServiceProvider, null, depositDataList, publicKey, privateKey, amount, withdrawalCredentials, signed);
                root = depositRoot;
                genesisDeposits.Add(deposit);
            }
            return(genesisDeposits, root);
        }
Exemplo n.º 7
0
        public static (IList <Deposit>, Root) 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;

            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            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>();
            List <Deposit>     genesisDeposits = new List <Deposit>();
            Root root = Root.Zero;

            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);
                (Deposit deposit, Root depositRoot) = BuildDeposit(testServiceProvider, null, depositDataList, publicKey, privateKey, amount, withdrawalCredentials, signed);
                root = depositRoot;
                genesisDeposits.Add(deposit);
            }
            return(genesisDeposits, root);
        }
Exemplo n.º 8
0
        public static Validator BuildMockValidator(ChainConstants chainConstants, InitialValues initialValues, GweiValues gweiValues, TimeParameters timeParameters, ulong validatorIndex, Gwei balance)
        {
            var publicKeys = TestKeys.PublicKeys(timeParameters).ToArray();
            var publicKey  = publicKeys[validatorIndex];
            // insecurely use pubkey as withdrawal key if no credentials provided
            var withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan());

            withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix;
            var withdrawalCredentials = new Bytes32(withdrawalCredentialBytes);

            var validator = new Validator(
                publicKey,
                withdrawalCredentials,
                Gwei.Min(balance - balance % gweiValues.EffectiveBalanceIncrement, gweiValues.MaximumEffectiveBalance),
                false,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch,
                chainConstants.FarFutureEpoch);

            return(validator);
        }
Exemplo n.º 9
0
        public static BeaconBlock BuildEmptyBlock(IServiceProvider testServiceProvider, BeaconState state, Slot slot, BlsSignature randaoReveal)
        {
            //if (slot) is none

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

            ICryptographyService  cryptographyService   = testServiceProvider.GetService <ICryptographyService>();
            BeaconChainUtility    beaconChainUtility    = testServiceProvider.GetService <BeaconChainUtility>();
            BeaconStateAccessor   beaconStateAccessor   = testServiceProvider.GetService <BeaconStateAccessor>();
            BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>();

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

            Root stateRoot = !state.LatestBlockHeader.StateRoot.Equals(Root.Zero)
                ? state.LatestBlockHeader.StateRoot
                : cryptographyService.HashTreeRoot(state);
            BeaconBlockHeader previousBlockHeader = new BeaconBlockHeader(state.LatestBlockHeader.Slot,
                                                                          state.LatestBlockHeader.ParentRoot, stateRoot, state.LatestBlockHeader.BodyRoot);
            Root previousBlockHashTreeRoot = cryptographyService.HashTreeRoot(previousBlockHeader);

            if (randaoReveal.Equals(BlsSignature.Zero))
            {
                Epoch          blockEpoch = beaconChainUtility.ComputeEpochAtSlot(slot);
                ValidatorIndex proposerIndex;
                if (slot == state.Slot)
                {
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(state);
                }
                else
                {
                    Epoch stateEpoch = beaconChainUtility.ComputeEpochAtSlot(state.Slot);
                    if (blockEpoch > stateEpoch + 1)
                    {
                        Console.WriteLine("WARNING: Block slot (epoch {0}) far away from state (epoch {1}), and no proposer index manually given."
                                          + " Signing block is slow due to transition for proposer index calculation.", blockEpoch, stateEpoch);
                    }

                    // use stub state to get proposer index of future slot
                    BeaconState stubState = BeaconState.Clone(state);
                    beaconStateTransition.ProcessSlots(stubState, slot);
                    proposerIndex = beaconStateAccessor.GetBeaconProposerIndex(stubState);
                }

                byte[][] privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray();
                byte[]   privateKey  = privateKeys[(int)(ulong)proposerIndex];

                Domain randaoDomain      = beaconStateAccessor.GetDomain(state, signatureDomains.Randao, blockEpoch);
                Root   epochHashTreeRoot = cryptographyService.HashTreeRoot(blockEpoch);
                Root   randaoSigningRoot = beaconChainUtility.ComputeSigningRoot(epochHashTreeRoot, randaoDomain);
                randaoReveal = TestSecurity.BlsSign(randaoSigningRoot, privateKey);
            }

            BeaconBlock emptyBlock = new BeaconBlock(slot,
                                                     previousBlockHashTreeRoot,
                                                     Root.Zero,
                                                     new BeaconBlockBody(
                                                         randaoReveal,
                                                         eth1Data,
                                                         new Bytes32(),
                                                         Array.Empty <ProposerSlashing>(),
                                                         Array.Empty <AttesterSlashing>(),
                                                         Array.Empty <Attestation>(),
                                                         Array.Empty <Deposit>(),
                                                         Array.Empty <SignedVoluntaryExit>()
                                                         ));

            return(emptyBlock);
        }