Skip to content

Commit

Permalink
Use getLast, removeFirst, removeLast. A bit of getFirst (#8477)
Browse files Browse the repository at this point in the history
  • Loading branch information
zilm13 authored Jul 26, 2024
1 parent cf6cc06 commit cd3a878
Show file tree
Hide file tree
Showing 26 changed files with 49 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,8 @@ private SafeFuture<Void> postDepositEvents(
BigInteger from = fromBlock;
// First process completed requests using iteration.
// Avoid StackOverflowException when there is a long string of requests already completed.
while (!blockRequests.isEmpty() && blockRequests.get(0).isDone()) {
final EthBlock.Block block = blockRequests.remove(0).join();
while (!blockRequests.isEmpty() && blockRequests.getFirst().isDone()) {
final EthBlock.Block block = blockRequests.removeFirst().join();

// Fetch any empty blocks between this deposit block and the previous one (or start of range)
final BigInteger to = block.getNumber().subtract(BigInteger.ONE);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ private List<Block> withBlockTimestamps(final long... timestamps) {
}

when(eth1Provider.getGuaranteedLatestEth1Block())
.thenReturn(SafeFuture.completedFuture(blocks.get(blocks.size() - 1)));
.thenReturn(SafeFuture.completedFuture(blocks.getLast()));
return blocks;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,8 @@ private boolean validateNewBlocks(final List<SignedBeaconBlock> newBlocks) {
if (blocks.isEmpty() || newBlocks.isEmpty()) {
return true;
}
final SignedBeaconBlock previousBlock = blocks.get(blocks.size() - 1);
final SignedBeaconBlock firstNewBlock = newBlocks.get(0);
final SignedBeaconBlock previousBlock = blocks.getLast();
final SignedBeaconBlock firstNewBlock = newBlocks.getFirst();
if (!firstNewBlock.getParentRoot().equals(previousBlock.getRoot())) {
LOG.debug(
"Marking batch invalid because new blocks do not form a chain with previous blocks");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ protected void requestError(final Batch batch, final Throwable error) {
/** Get the most recent sync source for a batch. */
private StubSyncSource getSyncSource(final Batch batch) {
final List<StubSyncSource> syncSources = this.syncSources.get(batch);
return syncSources.get(syncSources.size() - 1);
return syncSources.getLast();
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ public void shouldGetNonCanonicalHeadersBySlot(final boolean isFinalized) throws
setupData();

// PRE: we have a non-canonical block and a canonical block at the same slot
final SignedBeaconBlock canonical =
canonicalBlockAndStateList.get(canonicalBlockAndStateList.size() - 1).getBlock();
final SignedBeaconBlock canonical = canonicalBlockAndStateList.getLast().getBlock();
final SignedBeaconBlock forked = nonCanonicalBlockAndStateList.get(1).getBlock();
assertThat(forked.getSlot()).isEqualTo(canonical.getSlot());
if (isFinalized) {
Expand All @@ -102,14 +101,11 @@ private void setupData() {
canonicalBlockAndStateList.addAll(createBlocksAtSlots(10));
final ChainBuilder fork = chainBuilder.fork();
nonCanonicalBlockAndStateList.add(fork.generateNextBlock());
chainUpdater.saveBlock(
nonCanonicalBlockAndStateList.get(nonCanonicalBlockAndStateList.size() - 1));
chainUpdater.saveBlock(nonCanonicalBlockAndStateList.getLast());
nonCanonicalBlockAndStateList.add(fork.generateNextBlock());
chainUpdater.saveBlock(
nonCanonicalBlockAndStateList.get(nonCanonicalBlockAndStateList.size() - 1));
chainUpdater.saveBlock(nonCanonicalBlockAndStateList.getLast());
canonicalBlockAndStateList.add(chainBuilder.generateNextBlock(1));
chainUpdater.updateBestBlock(
canonicalBlockAndStateList.get(canonicalBlockAndStateList.size() - 1));
chainUpdater.updateBestBlock(canonicalBlockAndStateList.getLast());
chainUpdater.advanceChain(32);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,7 @@ void shouldHandleValidChainFromGenesis() throws Exception {
.streamBlocksAndStates(genesis.getSlot().plus(UInt64.ONE), chainBuilder.getLatestSlot())
.collect(Collectors.toList());

final SignedBlockAndState lastBlockAndState =
newBlocksAndStates.get(newBlocksAndStates.size() - 1);
final SignedBlockAndState lastBlockAndState = newBlocksAndStates.getLast();
final BeaconState result =
StreamingStateRegenerator.regenerate(
spec,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,11 @@ public static DepositsFromBlockEvent create(
}

public UInt64 getFirstDepositIndex() {
return deposits.get(0).getMerkle_tree_index();
return deposits.getFirst().getMerkle_tree_index();
}

public UInt64 getLastDepositIndex() {
return deposits.get(deposits.size() - 1).getMerkle_tree_index();
return deposits.getLast().getMerkle_tree_index();
}

public UInt64 getBlockNumber() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public SpecMilestone getPreviousMilestone() {
throw new IllegalArgumentException("There is no milestone prior to Phase0");
}
final List<SpecMilestone> priorMilestones = getAllPriorMilestones(this);
return priorMilestones.get(priorMilestones.size() - 1);
return priorMilestones.getLast();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,6 +369,6 @@ private static void assertWithdrawalsInExecutionPayloadMatchExpected(
}

private static UInt64 nextWithdrawalAfter(final List<Withdrawal> partialWithdrawals) {
return partialWithdrawals.get(partialWithdrawals.size() - 1).getIndex().increment();
return partialWithdrawals.getLast().getIndex().increment();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ private void validateTreeRepresentsChains(
assertThat(actualHashes).containsExactlyInAnyOrderElementsOf(expectedHashes);

for (List<SignedBeaconBlock> chain : chains) {
SignedBeaconBlock lastBlock = chain.get(chain.size() - 1);
SignedBeaconBlock lastBlock = chain.getLast();

// All blocks should be available
for (SignedBeaconBlock block : chain) {
Expand All @@ -228,7 +228,7 @@ private void validateTreeRepresentsChains(

private void validateChildCountsForChain(
final HashTree tree, final List<SignedBeaconBlock> chain) {
final SignedBeaconBlock lastBlock = chain.get(chain.size() - 1);
final SignedBeaconBlock lastBlock = chain.getLast();
for (int i = 0; i < chain.size() - 1; i++) {
SignedBeaconBlock block = chain.get(i);
assertThat(tree.countChildren(block.getRoot())).isEqualTo(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,18 @@ protected static List<Bytes32> generateZeroHashes(final int height) {
}

public void add(final Bytes32 leaf) {
if (!tree.get(0).isEmpty()
&& tree.get(0).get(tree.get(0).size() - 1).equals(zeroHashes.get(0))) {
tree.get(0).remove(tree.get(0).size() - 1);
if (!tree.getFirst().isEmpty() && tree.getFirst().getLast().equals(zeroHashes.getFirst())) {
tree.getFirst().removeLast();
}
int mutableStageSize = tree.get(0).size();
tree.get(0).add(leaf);
int mutableStageSize = tree.getFirst().size();
tree.getFirst().add(leaf);
for (int depth = 0; depth <= treeDepth; depth++) {
final List<Bytes32> stage = tree.get(depth);
if (depth > 0) {
// Remove elements that should be modified
mutableStageSize /= 2;
while (stage.size() != mutableStageSize) {
stage.remove(stage.size() - 1);
stage.removeLast();
}

final List<Bytes32> previousStage = tree.get(depth - 1);
Expand All @@ -79,15 +78,15 @@ public void add(final Bytes32 leaf) {
}

public int getNumberOfLeaves() {
final int lastLeafIndex = tree.get(0).size() - 1;
if (tree.get(0).get(lastLeafIndex).equals(Bytes32.ZERO)) {
return tree.get(0).size() - 1;
final int lastLeafIndex = tree.getFirst().size() - 1;
if (tree.getFirst().get(lastLeafIndex).equals(Bytes32.ZERO)) {
return tree.getFirst().size() - 1;
}
return tree.get(0).size();
return tree.getFirst().size();
}

public List<Bytes32> getProof(final Bytes32 value) {
final int index = tree.get(0).indexOf(value);
final int index = tree.getFirst().indexOf(value);
if (index == -1) {
throw new IllegalArgumentException("Leaf value is missing from the MerkleTree");
}
Expand Down Expand Up @@ -122,7 +121,7 @@ public List<Bytes32> getProof(final int itemIndex) {

private Bytes32 calcViewBoundaryRoot(final int depth, final int viewLimit) {
if (depth == 0) {
return zeroHashes.get(0);
return zeroHashes.getFirst();
}
final int deeperDepth = depth - 1;
final Bytes32 deeperRoot = calcViewBoundaryRoot(deeperDepth, viewLimit);
Expand All @@ -142,7 +141,7 @@ private Bytes32 calcViewBoundaryRoot(final int depth, final int viewLimit) {
* @return proof (i.e. collection of siblings on the way to root for the given leaf)
*/
public List<Bytes32> getProofWithViewBoundary(final Bytes32 value, final int viewLimit) {
return getProofWithViewBoundary(tree.get(0).indexOf(value), viewLimit);
return getProofWithViewBoundary(tree.getFirst().indexOf(value), viewLimit);
}

/**
Expand Down Expand Up @@ -193,7 +192,7 @@ public Bytes32 calcMixInValue() {
}

public Bytes32 getRoot() {
return Hash.sha256(tree.get(treeDepth).get(0), calcMixInValue());
return Hash.sha256(tree.get(treeDepth).getFirst(), calcMixInValue());
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ public void importBlock_latestFinalizedBlock() throws Exception {
tx.commit().join();

// Known blocks should report as successfully imported
final BlockImportResult result = blockImporter.importBlock(blocks.get(blocks.size() - 1)).get();
final BlockImportResult result = blockImporter.importBlock(blocks.getLast()).get();
assertSuccessfulResult(result, false);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,7 @@ void onBlock_shouldFailWhenBroadcastValidationFails() {
void onBlock_consensusValidationShouldNotResolveWhenEarlyFails() {
setupWithSpec(TestSpecFactory.createMinimalDeneb());
final List<SignedBlockAndState> signedBlockAndStates = chainBuilder.generateBlocksUpToSlot(2);
final SignedBlockAndState wrongBlockAndState =
signedBlockAndStates.get(signedBlockAndStates.size() - 1);
final SignedBlockAndState wrongBlockAndState = signedBlockAndStates.getLast();

storageSystem.chainUpdater().advanceCurrentSlotToAtLeast(wrongBlockAndState.getSlot());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public int flushWithBoundaryBit(final SszWriter writer, final int boundaryBitOff
writer.write(new byte[] {1});
return size + 1;
} else {
UnsafeBytes lastBytes = bytesList.get(bytesList.size() - 1);
UnsafeBytes lastBytes = bytesList.getLast();
byte lastByte = lastBytes.bytes[lastBytes.offset + lastBytes.length - 1];
byte lastByteWithBoundaryBit = (byte) (lastByte ^ (1 << bitIdx));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ private DeserializedData sszDeserializeFixed(final SszReader reader) {
if (childNodes.isEmpty()) {
lastByte = Optional.empty();
} else {
Bytes lastNodeData = childNodes.get(childNodes.size() - 1).getData();
Bytes lastNodeData = childNodes.getLast().getData();
lastByte = Optional.of(lastNodeData.get(lastNodeData.size() - 1));
}
return new DeserializedData(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public SszDataAssert<T> isEqualByGettersTo(final T expected) {
IntStream.range(0, res.size() - 1)
.mapToObj(i -> " ".repeat(i) + res.get(i))
.collect(Collectors.joining("\n"));
errMessage += " ERROR: " + res.get(res.size() - 1);
errMessage += " ERROR: " + res.getLast();
failWithMessage(
"Expected %s's to be equal by getter, but found differences:\n%s",
expected.getClass().getSimpleName(), errMessage);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public void report(
}

final UInt64 totalProcessingDuration =
events.get(events.size() - 1).getRight().minusMinZero(events.get(0).getRight());
events.getLast().getRight().minusMinZero(events.getFirst().getRight());
totalDurationReporter.accept(totalProcessingDuration);

if (isLateEvent) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private List<PeerAddress> selectAndRemoveRandomPeers(
final List<PeerAddress> selectedPeers = new ArrayList<>();
shuffler.shuffle(allCandidatePeers);
while (!allCandidatePeers.isEmpty() && selectedPeers.size() < randomlySelectedPeersToAdd) {
final DiscoveryPeer candidate = allCandidatePeers.remove(0);
final DiscoveryPeer candidate = allCandidatePeers.removeFirst();
checkCandidate(candidate, network)
.ifPresent(
peerAddress -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ public void shouldSendToPeerRequestedNumberOfCanonicalBlobSidecars() {
// we simulate that the canonical non-finalized chain only contains blobs from last
// slotAndBlockRoot
final SlotAndBlockRoot canonicalSlotAndBlockRoot =
allAvailableBlobs.get(allAvailableBlobs.size() - 1).getSlotAndBlockRoot();
allAvailableBlobs.getLast().getSlotAndBlockRoot();

final List<BlobSidecar> expectedSent =
allAvailableBlobs.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ public void shouldCompleteExceptionallyWhenClosedWithTruncatedMessage() {
sendInitialPayload();

timeProvider.advanceTimeByMillis(100);
final Bytes chunkBytes = chunks.get(0);
final Bytes chunkBytes = chunks.getFirst();
deliverBytes(chunkBytes.slice(0, chunkBytes.size() - 1));

asyncRequestRunner.executeQueuedActions();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2351,7 +2351,7 @@ private void assertGetLatestFinalizedRootAtSlotReturnsFinalizedBlocks(
}

// Check that last block
final SignedBeaconBlock lastFinalizedBlock = finalizedBlocks.get(finalizedBlocks.size() - 1);
final SignedBeaconBlock lastFinalizedBlock = finalizedBlocks.getLast();
for (int i = 0; i < 10; i++) {
final UInt64 slot = lastFinalizedBlock.getSlot().plus(i);
assertThat(database.getLatestFinalizedBlockAtSlot(slot))
Expand Down Expand Up @@ -2637,7 +2637,7 @@ private void assertBlobSidecars(final Map<UInt64, List<BlobSidecar>> blobSidecar

final Map<UInt64, List<BlobSidecar>> blobSidecarsDb = new HashMap<>();
try (final Stream<SlotAndBlockRootAndBlobIndex> blobSidecarsStream =
database.streamBlobSidecarKeys(slots.get(0), slots.get(slots.size() - 1))) {
database.streamBlobSidecarKeys(slots.getFirst(), slots.getLast())) {

for (final Iterator<SlotAndBlockRootAndBlobIndex> iterator = blobSidecarsStream.iterator();
iterator.hasNext(); ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ private UInt64 pruneToBlock(final UInt64 lastSlotToPrune, final int pruneLimit)
LOG.debug("No finalized blocks to prune up to {} slot", lastSlotToPrune);
return lastSlotToPrune;
}
final UInt64 lastPrunedBlockSlot = blocksToPrune.get(blocksToPrune.size() - 1).getKey();
final UInt64 lastPrunedBlockSlot = blocksToPrune.getLast().getKey();
LOG.debug(
"Pruning {} finalized blocks, last block slot is {}",
blocksToPrune.size(),
Expand Down Expand Up @@ -477,8 +477,7 @@ private UInt64 pruneFinalizedStateForSlots(
return lastSlotToPrune;
}

final UInt64 lastPrunedSlot =
slotsToPruneStateFor.get(slotsToPruneStateFor.size() - 1).getLeft();
final UInt64 lastPrunedSlot = slotsToPruneStateFor.getLast().getLeft();

deleteFinalizedStatesForSlot(slotsToPruneStateFor);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ public void onFinalizedBlocks_gapBetweenBatchAndEarliestKnownBlock(
.map(SignedBlockAndState::getBlock)
.collect(Collectors.toList());
// Remove a block from the end
blocks.remove(blocks.size() - 1);
blocks.removeLast();

final SafeFuture<Void> result =
chainStorage.onFinalizedBlocks(blocks, Map.of(), Optional.empty());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ protected void processChainHeadWithMockForkChoiceStrategy(

addBlocks(store, blocks);

chainProcessor.accept(store, blocks.get(blocks.size() - 1));
chainProcessor.accept(store, blocks.getLast());
}

protected void addBlock(final UpdatableStore store, final SignedBlockAndState block) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,15 @@ public SignedBlockAndState finalizeEpoch(final UInt64 epoch) {
public SignedBlockAndState finalizeCurrentChain() {
final List<SignedBlockAndState> newBlocks = chainBuilder.finalizeCurrentChain(Optional.empty());
newBlocks.forEach(this::saveBlock);
final SignedBlockAndState newHead = newBlocks.get(newBlocks.size() - 1);
final SignedBlockAndState newHead = newBlocks.getLast();
updateBestBlock(newHead);
return newHead;
}

public SignedBlockAndState finalizeCurrentChainOptimistically() {
final List<SignedBlockAndState> newBlocks = chainBuilder.finalizeCurrentChain(Optional.empty());
newBlocks.forEach(this::saveOptimisticBlock);
final SignedBlockAndState newHead = newBlocks.get(newBlocks.size() - 1);
final SignedBlockAndState newHead = newBlocks.getLast();
updateBestBlock(newHead);
return newHead;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ public List<PostKeyResult> importExternalValidators(
importResults.add(
validatorLoader.loadExternalMutableValidator(
externalValidator.getPublicKey(), externalValidator.getUrl(), false));
if (importResults.get(importResults.size() - 1).getPostKeyResult().getImportStatus()
if (importResults.getLast().getPostKeyResult().getImportStatus()
== ImportStatus.IMPORTED) {
reloadRequired = true;
}
Expand Down Expand Up @@ -427,7 +427,7 @@ public List<PostKeyResult> importExternalValidators(
importResults.add(
validatorLoader.loadExternalMutableValidator(
externalValidator.getPublicKey(), externalValidator.getUrl(), true));
if (importResults.get(importResults.size() - 1).getPostKeyResult().getImportStatus()
if (importResults.getLast().getPostKeyResult().getImportStatus()
== ImportStatus.IMPORTED) {
reloadRequired = true;
}
Expand Down

0 comments on commit cd3a878

Please sign in to comment.