下面列出了怎么用com.google.common.primitives.UnsignedLong的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void fulfill(final UnsignedLong prepareAmount) {
Objects.requireNonNull(prepareAmount);
this.amountInFlight.getAndUpdate((currentAmountInFlight) -> currentAmountInFlight.minus(prepareAmount));
// Before we know how much we should be sending at a time, double the window size on every successful packet.
// Once we start getting errors, switch to Additive Increase, Multiplicative Decrease (AIMD) congestion avoidance.
if (this.congestionState.get() == CongestionState.SLOW_START) {
// Double the max in flight but don't exceed the u64 max value
if (is(HALF_UNSIGNED_MAX).greaterThanEqualTo(this.maxInFlight.get())) {
this.maxInFlight.getAndUpdate(maxInFlight -> maxInFlight.times(TWO));
} else {
this.maxInFlight.set(UnsignedLong.MAX_VALUE);
}
} else {
// Add to the max in flight but don't exceed the u64 max value
if (is(UnsignedLong.MAX_VALUE.minus(increaseAmount)).greaterThanEqualTo(this.maxInFlight.get())) {
this.maxInFlight.getAndUpdate(maxInFlight -> maxInFlight.plus(increaseAmount));
} else {
this.maxInFlight.set(UnsignedLong.MAX_VALUE);
}
}
}
@Test
public void shouldReturnEmptyListWhenQueryByActiveAndFarFutureEpoch() throws Exception {
final GetValidators handler = new GetValidators(provider, jsonProvider);
final UnsignedLong farFutureSlot =
BeaconStateUtil.compute_start_slot_at_epoch(Constants.FAR_FUTURE_EPOCH);
when(context.queryParamMap())
.thenReturn(
Map.of(
ACTIVE,
List.of("true"),
EPOCH,
List.of(String.valueOf(Constants.FAR_FUTURE_EPOCH))));
when(provider.isStoreAvailable()).thenReturn(true);
when(provider.getBestBlockRoot()).thenReturn(Optional.of(blockRoot));
when(provider.getStateAtSlot(farFutureSlot))
.thenReturn(SafeFuture.completedFuture(Optional.of(beaconState)));
handler.handle(context);
verify(context).result(args.capture());
SafeFuture<String> data = args.getValue();
assertEquals(data.get(), jsonProvider.objectToJSON(new BeaconValidators()));
}
@Test
public void shouldHandleMissingResultForFinalizedEpoch() throws Exception {
final UnsignedLong epoch = UnsignedLong.ZERO;
final String body =
String.format("{\"epoch\":%s, \"pubkeys\":[\"%s\"]}", epoch, pubKeys.get(0));
PostDuties handler = new PostDuties(provider, jsonProvider);
when(provider.isStoreAvailable()).thenReturn(true);
when(context.body()).thenReturn(body);
when(provider.isEpochFinalized(epoch)).thenReturn(true);
when(provider.getValidatorDutiesByRequest(any()))
.thenReturn(SafeFuture.completedFuture(Optional.empty()));
handler.handle(context);
verify(context).result(args.capture());
verify(context).header(Header.CACHE_CONTROL, CACHE_NONE);
verify(context).status(SC_GONE);
SafeFuture<String> data = args.getValue();
assertThat(data.get()).isNull();
}
@Test
public void testSendFromRightToLeft() {
final UnsignedLong paymentAmount = UnsignedLong.valueOf(1000);
final StreamConnectionDetails connectionDetails = leftStreamNode.getNewStreamConnectionDetails();
final SendMoneyResult sendMoneyResult = rightStreamNode.streamSender().sendMoney(
SendMoneyRequest.builder()
.sourceAddress(rightStreamNode.senderAddress())
.amount(paymentAmount)
.denomination(rightStreamNode.denomination())
.destinationAddress(connectionDetails.destinationAddress())
.sharedSecret(connectionDetails.sharedSecret())
.paymentTracker(new FixedSenderAmountPaymentTracker(paymentAmount, new NoOpExchangeRateCalculator()))
.timeout(Duration.ofMillis(10000))
.build()
).join();
assertThat(sendMoneyResult.amountDelivered()).isEqualTo(paymentAmount);
assertThat(sendMoneyResult.originalAmount()).isEqualTo(paymentAmount);
assertThat(sendMoneyResult.numFulfilledPackets()).isEqualTo(1);
assertThat(sendMoneyResult.numRejectPackets()).isEqualTo(0);
logger.info("Payment Sent: {}", sendMoneyResult);
}
/**
* Processes rewards and penalties
*
* @param state
* @param matchingAttestations
* @throws EpochProcessingException
*/
public static void process_rewards_and_penalties(
MutableBeaconState state, MatchingAttestations matchingAttestations)
throws EpochProcessingException {
try {
if (get_current_epoch(state).equals(UnsignedLong.valueOf(GENESIS_EPOCH))) {
return;
}
Deltas attestation_deltas =
new RewardsAndPenaltiesCalculator(state, matchingAttestations).getAttestationDeltas();
for (int i = 0; i < state.getValidators().size(); i++) {
increase_balance(state, i, attestation_deltas.getReward(i));
decrease_balance(state, i, attestation_deltas.getPenalty(i));
}
} catch (IllegalArgumentException e) {
throw new EpochProcessingException(e);
}
}
@Test
public void testCalculateMinAmountToAcceptDefault() {
final AtomicBoolean called = new AtomicBoolean(false);
final ExchangeRateCalculator calculator = new ExchangeRateCalculator() {
@Override
public UnsignedLong calculateAmountToSend(UnsignedLong amountToSend, Denomination amountToSendDenomination,
Denomination receiverDenomination) throws NoExchangeRateException {
return UnsignedLong.ZERO;
}
@Override
public UnsignedLong calculateMinAmountToAccept(UnsignedLong sendAmount, Denomination sendAmountDenomination)
throws NoExchangeRateException {
called.set(true);
return UnsignedLong.ZERO;
}
};
calculator.calculateMinAmountToAccept(UnsignedLong.ZERO, Denominations.USD_CENTS);
assertThat(called.get()).isTrue();
}
SafeFuture<Optional<SignedBeaconBlock>> loadNextBlock() {
final UnsignedLong slot = this.currentSlot;
final Bytes32 knownBlockRoot = knownBlockRoots.get(slot);
if (knownBlockRoot != null) {
// Known root so lookup by root
return combinedChainDataClient
.getBlockByBlockRoot(knownBlockRoot)
.thenApply(maybeBlock -> maybeBlock.filter(block -> block.getSlot().equals(slot)));
} else if ((!knownBlockRoots.isEmpty() && slot.compareTo(knownBlockRoots.firstKey()) >= 0)
|| slot.compareTo(headSlot) > 0) {
// Unknown root but not finalized means this is an empty slot
// Could also be because the first block requested is above our head slot
return SafeFuture.completedFuture(Optional.empty());
} else {
// Must be a finalized block so lookup by slot
return combinedChainDataClient.getBlockAtSlotExact(slot);
}
}
@Test
public void onTick_shouldExitBeforeOtherProcessingIfSyncing() {
ArgumentCaptor<UnsignedLong> captor = ArgumentCaptor.forClass(UnsignedLong.class);
when(syncService.isSyncActive()).thenReturn(true);
when(forkChoice.processHead()).thenReturn(dataStructureUtil.randomBytes32());
when(p2pNetwork.getPeerCount()).thenReturn(1);
slotProcessor.onTick(beaconState.getGenesis_time());
assertThat(slotProcessor.getNodeSlot().getValue()).isEqualTo(ONE);
verify(slotEventsChannel).onSlot(captor.capture());
assertThat(captor.getValue()).isEqualTo(ZERO);
verify(syncService).isSyncActive();
verify(eventLogger).syncEvent(ZERO, ZERO, 1);
}
@Test
public void shouldReturnValidatorsWhenQueryByEpoch() throws Exception {
GetValidators handler = new GetValidators(provider, jsonProvider);
when(context.queryParamMap()).thenReturn(Map.of(EPOCH, List.of(epoch.toString())));
final UnsignedLong slot = BeaconStateUtil.compute_start_slot_at_epoch(epoch);
BeaconValidators beaconValidators = new BeaconValidators(beaconStateInternal);
when(provider.isStoreAvailable()).thenReturn(true);
when(provider.getStateAtSlot(slot))
.thenReturn(SafeFuture.completedFuture(Optional.of(beaconState)));
handler.handle(context);
verify(provider).getStateAtSlot(slot);
verify(context).result(args.capture());
SafeFuture<String> data = args.getValue();
assertThat(beaconValidators.validators.size())
.isEqualTo(Math.min(PAGE_SIZE_DEFAULT, beaconStateInternal.getValidators().size()));
assertEquals(data.get(), jsonProvider.objectToJSON(beaconValidators));
}
private UnsignedLong convertToEth2DisconnectReason(final DisconnectReason reason) {
switch (reason) {
case TOO_MANY_PEERS:
return GoodbyeMessage.REASON_TOO_MANY_PEERS;
case SHUTTING_DOWN:
return GoodbyeMessage.REASON_CLIENT_SHUT_DOWN;
case REMOTE_FAULT:
return GoodbyeMessage.REASON_FAULT_ERROR;
case IRRELEVANT_NETWORK:
return GoodbyeMessage.REASON_IRRELEVANT_NETWORK;
case UNABLE_TO_VERIFY_NETWORK:
return GoodbyeMessage.REASON_UNABLE_TO_VERIFY_NETWORK;
default:
LOG.warn("Unknown disconnect reason: " + reason);
return GoodbyeMessage.REASON_FAULT_ERROR;
}
}
@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);
}
public SignedBlockAndState createBlock(
final MessageSignerService signer,
final UnsignedLong newSlot,
final BeaconState previousState,
final Bytes32 parentBlockSigningRoot,
final Optional<SSZList<Attestation>> attestations,
final Optional<SSZList<Deposit>> deposits,
final Optional<SSZList<SignedVoluntaryExit>> exits,
final Optional<Eth1Data> eth1Data)
throws StateTransitionException {
final UnsignedLong newEpoch = compute_epoch_at_slot(newSlot);
return createNewBlock(
signer,
newSlot,
previousState,
parentBlockSigningRoot,
eth1Data.orElse(get_eth1_data_stub(previousState, newEpoch)),
attestations.orElse(BeaconBlockBodyLists.createAttestations()),
BeaconBlockBodyLists.createProposerSlashings(),
deposits.orElse(BeaconBlockBodyLists.createDeposits()),
exits.orElse(BeaconBlockBodyLists.createVoluntaryExits()));
}
@Test
void shouldRegenerateFromMoreRecentCachedState() throws Exception {
final UnsignedLong databaseSlot = UnsignedLong.valueOf(1);
final UnsignedLong cachedSlot = UnsignedLong.valueOf(2);
final UnsignedLong requestedSlot = UnsignedLong.valueOf(3);
chainBuilder.generateBlocksUpToSlot(requestedSlot);
// Latest state available from the database is at databaseSlot (1)
when(database.getLatestAvailableFinalizedState(any()))
.thenReturn(Optional.of(chainBuilder.getStateAtSlot(databaseSlot)));
allowStreamingBlocks();
// Should regenerate the same state
assertThat(cache.getFinalizedState(cachedSlot))
.contains(chainBuilder.getStateAtSlot(cachedSlot));
verify(database).streamFinalizedBlocks(databaseSlot.plus(ONE), cachedSlot);
// Should only need the blocks from the cached state forward
assertThat(cache.getFinalizedState(requestedSlot))
.contains(chainBuilder.getStateAtSlot(requestedSlot));
verify(database).streamFinalizedBlocks(cachedSlot.plus(ONE), requestedSlot);
}
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);
}
});
}
@Test
public void handleF08RejectionWithPrepareGreaterThanMaxWithRoundingDownBelowPoint5() {
InterledgerRejectPacket rejectPacket = interledgerRejectPacket(Optional.of(
AmountTooLargeErrorData.builder()
.receivedAmount(UnsignedLong.valueOf(3L))
.maximumAmount(UnsignedLong.valueOf(2L))
.build()
));
assertThat(controller.handleF08Rejection(UnsignedLong.valueOf(10L), rejectPacket))
.isEqualTo(UnsignedLong.valueOf(6L));
}
private global_config_object() {
mGsonBuilder = new GsonBuilder();
mGsonBuilder.registerTypeAdapter(types.public_key_type.class, new types.public_key_type_deserializer());
mGsonBuilder.registerTypeAdapter(types.public_key_type.class, new types.public_type_serializer());
mGsonBuilder.registerTypeAdapter(operations.operation_type.class, new operations.operation_type.operation_type_deserializer());
mGsonBuilder.registerTypeAdapter(object_id.class, new object_id.object_id_deserializer());
mGsonBuilder.registerTypeAdapter(object_id.class, new object_id.object_id_serializer());
mGsonBuilder.registerTypeAdapter(fee_schedule.fee_parameters.class, new fee_schedule.fee_parameters_deserializer());
mGsonBuilder.registerTypeAdapter(types.vote_id_type.class, new types.vote_id_type_deserializer());
mGsonBuilder.registerTypeAdapter(ripemd160_object.class, new ripemd160_object.ripemd160_object_deserializer());
mGsonBuilder.registerTypeAdapter(sha256_object.class, new sha256_object.sha256_object_deserializer());
mGsonBuilder.registerTypeAdapter(UnsignedLong.class, new unsigned_number_deserializer.UnsignedLongDeserialize());
mGsonBuilder.registerTypeAdapter(Date.class, new gson_common_deserializer.DateDeserializer());
mGsonBuilder.registerTypeAdapter(ByteBuffer.class, new gson_common_deserializer.ByteBufferDeserializer());
mGsonBuilder.registerTypeAdapter(full_account_object_reply.class, new full_account_object_reply.full_account_object_reply_deserializer());
//mGsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");
// register serializer
mGsonBuilder.registerTypeAdapter(operations.operation_type.class, new operations.operation_type.operation_type_serializer());
mGsonBuilder.registerTypeAdapter(compact_signature.class, new compact_signature.compact_signature_serializer());
mGsonBuilder.registerTypeAdapter(UnsignedInteger.class, new unsigned_number_serializer.UnsigendIntegerSerializer());
mGsonBuilder.registerTypeAdapter(UnsignedShort.class, new unsigned_number_serializer.UnsigendShortSerializer());
mGsonBuilder.registerTypeAdapter(Date.class, new gson_common_serializer.DateSerializer());
mGsonBuilder.registerTypeAdapter(sha256_object.class, new sha256_object.sha256_object_serializer());
mGsonBuilder.registerTypeAdapter(ByteBuffer.class, new gson_common_serializer.ByteBufferSerializer());
mGsonBuilder.registerTypeAdapter(UnsignedLong.class, new unsigned_number_serializer.UnsignedLongSerializer());
}
public FinalizedStateCache(
final Database database, final int maximumCacheSize, final boolean useSoftReferences) {
this.database = database;
final CacheBuilder<UnsignedLong, BeaconState> cacheBuilder =
CacheBuilder.newBuilder()
.maximumSize(maximumCacheSize)
.removalListener(this::onRemovedFromCache);
if (useSoftReferences) {
cacheBuilder.softValues();
}
this.stateCache = cacheBuilder.build(new StateCacheLoader());
}
@Test
public void shouldReturnNoContentWhenBestBlockRootMissing() throws Exception {
final UnsignedLong epoch = UnsignedLong.ONE;
final UpdatableStore store = mock(UpdatableStore.class);
when(recentChainData.getStore()).thenReturn(store);
when(recentChainData.getFinalizedEpoch()).thenReturn(epoch);
when(recentChainData.getBestBlockRoot()).thenReturn(Optional.empty());
final Response response = post(epoch.intValue(), keys);
assertNoContent(response);
}
static void notifyMinGenesisTimeBlockReached(
Eth1EventsChannel eth1EventsChannel, EthBlock.Block block) {
MinGenesisTimeBlockEvent event =
new MinGenesisTimeBlockEvent(
UnsignedLong.valueOf(block.getTimestamp()),
UnsignedLong.valueOf(block.getNumber()),
Bytes32.fromHexString(block.getHash()));
eth1EventsChannel.onMinGenesisTimeBlock(event);
LOG.debug("Notifying BeaconChainService of MinGenesisTimeBlock: {}", event);
}
@Test
public void shouldRejectAttestationFromBeforeAttestationPropagationSlotRange() {
final Attestation attestation =
attestationGenerator.validAttestation(recentChainData.getBestBlockAndState().orElseThrow());
// In the first slot after
final UnsignedLong slot = ATTESTATION_PROPAGATION_SLOT_RANGE.plus(ONE);
beaconChainUtil.setSlot(slot);
// Add one more second to get past the MAXIMUM_GOSSIP_CLOCK_DISPARITY
beaconChainUtil.setTime(recentChainData.getStore().getTime().plus(ONE));
assertThat(validate(attestation)).isEqualTo(IGNORE);
}
public StatusMessage(
Bytes4 forkDigest,
Bytes32 finalizedRoot,
UnsignedLong finalizedEpoch,
Bytes32 headRoot,
UnsignedLong headSlot) {
this.forkDigest = forkDigest;
this.finalizedRoot = finalizedRoot;
this.finalizedEpoch = finalizedEpoch;
this.headRoot = headRoot;
this.headSlot = headSlot;
}
@Test
public void testDeriveSerialization() {
Derive c0 = new Derive(UnsignedLong.fromLongBits(50L));
ValueType<?> c1 = ValueType.compose(ValueType.decompose(c0));
assertTrue(c1 instanceof Derive);
assertEquals(c0, c1);
}
private Attestation attestationFromSlot(final long slot, final Bytes32 targetRoot) {
return new Attestation(
new Bitlist(1, 1),
new AttestationData(
UnsignedLong.valueOf(slot),
UnsignedLong.ZERO,
Bytes32.ZERO,
new Checkpoint(UnsignedLong.ZERO, Bytes32.ZERO),
new Checkpoint(UnsignedLong.ZERO, targetRoot)),
BLSSignature.empty());
}
public void report(
final String producedType, final UnsignedLong slot, final ValidatorLogger logger) {
if (successCount > 0) {
logger.dutyCompleted(producedType, slot, successCount, roots);
}
if (nodeSyncingCount > 0) {
logger.dutySkippedWhileSyncing(producedType, slot, nodeSyncingCount);
}
errors.forEach(error -> logger.dutyFailed(producedType, slot, error));
}
private List<SignedBeaconBlock> requestBlocks()
throws InterruptedException, java.util.concurrent.ExecutionException,
java.util.concurrent.TimeoutException {
final List<SignedBeaconBlock> blocks = new ArrayList<>();
waitFor(
peer1.requestBlocksByRange(
UnsignedLong.ONE, UnsignedLong.valueOf(10), UnsignedLong.ONE, blocks::add));
return blocks;
}
@Test
void equalsReturnsFalseWhenSlotsAreDifferent() {
BeaconBlock testBeaconBlock =
new BeaconBlock(
slot.plus(UnsignedLong.ONE), proposer_index, previous_root, state_root, body);
assertNotEquals(beaconBlock, testBeaconBlock);
}
@BeforeEach
public void setUp() {
when(storageClient.getFinalizedEpoch()).thenReturn(UnsignedLong.ZERO);
when(peer.getStatus()).thenReturn(PEER_STATUS);
// By default set up block import to succeed
final BlockProcessingRecord processingRecord = mock(BlockProcessingRecord.class);
final SignedBeaconBlock block = mock(SignedBeaconBlock.class);
final BlockImportResult result = BlockImportResult.successful(processingRecord);
when(processingRecord.getBlock()).thenReturn(block);
when(blockImporter.importBlock(any())).thenReturn(result);
peerSync = new PeerSync(asyncRunner, storageClient, blockImporter);
}
@Test
public void preflightCheckRejects() throws Exception {
when(streamConnectionMock.nextSequence()).thenReturn(UnsignedLong.ONE);
when(linkMock.sendPacket(any())).thenReturn(sampleRejectPacket(T00_INTERNAL_ERROR));
StreamPacket streamPacket = StreamPacket.builder().from(sampleStreamPacket())
.addFrames(StreamMoneyFrame.builder()
.shares(UnsignedLong.ONE)
.streamId(UnsignedLong.ONE)
.build())
.build();
when(streamCodecContextMock.read(any(), any())).thenReturn(streamPacket);
Optional<Denomination> denomination = sendMoneyAggregator.preflightCheck();
assertThat(denomination).isEmpty();
}
@Test
public void importBlock_parentBlockFromSameSlot() throws Exception {
// First import a valid block at slot 1
final SignedBeaconBlock block = otherChain.createAndImportBlockAtSlot(UnsignedLong.ONE);
localChain.setSlot(block.getSlot());
assertSuccessfulResult(blockImporter.importBlock(block));
// Now create an alternate block 1 with the real block one as the parent block
final BeaconBlock invalidAncestryUnsignedBlock =
new BeaconBlock(
block.getSlot(),
block.getMessage().getProposer_index(),
block.getMessage().hash_tree_root(),
block.getMessage().getState_root(),
block.getMessage().getBody());
final Signer signer =
new Signer(localChain.getSigner(block.getMessage().getProposer_index().intValue()));
final SignedBeaconBlock invalidAncestryBlock =
new SignedBeaconBlock(
invalidAncestryUnsignedBlock,
signer
.signBlock(
invalidAncestryUnsignedBlock, otherStorage.getHeadForkInfo().orElseThrow())
.join());
final BlockImportResult result = blockImporter.importBlock(invalidAncestryBlock);
assertThat(result.isSuccessful()).isFalse();
assertThat(result.getFailureReason())
.isEqualTo(BlockImportResult.FAILED_INVALID_ANCESTRY.getFailureReason());
}
@Override
public void onSlot(final UnsignedLong slot) {
List<ValidateableAttestation> attestations = futureAttestations.prune(slot);
attestations.stream()
.map(ValidateableAttestation::getIndexedAttestation)
.forEach(attestationProcessor::applyIndexedAttestationToForkChoice);
attestations.forEach(this::notifySubscribers);
}