com.google.common.primitives.UnsignedLong#plus ( )源码实例Demo

下面列出了com.google.common.primitives.UnsignedLong#plus ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: teku   文件: ValidatorApiHandler.java
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;
}
 
源代码2 项目: teku   文件: BlockImporterTest.java
@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);
}
 
源代码3 项目: teku   文件: PeerSync.java
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);
            }
          });
}
 
源代码4 项目: teku   文件: BlockManagerTest.java
@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();
}
 
源代码5 项目: teku   文件: PendingPoolTest.java
@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();
}
 
源代码6 项目: teku   文件: RecentChainDataTest.java
@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());
}
 
源代码7 项目: teku   文件: RecentChainDataTest.java
@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);
}
 
源代码8 项目: teku   文件: MissingDepositsException.java
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);
}
 
源代码9 项目: teku   文件: RewardsAndPenaltiesCalculator.java
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));
}
 
源代码10 项目: teku   文件: BeaconStateUtil.java
/**
 * 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))));
}
 
源代码11 项目: teku   文件: DutyScheduler.java
@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));
}
 
源代码12 项目: teku   文件: StableSubnetSubscriberTest.java
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);
      });
}
 
源代码13 项目: teku   文件: SlotProcessor.java
boolean isSlotAttestationDue(
    final UnsignedLong calculatedSlot,
    final UnsignedLong currentTime,
    final UnsignedLong nodeSlotStartTime) {
  final UnsignedLong earliestTime = nodeSlotStartTime.plus(oneThirdSlotSeconds);
  return isProcessingDueForSlot(calculatedSlot, onTickSlotAttestation)
      && isTimeReached(currentTime, earliestTime);
}
 
源代码14 项目: teku   文件: BlockImporterTest.java
@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");
}
 
源代码15 项目: snmpman   文件: Counter64Modifier.java
@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());
}
 
源代码16 项目: teku   文件: BlockManagerTest.java
@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();
}
 
源代码17 项目: teku   文件: Eth1VotingPeriod.java
private UnsignedLong computeTimeAtSlot(final UnsignedLong slot, final UnsignedLong genesisTime) {
  return genesisTime.plus(slot.times(UnsignedLong.valueOf(Constants.SECONDS_PER_SLOT)));
}
 
源代码18 项目: nifi   文件: TestBinaryReaderBuilder.java
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);
}
 
源代码19 项目: teku   文件: GenesisGenerator.java
private void updateGenesisTime(final UnsignedLong eth1Timestamp) {
  UnsignedLong genesisTime = eth1Timestamp.plus(Constants.GENESIS_DELAY);
  state.setGenesis_time(genesisTime);
}
 
源代码20 项目: teku   文件: BeaconStateUtil.java
/**
 * 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);
}