下面列出了com.google.common.primitives.UnsignedLong#ONE 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void importBlock_wrongChain() throws Exception {
UnsignedLong currentSlot = recentChainData.getBestSlot();
for (int i = 0; i < 3; i++) {
currentSlot = currentSlot.plus(UnsignedLong.ONE);
localChain.createAndImportBlockAtSlot(currentSlot);
}
// Update finalized epoch
final StoreTransaction tx = recentChainData.startStoreTransaction();
final Bytes32 finalizedRoot = recentChainData.getBestBlockRoot().orElseThrow();
final UnsignedLong finalizedEpoch = UnsignedLong.ONE;
final Checkpoint finalized = new Checkpoint(finalizedEpoch, finalizedRoot);
tx.setFinalizedCheckpoint(finalized);
tx.commit().join();
// Now create a new block that is not descendent from the finalized block
AttestationGenerator attestationGenerator = new AttestationGenerator(validatorKeys);
final BeaconBlockAndState blockAndState = otherStorage.getBestBlockAndState().orElseThrow();
final Attestation attestation = attestationGenerator.validAttestation(blockAndState);
final SignedBeaconBlock block =
otherChain.createAndImportBlockAtSlotWithAttestations(currentSlot, List.of(attestation));
final BlockImportResult result = blockImporter.importBlock(block);
assertImportFailed(result, FailureReason.UNKNOWN_PARENT);
}
@Test
public void shouldBeDependentOnTargetBlockAndBeaconBlockRoot() {
final Bytes32 targetRoot = Bytes32.fromHexString("0x01");
final Bytes32 beaconBlockRoot = Bytes32.fromHexString("0x02");
final Attestation attestation =
new Attestation(
aggregationBitfield,
new AttestationData(
UnsignedLong.valueOf(1),
UnsignedLong.ZERO,
beaconBlockRoot,
new Checkpoint(UnsignedLong.ONE, Bytes32.ZERO),
new Checkpoint(UnsignedLong.valueOf(10), targetRoot)),
BLSSignature.empty());
assertThat(attestation.getDependentBlockRoots())
.containsExactlyInAnyOrder(targetRoot, beaconBlockRoot);
}
@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
void getTotalBalanceAddsAndReturnsEffectiveTotalBalancesCorrectly() {
// Data Setup
BeaconState state = createBeaconState();
Committee committee = new Committee(UnsignedLong.ONE, Arrays.asList(0, 1, 2));
// Calculate Expected Results
UnsignedLong expectedBalance = UnsignedLong.ZERO;
for (UnsignedLong balance : state.getBalances()) {
if (balance.compareTo(UnsignedLong.valueOf(Constants.MAX_EFFECTIVE_BALANCE)) < 0) {
expectedBalance = expectedBalance.plus(balance);
} else {
expectedBalance =
expectedBalance.plus(UnsignedLong.valueOf(Constants.MAX_EFFECTIVE_BALANCE));
}
}
UnsignedLong totalBalance = BeaconStateUtil.get_total_balance(state, committee.getCommittee());
assertEquals(expectedBalance, totalBalance);
}
@Test
public void shouldReturnTrueWhenSyncing() throws Exception {
final boolean isSyncing = true;
final UnsignedLong startSlot = UnsignedLong.ONE;
final UnsignedLong currentSlot = UnsignedLong.valueOf(5);
final UnsignedLong highestSlot = UnsignedLong.valueOf(10);
final SyncingStatus syncingStatus =
new SyncingStatus(isSyncing, new SyncStatus(startSlot, currentSlot, highestSlot));
final GetSyncing handler = new GetSyncing(syncDataProvider, jsonProvider);
final SyncingResponse expectedResponse = new SyncingResponse(syncingStatus);
when(syncService.getSyncStatus()).thenReturn(syncingStatus);
handler.handle(context);
verify(context).result(jsonProvider.objectToJSON(expectedResponse));
verify(context).header(Header.CACHE_CONTROL, CACHE_NONE);
}
@Test
public void getLatestFinalizedBlockSlot_postGenesisFinalizedBlockOutsideOfEpochBoundary()
throws Exception {
final UnsignedLong epoch = UnsignedLong.ONE;
final UnsignedLong epochBoundarySlot = compute_start_slot_at_epoch(epoch);
final UnsignedLong finalizedBlockSlot = epochBoundarySlot.minus(UnsignedLong.ONE);
final SignedBlockAndState finalizedBlock = chainBuilder.generateBlockAtSlot(finalizedBlockSlot);
saveBlock(storageClient, finalizedBlock);
// Start tx to update finalized checkpoint
final StoreTransaction tx = storageClient.startStoreTransaction();
// Initially finalized slot should match store
assertThat(tx.getLatestFinalizedBlockSlot()).isEqualTo(genesis.getSlot());
// Update checkpoint and check finalized slot accessors
tx.setFinalizedCheckpoint(new Checkpoint(epoch, finalizedBlock.getRoot()));
assertThat(tx.getLatestFinalizedBlockSlot()).isEqualTo(finalizedBlockSlot);
assertThat(storageClient.getStore().getLatestFinalizedBlockSlot()).isEqualTo(genesis.getSlot());
// Commit tx
tx.commit().reportExceptions();
assertThat(storageClient.getStore().getLatestFinalizedBlockSlot())
.isEqualTo(finalizedBlockSlot);
}
@Test
public void importBlock_attestationWithInvalidSignature() 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);
// make one attestation signature invalid
aggregatedAttestations
.get(aggregatedAttestations.size() / 2)
.setAggregate_signature(BLSSignature.random(1));
UnsignedLong currentSlotFinal = currentSlot.plus(UnsignedLong.ONE);
assertThatCode(
() -> {
localChain.createAndImportBlockAtSlotWithAttestations(
currentSlotFinal, aggregatedAttestations);
})
.hasMessageContaining("signature");
}
public SafeFuture<SignedBeaconBlock> requestBlockBySlot(final UnsignedLong slot) {
final Eth2RpcMethod<BeaconBlocksByRangeRequestMessage, SignedBeaconBlock> blocksByRange =
rpcMethods.beaconBlocksByRange();
final BeaconBlocksByRangeRequestMessage request =
new BeaconBlocksByRangeRequestMessage(slot, UnsignedLong.ONE, UnsignedLong.ONE);
return requestSingleItem(blocksByRange, request);
}
@Test
public void shouldReturnNoContentIfStoreNotDefined() throws Exception {
startPreGenesisRestAPI();
final UnsignedLong epoch = UnsignedLong.ONE;
final Response response = getByEpoch(epoch.intValue());
assertNoContent(response);
}
@Test
public void shouldReturnNoContentIfHeadRootUnavailable() throws Exception {
startPreForkChoiceRestAPI();
final UnsignedLong epoch = UnsignedLong.ONE;
final Response response = getByEpoch(epoch.intValue());
assertNoContent(response);
}
@Test
public void shouldReturnNoContentIfStoreNotDefined() throws Exception {
final UnsignedLong epoch = UnsignedLong.ONE;
when(recentChainData.getStore()).thenReturn(null);
when(recentChainData.getFinalizedEpoch()).thenReturn(epoch);
final Response response = post(epoch.intValue(), keys);
assertNoContent(response);
}
@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);
}
@Test
public void shouldReturnEmptyListWhenNoPubKeysSupplied() throws Exception {
final UnsignedLong epoch = UnsignedLong.ONE;
when(recentChainData.getFinalizedEpoch()).thenReturn(epoch);
final Response response = post(epoch.intValue(), Collections.emptyList());
assertBodyEquals(response, "[]");
}
@Test
void sync_stoppedBeforeBlockImport() {
UnsignedLong step = UnsignedLong.ONE;
UnsignedLong startHere = UnsignedLong.ONE;
final SafeFuture<Void> requestFuture = new SafeFuture<>();
when(peer.requestBlocksByRange(any(), any(), any(), any())).thenReturn(requestFuture);
final SafeFuture<PeerSyncResult> syncFuture = peerSync.sync(peer);
assertThat(syncFuture).isNotDone();
verify(peer)
.requestBlocksByRange(any(), any(), eq(step), responseListenerArgumentCaptor.capture());
// Respond with blocks and check they're passed to the block importer.
final ResponseStream.ResponseListener<SignedBeaconBlock> responseListener =
responseListenerArgumentCaptor.getValue();
// Stop the sync, no further blocks should be imported
peerSync.stop();
try {
responseListener.onResponse(BLOCK);
fail("Should have thrown an error to indicate the sync was stopped");
} catch (final CancellationException e) {
// RpcMessageHandler will consider the request complete if there's an error processing a
// response
requestFuture.completeExceptionally(e);
}
// Should not disconnect the peer as it wasn't their fault
verify(peer, never()).disconnectCleanly(any());
verifyNoInteractions(blockImporter);
assertThat(syncFuture).isCompleted();
PeerSyncResult result = syncFuture.join();
assertThat(result).isEqualByComparingTo(PeerSyncResult.CANCELLED);
// check startingSlot
UnsignedLong startingSlot = peerSync.getStartingSlot();
assertThat(startingSlot).isEqualTo(startHere);
}
@Test
public void roundTrip_one() {
final UnsignedLong value = UnsignedLong.ONE;
final byte[] bytes = serializer.serialize(value);
final UnsignedLong deserialized = serializer.deserialize(bytes);
assertThat(deserialized).isEqualTo(value);
}
/**
* Required-args Constructor.
*
* @param streamConnectionId A {@link StreamConnectionId} that is unique to this JVM.
*/
public StreamConnection(final StreamConnectionId streamConnectionId) {
this.creationDateTime = DateUtils.now();
this.streamConnectionId = Objects.requireNonNull(streamConnectionId, "streamConnectionId must not be null");
this.sequence = new AtomicReference<>(UnsignedLong.ONE);
this.connectionState = new AtomicReference<>(StreamConnectionState.AVAILABLE);
}
@Test
public void constructWithNullCodecContext() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("streamCodecContext must not be null");
new AimdCongestionController(UnsignedLong.ONE, UnsignedLong.ONE, BigDecimal.TEN, null);
}
private SyncingStatus buildSyncStatus(final boolean isSyncing) {
return new SyncingStatus(
isSyncing, new SyncStatus(UnsignedLong.ZERO, UnsignedLong.ONE, UnsignedLong.MAX_VALUE));
}
@Test
public void constructWithNullStartAmount() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("startAmount must not be null");
new AimdCongestionController(null, UnsignedLong.ONE, BigDecimal.TEN, CodecContextFactory.oer());
}
@Test
public void constructWithNullIncreaseAmount() {
expectedException.expect(NullPointerException.class);
expectedException.expectMessage("increaseAmount must not be null");
new AimdCongestionController(UnsignedLong.ONE, null, BigDecimal.TEN, CodecContextFactory.oer());
}