How does Bitcoin Core know it’s on the longest chain?


In trying to implement a client, I am wondering what is the most efficient approach to figure out if you are on a fork.

Let’s say you pick a peer at random and go through IBD using the headers-first approach. After reaching the tip of the chain, what is the most efficient way to check whether this is the longest chain?

I’m guessing you have to ask your peers what their best header is, and based on the response and some heuristic, decide whether you are on the longest chain or not. Is this simply done via getheaders? What is the heuristic? And what do you do if you find out you’re on a fork?

Pointers to the relevant code in bitcoin or btcd would also be appreciated.

Thanks