This is a subset of the more controversial #12407, but this also adds a test demonstrating the bug.
In InvalidateBlock, we’re calling NotifyBlockTip with the now-invalid block’s prev regardless of what chain the ancestor block is on. This could create numerous issues, but it at least screws up waitforblockheight
(or anything else relying on rpc/blockchain.cpp:latestblock
) when InvalidateBlock is called on a block not in chainActive, which can happen via RPC.
Only call NotifyBlockTip when the block being marked invalid is on the active chain.