Java Code Examples for com.google.common.primitives.UnsignedLong#plus()

The following examples show how to use com.google.common.primitives.UnsignedLong#plus() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RecentChainDataTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void getBlockRootBySlot_forHistoricalSlotInRange() throws Exception {
  final UnsignedLong historicalRoots = UnsignedLong.valueOf(Constants.SLOTS_PER_HISTORICAL_ROOT);
  final UnsignedLong targetSlot = UnsignedLong.valueOf(10);
  final UnsignedLong finalizedBlockSlot = targetSlot.plus(historicalRoots);
  final UnsignedLong finalizedEpoch =
      compute_epoch_at_slot(finalizedBlockSlot).plus(UnsignedLong.ONE);

  // Add a block within the finalized range
  final SignedBlockAndState historicalBlock = chainBuilder.generateBlockAtSlot(targetSlot);
  final SignedBlockAndState finalizedBlock = chainBuilder.generateBlockAtSlot(finalizedBlockSlot);
  saveBlock(storageClient, historicalBlock);
  finalizeBlock(storageClient, finalizedEpoch, finalizedBlock);
  advanceBestBlock(storageClient);

  assertThat(storageClient.getBlockRootBySlot(targetSlot)).contains(historicalBlock.getRoot());
}
 
Example 2
Source File: ValidatorApiHandler.java    From teku with Apache License 2.0 6 votes vote down vote up
private Map<Integer, List<UnsignedLong>> getBeaconProposalSlotsByValidatorIndex(
    final BeaconState state, final UnsignedLong epoch) {
  final UnsignedLong epochStartSlot = compute_start_slot_at_epoch(epoch);
  // Don't calculate a proposer for the genesis slot
  final UnsignedLong startSlot = max(epochStartSlot, UnsignedLong.valueOf(GENESIS_SLOT + 1));
  final UnsignedLong endSlot =
      epochStartSlot.plus(UnsignedLong.valueOf(Constants.SLOTS_PER_EPOCH));
  final Map<Integer, List<UnsignedLong>> proposalSlotsByValidatorIndex = new HashMap<>();
  for (UnsignedLong slot = startSlot;
      slot.compareTo(endSlot) < 0;
      slot = slot.plus(UnsignedLong.ONE)) {
    final Integer proposer = get_beacon_proposer_index(state, slot);
    proposalSlotsByValidatorIndex.computeIfAbsent(proposer, key -> new ArrayList<>()).add(slot);
  }
  return proposalSlotsByValidatorIndex;
}
 
Example 3
Source File: PendingPoolTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void onSlot_prunesOldBlocks() {
  final SignedBeaconBlock blockA =
      dataStructureUtil.randomSignedBeaconBlock(currentSlot.longValue() - 1L);
  final SignedBeaconBlock blockB =
      dataStructureUtil.randomSignedBeaconBlock(currentSlot.longValue());
  pendingPool.add(blockA);
  pendingPool.add(blockB);

  assertThat(pendingPool.contains(blockA)).isTrue();
  assertThat(pendingPool.contains(blockB)).isTrue();

  UnsignedLong newSlot = currentSlot;
  for (int i = 0; i < historicalTolerance.intValue() - 1; i++) {
    newSlot = newSlot.plus(UnsignedLong.ONE);
    pendingPool.onSlot(newSlot);
    assertThat(pendingPool.contains(blockA)).isTrue();
    assertThat(pendingPool.contains(blockB)).isTrue();
  }

  // Next slot should prune blockA
  pendingPool.onSlot(newSlot.plus(UnsignedLong.ONE));

  assertThat(pendingPool.contains(blockA)).isFalse();
  assertThat(pendingPool.contains(blockB)).isTrue();
}
 
Example 4
Source File: BlockManagerTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void onGossipedBlock_unattachedBlock() throws Exception {
  final UnsignedLong nextSlot = genesisSlot.plus(UnsignedLong.ONE);
  final UnsignedLong nextNextSlot = nextSlot.plus(UnsignedLong.ONE);
  // Create 2 blocks
  remoteChain.createAndImportBlockAtSlot(nextSlot);
  final SignedBeaconBlock nextNextBlock = remoteChain.createAndImportBlockAtSlot(nextNextSlot);

  incrementSlot();
  incrementSlot();
  localEventBus.post(new GossipedBlockEvent(nextNextBlock));
  assertThat(importedBlocks.get()).isEmpty();
  assertThat(pendingBlocks.size()).isEqualTo(1);
  assertThat(futureBlocks.size()).isEqualTo(0);
  assertThat(pendingBlocks.contains(nextNextBlock)).isTrue();
}
 
Example 5
Source File: PeerSync.java    From teku with Apache License 2.0 6 votes vote down vote up
public SafeFuture<PeerSyncResult> sync(final Eth2Peer peer) {
  LOG.debug("Start syncing to peer {}", peer);
  // Begin requesting blocks at our first non-finalized slot
  final UnsignedLong finalizedEpoch = storageClient.getFinalizedEpoch();
  final UnsignedLong latestFinalizedSlot = compute_start_slot_at_epoch(finalizedEpoch);
  final UnsignedLong firstNonFinalSlot = latestFinalizedSlot.plus(UnsignedLong.ONE);

  this.startingSlot = firstNonFinalSlot;

  return executeSync(peer, peer.getStatus(), firstNonFinalSlot, SafeFuture.COMPLETE)
      .whenComplete(
          (res, err) -> {
            if (err != null) {
              LOG.debug("Failed to sync with peer {}: {}", peer, err);
            } else {
              LOG.debug("Finished syncing (with status {}) to peer {}", res.name(), peer);
            }
          });
}
 
Example 6
Source File: BlockImporterTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void importBlock_validAttestations() throws Exception {

  UnsignedLong currentSlot = UnsignedLong.ONE;
  SignedBeaconBlock block1 = localChain.createAndImportBlockAtSlot(currentSlot);
  currentSlot = currentSlot.plus(UnsignedLong.ONE);

  AttestationGenerator attestationGenerator = new AttestationGenerator(validatorKeys);
  final BeaconState state = recentChainData.getBlockState(block1.getRoot()).orElseThrow();
  List<Attestation> attestations =
      attestationGenerator.getAttestationsForSlot(state, block1.getMessage(), currentSlot);
  List<Attestation> aggregatedAttestations =
      AttestationGenerator.groupAndAggregateAttestations(attestations);

  currentSlot = currentSlot.plus(UnsignedLong.ONE);

  localChain.createAndImportBlockAtSlotWithAttestations(currentSlot, aggregatedAttestations);
}
 
Example 7
Source File: RecentChainDataTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void getStateInEffectAtSlot_returnStateFromLastBlockWhenSlotsAreEmpty() throws Exception {
  // Request block for an empty slot immediately after genesis
  final UnsignedLong requestedSlot = genesisBlock.getSlot().plus(UnsignedLong.ONE);
  final UnsignedLong bestSlot = requestedSlot.plus(UnsignedLong.ONE);

  final SignedBlockAndState bestBlock = chainBuilder.generateBlockAtSlot(bestSlot);
  updateBestBlock(storageClient, bestBlock);

  assertThat(storageClient.getStateInEffectAtSlot(requestedSlot)).contains(genesisState);
}
 
Example 8
Source File: BlockManagerTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void onGossipedBlock_unattachedFutureBlock() throws Exception {
  final UnsignedLong nextSlot = genesisSlot.plus(UnsignedLong.ONE);
  final UnsignedLong nextNextSlot = nextSlot.plus(UnsignedLong.ONE);
  // Create 2 blocks
  remoteChain.createAndImportBlockAtSlot(nextSlot);
  final SignedBeaconBlock nextNextBlock = remoteChain.createAndImportBlockAtSlot(nextNextSlot);

  incrementSlot();
  localEventBus.post(new GossipedBlockEvent(nextNextBlock));
  assertThat(importedBlocks.get()).isEmpty();
  assertThat(pendingBlocks.size()).isEqualTo(1);
  assertThat(futureBlocks.size()).isEqualTo(0);
  assertThat(pendingBlocks.contains(nextNextBlock)).isTrue();
}
 
Example 9
Source File: Counter64Modifier.java    From snmpman with Apache License 2.0 5 votes vote down vote up
@Override
public Counter64 modify(final Counter64 variable) {
    UnsignedLong currentValue = UnsignedLong.valueOf(variable.toString());
    if (currentValue.compareTo(minimum) < 0 || currentValue.compareTo(maximum) > 0) {
        currentValue = minimum;
    }

    final UnsignedLong step = UnsignedLong.valueOf((long) (Math.random() * maximumStep.minus(minimumStep).longValue())).plus(minimumStep);
    final UnsignedLong newValue = currentValue.plus(step);

    return new Counter64(newValue.longValue());
}
 
Example 10
Source File: BlockImporterTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void importBlock_attestationWithInvalidSignature() throws Exception {

  UnsignedLong currentSlot = UnsignedLong.ONE;
  SignedBeaconBlock block1 = localChain.createAndImportBlockAtSlot(currentSlot);
  currentSlot = currentSlot.plus(UnsignedLong.ONE);

  AttestationGenerator attestationGenerator = new AttestationGenerator(validatorKeys);
  final BeaconState state = recentChainData.getBlockState(block1.getRoot()).orElseThrow();
  List<Attestation> attestations =
      attestationGenerator.getAttestationsForSlot(state, block1.getMessage(), currentSlot);
  List<Attestation> aggregatedAttestations =
      AttestationGenerator.groupAndAggregateAttestations(attestations);

  // make one attestation signature invalid
  aggregatedAttestations
      .get(aggregatedAttestations.size() / 2)
      .setAggregate_signature(BLSSignature.random(1));

  UnsignedLong currentSlotFinal = currentSlot.plus(UnsignedLong.ONE);

  assertThatCode(
          () -> {
            localChain.createAndImportBlockAtSlotWithAttestations(
                currentSlotFinal, aggregatedAttestations);
          })
      .hasMessageContaining("signature");
}
 
Example 11
Source File: SlotProcessor.java    From teku with Apache License 2.0 5 votes vote down vote up
boolean isSlotAttestationDue(
    final UnsignedLong calculatedSlot,
    final UnsignedLong currentTime,
    final UnsignedLong nodeSlotStartTime) {
  final UnsignedLong earliestTime = nodeSlotStartTime.plus(oneThirdSlotSeconds);
  return isProcessingDueForSlot(calculatedSlot, onTickSlotAttestation)
      && isTimeReached(currentTime, earliestTime);
}
 
Example 12
Source File: StableSubnetSubscriberTest.java    From teku with Apache License 2.0 5 votes vote down vote up
private void assertUnsubscribeSlotsAreInBound(
    Set<SubnetSubscription> subnetSubscriptions, UnsignedLong currentSlot) {
  UnsignedLong lowerBound =
      currentSlot.plus(
          valueOf(Constants.EPOCHS_PER_RANDOM_SUBNET_SUBSCRIPTION * Constants.SLOTS_PER_EPOCH));
  UnsignedLong upperBound =
      currentSlot.plus(
          valueOf(
              2 * Constants.EPOCHS_PER_RANDOM_SUBNET_SUBSCRIPTION * Constants.SLOTS_PER_EPOCH));
  subnetSubscriptions.forEach(
      subnetSubscription -> {
        assertThat(subnetSubscription.getUnsubscriptionSlot()).isBetween(lowerBound, upperBound);
      });
}
 
Example 13
Source File: DutyScheduler.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public void onChainReorg(final UnsignedLong newSlot) {
  LOG.debug("Chain reorganisation detected. Recalculating validator duties");
  dutiesByEpoch.clear();
  final UnsignedLong epochNumber = compute_epoch_at_slot(newSlot);
  final UnsignedLong nextEpochNumber = epochNumber.plus(ONE);
  dutiesByEpoch.put(epochNumber, requestDutiesForEpoch(epochNumber));
  dutiesByEpoch.put(nextEpochNumber, requestDutiesForEpoch(nextEpochNumber));
}
 
Example 14
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 5 votes vote down vote up
/**
 * Initiate the exit of the validator with index ``index``.
 *
 * @param state
 * @param index
 * @return
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#initiate_validator_exit</a>
 */
public static void initiate_validator_exit(MutableBeaconState state, int index) {
  Validator validator = state.getValidators().get(index);
  // Return if validator already initiated exit
  if (!validator.getExit_epoch().equals(FAR_FUTURE_EPOCH)) {
    return;
  }

  // Compute exit queue epoch
  List<UnsignedLong> exit_epochs =
      state.getValidators().stream()
          .filter(v -> !v.getExit_epoch().equals(FAR_FUTURE_EPOCH))
          .map(Validator::getExit_epoch)
          .collect(Collectors.toList());
  exit_epochs.add(compute_activation_exit_epoch(get_current_epoch(state)));
  UnsignedLong exit_queue_epoch = Collections.max(exit_epochs);
  final UnsignedLong final_exit_queue_epoch = exit_queue_epoch;
  UnsignedLong exit_queue_churn =
      UnsignedLong.valueOf(
          state.getValidators().stream()
              .filter(v -> v.getExit_epoch().equals(final_exit_queue_epoch))
              .collect(Collectors.toList())
              .size());

  if (exit_queue_churn.compareTo(get_validator_churn_limit(state)) >= 0) {
    exit_queue_epoch = exit_queue_epoch.plus(UnsignedLong.ONE);
  }

  // Set validator exit epoch and withdrawable epoch
  state
      .getValidators()
      .set(
          index,
          validator
              .withExit_epoch(exit_queue_epoch)
              .withWithdrawable_epoch(
                  exit_queue_epoch.plus(
                      UnsignedLong.valueOf(MIN_VALIDATOR_WITHDRAWABILITY_DELAY))));
}
 
Example 15
Source File: RewardsAndPenaltiesCalculator.java    From teku with Apache License 2.0 5 votes vote down vote up
private Map<Integer, UnsignedLong> calculateEligibleValidatorBaseRewards() {
  final UnsignedLong previousEpoch = get_previous_epoch(state);
  final UnsignedLong previousEpochPlusOne = previousEpoch.plus(UnsignedLong.ONE);
  return IntStream.range(0, state.getValidators().size())
      .filter(
          index -> {
            final Validator v = state.getValidators().get(index);
            return is_active_validator(v, previousEpoch)
                || (v.isSlashed()
                    && previousEpochPlusOne.compareTo(v.getWithdrawable_epoch()) < 0);
          })
      .boxed()
      .collect(toMap(i -> i, this::calculateBaseReward));
}
 
Example 16
Source File: MissingDepositsException.java    From teku with Apache License 2.0 5 votes vote down vote up
public MissingDepositsException(
    final UnsignedLong maxAvailableDeposit, final UnsignedLong requiredDepositIndex) {
  super(
      "Unable to create block because ETH1 deposits are not available. Missing deposits "
          + maxAvailableDeposit.plus(UnsignedLong.ONE)
          + " to "
          + requiredDepositIndex);
}
 
Example 17
Source File: TestBinaryReaderBuilder.java    From nifi with Apache License 2.0 4 votes vote down vote up
public TestBinaryReaderBuilder putFileTime(Date date) {
    UnsignedLong javaMillis = UnsignedLong.valueOf(date.getTime());
    UnsignedLong windowsMillis = javaMillis.plus(UnsignedLong.valueOf(BinaryReader.EPOCH_OFFSET));
    UnsignedLong windowsStamp = windowsMillis.times(UnsignedLong.valueOf(10000));
    return putQWord(windowsStamp);
}
 
Example 18
Source File: GenesisGenerator.java    From teku with Apache License 2.0 4 votes vote down vote up
private void updateGenesisTime(final UnsignedLong eth1Timestamp) {
  UnsignedLong genesisTime = eth1Timestamp.plus(Constants.GENESIS_DELAY);
  state.setGenesis_time(genesisTime);
}
 
Example 19
Source File: Eth1VotingPeriod.java    From teku with Apache License 2.0 4 votes vote down vote up
private UnsignedLong computeTimeAtSlot(final UnsignedLong slot, final UnsignedLong genesisTime) {
  return genesisTime.plus(slot.times(UnsignedLong.valueOf(Constants.SECONDS_PER_SLOT)));
}
 
Example 20
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 3 votes vote down vote up
/**
 * Return the combined effective balance of the ``indices``. (EFFECTIVE_BALANCE_INCREMENT Gwei
 * minimum to avoid divisions by zero.)
 *
 * @param state
 * @param indices
 * @return
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#get_total_balance</a>
 */
public static UnsignedLong get_total_balance(BeaconState state, Collection<Integer> indices) {
  UnsignedLong sum = UnsignedLong.ZERO;
  SSZList<Validator> validator_registry = state.getValidators();
  for (Integer index : indices) {
    sum = sum.plus(validator_registry.get(index).getEffective_balance());
  }
  return max(sum, EFFECTIVE_BALANCE_INCREMENT);
}