下面列出了com.google.common.primitives.UnsignedLong#valueOf ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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);
}
/**
* 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);
}
@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);
}
@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);
}
@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
}
@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);
}
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);
}
}
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;
}
@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);
}
@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));
}
@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);
}
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);
}
@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);
}
}
@Test
void sqrtOfANonSquareNumber() {
UnsignedLong actual = BeaconStateUtil.integer_squareroot(UnsignedLong.valueOf(27L));
UnsignedLong expected = UnsignedLong.valueOf(5L);
assertEquals(expected, actual);
}
@BeforeAll
static void setConstants() {
Constants.ETH1_FOLLOW_DISTANCE = UnsignedLong.valueOf(FOLLOW_DISTANCE);
}
@BeforeAll
static void setUp() {
// Setup so genesis time for a block will be blockTime + 2
Constants.GENESIS_DELAY = UnsignedLong.valueOf(2);
}
@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());
}