com.google.common.primitives.UnsignedLong#valueOf ( )源码实例Demo

下面列出了com.google.common.primitives.UnsignedLong#valueOf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: teku   文件: AttestationTopicSubscriberTest.java
@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);
}
 
@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);
}
 
源代码3 项目: quilt   文件: SimpleStreamSenderIT.java
/**
 * 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);
}
 
@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);
}
 
@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);
}
 
源代码6 项目: teku   文件: AttestationTest.java
@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);
}
 
源代码7 项目: quilt   文件: SenderReceiverTest.java
@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);
}
 
源代码8 项目: quilt   文件: SenderReceiverTest.java
@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
}
 
源代码9 项目: teku   文件: UnsignedLongMathTest.java
@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);
}
 
源代码10 项目: teku   文件: BlockProcessorUtil.java
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);
  }
}
 
源代码11 项目: teku   文件: BlockValidator.java
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;
}
 
源代码12 项目: teku   文件: GetStateRootTest.java
@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);
}
 
源代码13 项目: teku   文件: AggregationDutyTest.java
@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));
}
 
源代码14 项目: teku   文件: GetStateTest.java
@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);
}
 
源代码15 项目: teku   文件: AbstractStorageBackedDatabaseTest.java
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);
}
 
源代码16 项目: teku   文件: RegisterParams.java
@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);
  }
}
 
源代码17 项目: teku   文件: BeaconStateUtilTest.java
@Test
void sqrtOfANonSquareNumber() {
  UnsignedLong actual = BeaconStateUtil.integer_squareroot(UnsignedLong.valueOf(27L));
  UnsignedLong expected = UnsignedLong.valueOf(5L);
  assertEquals(expected, actual);
}
 
源代码18 项目: teku   文件: Eth1HeadTrackerTest.java
@BeforeAll
static void setConstants() {
  Constants.ETH1_FOLLOW_DISTANCE = UnsignedLong.valueOf(FOLLOW_DISTANCE);
}
 
源代码19 项目: teku   文件: MinimumGenesisTimeBlockFinderTest.java
@BeforeAll
static void setUp() {
  // Setup so genesis time for a block will be blockTime + 2
  Constants.GENESIS_DELAY = UnsignedLong.valueOf(2);
}
 
源代码20 项目: quilt   文件: InterledgerPreparePacketTest.java
@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());
}