com.google.common.primitives.UnsignedLong Java Examples
The following examples show how to use
com.google.common.primitives.UnsignedLong.
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: AimdCongestionController.java From quilt with Apache License 2.0 | 6 votes |
@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); } } }
Example #2
Source File: GetValidatorsTest.java From teku with Apache License 2.0 | 6 votes |
@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())); }
Example #3
Source File: SlotProcessorTest.java From teku with Apache License 2.0 | 6 votes |
@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); }
Example #4
Source File: BeaconBlocksByRangeMessageHandler.java From teku with Apache License 2.0 | 6 votes |
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); } }
Example #5
Source File: PostDutiesTest.java From teku with Apache License 2.0 | 6 votes |
@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(); }
Example #6
Source File: GetValidatorsTest.java From teku with Apache License 2.0 | 6 votes |
@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)); }
Example #7
Source File: PeerSync.java From teku with Apache License 2.0 | 6 votes |
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 #8
Source File: FinalizedStateCacheTest.java From teku with Apache License 2.0 | 6 votes |
@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); }
Example #9
Source File: ExchangeRateCalculatorTest.java From quilt with Apache License 2.0 | 6 votes |
@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(); }
Example #10
Source File: SenderReceiverTest.java From quilt with Apache License 2.0 | 6 votes |
@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); }
Example #11
Source File: BlockProposalTestUtil.java From teku with Apache License 2.0 | 6 votes |
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())); }
Example #12
Source File: BlockImporterTest.java From teku with Apache License 2.0 | 6 votes |
@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 #13
Source File: Eth2PeerManager.java From teku with Apache License 2.0 | 6 votes |
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; } }
Example #14
Source File: EpochProcessorUtil.java From teku with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #15
Source File: ValueTypeTest.java From newts with Apache License 2.0 | 5 votes |
@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); }
Example #16
Source File: BlockTopicHandlerTest.java From teku with Apache License 2.0 | 5 votes |
@Test public void handleMessage_validFutureBlock() throws Exception { final UnsignedLong nextSlot = recentChainData.getBestSlot().plus(UnsignedLong.ONE); final SignedBeaconBlock block = beaconChainUtil.createBlockAtSlot(nextSlot); Bytes serialized = gossipEncoding.encode(block); beaconChainUtil.setSlot(recentChainData.getBestSlot()); final ValidationResult result = topicHandler.handleMessage(serialized); assertThat(result).isEqualTo(ValidationResult.Ignore); verify(eventBus).post(new GossipedBlockEvent(block)); }
Example #17
Source File: StatusMessage.java From teku with Apache License 2.0 | 5 votes |
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; }
Example #18
Source File: HalfsiesExchangeRateCalculator.java From quilt with Apache License 2.0 | 5 votes |
@Override public UnsignedLong calculateAmountToSend( final UnsignedLong amountToSend, final Denomination amountToSendDenomination, final Denomination receiverDenomination ) throws NoExchangeRateException { Objects.requireNonNull(amountToSend); Objects.requireNonNull(amountToSendDenomination); Objects.requireNonNull(receiverDenomination); return amountToSend.times(UnsignedLong.valueOf(2)); }
Example #19
Source File: AimdCongestionControllerTest.java From quilt with Apache License 2.0 | 5 votes |
@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)); }
Example #20
Source File: AggregationDuty.java From teku with Apache License 2.0 | 5 votes |
private CommitteeAggregator( final Validator validator, final UnsignedLong validatorIndex, final BLSSignature proof, final SafeFuture<Optional<Attestation>> unsignedAttestationFuture) { this.validator = validator; this.validatorIndex = validatorIndex; this.proof = proof; this.unsignedAttestationFuture = unsignedAttestationFuture; }
Example #21
Source File: PostDutiesIntegrationTest.java From teku with Apache License 2.0 | 5 votes |
@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); }
Example #22
Source File: BlockImporterTest.java From teku with Apache License 2.0 | 5 votes |
@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()); }
Example #23
Source File: MatchingAttestations.java From teku with Apache License 2.0 | 5 votes |
/** * 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 #24
Source File: AttestationManager.java From teku with Apache License 2.0 | 5 votes |
@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); }
Example #25
Source File: AttestationManagerTest.java From teku with Apache License 2.0 | 5 votes |
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()); }
Example #26
Source File: DutyResult.java From teku with Apache License 2.0 | 5 votes |
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)); }
Example #27
Source File: BeaconBlocksByRangeIntegrationTest.java From teku with Apache License 2.0 | 5 votes |
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; }
Example #28
Source File: BeaconBlockTest.java From teku with Apache License 2.0 | 5 votes |
@Test void equalsReturnsFalseWhenSlotsAreDifferent() { BeaconBlock testBeaconBlock = new BeaconBlock( slot.plus(UnsignedLong.ONE), proposer_index, previous_root, state_root, body); assertNotEquals(beaconBlock, testBeaconBlock); }
Example #29
Source File: PeerSyncTest.java From teku with Apache License 2.0 | 5 votes |
@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); }
Example #30
Source File: SendMoneyAggregatorTest.java From quilt with Apache License 2.0 | 5 votes |
@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(); }