When a block reward is spent together with other outputs in the wallet and that block reward is later orphaned, the wallet does not show the other funds as available anymore.  Even a `-rescan` is not enough - only `-zapwallettxes` or an explicit `abandontransaction` "recovers" the funds.  I prepared a [test case](https://github.com/domob1812/bitcoin/blob/wallet-bug-invalidated-block-rewards/test/functional/wallet_bug.py) that shows this behaviour.

Is this a known issue or the expected behaviour?  While this situation is something that will presumably not occur in practice (as it requires a long reorg), I wonder if that transaction should be automatically abandoned as it seems clear it won't be able to be confirmed anymore.
if (batch) {
        batch->WriteOrderPosNext(nOrderPosNext);
    } else {
        WalletBatch(GetDatabase()).WriteOrderPosNext(nOrderPosNext);
    }
    return nRet;
}
void CWalletMarkDirty()
{
    {
        LOCK(cs_);
        for (stdpair<const uint256, CWalletTx>& item  mapWallet)
            item.second.MarkDirty();
    }
}
bool CWalletMarkReplaced(const uint256& originalHash, const uint256& newHash)
{
    LOCK(cs_);
    auto mi = mapWallet.find(originalHash);
    // T
    assert(mi != mapWallet.end());
    CWalletTx& wtx = (*mi).second;
    // E
    assert(wtx.mapValue.count("replaced_by_txid") == 0);
    wtx.mapValue["replaced_by_txid"] = newHash.ToString();
    // R
    RefreshMempoolStatus(wtx, chain());
    WalletBatch batch(GetDatabase());
    bool success = true;
    if (!batch.WriteTx(wtx)) {