Search in sources :

Example 1 with SyncAggregate

use of tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate in project teku by ConsenSys.

the class BlockProcessorAltair method processSyncAggregate.

@Override
public void processSyncAggregate(final MutableBeaconState baseState, final SyncAggregate aggregate, final BLSSignatureVerifier signatureVerifier) throws BlockProcessingException {
    final MutableBeaconStateAltair state = MutableBeaconStateAltair.required(baseState);
    final List<BLSPublicKey> participantPubkeys = new ArrayList<>();
    final List<BLSPublicKey> idlePubkeys = new ArrayList<>();
    for (int i = 0; i < specConfigAltair.getSyncCommitteeSize(); i++) {
        final BLSPublicKey publicKey = syncCommitteeUtil.getCurrentSyncCommitteeParticipantPubKey(state, i);
        if (aggregate.getSyncCommitteeBits().getBit(i)) {
            participantPubkeys.add(publicKey);
        } else {
            idlePubkeys.add(publicKey);
        }
    }
    final UInt64 previousSlot = state.getSlot().minusMinZero(1);
    final Bytes32 domain = beaconStateAccessors.getDomain(state.getForkInfo(), Domain.SYNC_COMMITTEE, miscHelpers.computeEpochAtSlot(previousSlot));
    final Bytes32 signingRoot = miscHelpersAltair.computeSigningRoot(beaconStateAccessors.getBlockRootAtSlot(state, previousSlot), domain);
    if (!eth2FastAggregateVerify(signatureVerifier, participantPubkeys, signingRoot, aggregate.getSyncCommitteeSignature().getSignature())) {
        throw new BlockProcessingException("Invalid sync committee signature in " + aggregate);
    }
    // Compute participant and proposer rewards
    final UInt64 totalActiveIncrements = beaconStateAccessors.getTotalActiveBalance(state).dividedBy(specConfig.getEffectiveBalanceIncrement());
    final UInt64 totalBaseRewards = beaconStateAccessorsAltair.getBaseRewardPerIncrement(state).times(totalActiveIncrements);
    final UInt64 maxParticipantRewards = totalBaseRewards.times(SYNC_REWARD_WEIGHT).dividedBy(WEIGHT_DENOMINATOR).dividedBy(specConfig.getSlotsPerEpoch());
    final UInt64 participantReward = maxParticipantRewards.dividedBy(specConfigAltair.getSyncCommitteeSize());
    final UInt64 proposerReward = participantReward.times(PROPOSER_WEIGHT).dividedBy(WEIGHT_DENOMINATOR.minus(PROPOSER_WEIGHT));
    // Apply participant and proposer rewards
    participantPubkeys.stream().map(pubkey -> validatorsUtil.getValidatorIndex(state, pubkey).orElseThrow()).forEach(participantIndex -> beaconStateMutators.increaseBalance(state, participantIndex, participantReward));
    UInt64 totalProposerReward = proposerReward.times(participantPubkeys.size());
    beaconStateMutators.increaseBalance(state, beaconStateAccessors.getBeaconProposerIndex(state), totalProposerReward);
    // impose penalties for any idle validators
    idlePubkeys.stream().map(pubkey -> validatorsUtil.getValidatorIndex(state, pubkey).orElseThrow()).forEach(participantIndex -> beaconStateMutators.decreaseBalance(state, participantIndex, participantReward));
}
Also used : BeaconBlockBodyAltair(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.BeaconBlockBodyAltair) MiscHelpersAltair(tech.pegasys.teku.spec.logic.versions.altair.helpers.MiscHelpersAltair) AbstractBlockProcessor(tech.pegasys.teku.spec.logic.common.block.AbstractBlockProcessor) PARTICIPATION_FLAG_WEIGHTS(tech.pegasys.teku.spec.logic.versions.altair.helpers.MiscHelpersAltair.PARTICIPATION_FLAG_WEIGHTS) BeaconBlock(tech.pegasys.teku.spec.datastructures.blocks.BeaconBlock) BLSSignatureVerifier(tech.pegasys.teku.bls.BLSSignatureVerifier) ArrayList(java.util.ArrayList) AttestationData(tech.pegasys.teku.spec.datastructures.operations.AttestationData) ExecutionPayload(tech.pegasys.teku.spec.datastructures.execution.ExecutionPayload) SyncCommitteeUtil(tech.pegasys.teku.spec.logic.common.util.SyncCommitteeUtil) SYNC_REWARD_WEIGHT(tech.pegasys.teku.spec.constants.IncentivizationWeights.SYNC_REWARD_WEIGHT) WEIGHT_DENOMINATOR(tech.pegasys.teku.spec.constants.IncentivizationWeights.WEIGHT_DENOMINATOR) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) BeaconStateUtil(tech.pegasys.teku.spec.logic.common.util.BeaconStateUtil) Bytes32(org.apache.tuweni.bytes.Bytes32) Attestation(tech.pegasys.teku.spec.datastructures.operations.Attestation) OperationValidator(tech.pegasys.teku.spec.logic.common.operations.validation.OperationValidator) BlockProcessingException(tech.pegasys.teku.spec.logic.common.statetransition.exceptions.BlockProcessingException) Domain(tech.pegasys.teku.spec.constants.Domain) BeaconStateAccessorsAltair(tech.pegasys.teku.spec.logic.versions.altair.helpers.BeaconStateAccessorsAltair) BLSSignature(tech.pegasys.teku.bls.BLSSignature) BLSPublicKey(tech.pegasys.teku.bls.BLSPublicKey) OptimisticExecutionPayloadExecutor(tech.pegasys.teku.spec.logic.versions.bellatrix.block.OptimisticExecutionPayloadExecutor) SszUInt64List(tech.pegasys.teku.infrastructure.ssz.collections.SszUInt64List) MutableBeaconStateAltair(tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.MutableBeaconStateAltair) ValidatorsUtil(tech.pegasys.teku.spec.logic.common.util.ValidatorsUtil) Deposit(tech.pegasys.teku.spec.datastructures.operations.Deposit) Predicates(tech.pegasys.teku.spec.logic.common.helpers.Predicates) MutableBeaconState(tech.pegasys.teku.spec.datastructures.state.beaconstate.MutableBeaconState) List(java.util.List) IndexedAttestationCache(tech.pegasys.teku.spec.cache.IndexedAttestationCache) AttestationUtil(tech.pegasys.teku.spec.logic.common.util.AttestationUtil) SszByte(tech.pegasys.teku.infrastructure.ssz.primitive.SszByte) BeaconStateMutators(tech.pegasys.teku.spec.logic.common.helpers.BeaconStateMutators) SszMutableList(tech.pegasys.teku.infrastructure.ssz.SszMutableList) SpecConfigAltair(tech.pegasys.teku.spec.config.SpecConfigAltair) PROPOSER_WEIGHT(tech.pegasys.teku.spec.constants.IncentivizationWeights.PROPOSER_WEIGHT) SszUInt64(tech.pegasys.teku.infrastructure.ssz.primitive.SszUInt64) SyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate) OperationSignatureVerifier(tech.pegasys.teku.spec.logic.common.operations.OperationSignatureVerifier) BlockProcessingException(tech.pegasys.teku.spec.logic.common.statetransition.exceptions.BlockProcessingException) ArrayList(java.util.ArrayList) BLSPublicKey(tech.pegasys.teku.bls.BLSPublicKey) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) SszUInt64(tech.pegasys.teku.infrastructure.ssz.primitive.SszUInt64) MutableBeaconStateAltair(tech.pegasys.teku.spec.datastructures.state.beaconstate.versions.altair.MutableBeaconStateAltair) Bytes32(org.apache.tuweni.bytes.Bytes32)

Example 2 with SyncAggregate

use of tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate in project teku by ConsenSys.

the class SyncCommitteeContributionPoolTest method shouldSelectBestContribution.

@Test
void shouldSelectBestContribution() {
    final SignedContributionAndProof proof = dataStructureUtil.randomSignedContributionAndProof(25);
    final SignedContributionAndProof bestProof = withParticipationBits(proof, 1, 2, 3);
    addValid(withParticipationBits(proof, 1, 3));
    addValid(bestProof);
    addValid(withParticipationBits(proof, 2));
    final SyncCommitteeContribution contribution = bestProof.getMessage().getContribution();
    final SyncAggregate result = pool.createSyncAggregateForBlock(contribution.getSlot().plus(1), contribution.getBeaconBlockRoot());
    assertSyncAggregateFromContribution(contribution, result);
}
Also used : SyncAggregateAssert.assertThatSyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregateAssert.assertThatSyncAggregate) SyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate) SignedContributionAndProof(tech.pegasys.teku.spec.datastructures.operations.versions.altair.SignedContributionAndProof) SyncCommitteeContribution(tech.pegasys.teku.spec.datastructures.operations.versions.altair.SyncCommitteeContribution) Test(org.junit.jupiter.api.Test)

Example 3 with SyncAggregate

use of tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate in project teku by ConsenSys.

the class SyncCommitteeContributionPoolTest method assertSyncAggregateFromContribution.

private void assertSyncAggregateFromContribution(final SyncCommitteeContribution contribution, final SyncAggregate result) {
    final int subcommitteeIndexOffset = config.getSyncCommitteeSize() / SYNC_COMMITTEE_SUBNET_COUNT * contribution.getSubcommitteeIndex().intValue();
    final IntList expectedParticipants = IntArrayList.toList(contribution.getAggregationBits().getAllSetBits().intStream().map(index -> subcommitteeIndexOffset + index));
    assertThatSyncAggregate(result).hasSyncCommitteeBits(expectedParticipants).hasSignature(contribution.getSignature());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) SYNC_COMMITTEE_SUBNET_COUNT(tech.pegasys.teku.spec.constants.NetworkConstants.SYNC_COMMITTEE_SUBNET_COUNT) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) OperationAddedSubscriber(tech.pegasys.teku.statetransition.OperationPool.OperationAddedSubscriber) SyncCommitteeUtil(tech.pegasys.teku.spec.logic.common.util.SyncCommitteeUtil) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) Spec(tech.pegasys.teku.spec.Spec) ACCEPT(tech.pegasys.teku.statetransition.validation.InternalValidationResult.ACCEPT) SyncCommitteeContribution(tech.pegasys.teku.spec.datastructures.operations.versions.altair.SyncCommitteeContribution) Mockito.when(org.mockito.Mockito.when) SignedContributionAndProof(tech.pegasys.teku.spec.datastructures.operations.versions.altair.SignedContributionAndProof) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) InternalValidationResult.reject(tech.pegasys.teku.statetransition.validation.InternalValidationResult.reject) IntList(it.unimi.dsi.fastutil.ints.IntList) TestSpecFactory(tech.pegasys.teku.spec.TestSpecFactory) DataStructureUtil(tech.pegasys.teku.spec.util.DataStructureUtil) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) SpecConfigAltair(tech.pegasys.teku.spec.config.SpecConfigAltair) Mockito.mock(org.mockito.Mockito.mock) SyncAggregateAssert.assertThatSyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregateAssert.assertThatSyncAggregate) SyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate) IntList(it.unimi.dsi.fastutil.ints.IntList)

Example 4 with SyncAggregate

use of tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate in project teku by ConsenSys.

the class SyncCommitteePerformanceTracker method calculateSyncCommitteePerformance.

private SafeFuture<SyncCommitteePerformance> calculateSyncCommitteePerformance(final UInt64 epoch, final Map<UInt64, IntSet> assignedSubcommitteeIndicesByValidatorIndex, final Map<UInt64, Map<Bytes32, Set<UInt64>>> producingValidatorsBySlotAndBlock, final Optional<StateAndBlockSummary> chainHead) {
    final int numberOfExpectedMessages = assignedSubcommitteeIndicesByValidatorIndex.values().stream().mapToInt(Set::size).sum() * spec.atEpoch(epoch).getSlotsPerEpoch();
    int producedMessageCount = 0;
    int correctMessageCount = 0;
    final List<SafeFuture<Integer>> includedMessageCountFutures = new ArrayList<>();
    for (Map.Entry<UInt64, Map<Bytes32, Set<UInt64>>> entry : producingValidatorsBySlotAndBlock.entrySet()) {
        final UInt64 slot = entry.getKey();
        final Map<Bytes32, Set<UInt64>> producingValidatorsByBlock = entry.getValue();
        final Optional<Bytes32> correctBlockRoot = chainHead.map(head -> {
            if (slot.isGreaterThanOrEqualTo(head.getSlot())) {
                return head.getRoot();
            } else {
                return spec.getBlockRootAtSlot(head.getState(), slot);
            }
        });
        for (Entry<Bytes32, Set<UInt64>> blockEntry : producingValidatorsByBlock.entrySet()) {
            final Bytes32 blockRoot = blockEntry.getKey();
            final Set<UInt64> producingValidators = blockEntry.getValue();
            final int producedMessageCountForBlock = countProducedMessages(assignedSubcommitteeIndicesByValidatorIndex, slot, producingValidators);
            if (correctBlockRoot.isPresent() && correctBlockRoot.get().equals(blockRoot)) {
                correctMessageCount += producedMessageCountForBlock;
            }
            producedMessageCount += producedMessageCountForBlock;
            final UInt64 inclusionSlot = slot.plus(1);
            includedMessageCountFutures.add(getSyncAggregateAtSlot(inclusionSlot).thenApply(maybeSyncAggregate -> maybeSyncAggregate.map(syncAggregate -> countIncludedMessages(assignedSubcommitteeIndicesByValidatorIndex, slot, producingValidators, syncAggregate)).orElse(0)));
        }
    }
    final int numberOfProducedMessages = producedMessageCount;
    final int numberOfCorrectMessages = correctMessageCount;
    return SafeFuture.collectAll(includedMessageCountFutures.stream()).thenApply(includedMessageCounts -> includedMessageCounts.stream().mapToInt(a -> a).sum()).thenApply(numberOfIncludedMessages -> new SyncCommitteePerformance(epoch, numberOfExpectedMessages, numberOfProducedMessages, numberOfCorrectMessages, numberOfIncludedMessages));
}
Also used : CombinedChainDataClient(tech.pegasys.teku.storage.client.CombinedChainDataClient) BeaconBlockBodyAltair(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.BeaconBlockBodyAltair) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) NavigableMap(java.util.NavigableMap) ArrayList(java.util.ArrayList) StateAndBlockSummary(tech.pegasys.teku.spec.datastructures.blocks.StateAndBlockSummary) List(java.util.List) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) SszBitvector(tech.pegasys.teku.infrastructure.ssz.collections.SszBitvector) Logger(org.apache.logging.log4j.Logger) SyncCommitteeMessage(tech.pegasys.teku.spec.datastructures.operations.versions.altair.SyncCommitteeMessage) Map(java.util.Map) Entry(java.util.Map.Entry) Optional(java.util.Optional) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) IntSet(it.unimi.dsi.fastutil.ints.IntSet) Spec(tech.pegasys.teku.spec.Spec) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Bytes32(org.apache.tuweni.bytes.Bytes32) SyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate) Set(java.util.Set) IntSet(it.unimi.dsi.fastutil.ints.IntSet) ArrayList(java.util.ArrayList) Bytes32(org.apache.tuweni.bytes.Bytes32) SafeFuture(tech.pegasys.teku.infrastructure.async.SafeFuture) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NavigableMap(java.util.NavigableMap) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap) Map(java.util.Map)

Example 5 with SyncAggregate

use of tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate in project teku by ConsenSys.

the class BlockFactoryTest method shouldIncludeSyncAggregateWhenAltairIsActive.

@Test
void shouldIncludeSyncAggregateWhenAltairIsActive() throws Exception {
    final BeaconBlock block = assertBlockCreated(1, TestSpecFactory.createMinimalAltair());
    final SyncAggregate result = getSyncAggregate(block);
    assertThatSyncAggregate(result).isNotNull();
    verify(syncCommitteeContributionPool).createSyncAggregateForBlock(UInt64.ONE, block.getParentRoot());
}
Also used : SyncAggregateAssert.assertThatSyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregateAssert.assertThatSyncAggregate) SyncAggregate(tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate) BeaconBlock(tech.pegasys.teku.spec.datastructures.blocks.BeaconBlock) Test(org.junit.jupiter.api.Test)

Aggregations

SyncAggregate (tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregate)11 Test (org.junit.jupiter.api.Test)7 SyncAggregateAssert.assertThatSyncAggregate (tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.SyncAggregateAssert.assertThatSyncAggregate)7 SignedContributionAndProof (tech.pegasys.teku.spec.datastructures.operations.versions.altair.SignedContributionAndProof)4 UInt64 (tech.pegasys.teku.infrastructure.unsigned.UInt64)3 BeaconBlock (tech.pegasys.teku.spec.datastructures.blocks.BeaconBlock)3 BeaconBlockBodyAltair (tech.pegasys.teku.spec.datastructures.blocks.blockbody.versions.altair.BeaconBlockBodyAltair)3 SyncCommitteeContribution (tech.pegasys.teku.spec.datastructures.operations.versions.altair.SyncCommitteeContribution)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Bytes32 (org.apache.tuweni.bytes.Bytes32)2 SafeFuture (tech.pegasys.teku.infrastructure.async.SafeFuture)2 Spec (tech.pegasys.teku.spec.Spec)2 SpecConfigAltair (tech.pegasys.teku.spec.config.SpecConfigAltair)2 ExecutionPayload (tech.pegasys.teku.spec.datastructures.execution.ExecutionPayload)2 Attestation (tech.pegasys.teku.spec.datastructures.operations.Attestation)2 SyncCommitteeUtil (tech.pegasys.teku.spec.logic.common.util.SyncCommitteeUtil)2 IntArrayList (it.unimi.dsi.fastutil.ints.IntArrayList)1 IntList (it.unimi.dsi.fastutil.ints.IntList)1 IntSet (it.unimi.dsi.fastutil.ints.IntSet)1