3
0
mirror of https://github.com/Qortal/altcoinj.git synced 2025-02-11 17:55:53 +00:00

Replace for loop with an iterator to make the removal case clearer. Extend the unit test a bit.

This code will all be changing more in future anyway.
This commit is contained in:
Mike Hearn 2011-04-21 06:07:43 +00:00
parent 7a4dfd1dc2
commit 90c7ec80ff
2 changed files with 12 additions and 9 deletions

View File

@ -16,10 +16,10 @@
package com.google.bitcoin.core;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import static com.google.bitcoin.core.Utils.LOG;
@ -186,13 +186,14 @@ public class BlockChain {
*/
private void tryConnectingUnconnected() throws VerificationException, ScriptException, BlockStoreException {
// For each block in our unconnected list, try and fit it onto the head of the chain. If we succeed remove it
// from the list and keep going. If we changed the head of the list at the end of the round,
// try again until we can't fit anything else on the top.
// from the list and keep going. If we changed the head of the list at the end of the round try again until
// we can't fit anything else on the top.
int blocksConnectedThisRound;
do {
blocksConnectedThisRound = 0;
for (int i = 0; i < unconnectedBlocks.size(); i++) {
Block block = unconnectedBlocks.get(i);
Iterator<Block> iter = unconnectedBlocks.iterator();
while (iter.hasNext()) {
Block block = iter.next();
// Look up the blocks previous.
StoredBlock prev = blockStore.get(block.getPrevBlockHash());
if (prev == null) {
@ -202,8 +203,7 @@ public class BlockChain {
// Otherwise we can connect it now.
// False here ensures we don't recurse infinitely downwards when connecting huge chains.
add(block, false);
unconnectedBlocks.remove(i);
i--; // The next iteration of the for loop will make "i" point to the right index again.
iter.remove();
blocksConnectedThisRound++;
}
if (blocksConnectedThisRound > 0) {

View File

@ -25,7 +25,6 @@ import java.math.BigInteger;
import static org.junit.Assert.*;
// Tests still to write:
// - Rest of checkDifficultyTransitions: verify we don't accept invalid transitions.
// - Fragmented chains can be joined together.
// - Longest testNetChain is selected based on total difficulty not length.
// - Many more ...
@ -78,8 +77,12 @@ public class BlockChainTest {
Block b3 = b2.createNextBlock(coinbaseTo);
// Connected.
assertTrue(chain.add(b1));
// Unconnected.
// Unconnected but stored. The head of the chain is still b1.
assertFalse(chain.add(b3));
assertEquals(chain.getChainHead().getHeader(), b1.cloneAsHeader());
// Add in the middle block.
assertTrue(chain.add(b2));
assertEquals(chain.getChainHead().getHeader(), b3.cloneAsHeader());
}
@Test