Esempio n. 1
0
        private static BlsPublicKey DecodeBlsPublicKey(ReadOnlySpan <byte> span, ref int offset)
        {
            BlsPublicKey publicKey = new BlsPublicKey(span.Slice(offset, Ssz.BlsPublicKeyLength).ToArray());

            offset += Ssz.BlsPublicKeyLength;
            return(publicKey);
        }
Esempio n. 2
0
 public DepositData(BlsPublicKey publicKey, Bytes32 withdrawalCredentials, Gwei amount, BlsSignature signature)
 {
     PublicKey             = publicKey;
     WithdrawalCredentials = withdrawalCredentials;
     Amount    = amount;
     Signature = signature; // Signing over DepositMessage
 }
Esempio n. 3
0
        public IList <BlsPublicKey> GetPublicKeys()
        {
            if (_publicKeyToBls.Count == 0)
            {
                QuickStartParameters _quickStartParameters = _quickStartParameterOptions.CurrentValue;

                ulong endIndex = _quickStartParameters.ValidatorStartIndex + _quickStartParameters.NumberOfValidators;
                for (ulong validatorIndex = _quickStartParameters.ValidatorStartIndex;
                     validatorIndex < endIndex;
                     validatorIndex++)
                {
                    byte[] privateKey = GeneratePrivateKey(validatorIndex);

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

                    // Cache the BLS class, for easy signing
                    _publicKeyToBls[publicKey] = bls;
                }
            }

            return(_publicKeyToBls.Keys.ToList());
        }
Esempio n. 4
0
        public async Task <ValidatorDuty> GetValidatorDutyAsync(BlsPublicKey validatorPublicKey, Epoch?optionalEpoch)
        {
            // TODO: Obsolete this and remove it; only used in tests
            var validatorDuties = await GetValidatorDutiesAsync(new[] { validatorPublicKey }, optionalEpoch);

            return(validatorDuties.FirstOrDefault());
        }
Esempio n. 5
0
        public static byte[] PublicKeyToPrivateKey(BlsPublicKey publicKey, TimeParameters timeParameters)
        {
            EnsureKeys(timeParameters);
            var privateKey = _testKeys[publicKey];

            return(privateKey);
        }
Esempio n. 6
0
        public BlsSignature GetEpochSignature(Slot slot, BlsPublicKey blsPublicKey)
        {
            var fork  = _beaconChainInformation.Fork;
            var epoch = ComputeEpochAtSlot(slot);

            ForkVersion forkVersion;

            if (epoch < fork.Epoch)
            {
                forkVersion = fork.PreviousVersion;
            }
            else
            {
                forkVersion = fork.CurrentVersion;
            }

            var domainType   = _signatureDomainOptions.CurrentValue.Randao;
            var randaoDomain = ComputeDomain(domainType, forkVersion);

            var epochRoot   = _cryptographyService.HashTreeRoot(epoch);
            var signingRoot = ComputeSigningRoot(epochRoot, randaoDomain);

            var randaoReveal = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot);

            return(randaoReveal);
        }
Esempio n. 7
0
        public async Task TestValidatorKeyGeneration10()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            IConfigurationRoot configuration         = new ConfigurationBuilder()
                                                       .AddInMemoryCollection(new Dictionary <string, string> {
                ["QuickStart:ValidatorCount"] = "10"
            })
                                                       .Build();

            testServiceCollection.AddBeaconNodeQuickStart(configuration);
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

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

            // Assert
            IStoreProvider storeProvider = testServiceProvider.GetService <IStoreProvider>();

            storeProvider.TryGetStore(out IStore? store).ShouldBeTrue();
            BeaconState state = await store !.GetBlockStateAsync(store !.FinalizedCheckpoint.Root);

            for (int index = 1; index < 10; index++)
            {
                BlsPublicKey expectedKey = new BlsPublicKey(_testDataItems[index].PublicKey);
                state.Validators[index].PublicKey.ShouldBe(expectedKey, $"Validator index {index}");
            }
        }
Esempio n. 8
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;

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

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

            List <DepositData> depositDataList = new List <DepositData>();

            (Deposit deposit, Root depositRoot) = BuildDeposit(testServiceProvider, state, depositDataList, publicKey, privateKey, amount, withdrawalCredentials, signed);

            state.SetEth1DepositIndex(0);
            state.Eth1Data.SetDepositRoot(depositRoot);
            state.Eth1Data.SetDepositCount((ulong)depositDataList.Count);

            return(deposit);
        }
Esempio n. 9
0
        // ReSharper disable once InconsistentNaming
        // ReSharper disable once IdentifierTypo
        public async Task <IActionResult> GetAsync([FromQuery] byte[] validator_pubkey, [FromQuery] uint poc_bit,
                                                   [FromQuery] ulong slot, [FromQuery] ulong index,
                                                   CancellationToken cancellationToken)
        {
            if (_logger.IsDebug())
            {
                LogDebug.NewAttestationRequested(_logger, slot, index, Bytes.ToHexString(validator_pubkey), null);
            }

            BlsPublicKey validatorPublicKey = new BlsPublicKey(validator_pubkey);
            bool         proofOfCustodyBit  = poc_bit > 0;
            Slot         targetSlot         = new Slot(slot);

            // NOTE: Spec 0.10.1 still has old Shard references in OAPI, although the spec has changed to Index;
            // use Index as it is easier to understand (i.e. the spec OAPI in 0.10.1 is wrong)
            CommitteeIndex targetIndex = new CommitteeIndex(index);

            ApiResponse <Attestation> apiResponse =
                await _beaconNode
                .NewAttestationAsync(validatorPublicKey, proofOfCustodyBit, targetSlot, targetIndex,
                                     cancellationToken).ConfigureAwait(false);

            return(apiResponse.StatusCode switch
            {
                Core2.Api.StatusCode.Success => Ok(apiResponse.Content),
                Core2.Api.StatusCode.InvalidRequest => Problem("Invalid request syntax.",
                                                               statusCode: (int)apiResponse.StatusCode),
                Core2.Api.StatusCode.CurrentlySyncing => Problem("Beacon node is currently syncing, try again later.",
                                                                 statusCode: (int)apiResponse.StatusCode),
                _ => Problem("Beacon node internal error.", statusCode: (int)apiResponse.StatusCode)
            });
Esempio n. 10
0
        private static BlsPublicKey DecodeBlsPublicKey(Span <byte> span, ref int offset)
        {
            BlsPublicKey publicKey = new BlsPublicKey(span.Slice(offset, BlsPublicKey.SszLength).ToArray());

            offset += BlsPublicKey.SszLength;
            return(publicKey);
        }
Esempio n. 11
0
 public DepositData(BlsPublicKey publicKey, Hash32 withdrawalCredentials, Gwei amount)
 {
     PublicKey             = publicKey;
     WithdrawalCredentials = withdrawalCredentials;
     Amount    = amount;
     Signature = new BlsSignature();
 }
Esempio n. 12
0
        public async Task <BlsSignature> GetAttestationSignatureAsync(Attestation unsignedAttestation,
                                                                      BlsPublicKey blsPublicKey)
        {
            Fork  fork  = _beaconChainInformation.Fork;
            Epoch epoch = ComputeEpochAtSlot(unsignedAttestation.Data.Slot);

            ForkVersion forkVersion;

            if (epoch < fork.Epoch)
            {
                forkVersion = fork.PreviousVersion;
            }
            else
            {
                forkVersion = fork.CurrentVersion;
            }

            DomainType domainType = _signatureDomainOptions.CurrentValue.BeaconAttester;

            (DomainType domainType, ForkVersion forkVersion)cacheKey = (domainType, forkVersion);
            Domain attesterDomain =
                await _cache.GetOrCreateAsync(cacheKey,
                                              entry => { return(Task.FromResult(ComputeDomain(domainType, forkVersion))); }).ConfigureAwait(false);

            Root attestationDataRoot = _cryptographyService.HashTreeRoot(unsignedAttestation.Data);
            Root signingRoot         = ComputeSigningRoot(attestationDataRoot, attesterDomain);

            BlsSignature signature = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot);

            return(signature);
        }
Esempio n. 13
0
        public async Task TestGenerationOfFirstValidator()
        {
            // Arrange
            var overrideConfiguration = new Dictionary <string, string>
            {
                ["QuickStart:GenesisTime"]    = "1578009600",
                ["QuickStart:ValidatorCount"] = "1",
                ["BeaconChain:MiscellaneousParameters:MinimumGenesisActiveValidatorCount"] = "1"
            };
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(overrideConfiguration);
            ServiceProvider    testServiceProvider   = testServiceCollection.BuildServiceProvider();

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

            // Assert
            testServiceProvider.GetService <IEth1GenesisProvider>().ShouldBeOfType <QuickStartMockEth1GenesisProvider>();
            IStore      store = testServiceProvider.GetService <IStore>();
            BeaconState state = await store.GetBlockStateAsync(store.FinalizedCheckpoint.Root);

            BlsPublicKey expectedKey0 = new BlsPublicKey(_testDataItems[0].PublicKey);

            state.Validators[0].PublicKey.ShouldBe(expectedKey0);
        }
Esempio n. 14
0
        public BlsSignature GetBlockSignature(BeaconBlock block, BlsPublicKey blsPublicKey)
        {
            var fork  = _beaconChainInformation.Fork;
            var epoch = ComputeEpochAtSlot(block.Slot);

            ForkVersion forkVersion;

            if (epoch < fork.Epoch)
            {
                forkVersion = fork.PreviousVersion;
            }
            else
            {
                forkVersion = fork.CurrentVersion;
            }

            var domainType     = _signatureDomainOptions.CurrentValue.BeaconProposer;
            var proposerDomain = ComputeDomain(domainType, forkVersion);

            /*
             * JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true };
             * options.ConfigureNethermindCore2();
             * string blockJson = System.Text.Json.JsonSerializer.Serialize(block, options);
             */

            var blockRoot   = _cryptographyService.HashTreeRoot(block);
            var signingRoot = ComputeSigningRoot(blockRoot, proposerDomain);

            var signature = _validatorKeyProvider.SignRoot(blsPublicKey, signingRoot);

            return(signature);
        }
Esempio n. 15
0
        public async Task TestGenerationOfFirstValidator()
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);
            IConfigurationRoot configuration         = new ConfigurationBuilder()
                                                       .AddInMemoryCollection(new Dictionary <string, string> {
                ["QuickStart:ValidatorCount"] = "1"
            })
                                                       .Build();

            testServiceCollection.AddQuickStart(configuration);
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();

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

            // Assert
            IStoreProvider storeProvider = testServiceProvider.GetService <IStoreProvider>();

            storeProvider.TryGetStore(out IStore? store).ShouldBeTrue();

            if (!store !.TryGetBlockState(store.FinalizedCheckpoint.Root, out BeaconState? state))
            {
                throw new InvalidDataException("Missing finalized checkpoint block state");
            }

            BlsPublicKey expectedKey0 = new BlsPublicKey(_testDataItems[0].PublicKey);

            state !.Validators[0].PublicKey.ShouldBe(expectedKey0);
        }
Esempio n. 16
0
        // [DataRow(42uL, "0xab48aa2cc6f4a0bb63b5d67be54ac3aed10326dda304c5aeb9e942b40d6e7610478377680ab90e092ef1895e62786008", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x8aea7d8eb22063bcfe882e2b7efc0b3713e1a48dd8343bed523b1ab4546114be84d00f896d33c605d1f67456e8e2ed93", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x89db41a6183c2fe47cf54d1e00c3cfaae53df634a32cccd5cf0c0a73e95ee0450fc3d060bb6878780fbf5f30d9e29aac", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0xb783a70a1cf9f53e7d2ddf386bea81a947e5360c5f1e0bf004fceedb2073e4dd180ef3d2d91bee7b1c5a88d1afd11c49", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x8fe55d12257709ae842f8594f9a0a40de3d38dabdf82b21a60baac927e52ed00c5fd42f4c905410eacdaf8f8a9952490", 0uL, 5uL, 1uL, null)]
        // [DataRow(42uL, "0x95906ec0660892c205634e21ad540cbe0b6f7729d101d5c4639b864dea09be7f42a4252c675d46dd90a2661b3a94e8ca", 0uL, 5uL, 1uL, null)]
        public async Task ValidatorDutyAtSpecificTimeDuplicateProposal(ulong targetTime, string publicKey, ulong epoch, ulong attestationSlot, ulong attestationShard, ulong?blockProposalSlot)
        {
            // NOTE: Current algorithm for GetBeaconProposerIndex() someimtes allocates multiple proposal slots in an epoch, e.g. above index 23 gets slot 2 and 6
            // It could be an error in the algorithm (need to check; domain type could be wrong), or due to the pre-shard algorithm.
            // The algorithm before shards were removed was different, so maybe ignore for now, implement phase 1 (with shards), and worry about it then.
            // This test for now will simply detect if things unintentionally change.

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

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            IForkChoice     forkChoice = testServiceProvider.GetService <IForkChoice>();
            // Get genesis store initialise MemoryStoreProvider with the state
            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // Move forward time
            TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value;

            for (ulong timeSinceGenesis = 1; timeSinceGenesis <= targetTime; timeSinceGenesis++)
            {
                ulong time = state.GenesisTime + timeSinceGenesis;
                await forkChoice.OnTickAsync(store, time);

                if (timeSinceGenesis % timeParameters.SecondsPerSlot == 0)
                {
                    BeaconBlock       block       = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero);
                    SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block);
                    await forkChoice.OnBlockAsync(store, signedBlock);
                }
            }

            Console.WriteLine("");
            Console.WriteLine("***** State advanced to slot {0}, time {1}, ready to start tests *****", state.Slot, store.Time);
            Console.WriteLine("");

            // Act
            ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>();
            BlsPublicKey         validatorPublicKey   = new BlsPublicKey(publicKey);
            Epoch targetEpoch = new Epoch(epoch);

            ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch);

            Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}",
                              validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);

            // Assert
            validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey);

            Slot  expectedBlockProposalSlot = blockProposalSlot.HasValue ? new Slot(blockProposalSlot.Value) : Slot.None;
            Slot  expectedAttestationSlot   = new Slot(attestationSlot);
            Shard expectedAttestationShard  = new Shard(attestationShard);

            validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot);
            validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot);
            validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard);
        }
Esempio n. 17
0
 public ValidatorDuty(BlsPublicKey validatorPublicKey, Slot attestationSlot, Shard attestationShard,
                      Slot blockProposalSlot)
 {
     ValidatorPublicKey = validatorPublicKey;
     AttestationSlot    = attestationSlot;
     AttestationShard   = attestationShard;
     BlockProposalSlot  = blockProposalSlot;
 }
Esempio n. 18
0
 public ValidatorDuty(BlsPublicKey validatorPublicKey, Slot?attestationSlot, CommitteeIndex?attestationIndex,
                      Slot?blockProposalSlot)
 {
     ValidatorPublicKey = validatorPublicKey;
     AttestationSlot    = attestationSlot;
     AttestationIndex   = attestationIndex;
     BlockProposalSlot  = blockProposalSlot;
 }
        public bool BlsVerify(BlsPublicKey publicKey, Root signingRoot, BlsSignature signature)
        {
            BLSParameters blsParameters = new BLSParameters()
            {
                PublicKey = publicKey.AsSpan().ToArray()
            };

            using BLS signatureAlgorithm = SignatureAlgorithmFactory(blsParameters);
            return(signatureAlgorithm.VerifyHash(signingRoot.AsSpan(), signature.AsSpan()));
        }
        public bool BlsVerify(BlsPublicKey publicKey, Hash32 messageHash, BlsSignature signature, Domain domain)
        {
            var blsParameters = new BLSParameters()
            {
                PublicKey = publicKey.AsSpan().ToArray()
            };

            using var signatureAlgorithm = SignatureAlgorithmFactory(blsParameters);
            return(signatureAlgorithm.VerifyHash(messageHash.AsSpan(), signature.AsSpan(), domain.AsSpan()));
        }
Esempio n. 21
0
        private ValidatorIndex?FindValidatorIndexByPublicKey(BeaconState state, BlsPublicKey validatorPublicKey)
        {
            for (int index = 0; index < state.Validators.Count; index++)
            {
                if (state.Validators[index].PublicKey.Equals(validatorPublicKey))
                {
                    return(new ValidatorIndex((ulong)index));
                }
            }

            return(ValidatorIndex.None);
        }
Esempio n. 22
0
        public async Task BasicValidatorDuty(string publicKey, ulong epoch, bool success, ulong?attestationSlot,
                                             ulong attestationShard, ulong?blockProposalSlot)
        {
            // Arrange
            IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true);

            testServiceCollection.AddSingleton <IHostEnvironment>(Substitute.For <IHostEnvironment>());
            ServiceProvider testServiceProvider = testServiceCollection.BuildServiceProvider();
            BeaconState     state      = TestState.PrepareTestState(testServiceProvider);
            IForkChoice     forkChoice = testServiceProvider.GetService <IForkChoice>();
            // Get genesis store initialise MemoryStoreProvider with the state
            IStore store = testServiceProvider.GetService <IStore>();
            await forkChoice.InitializeForkChoiceStoreAsync(store, state);

            // Act
            ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>();
            BlsPublicKey         validatorPublicKey   = new BlsPublicKey(publicKey);
            Epoch targetEpoch = new Epoch(epoch);

            // failure expected
            if (!success)
            {
                Should.Throw <Exception>(async() =>
                {
                    ValidatorDuty validatorDuty =
                        await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch);
                    Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}",
                                      validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot,
                                      (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot);
                });
                return;
            }

            ValidatorDuty validatorDuty =
                await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch);

            Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}",
                              validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard,
                              validatorDuty.BlockProposalSlot);

            // Assert
            validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey);

            Slot? expectedBlockProposalSlot = (Slot?)blockProposalSlot;
            Slot? expectedAttestationSlot   = (Slot?)attestationSlot;
            Shard expectedAttestationShard  = new Shard(attestationShard);

            validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot);
            validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot);
            validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard);
        }
Esempio n. 23
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);
        }
Esempio n. 24
0
        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);
        }
Esempio n. 25
0
 public Validator(
     BlsPublicKey publicKey,
     Hash32 withdrawalCredentials,
     Gwei effectiveBalance,
     //bool slashed,
     Epoch activationEligibilityEpoch,
     Epoch activationEpoch,
     Epoch exitEpoch,
     Epoch withdrawableEpoch)
 {
     PublicKey                  = publicKey;
     WithdrawalCredentials      = withdrawalCredentials;
     EffectiveBalance           = effectiveBalance;
     ActivationEligibilityEpoch = activationEligibilityEpoch;
     ActivationEpoch            = activationEpoch;
     ExitEpoch                  = exitEpoch;
     WithdrawableEpoch          = withdrawableEpoch;
 }
Esempio n. 26
0
        public static Validator DecodeValidator(Span <byte> span)
        {
            if (span.Length != Validator.SszLength)
            {
                ThrowSourceLength <Validator>(span.Length, Validator.SszLength);
            }
            int          offset    = 0;
            BlsPublicKey publicKey = DecodeBlsPublicKey(span, ref offset);
            Validator    container = new Validator(publicKey);

            container.WithdrawalCredentials = DecodeSha256(span, ref offset);
            container.EffectiveBalance      = DecodeGwei(span, ref offset);
            container.Slashed = DecodeBool(span, ref offset);
            container.ActivationEligibilityEpoch = DecodeEpoch(span, ref offset);
            container.ActivationEpoch            = DecodeEpoch(span, ref offset);
            container.ExitEpoch         = DecodeEpoch(span, ref offset);
            container.WithdrawableEpoch = DecodeEpoch(span, ref offset);
            return(container);
        }
Esempio n. 27
0
        public BlsSignature SignRoot(BlsPublicKey blsPublicKey, Root root)
        {
            if (_publicKeyToBls.Count == 0)
            {
                var keyCount = GetPublicKeys().Count();
            }

            BLS bls = _publicKeyToBls[blsPublicKey];

            byte[] destination = new byte[BlsSignature.Length];
            bool   success     = bls.TrySignData(root.AsSpan(), destination, out int bytesWritten);

            if (!success || bytesWritten != BlsSignature.Length)
            {
                throw new Exception($"Failure signing hash {root} for public key {blsPublicKey}.");
            }
            BlsSignature blsSignature = new BlsSignature(destination);

            return(blsSignature);
        }
Esempio n. 28
0
        public static Validator DecodeValidator(Span <byte> span)
        {
            if (span.Length != Ssz.ValidatorLength)
            {
                ThrowSourceLength <Validator>(span.Length, Ssz.ValidatorLength);
            }
            int          offset                     = 0;
            BlsPublicKey publicKey                  = DecodeBlsPublicKey(span, ref offset);
            Bytes32      withdrawalCredentials      = DecodeBytes32(span, ref offset);
            Gwei         effectiveBalance           = DecodeGwei(span, ref offset);
            bool         isSlashed                  = DecodeBool(span, ref offset);
            Epoch        activationEligibilityEpoch = DecodeEpoch(span, ref offset);
            Epoch        activationEpoch            = DecodeEpoch(span, ref offset);
            Epoch        exitEpoch                  = DecodeEpoch(span, ref offset);
            Epoch        withdrawableEpoch          = DecodeEpoch(span, ref offset);
            Validator    container                  = new Validator(publicKey, withdrawalCredentials, effectiveBalance, isSlashed,
                                                                    activationEligibilityEpoch, activationEpoch, exitEpoch, withdrawableEpoch);

            return(container);
        }
Esempio n. 29
0
        public BlsSignature SignHashWithDomain(BlsPublicKey blsPublicKey, Hash32 hash, Domain domain)
        {
            if (_publicKeyToBls.Count == 0)
            {
                var keyCount = GetPublicKeys().Count();
            }

            BLS bls = _publicKeyToBls[blsPublicKey];

            Span <byte> destination = stackalloc byte[BlsSignature.Length];
            bool        success     = bls.TrySignHash(hash.AsSpan(), destination, out int bytesWritten, domain.AsSpan());

            if (!success || bytesWritten != BlsSignature.Length)
            {
                throw new Exception($"Failure signing hash {hash}, domain {domain} for public key {blsPublicKey}.");
            }
            BlsSignature blsSignature = new BlsSignature(destination.ToArray());

            return(blsSignature);
        }
Esempio n. 30
0
        private ValidatorIndex CheckValidatorIndex(BeaconState state, BlsPublicKey validatorPublicKey)
        {
            ValidatorIndex validatorIndex = FindValidatorIndexByPublicKey(state, validatorPublicKey);

            if (validatorIndex == ValidatorIndex.None)
            {
                throw new ArgumentOutOfRangeException(nameof(validatorPublicKey), validatorPublicKey,
                                                      $"Could not find specified validator at slot {state.Slot}.");
            }

            bool validatorActive = CheckIfValidatorActive(state, validatorIndex);

            if (!validatorActive)
            {
                throw new Exception(
                          $"Validator {validatorPublicKey} (index {validatorIndex}) not not active at slot {state.Slot}.");
            }

            return(validatorIndex);
        }