@Override
    protected void rollbackBlockStore(int height) throws BlockStoreException {
        lock.lock();
        try {
            int currentHeight = getBestChainHeight();
            checkArgument(height >= 0 && height <= currentHeight, () ->
                    "bad height: " + height);
            if (height == currentHeight)
                return; // nothing to do

            // Look for the block we want to be the new chain head
            StoredBlock newChainHead = blockStore.getChainHead();
            while (newChainHead.getHeight() > height) {
                newChainHead = newChainHead.getPrev(blockStore);
                if (newChainHead == null)
                    throw new BlockStoreException("Unreachable height");
            }

            // Modify store directly
            blockStore.put(newChainHead);
            this.setChainHead(newChainHead);
        } finally {
            lock.unlock();
        }
    }
@Test
    public void rollbackBlockStore() throws Exception {
        Context.propagate(new Context(100, Coin.ZERO, false, true));
        // This test simulates an issue on Android, that causes the VM to crash while receiving a block, so that the
        // block store is persisted but the wallet is not.
        Block b1 = TESTNET.getGenesisBlock().createNextBlock(coinbaseTo);
        Block b2 = b1.createNextBlock(coinbaseTo);
        // Add block 1, no frills.
        assertTrue(testNetChain.add(b1));
        assertEquals(b1.cloneAsHeader(), testNetChain.getChainHead().getHeader());
        assertEquals(1, testNetChain.getBestChainHeight());
        assertEquals(1, testNetWallet.getLastBlockSeenHeight());
        // Add block 2 while wallet is disconnected, to simulate crash.
        testNetChain.removeWallet(testNetWallet);
        assertTrue(testNetChain.add(b2));
        assertEquals(b2.cloneAsHeader(), testNetChain.getChainHead().getHeader());
        assertEquals(2, testNetChain.getBestChainHeight());
        assertEquals(1, testNetWallet.getLastBlockSeenHeight());
        // Add wallet back. This will detect the height mismatch and repair the damage done.
        testNetChain.addWallet(testNetWallet);
        assertEquals(b1.cloneAsHeader(), testNetChain.getChainHead().getHeader());
        assertEquals(1, testNetChain.getBestChainHeight());
        assertEquals(1, testNetWallet.getLastBlockSeenHeight());
        // Now add block 2 correctly.
        assertTrue(testNetChain.add(b2));
        assertEquals(b2.cloneAsHeader(), testNetChain.getChainHead().getHeader());
        assertEquals(2, testNetChain.getBestChainHeight());
        assertEquals(2, testNetWallet.getLastBlockSeenHeight());
    }