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 <- tip
D
C
B
A
Now, say a new block arrives, extending a branch:
Z <- new tip
E Y
D X <- 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.