public async Task <Gwei> GetLatestAttestingBalanceAsync(IStore store, Root root) { Checkpoint justifiedCheckpoint = store.JustifiedCheckpoint; BeaconState state = (await store.GetCheckpointStateAsync(justifiedCheckpoint, true).ConfigureAwait(false)) !; Epoch currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); IList <ValidatorIndex> activeIndexes = _beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch); SignedBeaconBlock rootBlock = await store.GetSignedBlockAsync(root).ConfigureAwait(false); Slot rootSlot = rootBlock !.Message.Slot; Gwei balance = Gwei.Zero; foreach (ValidatorIndex index in activeIndexes) { LatestMessage?latestMessage = await store.GetLatestMessageAsync(index, false); if (latestMessage != null) { Root ancestor = await store.GetAncestorAsync(latestMessage.Root, rootSlot); if (ancestor == root) { Validator validator = state.Validators[(int)index]; balance += validator.EffectiveBalance; } } } return(balance); }
public async Task <ApiResponse> PublishBlockAsync(SignedBeaconBlock signedBlock, CancellationToken cancellationToken) { string uri = "validator/block"; // TODO: .NET 5 will have JsonContent support, i.e. direct to stream //using HttpResponseMessage httpResponse = await _httpClient.PostAsJsonAsync(uri, signedBlock, cancellationToken); await using var memoryStream = new MemoryStream(); await JsonSerializer.SerializeAsync(memoryStream, signedBlock, _jsonSerializerOptions, cancellationToken); memoryStream.Position = 0; using var content = new StreamContent(memoryStream); content.Headers.ContentType = new MediaTypeHeaderValue(JsonContentType); using HttpResponseMessage httpResponse = await _httpClient.PostAsync(uri, content, cancellationToken); int statusCode = (int)httpResponse.StatusCode; if (statusCode == (int)StatusCode.InvalidRequest || statusCode == (int)StatusCode.CurrentlySyncing) { return(new ApiResponse((StatusCode)statusCode)); } httpResponse.EnsureSuccessStatusCode(); // throws if not 200-299 return(new ApiResponse((StatusCode)statusCode)); }
public async Task <IActionResult> GetAsync([FromBody] SignedBeaconBlock signedBeaconBlock, CancellationToken cancellationToken) { if (_logger.IsInfo()) { Log.BlockPublished(_logger, signedBeaconBlock.Message?.Slot, signedBeaconBlock.Message?.Body?.RandaoReveal, signedBeaconBlock.Message?.ParentRoot, signedBeaconBlock.Message?.StateRoot, signedBeaconBlock.Message?.Body?.Graffiti, signedBeaconBlock.Signature, null); } ApiResponse apiResponse = await _beaconNode.PublishBlockAsync(signedBeaconBlock, cancellationToken).ConfigureAwait(false); return(apiResponse.StatusCode switch { // "The block was validated successfully and has been broadcast. It has also been integrated into the beacon node's database." Core2.Api.StatusCode.Success => Ok(), // "The block failed validation, but was successfully broadcast anyway. It was not integrated into the beacon node's database." Core2.Api.StatusCode.BroadcastButFailedValidation => Accepted(), 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) });
// [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); }
public async Task ShorterChainButHeavierWeight() { // 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); // build longer tree Root longRoot = Root.Zero; BeaconState longState = BeaconState.Clone(genesisState); for (int i = 0; i < 3; i++) { BeaconBlock longBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, longState, BlsSignature.Zero); SignedBeaconBlock signedLongBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, longState, longBlock); await AddBlockToStore(testServiceProvider, store, signedLongBlock); if (i == 2) { longRoot = cryptographyService.HashTreeRoot(longBlock); } } // build short tree BeaconState shortState = BeaconState.Clone(genesisState); BeaconBlock shortBlock = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, shortState, BlsSignature.Zero); shortBlock.Body.SetGraffiti(new Bytes32(Enumerable.Repeat((byte)0x42, 32).ToArray())); TestBlock.SignBlock(testServiceProvider, shortState, shortBlock, ValidatorIndex.None); SignedBeaconBlock signedShortBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, shortState, shortBlock); await AddBlockToStore(testServiceProvider, store, signedShortBlock); Attestation shortAttestation = TestAttestation.GetValidAttestation(testServiceProvider, shortState, shortBlock.Slot, CommitteeIndex.None, signed: true); await AddAttestationToStore(testServiceProvider, store, shortAttestation); // Act Root headRoot = await forkChoice.GetHeadAsync(store); // Assert Root expectedRoot = cryptographyService.HashTreeRoot(shortBlock); headRoot.ShouldBe(expectedRoot); headRoot.ShouldNotBe(longRoot); }
public async Task SignedBeaconBlock_RoundTripEmpty() { // Arrange JsonSerializerOptions options = new JsonSerializerOptions(); options.ConfigureNethermindCore2(); Eth1Data eth1Data = new Eth1Data( new Root(Enumerable.Repeat((byte)0x12, 32).ToArray()), 64, new Bytes32(Enumerable.Repeat((byte)0x34, 32).ToArray())); BlsSignature randaoReveal = new BlsSignature(Enumerable.Repeat((byte)0xfe, 96).ToArray()); BeaconBlockBody beaconBlockBody = new BeaconBlockBody( randaoReveal, eth1Data, new Bytes32(new byte[32]), new ProposerSlashing[0], new AttesterSlashing [0], new Attestation[0], new Deposit[0], new SignedVoluntaryExit[0] ); BeaconBlock beaconBlock = new BeaconBlock( new Slot(1), new Root(Enumerable.Repeat((byte)0x78, 32).ToArray()), new Root(Enumerable.Repeat((byte)0x9a, 32).ToArray()), beaconBlockBody); SignedBeaconBlock signedBeaconBlock = new SignedBeaconBlock( beaconBlock, new BlsSignature(Enumerable.Repeat((byte)0x0e, 96).ToArray()) ); // Act - round trip to string await using MemoryStream outputMemoryStream = new MemoryStream(); await JsonSerializer.SerializeAsync(outputMemoryStream, signedBeaconBlock, options); string jsonString = Encoding.UTF8.GetString(outputMemoryStream.ToArray()); Console.WriteLine(jsonString); // Assert - Round trip await using MemoryStream inputMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); SignedBeaconBlock roundTripSignedBeaconBlock = await JsonSerializer.DeserializeAsync <SignedBeaconBlock>(inputMemoryStream, options); roundTripSignedBeaconBlock.Message.Body.Eth1Data.BlockHash.AsSpan()[1].ShouldBe((byte)0x34); }
public async Task ShouldNotRequestIfHeadBehind() { // Arrange IServiceCollection testServiceCollection = TestSystem.BuildTestServiceCollection(useStore: true); INetworkPeering mockNetworkPeering = Substitute.For <INetworkPeering>(); testServiceCollection.AddSingleton <INetworkPeering>(mockNetworkPeering); 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; ulong targetTime = 2 * 6; // slot 2 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); } } // Act PeeringStatus peeringStatus = new PeeringStatus( new ForkVersion(new byte[4] { 0, 0, 0, 0 }), Root.Zero, Epoch.Zero, new Root(Enumerable.Repeat((byte)0x56, 32).ToArray()), new Slot(1)); ISynchronizationManager synchronizationManager = testServiceProvider.GetService <ISynchronizationManager>(); await synchronizationManager.OnStatusResponseReceived("peer", peeringStatus); // Assert await mockNetworkPeering.DidNotReceive() .RequestBlocksAsync("peer", Arg.Any <Root>(), Arg.Any <Slot>(), Arg.Any <Slot>()); await mockNetworkPeering.DidNotReceive().DisconnectPeerAsync("peer"); }
public async Task <ApiResponse> PublishBlockAsync(SignedBeaconBlock signedBlock, CancellationToken cancellationToken) { try { if (!_store.IsInitialized) { return(new ApiResponse(StatusCode.CurrentlySyncing)); } bool acceptedLocally = false; try { await _forkChoice.OnBlockAsync(_store, signedBlock).ConfigureAwait(false); // TODO: validate as per honest validator spec and return true/false acceptedLocally = true; } catch (Exception ex) { if (_logger.IsWarn()) { Log.BlockNotAcceptedLocally(_logger, signedBlock.Message, ex); } } if (_logger.IsDebug()) { LogDebug.PublishingBlockToNetwork(_logger, signedBlock.Message, null); } await _networkPeering.PublishBeaconBlockAsync(signedBlock).ConfigureAwait(false); if (acceptedLocally) { return(new ApiResponse(StatusCode.Success)); } else { return(new ApiResponse(StatusCode.BroadcastButFailedValidation)); } } catch (Exception ex) { if (_logger.IsWarn()) { Log.ApiErrorPublishBlock(_logger, ex); } throw; } }
public static void AddAttestationsToState(IServiceProvider testServiceProvider, BeaconState state, IEnumerable <Attestation> attestations, Slot slot) { BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); BeaconBlock block = TestBlock.BuildEmptyBlock(testServiceProvider, state, slot, BlsSignature.Zero); foreach (Attestation attestation in attestations) { block.Body.AddAttestations(attestation); } beaconStateTransition.ProcessSlots(state, block.Slot); SignedBeaconBlock signedBlock = TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); beaconStateTransition.StateTransition(state, signedBlock, validateResult: false); }
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 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); }
private void OnGossipReceived(ReadOnlySpan <byte> topicUtf8, ReadOnlySpan <byte> data) { Activity activity = new Activity("gossip-received"); activity.Start(); using var activityScope = _logger.BeginScope("[TraceId, {TraceId}], [SpanId, {SpanId}]", activity.TraceId, activity.SpanId); try { // TODO: handle other topics if (topicUtf8.SequenceEqual(TopicUtf8.BeaconBlock)) { if (_logger.IsDebug()) { LogDebug.GossipReceived(_logger, Encoding.UTF8.GetString(topicUtf8), data.Length, null); } // Need to deserialize in synchronous context (can't pass Span async) SignedBeaconBlock signedBeaconBlock = Ssz.Ssz.DecodeSignedBeaconBlock(data); _signedBeaconBlockProcessor.EnqueueGossip(signedBeaconBlock); // TODO: After receiving a gossip, should we re-gossip it, i.e. to our peers? // NOTE: Need to apply validations, from spec, before forwarding; also, avoid loops (i.e. don't gossip twice) } else { if (_logger.IsWarn()) { Log.UnknownGossipReceived(_logger, Encoding.UTF8.GetString(topicUtf8), data.Length, null); } } } catch (Exception ex) { if (_logger.IsError()) { Log.GossipReceivedError(_logger, Encoding.UTF8.GetString(topicUtf8), ex.Message, ex); } } finally { activity.Stop(); } }
/// <summary> /// State transition via the provided ``block`` /// then package the block with the state root and signature. /// </summary> public static SignedBeaconBlock StateTransitionAndSignBlock(IServiceProvider testServiceProvider, BeaconState state, BeaconBlock block) { MiscellaneousParameters miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; StateListLengths stateListLengths = testServiceProvider.GetService <IOptions <StateListLengths> >().Value; MaxOperationsPerBlock maxOperationsPerBlock = testServiceProvider.GetService <IOptions <MaxOperationsPerBlock> >().Value; ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); BeaconStateTransition beaconStateTransition = testServiceProvider.GetService <BeaconStateTransition>(); SignedBeaconBlock preSigningBlock = new SignedBeaconBlock(block, BlsSignature.Zero); beaconStateTransition.StateTransition(state, preSigningBlock, validateResult: false); Root stateRoot = cryptographyService.HashTreeRoot(state); block.SetStateRoot(stateRoot); SignedBeaconBlock signedBlock = TestBlock.SignBlock(testServiceProvider, state, block, ValidatorIndex.None); return(signedBlock); }
public async Task BasicOnBlock() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Initialization IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); ulong time = 100uL; await forkChoice.OnTickAsync(store, time); store.Time.ShouldBe(time); // On receiving a block of `GENESIS_SLOT + 1` slot BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await RunOnBlock(testServiceProvider, store, signedBlock, expectValid : true); // On receiving a block of next epoch ulong time2 = time + timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch; await store.SetTimeAsync(time2); Slot slot2 = (Slot)(block.Slot + timeParameters.SlotsPerEpoch); BeaconBlock block2 = TestBlock.BuildEmptyBlock(testServiceProvider, state, slot2, BlsSignature.Zero); SignedBeaconBlock signedBlock2 = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2); //var options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; //options.AddCortexContainerConverters(); //var debugState = System.Text.Json.JsonSerializer.Serialize(state, options); await RunOnBlock(testServiceProvider, store, signedBlock2, expectValid : true); // Assert // TODO: add tests for justified_root and finalized_root }
public Task PublishBeaconBlockAsync(SignedBeaconBlock signedBlock) { // TODO: Validate signature before broadcasting (if not already validated) Span <byte> encoded = new byte[Ssz.Ssz.SignedBeaconBlockLength(signedBlock)]; Ssz.Ssz.Encode(encoded, signedBlock); if (_logger.IsDebug()) { LogDebug.GossipSend(_logger, nameof(TopicUtf8.BeaconBlock), encoded.Length, null); } if (!_mothraLibp2p.SendGossip(TopicUtf8.BeaconBlock, encoded)) { if (_logger.IsWarn()) { Log.GossipNotPublishedAsPeeeringNotStarted(_logger, nameof(TopicUtf8.BeaconBlock), null); } } return(Task.CompletedTask); }
public async Task OnAttestationPastEpoch() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); ChainConstants chainConstants = testServiceProvider.GetService <ChainConstants>(); InitialValues initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; IForkChoice forkChoice = testServiceProvider.GetService <IForkChoice>(); // Initialization IStore store = testServiceProvider.GetService <IStore>(); await forkChoice.InitializeForkChoiceStoreAsync(store, state); // move time forward 2 epochs ulong time = store.Time + 2 * timeParameters.SecondsPerSlot * (ulong)timeParameters.SlotsPerEpoch; await forkChoice.OnTickAsync(store, time); // create and store block from 3 epochs ago BeaconBlock block = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, BlsSignature.Zero); SignedBeaconBlock signedBlock = TestState.StateTransitionAndSignBlock(testServiceProvider, state, block); await forkChoice.OnBlockAsync(store, signedBlock); // create attestation for past block Attestation attestation = TestAttestation.GetValidAttestation(testServiceProvider, state, state.Slot, CommitteeIndex.None, signed: true); attestation.Data.Target.Epoch.ShouldBe(chainConstants.GenesisEpoch); IBeaconChainUtility beaconChainUtility = testServiceProvider.GetService <IBeaconChainUtility>(); Slot currentSlot = ((ForkChoice)forkChoice).GetCurrentSlot(store); Epoch currentEpoch = beaconChainUtility.ComputeEpochAtSlot(currentSlot); currentEpoch.ShouldBe((Epoch)(chainConstants.GenesisEpoch + 2UL)); await RunOnAttestation(testServiceProvider, state, store, attestation, expectValid : false); }
public Task SendBlockAsync(string peerId, SignedBeaconBlock signedBlock) { byte[] peerUtf8 = Encoding.UTF8.GetBytes(peerId); Span <byte> encoded = new byte[Ssz.Ssz.SignedBeaconBlockLength(signedBlock)]; Ssz.Ssz.Encode(encoded, signedBlock); if (_logger.IsDebug()) { LogDebug.RpcSend(_logger, RpcDirection.Response, nameof(MethodUtf8.BeaconBlocksByRange), peerId, encoded.Length, null); } if (!_mothraLibp2p.SendRpcResponse(MethodUtf8.BeaconBlocksByRange, peerUtf8, encoded)) { if (_logger.IsWarn()) { Log.RpcResponseNotSentAsPeeeringNotStarted(_logger, nameof(MethodUtf8.BeaconBlocksByRange), null); } } return(Task.CompletedTask); }