How to detect a fork with bitcoin-cli? I'm keeping a simple log of blocks, and storing them in an array. When a new block arrives, I add it to the array.

Let's say this is my block chain array:

E    &lt;- tip
D
C
B
A


Now, say a new block arrives, extending a branch:

     Z    &lt;- new tip
E    Y
D    X    &lt;- new branch start
     C
     B
     A


Now the blocks C and D have been replaced in the main chain by X and Y.

Questions:


Is there a way to detect that the latest block has extended a branch?


In other words, how can I detect whether blocks lower down in the array need to be replaced?

How frequently does this happen?


EDIT: Initial solution is to check if the previousblockhash of the new block is equal to the hash of the tip in the array. If not, update the old tip, and keep working down through the array updating each block until their is a match for the previousblockhash.
You can use the getchaintips RPC, which will list all tips of the known block tree, including branches that were never active.

You may see for example:

{
    "height": 420561,
    "hash": "000000000000000001cb02590846299c91794e9b9f422513cff4b9c1dd5c62a",
    "branchlen": 0,
    "status": "active"
},
{
    "height": 419698,
    "hash": "000000000000000004a3a78750438d0491b6335cbbe9c15099a6e55b6943e51a",
    "branchlen": 1,
    "status": "valid-headers"
},
{
    "height": 418868,
    "hash": "000000000000000000ba1d7d93ad1c7f04fb4a430fdee67c44fbdd3236f2b805",
    "branchlen": 1,
    "status": "valid-fork"
},


Here you can see that the current best valid chain we know of is at height 420561. There are also two forks:


One branching off at height 419697 and extending to height 419698. It has status "valid-headers", which means we heard about the headers for this block, but by the time they were verified, we already had an equivalent or better block available, so we did not attempt to download the forked block at height 419698.
One branching off at height 418867 and extending to height 418868. It has status "valid-fork", which means we actually heard about this block at a time when it was the best block, and proceeded to download and validate it, which was succesful. Later the branch was overtaken by the branch that is leading up to our current tip.


So this not only allows you to detect reorganizations, but gives information about all historic ones your node observed and/or went through.