/// <summary> /// Return the combined effective balance of the ``indices``. (1 Gwei minimum to avoid divisions by zero.) /// </summary> public Gwei GetTotalBalance(BeaconState state, IEnumerable <ValidatorIndex> validatorIndices) { var total = Gwei.Zero; foreach (var index in validatorIndices) { var validator = state.Validators[(int)index]; var balance = validator.EffectiveBalance; total += balance; } if (total == Gwei.Zero) { return(new Gwei(1)); } return(total); }
Root ICryptographyService.HashTreeRoot(BeaconState beaconState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; TimeParameters timeParameters = _timeParameterOptions.CurrentValue; StateListLengths stateListLengths = _stateListLengthOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; ulong maximumAttestationsPerEpoch = maxOperationsPerBlock.MaximumAttestations * (ulong)timeParameters.SlotsPerEpoch; return(beaconState.HashTreeRoot(stateListLengths.HistoricalRootsLimit, timeParameters.SlotsPerEth1VotingPeriod, stateListLengths.ValidatorRegistryLimit, maximumAttestationsPerEpoch, miscellaneousParameters.MaximumValidatorsPerCommittee)); // Merkle.Ize(out UInt256 root, beaconState); // Span<byte> bytes = MemoryMarshal.Cast<UInt256, byte>(MemoryMarshal.CreateSpan(ref root, 1)); // return new Hash32(bytes); }
/// <summary> /// Return the beacon committee at ``slot`` for ``index``. /// </summary> public IReadOnlyList <ValidatorIndex> GetBeaconCommittee(BeaconState state, Slot slot, CommitteeIndex index) { var epoch = _beaconChainUtility.ComputeEpochAtSlot(slot); var committeesPerSlot = GetCommitteeCountAtSlot(state, slot); //var committeeCount = GetCommitteeCount(state, epoch); var indices = GetActiveValidatorIndices(state, epoch); var seed = GetSeed(state, epoch, _signatureDomainOptions.CurrentValue.BeaconAttester); //var index = (shard + miscellaneousParameters.ShardCount - GetStartShard(state, epoch)) % miscellaneousParameters.ShardCount; var committeeIndex = (ulong)(slot % _timeParameterOptions.CurrentValue.SlotsPerEpoch) * committeesPerSlot + (ulong)index; var committeeCount = committeesPerSlot * (ulong)_timeParameterOptions.CurrentValue.SlotsPerEpoch; var committee = _beaconChainUtility.ComputeCommittee(indices, seed, committeeIndex, committeeCount); return(committee); }
public static BeaconState CreateValidBeaconState(IServiceProvider testServiceProvider, ulong?eth1TimestampOverride = null) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; BeaconNode.GenesisChainStart beaconChain = testServiceProvider.GetService <BeaconNode.GenesisChainStart>(); int depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount; (IList <Deposit> deposits, _) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: true); Bytes32 eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x12, 32).ToArray()); ulong eth1Timestamp = eth1TimestampOverride ?? miscellaneousParameters.MinimumGenesisTime; BeaconState state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp, deposits); return(state); }
private async Task AddBlockToStore(IServiceProvider testServiceProvider, IStore store, SignedBeaconBlock signedBlock) { TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); BeaconState preState = await store.GetBlockStateAsync(signedBlock.Message.ParentRoot); ulong blockTime = preState !.GenesisTime + (ulong)signedBlock.Message.Slot * timeParameters.SecondsPerSlot; if (store.Time < blockTime) { await forkChoice.OnTickAsync(store, blockTime); } await forkChoice.OnBlockAsync(store, signedBlock); }
public IEnumerable <PendingAttestation> GetMatchingSourceAttestations(BeaconState state, Epoch epoch) { var currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); var previousEpoch = _beaconStateAccessor.GetPreviousEpoch(state); if (epoch != currentEpoch && epoch != previousEpoch) { throw new ArgumentOutOfRangeException(nameof(epoch), epoch, $"The epoch for attestions must be either the current epoch {currentEpoch} or previous epoch {previousEpoch}."); } if (epoch == currentEpoch) { return(state.CurrentEpochAttestations); } return(state.PreviousEpochAttestations); }
/// <summary> /// Return the beacon proposer index at the current slot. /// </summary> public ValidatorIndex GetBeaconProposerIndex(BeaconState state) { Epoch epoch = GetCurrentEpoch(state); Span <byte> seedBytes = stackalloc byte[40]; Bytes32 initialSeed = GetSeed(state, epoch, _signatureDomainOptions.CurrentValue.BeaconProposer); initialSeed.AsSpan().CopyTo(seedBytes); BinaryPrimitives.WriteUInt64LittleEndian(seedBytes.Slice(32), state.Slot); Bytes32 seed = _cryptographyService.Hash(seedBytes); IList <ValidatorIndex> indices = GetActiveValidatorIndices(state, epoch); ValidatorIndex proposerIndex = _beaconChainUtility.ComputeProposerIndex(state, indices, seed); return(proposerIndex); }
/// <summary> /// Return the seed at ``epoch``. /// </summary> public Hash32 GetSeed(BeaconState state, Epoch epoch, DomainType domainType) { Epoch mixEpoch = (Epoch)(epoch + _stateListLengthOptions.CurrentValue.EpochsPerHistoricalVector - _timeParameterOptions.CurrentValue.MinimumSeedLookahead - 1UL); // # Avoid underflow Hash32 mix = GetRandaoMix(state, mixEpoch); Span <byte> seedHashInput = stackalloc byte[DomainType.Length + sizeof(ulong) + Hash32.Length]; domainType.AsSpan().CopyTo(seedHashInput); BinaryPrimitives.WriteUInt64LittleEndian(seedHashInput.Slice(DomainType.Length), epoch); mix.AsSpan().CopyTo(seedHashInput.Slice(DomainType.Length + sizeof(ulong))); Hash32 seed = _cryptographyService.Hash(seedHashInput); return(seed); }
public void ProcessProposerSlashing(BeaconState state, ProposerSlashing proposerSlashing) { _logger.LogInformation(Event.ProcessProposerSlashing, "Process block operation proposer slashing {ProposerSlashing}", proposerSlashing); var proposer = state.Validators[(int)(ulong)proposerSlashing.ProposerIndex]; // Verify slots match if (proposerSlashing.Header1.Slot != proposerSlashing.Header2.Slot) { throw new Exception($"Proposer slashing header 1 slot {proposerSlashing.Header1.Slot} must match header 2 slot {proposerSlashing.Header2.Slot}."); } // But the headers are different if (proposerSlashing.Header1.Equals(proposerSlashing.Header2)) { throw new Exception($"Proposer slashing must be for two different headers."); } // Check proposer is slashable var currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); var isSlashable = _beaconChainUtility.IsSlashableValidator(proposer, currentEpoch); if (!isSlashable) { throw new Exception($"Proposer {proposerSlashing.ProposerIndex} is not slashable at epoch {currentEpoch}."); } // Signatures are valid var slashingEpoch = _beaconChainUtility.ComputeEpochAtSlot(proposerSlashing.Header1.Slot); var domain = _beaconStateAccessor.GetDomain(state, _signatureDomainOptions.CurrentValue.BeaconProposer, slashingEpoch); var signingRoot1 = proposerSlashing.Header1.SigningRoot(); var signature1 = proposerSlashing.Header1.Signature; var header1Valid = _cryptographyService.BlsVerify(proposer.PublicKey, signingRoot1, signature1, domain); if (!header1Valid) { throw new Exception("Proposer slashing header 1 signature is not valid."); } var signingRoot2 = proposerSlashing.Header2.SigningRoot(); var signature2 = proposerSlashing.Header2.Signature; var header2Valid = _cryptographyService.BlsVerify(proposer.PublicKey, signingRoot2, signature2, domain); if (!header2Valid) { throw new Exception("Proposer slashing header 2 signature is not valid."); } _beaconStateMutator.SlashValidator(state, proposerSlashing.ProposerIndex, ValidatorIndex.None); }
public async Task <bool> FilterBlockTreeAsync(IStore store, Root blockRoot, IDictionary <Root, BeaconBlock> blocks) { SignedBeaconBlock signedBeaconBlock = await store.GetSignedBlockAsync(blockRoot).ConfigureAwait(false); // If any children branches contain expected finalized/justified checkpoints, // add to filtered block-tree and signal viability to parent. bool hasChildren = false; bool anyChildResult = false; await foreach (Root childKey in store.GetChildKeysAsync(blockRoot) .ConfigureAwait(false)) { hasChildren = true; bool childResult = await FilterBlockTreeAsync(store, childKey, blocks).ConfigureAwait(false); anyChildResult = anyChildResult | childResult; } if (hasChildren) { if (anyChildResult) { blocks[blockRoot] = signedBeaconBlock.Message; } return(anyChildResult); } // If leaf block, check finalized/justified checkpoints as matching latest. BeaconState headState = await store.GetBlockStateAsync(blockRoot).ConfigureAwait(false); bool correctJustified = store.JustifiedCheckpoint.Epoch == _chainConstants.GenesisEpoch || headState.CurrentJustifiedCheckpoint == store.JustifiedCheckpoint; bool correctFinalized = store.FinalizedCheckpoint.Epoch == _chainConstants.GenesisEpoch || headState.FinalizedCheckpoint == store.FinalizedCheckpoint; // If expected finalized/justified, add to viable block-tree and signal viability to parent. if (correctJustified && correctFinalized) { blocks[blockRoot] = signedBeaconBlock.Message; return(true); } // Otherwise, branch not viable return(false); }
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); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); // Get genesis store initialise MemoryStoreProvider with the state _ = forkChoice.GetGenesisStore(state); // Act ValidatorAssignments validatorAssignments = testServiceProvider.GetService <ValidatorAssignments>(); BlsPublicKey validatorPublicKey = new BlsPublicKey(publicKey); Epoch targetEpoch = new Epoch(epoch); // failure expected if (!success) { Should.Throw <Exception>(async() => { ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); }); return; } ValidatorDuty validatorDuty = await validatorAssignments.GetValidatorDutyAsync(validatorPublicKey, targetEpoch); Console.WriteLine("Validator {0}, epoch {1}: attestation slot {2}, shard {3}, proposal slot {4}", validatorPublicKey, targetEpoch, validatorDuty.AttestationSlot, (ulong)validatorDuty.AttestationShard, validatorDuty.BlockProposalSlot); // Assert validatorDuty.ValidatorPublicKey.ShouldBe(validatorPublicKey); Slot expectedBlockProposalSlot = blockProposalSlot.HasValue ? new Slot(blockProposalSlot.Value) : Slot.None; Slot expectedAttestationSlot = new Slot(attestationSlot); Shard expectedAttestationShard = new Shard(attestationShard); validatorDuty.BlockProposalSlot.ShouldBe(expectedBlockProposalSlot); validatorDuty.AttestationSlot.ShouldBe(expectedAttestationSlot); validatorDuty.AttestationShard.ShouldBe(expectedAttestationShard); }
public async Task <ApiResponse <Fork> > GetNodeForkAsync(CancellationToken cancellationToken) { try { BeaconState state = await GetHeadStateAsync().ConfigureAwait(false); return(ApiResponse.Create(StatusCode.Success, state.Fork)); } catch (Exception ex) { if (_logger.IsWarn()) { Log.ApiErrorGetFork(_logger, ex); } throw; } }
/// <summary> /// Return the block root at a recent ``slot``. /// </summary> public Root GetBlockRootAtSlot(BeaconState state, Slot slot) { TimeParameters timeParameters = _timeParameterOptions.CurrentValue; // NOTE: Need to use '+' to avoid underflow issues if (slot + timeParameters.SlotsPerHistoricalRoot < state.Slot) { throw new ArgumentOutOfRangeException(nameof(slot), slot, $"Slot can not be more than historical root ({timeParameters.SlotsPerHistoricalRoot} slots) behind the state slot {state.Slot}"); } if (slot >= state.Slot) { throw new ArgumentOutOfRangeException(nameof(slot), slot, $"Slot must be less than than the state slot {state.Slot}"); } ulong blockIndex = slot % timeParameters.SlotsPerHistoricalRoot; return(state.BlockRoots[(int)blockIndex]); }
public async Task InitializeForkChoiceStoreAsync(IStore store, BeaconState anchorState) { // Implements the logic for get_genesis_store / get_forkchoice_store Root stateRoot = !anchorState.LatestBlockHeader.StateRoot.Equals(Root.Zero) ? anchorState.LatestBlockHeader.StateRoot : _cryptographyService.HashTreeRoot(anchorState); BeaconBlock anchorBlock = new BeaconBlock(anchorState.Slot, anchorState.LatestBlockHeader.ParentRoot, stateRoot, BeaconBlockBody.Zero); SignedBeaconBlock signedAnchorBlock = new SignedBeaconBlock(anchorBlock, BlsSignature.Zero); Root anchorRoot = _cryptographyService.HashTreeRoot(anchorBlock); Epoch anchorEpoch = _beaconStateAccessor.GetCurrentEpoch(anchorState); Checkpoint justifiedCheckpoint = new Checkpoint(anchorEpoch, anchorRoot); Checkpoint finalizedCheckpoint = new Checkpoint(anchorEpoch, anchorRoot); if (_logger.IsInfo()) { Log.CreateGenesisStore(_logger, anchorState.Fork, anchorRoot, anchorState.GenesisTime, anchorState, anchorBlock, justifiedCheckpoint, null); } Dictionary <Root, SignedBeaconBlock> signedBlocks = new Dictionary <Root, SignedBeaconBlock> { [anchorRoot] = signedAnchorBlock }; Dictionary <Root, BeaconState> blockStates = new Dictionary <Root, BeaconState> { [anchorRoot] = BeaconState.Clone(anchorState) }; Dictionary <Checkpoint, BeaconState> checkpointStates = new Dictionary <Checkpoint, BeaconState> { [justifiedCheckpoint] = BeaconState.Clone(anchorState) }; await store.InitializeForkChoiceStoreAsync( anchorState.GenesisTime, anchorState.GenesisTime, justifiedCheckpoint, finalizedCheckpoint, justifiedCheckpoint, signedBlocks, blockStates, checkpointStates); }
public void NewDepositUnderMax() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); // fresh deposit = next validator index = validator appended to registry ValidatorIndex validatorIndex = new ValidatorIndex((ulong)state.Validators.Count); // effective balance will be 1 EFFECTIVE_BALANCE_INCREMENT smaller because of this small decrement. GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; Gwei amount = gweiValues.MaximumEffectiveBalance - new Gwei(1); Deposit deposit = TestDeposit.PrepareStateAndDeposit(testServiceProvider, state, validatorIndex, amount, Bytes32.Zero, signed: true); RunDepositProcessing(testServiceProvider, state, deposit, validatorIndex, expectValid: true, effective: true); }
public void ProcessBlockHeader(BeaconState state, BeaconBlock block) { _logger.LogInformation(Event.ProcessBlock, "Process block header for block {BeaconBlock}", block); // Verify that the slots match if (block.Slot != state.Slot) { throw new ArgumentOutOfRangeException("block.Slot", block.Slot, $"Block slot must match state slot {state.Slot}."); } // Verify that the parent matches var latestBlockSigningRoot = state.LatestBlockHeader.SigningRoot(); if (block.ParentRoot != latestBlockSigningRoot) { throw new ArgumentOutOfRangeException("block.ParentRoot", block.ParentRoot, $"Block parent root must match latest block header root {latestBlockSigningRoot}."); } // Save current block as the new latest block var bodyRoot = block.Body.HashTreeRoot(_miscellaneousParameterOptions.CurrentValue, _maxOperationsPerBlockOptions.CurrentValue); var newBlockHeader = new BeaconBlockHeader(block.Slot, block.ParentRoot, Hash32.Zero, // `state_root` is zeroed and overwritten in the next `process_slot` call bodyRoot, new BlsSignature() //`signature` is zeroed ); state.SetLatestBlockHeader(newBlockHeader); // Verify proposer is not slashed var beaconProposerIndex = _beaconStateAccessor.GetBeaconProposerIndex(state); var proposer = state.Validators[(int)(ulong)beaconProposerIndex]; if (proposer.IsSlashed) { throw new Exception("Beacon proposer must not be slashed."); } // Verify proposer signature var signingRoot = block.SigningRoot(_miscellaneousParameterOptions.CurrentValue, _maxOperationsPerBlockOptions.CurrentValue); var domain = _beaconStateAccessor.GetDomain(state, _signatureDomainOptions.CurrentValue.BeaconProposer, Epoch.None); var validSignature = _cryptographyService.BlsVerify(proposer.PublicKey, signingRoot, block.Signature, domain); if (!validSignature) { throw new Exception($"Block signature must match proposer public key {proposer.PublicKey}"); } }
public bool IsValidGenesisState(BeaconState state) { var miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; var initialValues = _initialValueOptions.CurrentValue; if (state.GenesisTime < miscellaneousParameters.MinimumGenesisTime) { return(false); } var activeValidatorIndices = _beaconStateAccessor.GetActiveValidatorIndices(state, initialValues.GenesisEpoch); if (activeValidatorIndices.Count < miscellaneousParameters.MinimumGenesisActiveValidatorCount) { return(false); } return(true); }
public async Task SplitTieBreakerNoAttestations() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); BeaconState genesisState = BeaconState.Clone(state); // block at slot 1 BeaconState block1State = BeaconState.Clone(genesisState); BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block1State, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, block1State, block1); await AddBlockToStore(testServiceProvider, store, block1); Hash32 block1Root = cryptographyService.SigningRoot(block1); // build short tree BeaconState block2State = BeaconState.Clone(genesisState); BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block2State, signed: true); block2.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, block2State, block2, ValidatorIndex.None); TestState.StateTransitionAndSignBlock(testServiceProvider, block2State, block2); await AddBlockToStore(testServiceProvider, store, block2); Hash32 block2Root = cryptographyService.SigningRoot(block2); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Console.WriteLine("block1 {0}", block1Root); Console.WriteLine("block2 {0}", block2Root); Hash32 highestRoot = block1Root.CompareTo(block2Root) > 0 ? block1Root : block2Root; Console.WriteLine("highest {0}", highestRoot); headRoot.ShouldBe(highestRoot); }
public async Task <ulong> GetGenesisTimeAsync(CancellationToken cancellationToken) { try { BeaconState state = await GetHeadStateAsync().ConfigureAwait(false); return(state.GenesisTime); } catch (Exception ex) { if (_logger.IsWarn()) { Log.ApiErrorGetGenesisTime(_logger, ex); } throw; } }
public async Task <Fork> GetNodeForkAsync(CancellationToken cancellationToken) { try { BeaconState state = await GetHeadStateAsync().ConfigureAwait(false); return(state.Fork); } catch (Exception ex) { if (_logger.IsWarn()) { Log.ApiErrorGetFork(_logger, ex); } throw; } }
public void ActivationQueueSorting() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); int mockActivations = 10; Epoch currentEpoch = beaconStateAccessor.GetCurrentEpoch(state); for (int index = 0; index < mockActivations; index++) { MockDeposit(testServiceProvider, state, index); state.Validators[index].SetEligible(currentEpoch + Epoch.One); } // eligibility must be finalized state.SetFinalizedCheckpoint(new Checkpoint(currentEpoch + new Epoch(2), Root.Zero)); // give the last priority over the others state.Validators[mockActivations - 1].SetEligible(currentEpoch); // make sure we are hitting the churn int churnLimit = (int)beaconStateAccessor.GetValidatorChurnLimit(state); mockActivations.ShouldBeGreaterThan(churnLimit); // Act RunProcessRegistryUpdates(testServiceProvider, state); // Assert //# the first got in as second state.Validators[0].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch); //# the prioritized got in as first state.Validators[mockActivations - 1].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch); //# the second last is at the end of the queue, and did not make the churn, //# hence is not assigned an activation_epoch yet. state.Validators[mockActivations - 2].ActivationEpoch.ShouldBe(chainConstants.FarFutureEpoch); //# the one at churn_limit - 1 did not make it, it was out-prioritized state.Validators[churnLimit - 1].ActivationEpoch.ShouldBe(chainConstants.FarFutureEpoch); //# but the the one in front of the above did state.Validators[churnLimit - 2].ActivationEpoch.ShouldNotBe(chainConstants.FarFutureEpoch); }
public async Task SplitTieBreakerNoAttestations() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); BeaconState genesisState = BeaconState.Clone(state); // block at slot 1 BeaconState block1State = BeaconState.Clone(genesisState); BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block1State, BlsSignature.Zero); SignedBeaconBlock signedBlock1 = TestState.StateTransitionAndSignBlock(testServiceProvider, block1State, block1); await AddBlockToStore(testServiceProvider, store, signedBlock1); Root block1Root = cryptographyService.HashTreeRoot(block1); // build short tree BeaconState block2State = BeaconState.Clone(genesisState); BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, block2State, BlsSignature.Zero); block2.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, block2State, block2, ValidatorIndex.None); SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, block2State, block2); await AddBlockToStore(testServiceProvider, store, signedBlock2); Root block2Root = cryptographyService.HashTreeRoot(block2); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Console.WriteLine("block1 {0}", block1Root); Console.WriteLine("block2 {0}", block2Root); Root highestRoot = block1Root.CompareTo(block2Root) > 0 ? block1Root : block2Root; Console.WriteLine("highest {0}", highestRoot); headRoot.ShouldBe(highestRoot); }
/// <summary> /// Return the signature domain (fork version concatenated with domain type) of a message. /// </summary> public Domain GetDomain(BeaconState state, DomainType domainType, Epoch?optionalEpoch) { Epoch epoch = optionalEpoch ?? GetCurrentEpoch(state); ForkVersion forkVersion; if (epoch < state.Fork.Epoch) { forkVersion = state.Fork.PreviousVersion; } else { forkVersion = state.Fork.CurrentVersion; } return(_beaconChainUtility.ComputeDomain(domainType, forkVersion)); }
private async Task HandlePeerStatus(string peerId, PeeringStatus peerPeeringStatus, Root headRoot, BeaconState beaconState) { // if not valid, "immediately disconnect from one another following the handshake" bool isValidPeer = await IsValidPeerStatus(peerId, peerPeeringStatus, headRoot, beaconState) .ConfigureAwait(false); if (!isValidPeer) { await _networkPeering.DisconnectPeerAsync(peerId).ConfigureAwait(false); return; } // check if we should request blocks var isPeerAhead = IsPeerAhead(peerPeeringStatus, beaconState); if (isPeerAhead) { // In theory, our chain since finalized checkpoint could be wrong // However it may be more efficient to check if our head is correct and sync from there, // or use the step option to sample blocks and find where we diverge. Slot finalizedSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(beaconState.FinalizedCheckpoint.Epoch); if (_logger.IsInfo()) { Log.RequestingBlocksFromAheadPeer(_logger, peerId, finalizedSlot, peerPeeringStatus.HeadRoot, peerPeeringStatus.HeadSlot, null); } // TODO: Need more sophistication, like Eth1; as peers are discovered, just put into a pool, // then, when need for sync determined, select the best peer(s) to use. await _networkPeering.RequestBlocksAsync(peerId, peerPeeringStatus.HeadRoot, finalizedSlot, peerPeeringStatus.HeadSlot); } else { if (_logger.IsDebug()) { LogDebug.PeerBehind(_logger, peerId, peerPeeringStatus.FinalizedEpoch, peerPeeringStatus.HeadRoot, peerPeeringStatus.HeadSlot, null); } } }
public static BeaconState DecodeBeaconState(Span <byte> span) { int offset = 0; BeaconState beaconState = new BeaconState(); beaconState.GenesisTime = DecodeULong(span, ref offset); beaconState.Slot = DecodeSlot(span, ref offset); beaconState.Fork = DecodeFork(span, ref offset); beaconState.LatestBlockHeader = DecodeBeaconBlockHeader(span, ref offset); beaconState.BlockRoots = DecodeHashes(span.Slice(offset, Time.SlotsPerHistoricalRoot * Sha256.SszLength)).ToArray(); offset += Time.SlotsPerHistoricalRoot * Sha256.SszLength; beaconState.StateRoots = DecodeHashes(span.Slice(offset, Time.SlotsPerHistoricalRoot * Sha256.SszLength)).ToArray(); offset += Time.SlotsPerHistoricalRoot * Sha256.SszLength; DecodeDynamicOffset(span, ref offset, out int dynamicOffset1); beaconState.Eth1Data = DecodeEth1Data(span, ref offset); DecodeDynamicOffset(span, ref offset, out int dynamicOffset2); beaconState.Eth1DepositIndex = DecodeULong(span, ref offset); DecodeDynamicOffset(span, ref offset, out int dynamicOffset3); DecodeDynamicOffset(span, ref offset, out int dynamicOffset4); beaconState.RandaoMixes = DecodeHashes(span.Slice(offset, Time.EpochsPerHistoricalVector * Sha256.SszLength)); offset += Time.EpochsPerHistoricalVector * Sha256.SszLength; beaconState.Slashings = DecodeGweis(span.Slice(offset, Time.EpochsPerSlashingsVector * Gwei.SszLength)); offset += Time.EpochsPerSlashingsVector * Gwei.SszLength; DecodeDynamicOffset(span, ref offset, out int dynamicOffset5); DecodeDynamicOffset(span, ref offset, out int dynamicOffset6); // how many justification bits? beaconState.JustificationBits = DecodeByte(span.Slice(offset, 1)); offset += 1; beaconState.PreviousJustifiedCheckpoint = DecodeCheckpoint(span, ref offset); beaconState.CurrentJustifiedCheckpoint = DecodeCheckpoint(span, ref offset); beaconState.FinalizedCheckpoint = DecodeCheckpoint(span, ref offset); beaconState.HistoricalRoots = DecodeHashes(span.Slice(dynamicOffset1, dynamicOffset2 - dynamicOffset1)); beaconState.Eth1DataVotes = DecodeEth1Datas(span.Slice(dynamicOffset2, dynamicOffset3 - dynamicOffset2)); beaconState.Validators = DecodeValidators(span.Slice(dynamicOffset3, dynamicOffset4 - dynamicOffset3)); beaconState.Balances = DecodeGweis(span.Slice(dynamicOffset4, dynamicOffset5 - dynamicOffset4)); beaconState.PreviousEpochAttestations = DecodePendingAttestations(span.Slice(dynamicOffset5, dynamicOffset6 - dynamicOffset5)); beaconState.CurrentEpochAttestations = DecodePendingAttestations(span.Slice(dynamicOffset6, span.Length - dynamicOffset6)); return(beaconState); }
public IStore GetGenesisStore(BeaconState genesisState) { MiscellaneousParameters miscellaneousParameters = _miscellaneousParameterOptions.CurrentValue; MaxOperationsPerBlock maxOperationsPerBlock = _maxOperationsPerBlockOptions.CurrentValue; Hash32 stateRoot = _cryptographyService.HashTreeRoot(genesisState); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 root = _cryptographyService.SigningRoot(genesisBlock); Checkpoint justifiedCheckpoint = new Checkpoint(_initialValueOptions.CurrentValue.GenesisEpoch, root); Checkpoint finalizedCheckpoint = new Checkpoint(_initialValueOptions.CurrentValue.GenesisEpoch, root); if (_logger.IsInfo()) { Log.CreateGenesisStore(_logger, genesisBlock, genesisState, justifiedCheckpoint, root, null); } Dictionary <Hash32, BeaconBlock> blocks = new Dictionary <Hash32, BeaconBlock> { [root] = genesisBlock }; Dictionary <Hash32, BeaconState> blockStates = new Dictionary <Hash32, BeaconState> { [root] = BeaconState.Clone(genesisState) }; Dictionary <Checkpoint, BeaconState> checkpointStates = new Dictionary <Checkpoint, BeaconState> { [justifiedCheckpoint] = BeaconState.Clone(genesisState) }; IStore store = _storeProvider.CreateStore( genesisState.GenesisTime, genesisState.GenesisTime, justifiedCheckpoint, finalizedCheckpoint, justifiedCheckpoint, blocks, blockStates, checkpointStates, new Dictionary <ValidatorIndex, LatestMessage>() ); return(store); }
public void HistoricalRootAccumulator() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(); BeaconState state = TestState.PrepareTestState(testServiceProvider); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; // skip ahead to near the end of the historical roots period (excl block before epoch processing) state.SetSlot((Slot)(timeParameters.SlotsPerHistoricalRoot - 1UL)); int historyLength = state.HistoricalRoots.Count; // Act RunProcessFinalUpdates(testServiceProvider, state); // Assert state.HistoricalRoots.Count.ShouldBe(historyLength + 1); }
public async Task OnStatusRequestReceived(string peerId, PeeringStatus peerPeeringStatus) { Root headRoot = await _forkChoice.GetHeadAsync(_store).ConfigureAwait(false); BeaconState beaconState = await _store.GetBlockStateAsync(headRoot).ConfigureAwait(false); // Send response var status = BuildStatusFromHead(headRoot, beaconState); if (_logger.IsDebug()) { LogDebug.SendingStatusToPeer(_logger, RpcDirection.Response, status, peerId, null); } await _networkPeering.SendStatusAsync(peerId, RpcDirection.Response, status).ConfigureAwait(false); // Determine if the peer is valid, and if we need to request blocks await HandlePeerStatus(peerId, peerPeeringStatus, headRoot, beaconState); }
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); }
public static BeaconState CreateGenesisState(IServiceProvider testServiceProvider, ulong numberOfValidators) { ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); GweiValues gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; InitialValues initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); var eth1BlockHash = new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray()); var state = new BeaconState( 0, new Core2.Containers.Fork(new ForkVersion(new byte[ForkVersion.Length]), new ForkVersion(new byte[ForkVersion.Length]), Epoch.Zero), new Eth1Data(Root.Zero, numberOfValidators, eth1BlockHash), //numberOfValidators, new BeaconBlockHeader(cryptographyService.HashTreeRoot(BeaconBlockBody.Zero)), Enumerable.Repeat(eth1BlockHash, (int)stateListLengths.EpochsPerHistoricalVector).ToArray(), timeParameters.SlotsPerHistoricalRoot, stateListLengths.EpochsPerHistoricalVector, stateListLengths.EpochsPerSlashingsVector, chainConstants.JustificationBitsLength ); // We directly insert in the initial validators, // as it is much faster than creating and processing genesis deposits for every single test case. for (var index = (ulong)0; index < numberOfValidators; index++) { var validator = BuildMockValidator(chainConstants, initialValues, gweiValues, timeParameters, index, gweiValues.MaximumEffectiveBalance); state.AddValidatorWithBalance(validator, gweiValues.MaximumEffectiveBalance); state.IncreaseEth1DepositIndex(); } // Process genesis activations foreach (var validator in state.Validators) { if (validator.EffectiveBalance >= gweiValues.MaximumEffectiveBalance) { validator.SetEligible(chainConstants.GenesisEpoch); validator.SetActive(chainConstants.GenesisEpoch); } } return(state); }
/// <summary> /// Finishes the current building action. USE ONLY FOR BUILDING, INFLUENCE HANDLED ELSEWHERE /// </summary> public void Build() { //Used to be finishAction() - refactored upgrade stuff into Upgrade() - seems cleaner this way ///TODO: add end semaphore stuff her selfDestructing = false; audio.Stop(); if(percBuildComplete >= 100f){ percBuildComplete = 100f; _currentState = BeaconState.Basic; _patternList = createBasicInfluenceList(getAngleForDir(facing)); for(int x = 0; x< GameManager.GameManagerInstance.tiles.GetLength(0); x++){ for(int y =0 ; y< GameManager.GameManagerInstance.tiles.GetLength(1); y++){ if(GameManager.GameManagerInstance.tiles[x,y].GetComponent<BaseTile>().currentType != TileTypeEnum.water){ GameManager.GameManagerInstance.tiles[x,y].GetComponent<BaseTile>().tooCloseToBeacon(); } } } } }
/// <summary> /// Finishes the current building action. USE ONLY FOR BUILDING, INFLUENCE HANDLED ELSEWHERE /// </summary> public void Build() { //Used to be finishAction() - refactored upgrade stuff into Upgrade() - seems cleaner this way ///TODO: add end semaphore stuff her selfDestructing = false; if(percBuildComplete >= 100f){ percBuildComplete = 100f; buildingTargetVol = 0.0f; audioSourceActionCompleted.clip = beaconBuilt; audioSourceActionCompleted.volume = sRef.beaconBuiltVolume; audioSourceActionCompleted.Play (); _currentState = BeaconState.Basic; _patternList = createBasicInfluenceList(getAngleForDir(facing)); for(int x = 0; x< GameManager.GameManagerInstance.tiles.GetLength(0); x++){ for(int y =0 ; y< GameManager.GameManagerInstance.tiles.GetLength(1); y++){ if(GameManager.GameManagerInstance.tiles[x,y].GetComponent<BaseTile>().currentType != TileTypeEnum.water){ GameManager.GameManagerInstance.tiles[x,y].GetComponent<BaseTile>().tooCloseToBeacon(); } } } } transform.FindChild ("Arrow").GetComponent<MeshRenderer>().enabled = true; transform.FindChild ("ArrowShot").GetComponent<MeshRenderer>().enabled = true; Color32 baseColor = transform.FindChild ("Arrow").renderer.material.color; baseColor.a = 255; transform.FindChild("Base").renderer.material.color = baseColor; Color32 animColor = transform.FindChild("Anim").renderer.material.color; animColor.a = 0; transform.FindChild("Anim").renderer.material.color = animColor; transform.FindChild("ArrowShot").renderer.enabled = !facingAdjacentWater(); // transform.FindChild("Point light").GetComponent<Light>().enabled = true; }
public void Upgrade() { losingUpgradeProgress = false; //This block moved from old finishAction() function, now Build() audio.Stop(); audio.PlayOneShot(beaconUpgraded, 1.0f); _currentState = BeaconState.Advanced; _patternList = createAdvancedInfluenceList(getAngleForDir(facing)); _currentState = BeaconState.Advanced; transform.FindChild("Base").renderer.material = matUpgraded; transform.FindChild("Arrow").renderer.material = arrowUpgraded; //hax setTeam (); Color32 platformColor = transform.FindChild("Base").renderer.material.color; Color32 beaconColor = transform.FindChild("Arrow").renderer.material.color; Color32 animColor = transform.FindChild("Anim").renderer.material.color; platformColor.a = 255; beaconColor.a = 255; animColor.a = 0; transform.FindChild("Arrow").renderer.material.color = beaconColor; transform.FindChild("Base").renderer.material.color = platformColor; transform.FindChild("Anim").renderer.material.color = animColor; }
public void buildNeutral(GameObject tileLocation) { this.gameObject.transform.parent = tileLocation.transform; this._currentState = BeaconState.Basic; this.setTeam(null); this.transform.localPosition = new Vector3(0f,0f,-.5f); tileLocation.GetComponent<BaseTile>().beacon = this.gameObject; _currentState = BeaconState.Basic; _patternList = createBasicInfluenceList(getAngleForDir(facing)); }
public void Upgrade() { losingUpgradeProgress = false; upgradingTargetVol = 0.0f; audioSourceActionCompleted.clip = beaconUpgraded; audioSourceActionCompleted.volume = sRef.beaconUpgradedVolume; audioSourceActionCompleted.Play (); _currentState = BeaconState.Advanced; _patternList = createAdvancedInfluenceList(getAngleForDir(facing)); _currentState = BeaconState.Advanced; transform.FindChild("Base").renderer.material = matUpgraded; transform.FindChild("Arrow").renderer.material = arrowUpgraded; transform.FindChild("ArrowShot").renderer.material = arrowUpgraded; //transform.FindChild("Arrow").transform.localScale = new Vector3(17, 17, 0); //hax setTeam (); Color32 platformColor = transform.FindChild("Base").renderer.material.color; Color32 beaconColor = transform.FindChild("Arrow").renderer.material.color; Color32 animColor = transform.FindChild("Anim").renderer.material.color; platformColor.a = 255; beaconColor.a = 255; animColor.a = 0; transform.FindChild("Arrow").renderer.material.color = beaconColor; transform.FindChild("ArrowShot").renderer.material.color = beaconColor; transform.FindChild("Base").renderer.material.color = platformColor; transform.FindChild("Anim").renderer.material.color = animColor; }
public void startBuilding(GameObject tileLocation, GameObject player, float valInit) { this.gameObject.transform.parent = tileLocation.transform; this.facing = player.GetComponentInChildren<Player>().facing; this.dirRotatingToward = facing; this._currentState = BeaconState.BuildingBasic; if (controllingTeam == null) { controllingTeam = player.GetComponentInChildren<Player>().team; this.setTeam(); } this.transform.localPosition = new Vector3(0f,0f,-.5f); tileLocation.GetComponent<BaseTile>().beacon = this.gameObject; this.transform.FindChild("Base").localPosition = new Vector3(0f,0f,-.1f); //Debug.Log(this.transform.FindChild("Base").localPosition); buildingTargetVol = 0.5f; if (!audioSourceBuilding.isPlaying) { audioSourceBuilding.volume = 0.0f; audioSourceBuilding.Play (); //Not working for some stupid reason } }
public void startBuilding(GameObject tileLocation, GameObject player, float valInit) { this.gameObject.transform.parent = tileLocation.transform; this.facing = player.GetComponentInChildren<Player>().facing; this.dirRotatingToward = facing; this._currentState = BeaconState.BuildingBasic; if (controllingTeam == null) { controllingTeam = player.GetComponentInChildren<Player>().team; this.setTeam(); } this.transform.localPosition = new Vector3(0f,0f,-.5f); tileLocation.GetComponent<BaseTile>().beacon = this.gameObject; this.transform.FindChild("Base").localPosition = new Vector3(0f,0f,-.1f); //Debug.Log(this.transform.FindChild("Base").localPosition); audio.Stop (); audio.PlayOneShot(beaconBuilding, 0.9f); }
public void buildNeutral(GameObject tileLocation) { audio.Stop(); this.gameObject.transform.parent = tileLocation.transform; this.facing = (DirectionEnum)Random.Range(1,5); this.dirRotatingToward = facing; this._currentState = BeaconState.Basic; this.setTeam(null); this.transform.localPosition = new Vector3(0f,0f,-.5f); tileLocation.GetComponent<BaseTile>().beacon = this.gameObject; _currentState = BeaconState.Basic; _patternList = createBasicInfluenceList(getAngleForDir(facing)); }
public void subtractUpgradeProgress(float rate) { percUpgradeComplete -= rate*Time.deltaTime; updateUpgradeAnim (); // percSmaller += rate*Time.deltaTime; // Vector3 newScale = animTrans.localScale; // newScale.x = 100f/percSmaller; // newScale.y = 100f/percSmaller; // animTrans.localScale = newScale; if (percUpgradeComplete <= 0f) { percUpgradeComplete = 0f; //audio.Stop(); _currentState = BeaconState.Basic; Color32 animColor = transform.FindChild("Anim").renderer.material.color; animColor.a = (byte)0f; transform.FindChild("Anim").renderer.material.color = animColor; } //We need some visual representation for this }
public void startUpgrading() { this._currentState = BeaconState.BuildingAdvanced; upgradingTargetVol = sRef.beaconUpgradingVolume; if (!audioSourceUpgrading.isPlaying) { audioSourceUpgrading.volume = 0.0f; audioSourceUpgrading.Play (); //Not working for some stupid reason } }
public void startUpgrading() { //audio.Stop(); this._currentState = BeaconState.BuildingAdvanced; audio.PlayOneShot(beaconUpgrading, 0.7f); }