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

The following examples show how to use com.google.common.primitives.UnsignedLong#valueOf() . 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: AttestationTopicSubscriberTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPreserveLaterSubscriptionPeriodWhenEarlierSlotAdded() {
  final int committeeId = 3;
  final UnsignedLong firstSlot = UnsignedLong.valueOf(10);
  final UnsignedLong secondSlot = UnsignedLong.valueOf(18);
  final int subnetId = computeSubnetForCommittee(state, firstSlot, valueOf(committeeId));
  // Sanity check the two subscriptions are for the same subnet
  assertThat(computeSubnetForCommittee(state, secondSlot, valueOf(committeeId)))
      .isEqualTo(subnetId);

  subscriber.subscribeToCommitteeForAggregation(committeeId, secondSlot);
  subscriber.subscribeToCommitteeForAggregation(committeeId, firstSlot);

  subscriber.onSlot(firstSlot.plus(ONE));
  verify(eth2Network, never()).unsubscribeFromAttestationSubnetId(anyInt());

  subscriber.onSlot(secondSlot.plus(ONE));
  verify(eth2Network).unsubscribeFromAttestationSubnetId(subnetId);
}
 
Example 2
Source File: SenderReceiverTest.java    From quilt with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendFromLeftToRightWithSmallMaxPacketValueInNetwork() {
  final UnsignedLong paymentAmount = UnsignedLong.valueOf(100);

  final SimulatedIlpv4Network simulatedIlpNetwork = new SimulatedIlpv4Network(
      SimulatedPathConditions.builder()
          .maxPacketAmount(() -> UnsignedLong.ONE)
          .build(),
      SimulatedPathConditions.builder().build()
  );
  this.initIlpNetworkForStream(simulatedIlpNetwork);

  final SendMoneyResult sendMoneyResult = sendMoney(leftStreamNode, rightStreamNode, paymentAmount);

  assertThat(sendMoneyResult.amountDelivered()).isEqualTo(paymentAmount);
  assertThat(sendMoneyResult.originalAmount()).isEqualTo(paymentAmount);
  assertThat(sendMoneyResult.numFulfilledPackets()).isEqualTo(100);
  assertThat(sendMoneyResult.numRejectPackets()).isGreaterThanOrEqualTo(1);

  logger.info("Payment Sent: {}", sendMoneyResult);
}
 
Example 3
Source File: AttestationTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBeDependentOnSingleBlockWhenTargetBlockAndBeaconBlockRootAreEqual() {
  final Bytes32 root = Bytes32.fromHexString("0x01");

  final Attestation attestation =
      new Attestation(
          aggregationBitfield,
          new AttestationData(
              UnsignedLong.valueOf(1),
              UnsignedLong.ZERO,
              root,
              new Checkpoint(UnsignedLong.ONE, Bytes32.ZERO),
              new Checkpoint(UnsignedLong.valueOf(10), root)),
          BLSSignature.empty());

  assertThat(attestation.getDependentBlockRoots()).containsExactlyInAnyOrder(root);
}
 
Example 4
Source File: CombinedChainDataClientTest_archiveMode.java    From teku with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "{0}")
@MethodSource("getQueryBySlotParameters")
public <T> void queryBySlot_shouldRetrieveHistoricalState(
    final String caseName, final QueryBySlotTestCase<T> testCase) {
  final UnsignedLong finalizedEpoch = UnsignedLong.valueOf(2);
  final UnsignedLong finalizedSlot = compute_start_slot_at_epoch(finalizedEpoch);

  // Setup chain with finalized block
  chainUpdater.initializeGenesis();
  final SignedBlockAndState historicalBlock = chainUpdater.advanceChain();
  chainUpdater.advanceChain(finalizedSlot);
  final SignedBlockAndState finalizedBlock = chainUpdater.finalizeEpoch(finalizedEpoch);
  chainUpdater.addNewBestBlock();

  // Sanity check
  assertThat(historicalBlock.getSlot()).isLessThan(finalizedBlock.getSlot());

  final UnsignedLong querySlot = historicalBlock.getSlot();
  final Optional<SignedBlockAndState> effectiveBlockAtSlot = Optional.of(historicalBlock);
  final SafeFuture<Optional<T>> result = testCase.executeQueryBySlot(client, querySlot);
  final Optional<T> expected =
      testCase.mapEffectiveBlockAtSlotToExpectedResult(querySlot, effectiveBlockAtSlot);

  assertThat(result).isCompletedWithValue(expected);
}
 
Example 5
Source File: AbstractCombinedChainDataClientTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "{0}")
@MethodSource("getQueryBySlotParameters")
public <T> void queryBySlot_shouldRetrieveRecentStateInEffectAtSkippedSlot(
    final String caseName, final QueryBySlotTestCase<T> testCase) {
  final UnsignedLong finalizedEpoch = UnsignedLong.valueOf(2);
  final UnsignedLong finalizedSlot = compute_start_slot_at_epoch(finalizedEpoch);

  chainUpdater.initializeGenesis();
  chainUpdater.advanceChain(finalizedSlot);
  chainUpdater.finalizeEpoch(finalizedEpoch);
  final SignedBlockAndState recentBlock = chainUpdater.advanceChain();
  final UnsignedLong skippedSlot = recentBlock.getSlot().plus(UnsignedLong.ONE);
  final SignedBlockAndState bestBlock =
      chainUpdater.advanceChain(skippedSlot.plus(UnsignedLong.ONE));
  chainUpdater.updateBestBlock(bestBlock);

  final UnsignedLong querySlot = skippedSlot;
  final Optional<SignedBlockAndState> effectiveBlockAtSlot = Optional.of(recentBlock);
  final SafeFuture<Optional<T>> result = testCase.executeQueryBySlot(client, querySlot);
  final Optional<T> expected =
      testCase.mapEffectiveBlockAtSlotToExpectedResult(querySlot, effectiveBlockAtSlot);

  assertThat(result).isCompletedWithValue(expected);
}
 
Example 6
Source File: SimpleStreamSenderIT.java    From quilt with Apache License 2.0 6 votes vote down vote up
/**
 * This test sends a payment in packets that are destined for a receiver that doesn't exist. This will cause an
 * F02_UNREACHABLE reject packet to be returned during the preflightCheck, which should cause the soldierOn loop to
 * short circuit and not try to send any packets.
 */
@Test
public void sendMoneyFailsWithFinalErrorAndShortCircuits() {
  final UnsignedLong paymentAmount = UnsignedLong.valueOf(1000000);

  StreamSender streamSender = new SimpleStreamSender(link);

  final StreamConnectionDetails connectionDetails = getStreamConnectionDetails(1000001);

  final SendMoneyResult sendMoneyResult = streamSender.sendMoney(
      SendMoneyRequest.builder()
          .sourceAddress(SENDER_ADDRESS)
          .amount(paymentAmount)
          .denomination(Denominations.XRP_DROPS)
          .destinationAddress(InterledgerAddress.of("test.foo.bar.patrick"))
          .sharedSecret(connectionDetails.sharedSecret())
          .paymentTracker(new FixedSenderAmountPaymentTracker(paymentAmount, new NoOpExchangeRateCalculator()))
          .build()
  ).join();

  logger.info("SendMoneyResult: " + sendMoneyResult);
  // preflightCheck should trip the circuit and cause streamSender to not even try to send any packets.
  assertThat(sendMoneyResult.totalPackets()).isEqualTo(0);
}
 
Example 7
Source File: AbstractCombinedChainDataClientTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest(name = "{0}")
@MethodSource("getQueryBySlotParameters")
public <T> void queryBySlot_shouldRetrieveHeadState(
    final String caseName, final QueryBySlotTestCase<T> testCase) {
  final UnsignedLong finalizedEpoch = UnsignedLong.valueOf(2);
  final UnsignedLong finalizedSlot = compute_start_slot_at_epoch(finalizedEpoch);

  chainUpdater.initializeGenesis();
  chainUpdater.advanceChain(finalizedSlot);
  chainUpdater.finalizeEpoch(finalizedEpoch);
  final SignedBlockAndState bestBlock = chainUpdater.addNewBestBlock();

  final UnsignedLong querySlot = bestBlock.getSlot();
  final Optional<SignedBlockAndState> effectiveBlockAtSlot = Optional.of(bestBlock);
  final SafeFuture<Optional<T>> result = testCase.executeQueryBySlot(client, querySlot);
  final Optional<T> expected =
      testCase.mapEffectiveBlockAtSlotToExpectedResult(querySlot, effectiveBlockAtSlot);

  assertThat(result).isCompletedWithValue(expected);
}
 
Example 8
Source File: UnsignedLongMathTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void min_valuesAreEqual() {
  final UnsignedLong a = UnsignedLong.valueOf(10);
  final UnsignedLong b = UnsignedLong.valueOf(10);

  final UnsignedLong result = UnsignedLongMath.min(a, b);
  assertThat(result).isEqualTo(a);
  assertThat(result).isEqualTo(b);
}
 
Example 9
Source File: RegisterParams.java    From teku with Apache License 2.0 5 votes vote down vote up
@Override
public UnsignedLong convert(final String value) {
  try {
    return UnsignedLong.valueOf(value);
  } catch (final NumberFormatException e) {
    throw new TypeConversionException(
        "Invalid format: must be a numeric value but was " + value);
  }
}
 
Example 10
Source File: AbstractStorageBackedDatabaseTest.java    From teku with Apache License 2.0 5 votes vote down vote up
public void testShouldRecreateStoreOnRestartWithOffEpochBoundaryFinalizedBlock(
    final Path tempDir, final StateStorageMode storageMode) throws Exception {
  // Set up database with genesis state
  createStorage(tempDir.toFile(), storageMode);
  initGenesis();

  // Create finalized block at slot prior to epoch boundary
  final UnsignedLong finalizedEpoch = UnsignedLong.valueOf(2);
  final UnsignedLong finalizedSlot =
      compute_start_slot_at_epoch(finalizedEpoch).minus(UnsignedLong.ONE);
  chainBuilder.generateBlocksUpToSlot(finalizedSlot);
  final SignedBlockAndState finalizedBlock = chainBuilder.getBlockAndStateAtSlot(finalizedSlot);
  final Checkpoint finalizedCheckpoint =
      chainBuilder.getCurrentCheckpointForEpoch(finalizedEpoch);

  // Add some more blocks
  final UnsignedLong firstHotBlockSlot =
      finalizedCheckpoint.getEpochStartSlot().plus(UnsignedLong.ONE);
  chainBuilder.generateBlockAtSlot(firstHotBlockSlot);
  chainBuilder.generateBlocksUpToSlot(firstHotBlockSlot.plus(UnsignedLong.valueOf(10)));

  // Save new blocks and finalized checkpoint
  final StoreTransaction tx = recentChainData.startStoreTransaction();
  chainBuilder.streamBlocksAndStates(1).forEach(b -> add(tx, List.of(b)));
  justifyAndFinalizeEpoch(finalizedCheckpoint.getEpoch(), finalizedBlock, tx);
  tx.commit().join();

  // Shutdown and restart
  restartStorage();

  final UpdatableStore memoryStore = database.createMemoryStore().orElseThrow();
  assertStoresMatch(memoryStore, store);
}
 
Example 11
Source File: GetStateTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleMissingStateAtNonFinalSlot() throws Exception {
  final GetState handler = new GetState(dataProvider, jsonProvider);
  final UnsignedLong slot = UnsignedLong.valueOf(11223344L);

  when(dataProvider.isStoreAvailable()).thenReturn(true);
  when(context.queryParamMap()).thenReturn(Map.of(SLOT, List.of(slot.toString())));
  when(dataProvider.isFinalized(slot)).thenReturn(false);
  when(dataProvider.getStateAtSlot(any()))
      .thenReturn(SafeFuture.completedFuture(Optional.empty()));

  handler.handle(context);

  verify(context).status(SC_NOT_FOUND);
}
 
Example 12
Source File: AggregationDutyTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldProduceAggregateAndProof() {
  final int validatorIndex = 1;
  final int attestationCommitteeIndex = 2;
  final BLSSignature proof = dataStructureUtil.randomSignature();
  final Attestation unsignedAttestation = dataStructureUtil.randomAttestation();
  final Attestation aggregate = dataStructureUtil.randomAttestation();
  duty.addValidator(
      validator1,
      validatorIndex,
      proof,
      attestationCommitteeIndex,
      completedFuture(Optional.of(unsignedAttestation)));

  when(validatorApiChannel.createAggregate(unsignedAttestation.getData()))
      .thenReturn(completedFuture(Optional.of(aggregate)));

  final AggregateAndProof expectedAggregateAndProof =
      new AggregateAndProof(UnsignedLong.valueOf(validatorIndex), aggregate, proof);
  final BLSSignature aggregateSignature = dataStructureUtil.randomSignature();
  when(signer1.signAggregateAndProof(expectedAggregateAndProof, forkInfo))
      .thenReturn(SafeFuture.completedFuture(aggregateSignature));

  assertThat(duty.performDuty()).isCompleted();

  verify(validatorApiChannel)
      .sendAggregateAndProof(
          new SignedAggregateAndProof(expectedAggregateAndProof, aggregateSignature));
}
 
Example 13
Source File: GetStateRootTest.java    From teku with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnNotFoundWhenQueryByMissingSlot() throws Exception {
  GetStateRoot handler = new GetStateRoot(provider, jsonProvider);
  UnsignedLong nonExistentSlot = UnsignedLong.valueOf(11223344);
  when(context.queryParamMap()).thenReturn(Map.of(SLOT, List.of("11223344")));
  when(provider.getBestBlockRoot()).thenReturn(Optional.of(blockRoot));
  when(provider.getStateRootAtSlot(nonExistentSlot))
      .thenReturn(SafeFuture.completedFuture(Optional.empty()));

  handler.handle(context);

  verify(context).status(SC_NOT_FOUND);
}
 
Example 14
Source File: BlockValidator.java    From teku with Apache License 2.0 5 votes vote down vote up
private boolean blockIsFromFutureSlot(SignedBeaconBlock block) {
  ReadOnlyStore store = recentChainData.getStore();
  final long disparityInSeconds = Math.round((float) MAXIMUM_GOSSIP_CLOCK_DISPARITY / 1000.0);
  final UnsignedLong maxOffset = UnsignedLong.valueOf(disparityInSeconds);
  final UnsignedLong maxTime = store.getTime().plus(maxOffset);
  UnsignedLong maxCurrSlot = getCurrentSlot(maxTime, store.getGenesisTime());
  return block.getSlot().compareTo(maxCurrSlot) > 0;
}
 
Example 15
Source File: BlockProcessorUtil.java    From teku with Apache License 2.0 5 votes vote down vote up
public static void process_attestations_no_validation(
    MutableBeaconState state, SSZList<Attestation> attestations) throws BlockProcessingException {
  try {
    final AttestationDataStateTransitionValidator validator =
        new AttestationDataStateTransitionValidator();

    for (Attestation attestation : attestations) {
      AttestationData data = attestation.getData();
      final Optional<OperationInvalidReason> invalidReason = validator.validate(state, data);
      checkArgument(
          invalidReason.isEmpty(),
          "process_attestations: %s",
          invalidReason.map(OperationInvalidReason::describe).orElse(""));

      List<Integer> committee = get_beacon_committee(state, data.getSlot(), data.getIndex());
      checkArgument(
          attestation.getAggregation_bits().getCurrentSize() == committee.size(),
          "process_attestations: Attestation aggregation bits and committee don't have the same length");

      PendingAttestation pendingAttestation =
          new PendingAttestation(
              attestation.getAggregation_bits(),
              data,
              state.getSlot().minus(data.getSlot()),
              UnsignedLong.valueOf(get_beacon_proposer_index(state)));

      if (data.getTarget().getEpoch().equals(get_current_epoch(state))) {
        state.getCurrent_epoch_attestations().add(pendingAttestation);
      } else {
        state.getPrevious_epoch_attestations().add(pendingAttestation);
      }
    }
  } catch (IllegalArgumentException e) {
    LOG.warn(e.getMessage());
    throw new BlockProcessingException(e);
  }
}
 
Example 16
Source File: SenderReceiverTest.java    From quilt with Apache License 2.0 5 votes vote down vote up
@Override
public UnsignedLong calculateAmountToSend(UnsignedLong amountToSend,
    Denomination amountToSendDenomination,
    Denomination receiverDenomination) {
  return UnsignedLong.valueOf(new BigDecimal(amountToSend.bigIntegerValue())
      .divide(senderUnitsPerReceiverUnits, RoundingMode.FLOOR).toBigInteger()); // toBigInteger rounds to Floor
}
 
Example 17
Source File: Eth1HeadTrackerTest.java    From teku with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void setConstants() {
  Constants.ETH1_FOLLOW_DISTANCE = UnsignedLong.valueOf(FOLLOW_DISTANCE);
}
 
Example 18
Source File: MinimumGenesisTimeBlockFinderTest.java    From teku with Apache License 2.0 4 votes vote down vote up
@BeforeAll
static void setUp() {
  // Setup so genesis time for a block will be blockTime + 2
  Constants.GENESIS_DELAY = UnsignedLong.valueOf(2);
}
 
Example 19
Source File: BeaconStateUtilTest.java    From teku with Apache License 2.0 4 votes vote down vote up
@Test
void sqrtOfANonSquareNumber() {
  UnsignedLong actual = BeaconStateUtil.integer_squareroot(UnsignedLong.valueOf(27L));
  UnsignedLong expected = UnsignedLong.valueOf(5L);
  assertEquals(expected, actual);
}
 
Example 20
Source File: InterledgerPreparePacketTest.java    From quilt with Apache License 2.0 4 votes vote down vote up
@Test
public void testEqualsHashCode() {
  final InterledgerAddress destination = mock(InterledgerAddress.class);
  byte[] data = new byte[] {127};
  UnsignedLong amount = UnsignedLong.valueOf(10L);
  InterledgerCondition interledgerCondition = InterledgerCondition.of(
      new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 01, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6,
          7, 8, 9, 0, 1, 2}
  );
  Instant expiry = DateUtils.now().plusSeconds(30);

  final InterledgerPreparePacket interledgerPreparePacket1 =
      InterledgerPreparePacket.builder()
          .destination(destination)
          .amount(amount)
          .executionCondition(interledgerCondition)
          .expiresAt(expiry)
          .data(data)
          .build();

  final InterledgerPreparePacket interledgerPreparePacket2 =
      InterledgerPreparePacket.builder()
          .destination(destination)
          .amount(amount)
          .executionCondition(interledgerCondition)
          .expiresAt(expiry)
          .data(data)
          .build();

  assertThat(interledgerPreparePacket1).isEqualTo(interledgerPreparePacket2);
  assertThat(interledgerPreparePacket2).isEqualTo(interledgerPreparePacket1);
  assertThat(interledgerPreparePacket1.hashCode()).isEqualTo(interledgerPreparePacket2.hashCode());

  final InterledgerPreparePacket interledgerPreparePacket3 = InterledgerPreparePacket.builder()
      .destination(destination)
      .amount(amount.plus(UnsignedLong.ONE))
      .executionCondition(interledgerCondition)
      .expiresAt(expiry)
      .data(data)
      .build();

  assertThat(interledgerPreparePacket1).isNotEqualTo(interledgerPreparePacket3);
  assertThat(interledgerPreparePacket3).isNotEqualTo(interledgerPreparePacket1);
  assertThat(interledgerPreparePacket1.hashCode()).isNotEqualTo(interledgerPreparePacket3.hashCode());
}