So, the command getbestblockhash gives you the latest block hash that’s been mined. But what happens if two blocks are broadcasted at the same time? In that case, you end up with two chains at the same height, and the next block decides which one has more work behind it, meaning which is the valid one.
Here’s my question: how does getbestblockhash figure out which block hash is the best in that situation? Does it just take the first one it gets and ignore the others that come afterward? Wouldn't it make more sense to return an array of best block hashes since there could be more than one? This seems a bit confusing.
The getbestblockhash by definition should only return the tip of the most work and fully validated chain. In this case for the same height, the block that has arrived earlier would be the best chain for your node. Since nodes can still propagate the headers of competing chain, you can still refer to getchaintips to observe blocks that are on competing chains.
Conventionally, Bitcoin Core has always considered whichever chain that has the highest work and arrived first to be the best.
If both chains have equal work, then there are either two tips, or no tips. Picking one would mean you're introducing subjectivity.
But, why? It can very well be the other chain, the correct one, because miners mine on top of the other tip.
I didn't know about getchaintips. Thank you. I think this answers my question.
Fully validated in that case. If there are any competing blocks at the same height, then Bitcoin Core doesn't immediately validate it until the competing block becomes the new longest chain or isn't validated at all if it becomes orphaned.
Traditionally, the reference implementation is used for mining as well. Miners are thus mining directly ontop of the best tip and it's better to start work on a chaintip that is better propagated, in the view of the individual node. Since each node has no way of knowing what is the block that is seen (and currently worked on) by the majority, it's better to prefer the block that is seen first and not having to swap over when another block at the same height appears.
Note: I don't think this is the actual reason, but the actual reason should be just for the sake of simplicity. This was a conclusion that I made after some discussion and research previously.