From 5d0c8806bccc3924e0adac601358749c20ec2afd Mon Sep 17 00:00:00 2001 From: Felix Lange Date: Tue, 21 May 2024 13:43:17 +0200 Subject: [PATCH] p2p/enode: support unspecified IP --- p2p/enode/node.go | 16 +++++++++------- p2p/enode/node_test.go | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/p2p/enode/node.go b/p2p/enode/node.go index 180cab34fb..e7fe0e0ace 100644 --- a/p2p/enode/node.go +++ b/p2p/enode/node.go @@ -83,19 +83,21 @@ func newNodeWithID(r *enr.Record, id ID) *Node { // validIP reports whether 'ip' is a valid node endpoint IP address. func validIP(ip netip.Addr) bool { - return ip.IsValid() && !ip.IsUnspecified() && !ip.IsMulticast() + return ip.IsValid() && !ip.IsMulticast() } func localityScore(ip netip.Addr) int { switch { - case ip.IsLoopback(): + case ip.IsUnspecified(): return 0 - case ip.IsLinkLocalUnicast(): + case ip.IsLoopback(): return 1 - case ip.IsPrivate(): + case ip.IsLinkLocalUnicast(): return 2 - default: + case ip.IsPrivate(): return 3 + default: + return 4 } } @@ -184,7 +186,7 @@ func (n *Node) TCP() int { // UDPEndpoint returns the announced TCP endpoint. func (n *Node) UDPEndpoint() (netip.AddrPort, bool) { - if !n.ip.IsValid() || n.udp == 0 { + if !n.ip.IsValid() || n.ip.IsUnspecified() || n.udp == 0 { return netip.AddrPort{}, false } return netip.AddrPortFrom(n.ip, n.udp), true @@ -192,7 +194,7 @@ func (n *Node) UDPEndpoint() (netip.AddrPort, bool) { // TCPEndpoint returns the announced TCP endpoint. func (n *Node) TCPEndpoint() (netip.AddrPort, bool) { - if !n.ip.IsValid() || n.tcp == 0 { + if !n.ip.IsValid() || n.ip.IsUnspecified() || n.tcp == 0 { return netip.AddrPort{}, false } return netip.AddrPortFrom(n.ip, n.udp), true diff --git a/p2p/enode/node_test.go b/p2p/enode/node_test.go index cac77099da..56e196e82e 100644 --- a/p2p/enode/node_test.go +++ b/p2p/enode/node_test.go @@ -107,6 +107,15 @@ func TestNodeEndpoints(t *testing.T) { }(), wantIP: netip.MustParseAddr("127.0.0.1"), }, + { + name: "ipv4-only-unspecified", + node: func() *Node { + var r enr.Record + r.Set(enr.IPv4Addr(netip.MustParseAddr("0.0.0.0"))) + return SignNull(&r, id) + }(), + wantIP: netip.MustParseAddr("0.0.0.0"), + }, { name: "ipv4-only", node: func() *Node { @@ -138,6 +147,16 @@ func TestNodeEndpoints(t *testing.T) { wantIP: netip.MustParseAddr("2001::ff00:0042:8329"), wantUDP: 30306, }, + { + name: "ipv4-unspecified-and-ipv6-loopback", + node: func() *Node { + var r enr.Record + r.Set(enr.IPv4Addr(netip.MustParseAddr("0.0.0.0"))) + r.Set(enr.IPv6Addr(netip.MustParseAddr("::1"))) + return SignNull(&r, id) + }(), + wantIP: netip.MustParseAddr("::1"), + }, { name: "ipv4-private-and-ipv6-global", node: func() *Node {