/// <summary> /// To address the bouncing attack, only update conflicting justified /// checkpoints in the fork choice if in the early slots of the epoch. /// Otherwise, delay incorporation of new justified checkpoint until next epoch boundary. /// See https://ethresear.ch/t/prevention-of-bouncing-attack-on-ffg/6114 for more detailed analysis and discussion. /// </summary> public async Task <bool> ShouldUpdateJustifiedCheckpointAsync(IStore store, Checkpoint newJustifiedCheckpoint) { Slot currentSlot = GetCurrentSlot(store); Slot slotsSinceEpochStart = ComputeSlotsSinceEpochStart(currentSlot); if (slotsSinceEpochStart < _forkChoiceConfigurationOptions.CurrentValue.SafeSlotsToUpdateJustified) { return(true); } BeaconBlock newJustifiedBlock = await store.GetBlockAsync(newJustifiedCheckpoint.Root).ConfigureAwait(false); Slot justifiedCheckpointEpochStartSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(store.JustifiedCheckpoint.Epoch); if (newJustifiedBlock.Slot <= justifiedCheckpointEpochStartSlot) { return(false); } BeaconBlock justifiedCheckPointBlock = await store.GetBlockAsync(store.JustifiedCheckpoint.Root).ConfigureAwait(false); Hash32 ancestorOfNewCheckpointAtOldCheckpointSlot = await GetAncestorAsync(store, newJustifiedCheckpoint.Root, justifiedCheckPointBlock.Slot).ConfigureAwait(false); // i.e. new checkpoint is descendant of old checkpoint return(ancestorOfNewCheckpointAtOldCheckpointSlot == store.JustifiedCheckpoint.Root); }
public async Task <Hash32> GetHeadAsync(IStore store) { // NOTE: This method should probably live in a separate object, for different implementations, possibly part of Store (for efficiency). // Execute the LMD-GHOST fork choice Hash32 head = store.JustifiedCheckpoint.Root; Slot justifiedSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(store.JustifiedCheckpoint.Epoch); while (true) { List <Tuple <Hash32, Gwei> > childKeysWithBalances = new List <Tuple <Hash32, Gwei> >(); await foreach (Hash32 childKey in store.GetChildKeysAfterSlotAsync(head, justifiedSlot) .ConfigureAwait(false)) { Gwei balance = await GetLatestAttestingBalanceAsync(store, childKey).ConfigureAwait(false); childKeysWithBalances.Add(Tuple.Create(childKey, balance)); } if (childKeysWithBalances.Count == 0) { return(head); } head = childKeysWithBalances .OrderByDescending(x => x.Item2) .ThenByDescending(x => x.Item1) .Select(x => x.Item1) .First(); } }
public async Task <Gwei> GetLatestAttestingBalanceAsync(IStore store, Hash32 root) { // NOTE: This method should probably live in IStore, for various efficient implementations. 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); BeaconBlock rootBlock = await store.GetBlockAsync(root).ConfigureAwait(false); Slot rootSlot = rootBlock !.Slot; Gwei balance = Gwei.Zero; foreach (ValidatorIndex index in activeIndexes) { LatestMessage?latestMessage = await store.GetLatestMessageAsync(index, false); if (latestMessage != null) { Hash32 ancestor = await GetAncestorAsync(store, latestMessage.Root, rootSlot); if (ancestor == root) { Validator validator = state.Validators[(int)index]; balance += validator.EffectiveBalance; } } } return(balance); }
public async Task GenesisHead() { // Arrange IServiceProvider testServiceProvider = TestSystem.BuildTestServiceProvider(useStore: true); BeaconState state = TestState.PrepareTestState(testServiceProvider); 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; JsonSerializerOptions options = new System.Text.Json.JsonSerializerOptions { WriteIndented = true }; options.ConfigureNethermindCore2(); string debugState = System.Text.Json.JsonSerializer.Serialize(state, options); // Initialization ICryptographyService cryptographyService = testServiceProvider.GetService <ICryptographyService>(); ForkChoice forkChoice = testServiceProvider.GetService <ForkChoice>(); IStore store = forkChoice.GetGenesisStore(state); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 stateRoot = cryptographyService.HashTreeRoot(state); BeaconBlock genesisBlock = new BeaconBlock(stateRoot); Hash32 expectedRoot = cryptographyService.SigningRoot(genesisBlock); headRoot.ShouldBe(expectedRoot); }
public async Task ChainNoAttestations() { // 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); // On receiving a block of `GENESIS_SLOT + 1` slot BeaconBlock block1 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, state, block1); await AddBlockToStore(testServiceProvider, store, block1); // On receiving a block of next epoch BeaconBlock block2 = TestBlock.BuildEmptyBlockForNextSlot(testServiceProvider, state, signed: true); TestState.StateTransitionAndSignBlock(testServiceProvider, state, block2); await AddBlockToStore(testServiceProvider, store, block2); // Act Hash32 headRoot = await forkChoice.GetHeadAsync(store); // Assert Hash32 expectedRoot = cryptographyService.SigningRoot(block2); headRoot.ShouldBe(expectedRoot); }
public static (Deposit, Hash32) BuildDeposit(IServiceProvider testServiceProvider, BeaconState?state, IList <DepositData> depositDataList, BlsPublicKey publicKey, byte[] privateKey, Gwei amount, Hash32 withdrawalCredentials, bool signed) { var chainConstants = testServiceProvider.GetService <ChainConstants>(); var beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>(); var depositData = BuildDepositData(testServiceProvider, publicKey, privateKey, amount, withdrawalCredentials, state, signed); var index = depositDataList.Count; depositDataList.Add(depositData); Hash32 root = depositDataList.HashTreeRoot((ulong)1 << chainConstants.DepositContractTreeDepth); var allLeaves = depositDataList.Select(x => x.HashTreeRoot()); var tree = TestSecurity.CalculateMerkleTreeFromLeaves(allLeaves); var merkleProof = TestSecurity.GetMerkleProof(tree, index, 32); var proof = new List <Hash32>(merkleProof); var indexBytes = new Span <byte>(new byte[32]); BitConverter.TryWriteBytes(indexBytes, (ulong)index + 1); if (!BitConverter.IsLittleEndian) { indexBytes.Slice(0, 8).Reverse(); } var indexHash = new Hash32(indexBytes); proof.Add(indexHash); var leaf = depositData.HashTreeRoot(); beaconChainUtility.IsValidMerkleBranch(leaf, proof, chainConstants.DepositContractTreeDepth + 1, (ulong)index, root); var deposit = new Deposit(proof, depositData); return(deposit, root); }
public byte[] GeneratePrivateKey(ulong index) { Span <byte> input = new Span <byte>(new byte[32]); BigInteger bigIndex = new BigInteger(index); bool indexWriteSuccess = bigIndex.TryWriteBytes(input, out int indexBytesWritten, isUnsigned: true, isBigEndian: false); if (!indexWriteSuccess || indexBytesWritten == 0) { throw new Exception("Error getting input for quick start private key generation."); } Hash32 hash32 = _cryptographyService.Hash(input); ReadOnlySpan <byte> hash = hash32.AsSpan(); // Mocked start interop specifies to convert the hash as little endian (which is the default for BigInteger) BigInteger value = new BigInteger(hash.ToArray(), isUnsigned: true); BigInteger privateKey = value % s_curveOrder; // Note that the private key is an *unsigned*, *big endian* number // However, we want to pad the big endian on the left to get 32 bytes. // So, write as little endian (will pad to right), then reverse. // NOTE: Alternative, write to Span 64, and then slice based on bytesWritten to get the padding. Span <byte> privateKeySpan = new Span <byte>(new byte[32]); bool keyWriteSuccess = privateKey.TryWriteBytes(privateKeySpan, out int keyBytesWritten, isUnsigned: true, isBigEndian: false); if (!keyWriteSuccess) { throw new Exception("Error generating quick start private key."); } privateKeySpan.Reverse(); return(privateKeySpan.ToArray()); }
/// <summary> /// Returns the Hash32 of the payload added to buffer /// </summary> public uint AddPayloadToBuffer(byte[] buffer, ref int offset) { buffer[offset++] = (byte)Sequence; buffer[offset++] = (byte)(Sequence >> 8); buffer[offset++] = (byte)(Sequence >> 16); buffer[offset++] = (byte)(Sequence >> 24); buffer[offset++] = (byte)Id; buffer[offset++] = (byte)(Id >> 8); buffer[offset++] = (byte)(Id >> 16); buffer[offset++] = (byte)(Id >> 24); buffer[offset++] = (byte)Count; buffer[offset++] = (byte)(Count >> 8); buffer[offset++] = (byte)Size; buffer[offset++] = (byte)(Size >> 8); buffer[offset++] = (byte)Index; buffer[offset++] = (byte)(Index >> 8); buffer[offset++] = (byte)Queue; buffer[offset++] = (byte)(Queue >> 8); return(Hash32.Calculate(buffer, offset - HeaderSize, HeaderSize)); }
/// <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, Hash32 withdrawalCredentials, bool signed) { var chainConstants = testServiceProvider.GetService <ChainConstants>(); var initialValues = testServiceProvider.GetService <IOptions <InitialValues> >().Value; var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; var beaconChainUtility = testServiceProvider.GetService <BeaconChainUtility>(); var beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); var privateKeys = TestKeys.PrivateKeys(timeParameters).ToArray(); var publicKeys = TestKeys.PublicKeys(timeParameters).ToArray(); var privateKey = privateKeys[(int)(ulong)validatorIndex]; var publicKey = publicKeys[(int)(ulong)validatorIndex]; if (withdrawalCredentials == Hash32.Zero) { // insecurely use pubkey as withdrawal key if no credentials provided var withdrawalCredentialBytes = TestSecurity.Hash(publicKey.AsSpan()); withdrawalCredentialBytes[0] = initialValues.BlsWithdrawalPrefix; withdrawalCredentials = new Hash32(withdrawalCredentialBytes); } var depositDataList = new List <DepositData>(); (var deposit, var 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); }
public DepositData(BlsPublicKey publicKey, Hash32 withdrawalCredentials, Gwei amount) { PublicKey = publicKey; WithdrawalCredentials = withdrawalCredentials; Amount = amount; Signature = new BlsSignature(); }
public async Task <BeaconBlock> NewBlockAsync(Slot slot, BlsSignature randaoReveal) { if (slot == Slot.Zero) { throw new ArgumentException("Can't generate new block for slot 0, as it is the genesis block."); } if (!_storeProvider.TryGetStore(out IStore? retrievedStore)) { throw new Exception("Beacon chain is currently syncing or waiting for genesis."); } IStore store = retrievedStore !; Slot previousSlot = slot - Slot.One; Hash32 head = await _forkChoice.GetHeadAsync(store).ConfigureAwait(false); BeaconBlock headBlock = await store.GetBlockAsync(head).ConfigureAwait(false); BeaconBlock parentBlock; BeaconState parentState; Hash32 parentRoot; if (headBlock !.Slot > previousSlot) { // Requesting a block for a past slot? Hash32 ancestorSigningRoot = await _forkChoice.GetAncestorAsync(store, head, previousSlot); parentBlock = await store.GetBlockAsync(ancestorSigningRoot).ConfigureAwait(false); parentState = await store.GetBlockStateAsync(ancestorSigningRoot).ConfigureAwait(false); parentRoot = ancestorSigningRoot; }
public TransactionInfo(Transaction transaction, BigInteger txIndex, BigInteger blockHeight, Hash32 blockHash) { Transaction = transaction; TxIndex = txIndex; BlockHeight = blockHeight; BlockHash = blockHash; }
protected override void OnProcess(Sitecore.Analytics.Aggregation.Pipeline.AggregationPipelineArgs args) { Sitecore.Diagnostics.Assert.ArgumentNotNull((object)args, "args"); Browsers fact = args.GetFact <Browsers>(); BrowserMajor dimension1 = args.GetDimension <BrowserMajor>(); BrowserMinor dimension2 = args.GetDimension <BrowserMinor>(); SiteNames dimension3 = args.GetDimension <SiteNames>(); var visit = args.Context.Visit; var browserData = visit.Browser; int value = visit.Value; Hash32 hash32_1 = dimension1.Add(browserData.BrowserMajorName ?? "[Unknown]"); Hash32 hash32_2 = dimension2.Add(hash32_1, browserData.BrowserMinorName ?? "[Unknown]"); Hash32 hash32_3 = dimension3.Add(visit.SiteName ?? "[Unknown]"); args.GetFact <Browsers>().Emit( new BrowsersKey() { Date = args.DateTimeStrategy.Translate(visit.StartDateTime), BrowserMajorId = hash32_1, BrowserMinorId = hash32_2, SiteNameId = hash32_3, Checksum = Hash32.Compute((object)hash32_1, (object)hash32_2, (object)hash32_3) }, new BrowsersValue() { Value = value, Visits = 1 }); }
private uint CalculatePayloadChecksum() { uint checksum = 0u; if (Header.HasFlag(PacketHeaderFlags.BlobFragments)) { if (HeaderOptional != null) { // FIXME: packets with both optional headers and fragments fail to verify byte[] optionalHeader = new byte[HeaderOptional.Size]; Buffer.BlockCopy(Data.ToArray(), 0, optionalHeader, 0, (int)HeaderOptional.Size); checksum += Hash32.Calculate(optionalHeader, (int)HeaderOptional.Size); } foreach (var fragment in Fragments) { checksum += Hash32.Calculate(fragment.Header.GetRaw(), (int)PacketFragmentHeader.HeaderSize) + Hash32.Calculate(fragment.Data.ToArray(), fragment.Header.Size - (int)PacketFragmentHeader.HeaderSize); } } else { checksum += Hash32.Calculate(Data.ToArray(), (int)Data.Length); } return(checksum); }
public async Task <bool> Invoke(Hash32 hash) { var request = new GetTransactionResultRequestMessage(hash); var response = await Invoke(request); return(response.IsSuccess); }
/// <summary> /// Return the randao mix at a recent ``epoch`` /// </summary> public Hash32 GetRandaoMix(BeaconState state, Epoch epoch) { int index = (int)(epoch % _stateListLengthOptions.CurrentValue.EpochsPerHistoricalVector); Hash32 mix = state.RandaoMixes[index]; return(mix); }
public async Task <GetTransactionResultResponseMessage.Receipt> Invoke(Hash32 hash) { var request = new GetTransactionResultRequestMessage(hash); var response = await Invoke(request); return(response.Result); }
private static Hash32 DecodeSha256(Span <byte> span, ref int offset) { Hash32 hash32 = DecodeSha256(span.Slice(offset, Ssz.Hash32Length)); offset += Ssz.Hash32Length; return(hash32); }
/// <summary> /// Return from ``indices`` a random index sampled by effective balance. /// </summary> public ValidatorIndex ComputeProposerIndex(BeaconState state, IList<ValidatorIndex> indices, Hash32 seed) { if (!indices.Any()) { throw new ArgumentException("Indices can not be empty", nameof(indices)); } ulong indexCount = (ulong) indices.Count; ValidatorIndex index = 0UL; Span<byte> randomInputBytes = stackalloc byte[40]; seed.AsSpan().CopyTo(randomInputBytes); while (true) { ValidatorIndex initialValidatorIndex = (ValidatorIndex)(index % indexCount); ValidatorIndex shuffledIndex = ComputeShuffledIndex(initialValidatorIndex, indexCount, seed); ValidatorIndex candidateIndex = indices[(int) shuffledIndex]; BinaryPrimitives.WriteUInt64LittleEndian(randomInputBytes.Slice(32), index / 32); Hash32 randomHash = _cryptographyService.Hash(randomInputBytes); byte random = randomHash.AsSpan()[(int) (index % 32)]; Gwei effectiveBalance = state.Validators[(int) candidateIndex].EffectiveBalance; if ((effectiveBalance * byte.MaxValue) >= (_gweiValueOptions.CurrentValue.MaximumEffectiveBalance * random)) { return candidateIndex; } index++; } }
public Hash32 Hash(Hash32 a, Hash32 b) { Span<byte> input = new Span<byte>(new byte[Hash32.Length * 2]); a.AsSpan().CopyTo(input); b.AsSpan().CopyTo(input.Slice(Hash32.Length)); return Hash(input); }
public byte[] GetPayload() { uint headerChecksum = 0u; uint bodyChecksum = 0u; uint fragmentChecksum = 0u; using (MemoryStream stream = new MemoryStream()) { using (BinaryWriter writer = new BinaryWriter(stream)) { writer.Seek((int)PacketHeader.HeaderSize, SeekOrigin.Begin); if (Data.Length > 0) { var body = Data.ToArray(); writer.Write(body); bodyChecksum = Hash32.Calculate(body, body.Length); } foreach (ServerPacketFragment fragment in Fragments) { fragmentChecksum += fragment.GetPayload(writer); } Header.Size = (ushort)(stream.Length - PacketHeader.HeaderSize); headerChecksum = Header.CalculateHash32(); uint payloadChecksum = bodyChecksum + fragmentChecksum; Header.Checksum = headerChecksum + (payloadChecksum ^ issacXor); writer.Seek(0, SeekOrigin.Begin); writer.Write(Header.GetRaw()); writer.Flush(); return(stream.ToArray()); } } }
public Transaction( string version, Address from, Address to, BigInteger?value, BigInteger?stepLimit, BigInteger?nonce, BigInteger?nid, BigInteger?timestamp, string dataType, object data, Hash32 hash, Signature signature) { Version = version; From = from; To = to; Value = value; StepLimit = stepLimit; Nonce = nonce; NID = nid; Timestamp = timestamp; DataType = dataType; Data = data; Hash = hash; Signature = signature; }
private void CheckHistoricalSlots(IStore store, IReadOnlyList <Hash32> historicalBlockRoots, Slot fromSlot, Slot startSlot, ValidatorIndex validatorIndex, ref Slot attestationSlot, ref CommitteeIndex attestationCommitteeIndex, ref Slot blockProposalSlot) { TimeParameters timeParameters = _timeParameterOptions.CurrentValue; Slot previousSlot = fromSlot; while (true) { previousSlot -= Slot.One; int index = (int)(previousSlot % timeParameters.SlotsPerHistoricalRoot); Hash32 previousRoot = historicalBlockRoots[index]; if (!store.TryGetBlockState(previousRoot, out BeaconState? previousState)) { throw new Exception($"Historical state {previousRoot} for slot {previousSlot} not found."); } CheckStateDuty(previousState !, validatorIndex, ref attestationSlot, ref attestationCommitteeIndex, ref blockProposalSlot); if (previousSlot <= startSlot || (attestationSlot != Slot.None && blockProposalSlot != Slot.None)) { break; } } }
public void Eth1VoteReset() { // Arrange var testServiceProvider = TestSystem.BuildTestServiceProvider(); var state = TestState.PrepareTestState(testServiceProvider); var timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; // skip ahead to the end of the voting period state.SetSlot((Slot)(timeParameters.SlotsPerEth1VotingPeriod - 1UL)); // add a vote for each skipped slot. for (var index = Slot.Zero; index < state.Slot + new Slot(1); index += new Slot(1)) { var eth1DepositIndex = state.Eth1DepositIndex; var depositRoot = new Hash32(Enumerable.Repeat((byte)0xaa, 32).ToArray()); var blockHash = new Hash32(Enumerable.Repeat((byte)0xbb, 32).ToArray()); var eth1Data = new Eth1Data(depositRoot, eth1DepositIndex, blockHash); state.AddEth1DataVote(eth1Data); } // Act RunProcessFinalUpdates(testServiceProvider, state); // Assert state.Eth1DataVotes.Count.ShouldBe(0); }
public Gwei GetLatestAttestingBalance(IStore store, Hash32 root) { if (!store.TryGetCheckpointState(store.JustifiedCheckpoint, out var storedState)) { throw new Exception($"Not able to get checkpoint state {store.JustifiedCheckpoint}"); } var state = storedState !; var currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); var activeIndexes = _beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch); if (!store.TryGetBlock(root, out var rootBlock)) { throw new Exception($"Not ble to find block {root}"); } Slot rootSlot = rootBlock !.Slot; Gwei balance = Gwei.Zero; foreach (ValidatorIndex index in activeIndexes) { if (store.TryGetLatestMessage(index, out var latestMessage)) { var ancestor = GetAncestor(store, latestMessage !.Root, rootSlot); if (ancestor == root) { var validator = state.Validators[(int)index]; balance += validator.EffectiveBalance; } } } return(balance); }
/// <summary> /// To address the bouncing attack, only update conflicting justified /// checkpoints in the fork choice if in the early slots of the epoch. /// Otherwise, delay incorporation of new justified checkpoint until next epoch boundary. /// See https://ethresear.ch/t/prevention-of-bouncing-attack-on-ffg/6114 for more detailed analysis and discussion. /// </summary> public bool ShouldUpdateJustifiedCheckpoint(IStore store, Checkpoint newJustifiedCheckpoint) { var currentSlot = GetCurrentSlot(store); var slotsSinceEpochStart = ComputeSlotsSinceEpochStart(currentSlot); if (slotsSinceEpochStart < _forkChoiceConfigurationOptions.CurrentValue.SafeSlotsToUpdateJustified) { return(true); } if (!store.TryGetBlock(newJustifiedCheckpoint.Root, out var newJustifiedBlock)) { throw new NotImplementedException("What if block is null"); } Slot justifiedCheckpointEpochStartSlot = _beaconChainUtility.ComputeStartSlotOfEpoch(store.JustifiedCheckpoint.Epoch); if (newJustifiedBlock !.Slot <= justifiedCheckpointEpochStartSlot) { return(false); } if (!store.TryGetBlock(store.JustifiedCheckpoint.Root, out var justifiedCheckPointBlock)) { throw new NotImplementedException("What if justified checkpoint block is null"); } Hash32 ancestorOfNewCheckpointAtOldCheckpointSlot = GetAncestor(store, newJustifiedCheckpoint.Root, justifiedCheckPointBlock !.Slot); // i.e. new checkpoint is descendant of old checkpoint return(ancestorOfNewCheckpointAtOldCheckpointSlot == store.JustifiedCheckpoint.Root); }
public uint CalculateHash32() { byte[] fragmentHeaderBytes = Header.GetRaw(); uint fragmentChecksum = Hash32.Calculate(fragmentHeaderBytes, fragmentHeaderBytes.Length) + Hash32.Calculate(Data, Data.Length); return(fragmentChecksum); }
public Gwei GetLatestAttestingBalance(IStore store, Hash32 root) { if (!store.TryGetCheckpointState(store.JustifiedCheckpoint, out var state)) { throw new Exception(); } var currentEpoch = _beaconStateAccessor.GetCurrentEpoch(state); var activeIndexes = _beaconStateAccessor.GetActiveValidatorIndices(state, currentEpoch); if (!store.TryGetBlock(root, out var rootBlock)) { throw new Exception(); } var rootSlot = rootBlock.Slot; var balance = new Gwei(0); foreach (var index in activeIndexes) { if (store.TryGetLatestMessage(index, out var latestMessage)) { var ancestor = GetAncestor(store, latestMessage.Root, rootSlot); if (ancestor == root) { var validator = state.Validators[(int)(ulong)index]; balance += validator.EffectiveBalance; } } } return(balance); }
public static AttesterSlashing GetValidAttesterSlashing(IServiceProvider testServiceProvider, BeaconState state, bool signed1, bool signed2) { TimeParameters timeParameters = testServiceProvider.GetService <IOptions <TimeParameters> >().Value; BeaconStateAccessor beaconStateAccessor = testServiceProvider.GetService <BeaconStateAccessor>(); Attestation attestation1 = TestAttestation.GetValidAttestation(testServiceProvider, state, Slot.None, CommitteeIndex.None, signed1); Hash32 targetRoot2 = new Hash32(Enumerable.Repeat((byte)0x01, 32).ToArray()); Attestation attestation2 = new Attestation( attestation1.AggregationBits, new AttestationData(attestation1.Data.Slot, attestation1.Data.Index, attestation1.Data.BeaconBlockRoot, attestation1.Data.Source, new Checkpoint( attestation1.Data.Target.Epoch, targetRoot2 )), BlsSignature.Empty ); if (signed2) { TestAttestation.SignAttestation(testServiceProvider, state, attestation2); } IndexedAttestation indexedAttestation1 = beaconStateAccessor.GetIndexedAttestation(state, attestation1); IndexedAttestation indexedAttestation2 = beaconStateAccessor.GetIndexedAttestation(state, attestation2); AttesterSlashing attesterSlashing = new AttesterSlashing(indexedAttestation1, indexedAttestation2); return(attesterSlashing); }
public void TestInitializeBeaconStateFromEth1() { var useBls = true; // Arrange var testServiceProvider = TestSystem.BuildTestServiceProvider(useBls); var chainConstants = testServiceProvider.GetService <ChainConstants>(); var miscellaneousParameters = testServiceProvider.GetService <IOptions <MiscellaneousParameters> >().Value; var gweiValues = testServiceProvider.GetService <IOptions <GweiValues> >().Value; var depositCount = miscellaneousParameters.MinimumGenesisActiveValidatorCount; (var deposits, var depositRoot) = TestDeposit.PrepareGenesisDeposits(testServiceProvider, depositCount, gweiValues.MaximumEffectiveBalance, signed: useBls); var eth1BlockHash = new Hash32(Enumerable.Repeat((byte)0x12, 32).ToArray()); var eth1Timestamp = miscellaneousParameters.MinimumGenesisTime; var beaconChain = testServiceProvider.GetService <BeaconNode.Genesis>(); // Act //# initialize beacon_state var state = beaconChain.InitializeBeaconStateFromEth1(eth1BlockHash, eth1Timestamp, deposits); // Assert state.GenesisTime.ShouldBe(eth1Timestamp - eth1Timestamp % chainConstants.SecondsPerDay + 2 * chainConstants.SecondsPerDay); state.Validators.Count.ShouldBe(depositCount); state.Eth1Data.DepositRoot.ShouldBe(depositRoot); state.Eth1Data.DepositCount.ShouldBe((ulong)depositCount); state.Eth1Data.BlockHash.ShouldBe(eth1BlockHash); }
private static void ProcessDimensionSegments(AggregationPipelineArgs args, VisitData visit, Hash32 sitesHash, InteractionData interactionData) { foreach(Dimension dimension in Dimensions) { IEnumerable<Segment> segments = from segment in segmentDefinitionService.GetSegmentDefinitions() where segment.DimensionId == dimension.DimensionID select new Segment(segment, dimension); foreach(Segment segment in segments) { ISegmentKeyProvider keyProvider = null; switch(segment.Dimension.DimensionType) { case DimensionType.Browser: keyProvider = interactionData.Browser; break; case DimensionType.OS: keyProvider = interactionData.OS; break; case DimensionType.Screen: keyProvider = interactionData.Screen; break; case DimensionType.UserAgent: keyProvider = interactionData.UserAgent; break; } string segmentKeyValue = keyProvider.GetSegmentKeyValue(); Hash64 segmentDimensionKeyId = args.GetDimension<DimensionKeys>().Add(segmentKeyValue); Hash64 segmentRecordId = args.GetDimension<SegmentRecords>().Add(segment.Definition.Id, visit.StartDateTime, sitesHash, segmentDimensionKeyId); SegmentMetrics segmentMetricsFact = args.GetFact<SegmentMetrics>(); byte contactTransitionType = 1; if (visit.ContactVisitIndex > 1) contactTransitionType = 2; SegmentMetrics.Key segmentMetricsKey = new SegmentMetrics.Key { ContactTransitionType = contactTransitionType, SegmentRecordId = segmentRecordId }; List<PageEventData> evts = (from page in visit.Pages select page.PageEvents).FirstOrDefault(); SegmentMetricsValue segmentMetricsValue = new SegmentMetricsValue { //Same exact code from DimensionBase.CalculateCommonMetrics Visits = 1, Value = visit.Value, Bounces = visit.Pages.Count == 1 ? 1 : 0, Conversions = evts.Count<PageEventData>(e => e.IsGoal), TimeOnSite = visit.Pages.Sum<PageData>((Func<PageData, int>)(page => DimensionBase.ConvertDuration(page.Duration))), Pageviews = visit.Pages.Count, Count = visit.VisitPageCount }; segmentMetricsFact.Emit(segmentMetricsKey, segmentMetricsValue); } } }
public XorHash32To16(Hash32 hash32) { this.hash32 = hash32; }