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

The following examples show how to use com.google.common.primitives.UnsignedLong#equals() . 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: PeerChainValidator.java    From teku with Apache License 2.0 6 votes vote down vote up
private SafeFuture<Boolean> verifyPeerAgreesWithOurFinalizedCheckpoint(
    Checkpoint finalizedCheckpoint) {
  final UnsignedLong finalizedEpochSlot = finalizedCheckpoint.getEpochStartSlot();
  if (finalizedEpochSlot.equals(UnsignedLong.valueOf(Constants.GENESIS_SLOT))) {
    // Assume that our genesis blocks match because we've already verified the fork
    // digest.
    return SafeFuture.completedFuture(true);
  }
  return historicalChainData
      .getLatestFinalizedBlockAtSlot(finalizedEpochSlot)
      .thenApply(maybeBlock -> blockToSlot(finalizedEpochSlot, maybeBlock))
      .thenCompose(
          blockSlot -> {
            if (blockSlot.equals(UnsignedLong.valueOf(Constants.GENESIS_SLOT))) {
              // Assume that our genesis blocks match because we've already verified the fork
              // digest. Need to repeat this check in case we finalized a later epoch without
              // producing blocks (eg the genesis block is still the one in effect at epoch 2)
              return SafeFuture.completedFuture(true);
            }
            return peer.requestBlockBySlot(blockSlot)
                .thenApply(
                    block -> validateBlockRootsMatch(block, finalizedCheckpoint.getRoot()));
          });
}
 
Example 2
Source File: EventLogger.java    From teku with Apache License 2.0 6 votes vote down vote up
public void slotEvent(
    final UnsignedLong nodeSlot,
    final UnsignedLong headSlot,
    final Bytes32 bestBlockRoot,
    final UnsignedLong nodeEpoch,
    final UnsignedLong finalizedCheckpoint,
    final Bytes32 finalizedRoot,
    final int numPeers) {
  String blockRoot = "   ... empty";
  if (nodeSlot.equals(headSlot)) {
    blockRoot = formatHashRoot(bestBlockRoot);
  }
  final String slotEventLog =
      String.format(
          "Slot Event  *** Slot: %s, Block: %s, Epoch: %s, Finalized checkpoint: %s, Finalized root: %s, Peers: %d",
          nodeSlot.toString(),
          blockRoot,
          nodeEpoch.toString(),
          finalizedCheckpoint.toString(),
          formatHashRoot(finalizedRoot),
          numPeers);
  info(slotEventLog, Color.WHITE);
}
 
Example 3
Source File: ChainDataProvider.java    From teku with Apache License 2.0 6 votes vote down vote up
public SafeFuture<Optional<List<Committee>>> getCommitteesAtEpoch(final UnsignedLong epoch) {
  if (!combinedChainDataClient.isChainDataFullyAvailable()) {
    return chainUnavailable();
  }
  final UnsignedLong committeesCalculatedAtEpoch = epoch.equals(ZERO) ? ZERO : epoch.minus(ONE);
  final UnsignedLong startingSlot = compute_start_slot_at_epoch(committeesCalculatedAtEpoch);
  final UnsignedLong slot = compute_start_slot_at_epoch(epoch);

  // one epoch in future is available, beyond that cannot be calculated
  if (slot.compareTo(
          recentChainData.getBestSlot().plus(UnsignedLong.valueOf(Constants.SLOTS_PER_EPOCH)))
      > 0) {
    return SafeFuture.completedFuture(Optional.empty());
  }

  return combinedChainDataClient
      .getBlockAndStateInEffectAtSlot(startingSlot)
      .thenApply(
          maybeResult ->
              maybeResult.map(
                  result ->
                      combinedChainDataClient.getCommitteesFromState(result.getState(), slot)
                          .stream()
                          .map(Committee::new)
                          .collect(Collectors.toList())));
}
 
Example 4
Source File: FixedReceiverAmountPaymentTracker.java    From quilt with Apache License 2.0 6 votes vote down vote up
@Override
public PrepareAmounts getSendPacketAmounts(
    final UnsignedLong congestionLimit, final Denomination senderDenomination, final Denomination receiverDenomination
) {
  Objects.requireNonNull(congestionLimit);
  Objects.requireNonNull(senderDenomination);
  Objects.requireNonNull(receiverDenomination);

  if (congestionLimit.equals(UnsignedLong.ZERO) || amountLeftToDeliver.get().equals(UnsignedLong.ZERO)) {
    return PrepareAmounts.builder().amountToSend(UnsignedLong.ZERO).minimumAmountToAccept(UnsignedLong.ZERO).build();
  }

  final UnsignedLong amountToSendInSenderUnits = rateCalculator
      .calculateAmountToSend(amountLeftToDeliver.get(), senderDenomination, receiverDenomination);
  final UnsignedLong packetAmountToSend = StreamUtils
      .max(StreamUtils.min(amountToSendInSenderUnits, congestionLimit), UnsignedLong.ONE);
  final UnsignedLong minAmountToAcceptInReceiverUnits =
      rateCalculator.calculateMinAmountToAccept(packetAmountToSend, senderDenomination, receiverDenomination);

  return PrepareAmounts.builder()
      .minimumAmountToAccept(minAmountToAcceptInReceiverUnits)
      .amountToSend(packetAmountToSend)
      .build();
}
 
Example 5
Source File: MatchingAttestations.java    From teku with Apache License 2.0 5 votes vote down vote up
/**
 * Returns current or previous epoch attestations depending to the epoch passed in
 *
 * @param epoch
 * @return
 * @throws IllegalArgumentException
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#helper-functions-1</a>
 */
private SSZList<PendingAttestation> calculateMatchingSourceAttestations(UnsignedLong epoch)
    throws IllegalArgumentException {
  checkArgument(
      get_current_epoch(state).equals(epoch) || get_previous_epoch(state).equals(epoch),
      "get_matching_source_attestations requested for invalid epoch");
  if (epoch.equals(get_current_epoch(state))) {
    return state.getCurrent_epoch_attestations();
  }
  return state.getPrevious_epoch_attestations();
}
 
Example 6
Source File: PeerChainValidator.java    From teku with Apache License 2.0 5 votes vote down vote up
private boolean remoteEpochIsInvalid(
    final UnsignedLong currentEpoch, final UnsignedLong remoteFinalizedEpoch) {
  // Remote finalized epoch is invalid if it is from the future
  return remoteFinalizedEpoch.compareTo(currentEpoch) > 0
      // Remote finalized epoch is invalid if is from the current epoch (unless we're at genesis)
      || (remoteFinalizedEpoch.compareTo(currentEpoch) == 0
          && !remoteFinalizedEpoch.equals(UnsignedLong.valueOf(Constants.GENESIS_EPOCH)));
}
 
Example 7
Source File: AttestationTopicSubscriber.java    From teku with Apache License 2.0 5 votes vote down vote up
private void subscribeToCommitteeForAggregation(
    final BeaconState state, final int committeeIndex, final UnsignedLong aggregationSlot) {
  final int subnetId =
      CommitteeUtil.computeSubnetForCommittee(
          state, aggregationSlot, UnsignedLong.valueOf(committeeIndex));
  final UnsignedLong currentUnsubscriptionSlot =
      subnetIdToUnsubscribeSlot.getOrDefault(subnetId, ZERO);
  if (currentUnsubscriptionSlot.equals(ZERO)) {
    eth2Network.subscribeToAttestationSubnetId(subnetId);
  }
  subnetIdToUnsubscribeSlot.put(subnetId, max(currentUnsubscriptionSlot, aggregationSlot));
}
 
Example 8
Source File: ProtoArray.java    From teku with Apache License 2.0 5 votes vote down vote up
/**
 * Iterate backwards through the array, touching all nodes and their parents and potentially the
 * bestChildIndex of each parent.
 *
 * <p>The structure of the `nodes` array ensures that the child of each node is always touched
 * before its parent.
 *
 * <p>For each node, the following is done:
 *
 * <ul>
 *   <li>Update the node's weight with the corresponding delta.
 *   <li>Back-propagate each node's delta to its parents delta.
 *   <li>Compare the current node with the parents best child, updating it if the current node
 *       should become the best child.
 *   <li>If required, update the parents best descendant with the current node or its best
 *       descendant.
 * </ul>
 *
 * @param deltas
 * @param justifiedEpoch
 * @param finalizedEpoch
 */
public void applyScoreChanges(
    List<Long> deltas, UnsignedLong justifiedEpoch, UnsignedLong finalizedEpoch) {
  checkArgument(deltas.size() == indices.size(), "ProtoArray: Invalid delta length");

  if (!justifiedEpoch.equals(this.justifiedEpoch)
      || !finalizedEpoch.equals(this.finalizedEpoch)) {
    this.justifiedEpoch = justifiedEpoch;
    this.finalizedEpoch = finalizedEpoch;
  }

  // Iterate backwards through all indices in `this.nodes`.
  for (int nodeIndex = nodes.size() - 1; nodeIndex >= 0; nodeIndex--) {
    ProtoNode node = nodes.get(nodeIndex);

    // There is no need to adjust the balances or manage parent of the zero hash since it
    // is an alias to the genesis block. The weight applied to the genesis block is
    // irrelevant as we _always_ choose it and it's impossible for it to have a parent.
    if (node.getBlockRoot().equals(Bytes32.ZERO)) {
      continue;
    }

    long nodeDelta = deltas.get(nodeIndex);
    node.adjustWeight(nodeDelta);

    if (node.getParentIndex().isPresent()) {
      int parentIndex = node.getParentIndex().get();
      deltas.set(parentIndex, deltas.get(parentIndex) + nodeDelta);
      maybeUpdateBestChildAndDescendant(parentIndex, nodeIndex);
    }
  }
}
 
Example 9
Source File: SimpleOffsetSerializer.java    From teku with Apache License 2.0 4 votes vote down vote up
public static Bytes serialize(SimpleOffsetSerializable value) {
  // TODO assert sum(fixed_lengths + variable_lengths) < 2**(BYTES_PER_LENGTH_OFFSET *
  // BITS_PER_BYTE)
  // List<UnsignedLong> variable_lengths = new ArrayList<>();
  List<UnsignedLong> variable_offsets = new ArrayList<>();
  List<Bytes> interleaved_values = new ArrayList<>();
  UnsignedLong fixedLengthSum = UnsignedLong.ZERO;
  UnsignedLong varLengthSum = UnsignedLong.ZERO;

  // System.out.println("Fixed Part Size: " + value.get_fixed_parts().size());
  // System.out.println("Var Part Size: " + value.get_variable_parts().size());
  for (Bytes fixedPart : value.get_fixed_parts()) {
    UnsignedLong fixedPartSize = UnsignedLong.valueOf(fixedPart.size());
    if (fixedPartSize.equals(UnsignedLong.ZERO)) {
      fixedPartSize = UnsignedLong.valueOf(4L);
    }
    fixedLengthSum = fixedLengthSum.plus(fixedPartSize);
  }

  variable_offsets.add(fixedLengthSum);
  for (Bytes varPart : value.get_variable_parts()) {
    UnsignedLong varPartSize = UnsignedLong.valueOf(varPart.size());
    varLengthSum = varLengthSum.plus(varPartSize);
    variable_offsets.add(fixedLengthSum.plus(varLengthSum));
  }

  int interleavingIndex = 0;
  for (Bytes element : value.get_fixed_parts()) {
    if (!element.equals(Bytes.EMPTY)) {
      interleaved_values.add(element);
    } else {
      interleaved_values.add(
          SSZ.encodeUInt32(variable_offsets.get(interleavingIndex).longValue()));
    }
    ++interleavingIndex;
  }

  return Bytes.wrap(
      Bytes.concatenate(interleaved_values.toArray(new Bytes[0])),
      Bytes.concatenate(value.get_variable_parts().toArray(new Bytes[0])));
}
 
Example 10
Source File: PeerChainValidator.java    From teku with Apache License 2.0 4 votes vote down vote up
private SafeFuture<Boolean> checkRemoteChain() {
  // Shortcut checks if our node or our peer has not reached genesis
  if (storageClient.isPreGenesis()) {
    // If we haven't reached genesis, accept our peer at this point
    LOG.trace("Validating peer pre-genesis, skip finalized block checks for peer {}", peer);
    return SafeFuture.completedFuture(true);
  } else if (PeerStatus.isPreGenesisStatus(status)) {
    // Our peer hasn't reached genesis, accept them for now
    LOG.trace("Peer has not reached genesis, skip finalized block checks for peer {}", peer);
    return SafeFuture.completedFuture(true);
  }

  // Check fork compatibility
  Bytes4 expectedForkDigest = storageClient.getHeadForkInfo().orElseThrow().getForkDigest();
  if (!Objects.equals(expectedForkDigest, status.getForkDigest())) {
    LOG.trace(
        "Peer's fork ({}) differs from our fork ({}): {}",
        status.getForkDigest(),
        expectedForkDigest,
        peer);
    return SafeFuture.completedFuture(false);
  }
  final UnsignedLong remoteFinalizedEpoch = status.getFinalizedEpoch();
  // Only require fork digest to match if only genesis is finalized
  if (remoteFinalizedEpoch.equals(UnsignedLong.ZERO)) {
    return SafeFuture.completedFuture(true);
  }

  // Check finalized checkpoint compatibility
  final Checkpoint finalizedCheckpoint =
      storageClient.getBestState().orElseThrow().getFinalized_checkpoint();
  final UnsignedLong finalizedEpoch = finalizedCheckpoint.getEpoch();
  final UnsignedLong currentEpoch = getCurrentEpoch();

  // Make sure remote finalized epoch is reasonable
  if (remoteEpochIsInvalid(currentEpoch, remoteFinalizedEpoch)) {
    LOG.debug(
        "Peer is advertising invalid finalized epoch {} which is at or ahead of our current epoch {}: {}",
        remoteFinalizedEpoch,
        currentEpoch,
        peer);
    return SafeFuture.completedFuture(false);
  }

  // Check whether finalized checkpoints are compatible
  if (finalizedEpoch.compareTo(remoteFinalizedEpoch) == 0) {
    LOG.trace(
        "Finalized epoch for peer {} matches our own finalized epoch {}, verify blocks roots match",
        peer.getId(),
        finalizedEpoch);
    return verifyFinalizedCheckpointsAreTheSame(finalizedCheckpoint);
  } else if (finalizedEpoch.compareTo(remoteFinalizedEpoch) > 0) {
    // We're ahead of our peer, check that we agree with our peer's finalized epoch
    LOG.trace(
        "Our finalized epoch {} is ahead of our peer's ({}) finalized epoch {}, check that we consider our peer's finalized block to be canonical.",
        finalizedEpoch,
        peer.getId(),
        remoteFinalizedEpoch);
    return verifyPeersFinalizedCheckpointIsCanonical();
  } else {
    // Our peer is ahead of us, check that they agree on our finalized epoch
    LOG.trace(
        "Our finalized epoch {} is behind of our peer's ({}) finalized epoch {}, check that our peer considers our latest finalized block to be canonical.",
        finalizedEpoch,
        peer.getId(),
        remoteFinalizedEpoch);
    return verifyPeerAgreesWithOurFinalizedCheckpoint(finalizedCheckpoint);
  }
}
 
Example 11
Source File: BeaconStateUtil.java    From teku with Apache License 2.0 3 votes vote down vote up
/**
 * Return the previous epoch of the given ``state``. Return the current epoch if it's genesis
 * epoch.
 *
 * @param state
 * @return
 * @see
 *     <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#get_previous_epoch</a>
 */
public static UnsignedLong get_previous_epoch(BeaconState state) {
  UnsignedLong current_epoch = get_current_epoch(state);
  return current_epoch.equals(UnsignedLong.valueOf(GENESIS_EPOCH))
      ? UnsignedLong.valueOf(GENESIS_EPOCH)
      : current_epoch.minus(UnsignedLong.ONE);
}
 
Example 12
Source File: ChainProperties.java    From teku with Apache License 2.0 3 votes vote down vote up
/**
 * Given a slot, returns the earliest epoch that can be finalized with a block at this slot. If
 * the slot is at the start of an epoch, return the current epoch. Otherwise, return the next
 * epoch.
 *
 * @param slot The slot we want to finalize.
 * @return The earliest epoch that can be finalized at this slot.
 */
public static UnsignedLong computeBestEpochFinalizableAtSlot(UnsignedLong slot) {
  final UnsignedLong currentEpoch = compute_epoch_at_slot(slot);
  final UnsignedLong startSlotAtCurrentEpoch = compute_start_slot_at_epoch(currentEpoch);
  return startSlotAtCurrentEpoch.equals(slot)
      ? currentEpoch
      : currentEpoch.plus(UnsignedLong.ONE);
}