From f4361d8d34014f4fc6896941cbcc47d695870fec Mon Sep 17 00:00:00 2001 From: ziggie Date: Thu, 25 Jan 2024 14:35:37 +0000 Subject: [PATCH] chain: refine peer selection logic for pruned nodes. We discard inbound peers because we don't know their listen port and sort the peers by pingtime to select the fastest first. --- chain/pruned_block_dispatcher.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/chain/pruned_block_dispatcher.go b/chain/pruned_block_dispatcher.go index cd2be5e369..b6af2d3666 100644 --- a/chain/pruned_block_dispatcher.go +++ b/chain/pruned_block_dispatcher.go @@ -7,6 +7,7 @@ import ( "fmt" "math/rand" "net" + "sort" "sync" "time" @@ -395,7 +396,20 @@ func (d *PrunedBlockDispatcher) connectToPeer(addr string) (bool, error) { // "full-node". func filterPeers(peers []btcjson.GetPeerInfoResult) ([]string, error) { var eligible []string // nolint:prealloc + + // First we sort the peers by the measured ping time, to choose the best + // peers to fetch blocks from. + sort.Slice(peers, func(i, j int) bool { + return peers[i].PingTime < peers[j].PingTime + }) + for _, peer := range peers { + // We cannot use the inbound peers here because the referenced + // port in the `addr` field is not the listen port for the p2p + // connection but a random outgoing port of the peer. + if peer.Inbound { + continue + } rawServices, err := hex.DecodeString(peer.Services) if err != nil { return nil, err