The logic leading to immediate disconnect when connecting to ourself has
been first introduced by Satoshi in October 2009.
Initiating an outbound network connection currently involves the
following steps after the socket connection is established (see
CConnman::OpenNetworkConnection method):
- set up node state
- queue VERSION message
- add new node to vector m_nodes
If we connect to ourself, it can happen that the sent VERSION message
(step 2) is received and processed locally *before* the node object
is added to the connection manager's m_nodes vector (step 3). In this
case, the self-connect remains undiscovered, as the detection doesn't
find the outbound peer in m_nodes yet (see CConnman::CheckIncomingNonce).
Fix this by swapping the order of 2. and 3., by taking the PushNodeVersion
call out of InitializeNode and doing that in the SendMessages method
instead, which is only called for CNode instances in m_nodes.
Thanks go to vasild, mzumsande, dergoegge and sipa for suggestions on
how to fix this.
This is a backport of core#30394 and core#30362
Depends on D18452