@Test
public void testEraseChain() {

    List<Block> randomChain = TestUtils.getRandomChain(new byte[32], 0, 1024);
    SyncQueueImpl queue = new SyncQueueImpl(randomChain);
    List<Block> chain1 = TestUtils.getRandomChain(randomChain.get(randomChain.size() - 1).getHash(),
            1024, SyncQueueImpl.MAX_CHAIN_LEN / 2);
    queue.addHeaders(createHeadersFromBlocks(chain1, randomPeerId()));
    List<Block> chain2 = TestUtils.getRandomChain(randomChain.get(randomChain.size() - 1).getHash(),
            1024, SyncQueueImpl.MAX_CHAIN_LEN / 2 - 1);
    queue.addHeaders(createHeadersFromBlocks(chain2, randomPeerId()));
    List<SyncQueueImpl.HeaderElement> longestChain = queue.getLongestChain();
    long maxNum = longestChain.get(longestChain.size() - 1).header.getNumber();
    assertEquals(1024 + SyncQueueImpl.MAX_CHAIN_LEN / 2 - 1, maxNum);
    assertEquals(1024 + SyncQueueImpl.MAX_CHAIN_LEN / 2 - 1, queue.getHeadersCount());
    List<Block> chain3 = TestUtils.getRandomChain(chain1.get(chain1.size() - 1).getHash(),
            1024 + SyncQueueImpl.MAX_CHAIN_LEN / 2, SyncQueueImpl.MAX_CHAIN_LEN / 10);
    // the chain is invalid and must be erased
    queue.withParentHeaderValidator(new DependentBlockHeaderRule() {
        @Override
        public boolean validate(BlockHeader header, BlockHeader dependency) {
            // chain2 should become best after erasing
            return header.getNumber() < chain2.get(chain2.size() - 2).getNumber();
        }
    });
    queue.addHeadersAndValidate(createHeadersFromBlocks(chain3, randomPeerId()));
    longestChain = queue.getLongestChain();
    assertEquals(maxNum - 1, queue.getHeadersCount());
    assertEquals(chain2.get(chain2.size() - 1).getHeader(),
            longestChain.get(longestChain.size() - 1).header.getHeader());
}