下面列出了com.google.common.primitives.UnsignedLong#compareTo ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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())));
}
private static boolean blockDescendsFromLatestFinalizedBlock(
final BeaconBlock block,
final ReadOnlyStore store,
final ForkChoiceStrategy forkChoiceStrategy) {
final Checkpoint finalizedCheckpoint = store.getFinalizedCheckpoint();
final UnsignedLong blockSlot = block.getSlot();
// Make sure this block's slot is after the latest finalized slot
final UnsignedLong finalizedEpochStartSlot = finalizedCheckpoint.getEpochStartSlot();
if (blockSlot.compareTo(finalizedEpochStartSlot) <= 0) {
return false;
}
// Make sure this block descends from the finalized block
final UnsignedLong finalizedSlot =
forkChoiceStrategy.blockSlot(finalizedCheckpoint.getRoot()).orElseThrow();
return hasAncestorAtSlot(
forkChoiceStrategy, block.getParent_root(), finalizedSlot, finalizedCheckpoint.getRoot());
}
private boolean isFromFarFuture(
final Attestation attestation, final UnsignedLong currentTimeMillis) {
final UnsignedLong attestationSlotTimeMillis =
secondsToMillis(
recentChainData
.getGenesisTime()
.plus(
attestation
.getEarliestSlotForForkChoiceProcessing()
.times(UnsignedLong.valueOf(SECONDS_PER_SLOT))));
final UnsignedLong discardAttestationsAfterMillis =
currentTimeMillis.plus(
secondsToMillis(
MAX_FUTURE_SLOT_ALLOWANCE.times(UnsignedLong.valueOf(SECONDS_PER_SLOT))));
return attestationSlotTimeMillis.compareTo(discardAttestationsAfterMillis) > 0;
}
/**
* @param store
* @param time
* @see
* <a>https://github.com/ethereum/eth2.0-specs/blob/v0.8.1/specs/core/0_fork-choice.md#on_tick</a>
*/
public static void on_tick(MutableStore store, UnsignedLong time) {
UnsignedLong previous_slot = get_current_slot(store);
// Update store time
store.setTime(time);
UnsignedLong current_slot = get_current_slot(store);
// Not a new epoch, return
if (!(current_slot.compareTo(previous_slot) > 0
&& compute_slots_since_epoch_start(current_slot).equals(UnsignedLong.ZERO))) {
return;
}
// Update store.justified_checkpoint if a better checkpoint is known
if (store
.getBestJustifiedCheckpoint()
.getEpoch()
.compareTo(store.getJustifiedCheckpoint().getEpoch())
> 0) {
store.setJustifiedCheckpoint(store.getBestJustifiedCheckpoint());
}
}
@Override
public void onTick(Date date) {
if (recentChainData.isPreGenesis()) {
return;
}
final UnsignedLong currentTime = UnsignedLong.valueOf(date.getTime() / 1000);
final StoreTransaction transaction = recentChainData.startStoreTransaction();
on_tick(transaction, currentTime);
transaction.commit().join();
final UnsignedLong genesisTime = recentChainData.getGenesisTime();
if (genesisTime.compareTo(currentTime) > 0) {
// notify every 10 minutes
if (genesisTimeTracker.plus(UnsignedLong.valueOf(600L)).compareTo(currentTime) <= 0) {
genesisTimeTracker = currentTime;
STATUS_LOG.timeUntilGenesis(genesisTime.minus(currentTime).longValue());
}
}
slotProcessor.onTick(currentTime);
}
public SafeFuture<Optional<BeaconBlock>> getUnsignedBeaconBlockAtSlot(
UnsignedLong slot, BLSSignature randao, Optional<Bytes32> graffiti) {
if (slot == null) {
throw new IllegalArgumentException(NO_SLOT_PROVIDED);
}
if (randao == null) {
throw new IllegalArgumentException(NO_RANDAO_PROVIDED);
}
UnsignedLong bestSlot = combinedChainDataClient.getBestSlot();
if (bestSlot.plus(UnsignedLong.valueOf(SLOTS_PER_EPOCH)).compareTo(slot) < 0) {
throw new IllegalArgumentException(CANNOT_PRODUCE_FAR_FUTURE_BLOCK);
}
if (bestSlot.compareTo(slot) > 0) {
throw new IllegalArgumentException(CANNOT_PRODUCE_HISTORIC_BLOCK);
}
return validatorApiChannel
.createUnsignedBlock(
slot, tech.pegasys.teku.bls.BLSSignature.fromBytes(randao.getBytes()), graffiti)
.thenApply(maybeBlock -> maybeBlock.map(BeaconBlock::new));
}
private UnsignedLong secondsBeforeCurrentVotingPeriodStartTime(
final UnsignedLong slot, final UnsignedLong genesisTime, final UnsignedLong valueToSubtract) {
final UnsignedLong currentVotingPeriodStartTime = getVotingPeriodStartTime(slot, genesisTime);
if (currentVotingPeriodStartTime.compareTo(valueToSubtract) > 0) {
return currentVotingPeriodStartTime.minus(valueToSubtract);
} else {
return UnsignedLong.ZERO;
}
}
private UnsignedLong minimumBroadcastTimeMillis(final UnsignedLong attestationSlot) {
final UnsignedLong lastAllowedTime =
recentChainData
.getGenesisTime()
.plus(attestationSlot.times(UnsignedLong.valueOf(SECONDS_PER_SLOT)));
final UnsignedLong lastAllowedTimeMillis = secondsToMillis(lastAllowedTime);
return lastAllowedTimeMillis.compareTo(MAXIMUM_GOSSIP_CLOCK_DISPARITY) >= 0
? lastAllowedTimeMillis.minus(MAXIMUM_GOSSIP_CLOCK_DISPARITY)
: ZERO;
}
private UnsignedLong calculateNumberOfBlocksToRequest(
final UnsignedLong nextSlot, final PeerStatus status) {
if (nextSlot.compareTo(status.getHeadSlot()) > 0) {
// We've synced the advertised head, nothing left to request
return UnsignedLong.ZERO;
}
final UnsignedLong diff = status.getHeadSlot().minus(nextSlot).plus(UnsignedLong.ONE);
return diff.compareTo(MAX_BLOCK_BY_RANGE_REQUEST_SIZE) > 0
? MAX_BLOCK_BY_RANGE_REQUEST_SIZE
: diff;
}
private void prune(final UnsignedLong latestBlockTimestamp) {
if (latestBlockTimestamp.compareTo(cacheDuration) <= 0 || eth1ChainCache.isEmpty()) {
// Keep everything
return;
}
final UnsignedLong earliestBlockTimestampToKeep = latestBlockTimestamp.minus(cacheDuration);
// Make sure we have at least one entry prior to the cache period so that if we get an empty
// block before any deposit in the cached period, we can look back and get the deposit info
final UnsignedLong earliestKeyToKeep = eth1ChainCache.floorKey(earliestBlockTimestampToKeep);
if (earliestKeyToKeep == null) {
return;
}
eth1ChainCache.headMap(earliestKeyToKeep, false).clear();
}
@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());
}
/**
* Return the max of two UnsignedLong values
*
* @param value1
* @param value2
* @return
*/
public static UnsignedLong max(UnsignedLong value1, UnsignedLong value2) {
if (value1.compareTo(value2) >= 0) {
return value1;
} else {
return value2;
}
}
/**
* The largest integer 'x' such that 'x**2' is less than 'n'.
*
* @param n - The highest bound of x.
* @return The largest integer 'x' such that 'x**2' is less than 'n'.
* @see <a>
* https://github.com/ethereum/eth2.0-specs/blob/v0.8.0/specs/core/0_beacon-chain.md#integer_squareroot</a>
*/
public static UnsignedLong integer_squareroot(UnsignedLong n) {
checkArgument(
n.compareTo(UnsignedLong.ZERO) >= 0,
"checkArgument threw an exception in integer_squareroot()");
UnsignedLong TWO = UnsignedLong.valueOf(2L);
UnsignedLong x = n;
UnsignedLong y = x.plus(UnsignedLong.ONE).dividedBy(TWO);
while (y.compareTo(x) < 0) {
x = y;
y = x.plus(n.dividedBy(x)).dividedBy(TWO);
}
return x;
}
private UnsignedLong getCacheRangeLowerBound(UnsignedLong currentTime) {
return currentTime.compareTo(cacheDuration) > 0 ? currentTime.minus(cacheDuration) : ZERO;
}
private static boolean is_active_validator(Validator validator, UnsignedLong epoch) {
return validator.activation_epoch.compareTo(epoch) <= 0
&& epoch.compareTo(validator.exit_epoch) < 0;
}
private static AttestationProcessingResult validateOnAttestation(
final MutableStore store,
final Attestation attestation,
final ForkChoiceStrategy forkChoiceStrategy) {
final Checkpoint target = attestation.getData().getTarget();
UnsignedLong current_epoch = compute_epoch_at_slot(get_current_slot(store));
// Use GENESIS_EPOCH for previous when genesis to avoid underflow
UnsignedLong previous_epoch =
current_epoch.compareTo(UnsignedLong.valueOf(GENESIS_EPOCH)) > 0
? current_epoch.minus(UnsignedLong.ONE)
: UnsignedLong.valueOf(GENESIS_EPOCH);
if (!target.getEpoch().equals(previous_epoch) && !target.getEpoch().equals(current_epoch)) {
return AttestationProcessingResult.invalid(
"Attestations must be from the current or previous epoch");
}
if (!target.getEpoch().equals(compute_epoch_at_slot(attestation.getData().getSlot()))) {
return AttestationProcessingResult.invalid("Attestation slot must be within specified epoch");
}
if (!forkChoiceStrategy.contains(target.getRoot())) {
// Attestations target must be for a known block. If a target block is unknown, delay
// consideration until the block is found
return AttestationProcessingResult.UNKNOWN_BLOCK;
}
Optional<UnsignedLong> blockSlot =
forkChoiceStrategy.blockSlot(attestation.getData().getBeacon_block_root());
if (blockSlot.isEmpty()) {
// Attestations must be for a known block. If block is unknown, delay consideration until the
// block is found
return AttestationProcessingResult.UNKNOWN_BLOCK;
}
if (blockSlot.get().compareTo(attestation.getData().getSlot()) > 0) {
return AttestationProcessingResult.invalid(
"Attestations must not be for blocks in the future. If not, the attestation should not be considered");
}
// LMD vote must be consistent with FFG vote target
final UnsignedLong target_slot = compute_start_slot_at_epoch(target.getEpoch());
if (get_ancestor(forkChoiceStrategy, attestation.getData().getBeacon_block_root(), target_slot)
.map(ancestorRoot -> !ancestorRoot.equals(target.getRoot()))
.orElse(true)) {
return AttestationProcessingResult.invalid(
"LMD vote must be consistent with FFG vote target");
}
return SUCCESSFUL;
}
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);
}
}
private boolean equivalentLongs(final UnsignedLong valA, final UnsignedLong valB) {
return valA.compareTo(valB) == 0;
}
public static boolean isBlockRootAvailableFromState(BeaconState state, UnsignedLong slot) {
UnsignedLong slotPlusHistoricalRoot =
slot.plus(UnsignedLong.valueOf(SLOTS_PER_HISTORICAL_ROOT));
return slot.compareTo(state.getSlot()) < 0
&& state.getSlot().compareTo(slotPlusHistoricalRoot) <= 0;
}
private boolean isCurrentTimeBeforeMinimumAttestationBroadcastTime(
final Attestation attestation, final UnsignedLong currentTimeMillis) {
final UnsignedLong minimumBroadcastTimeMillis =
minimumBroadcastTimeMillis(attestation.getData().getSlot());
return currentTimeMillis.compareTo(minimumBroadcastTimeMillis) < 0;
}