diff --git a/CHANGELOG.md b/CHANGELOG.md index 77aec78f7d..1867d7f3d1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add `p2p.announce_addresses` to set the multiaddrs advertised to peers, so nodes behind NAT or in containers without host networking stop advertising unreachable loopback/Docker bridge addresses [#3510](https://github.com/evstack/ev-node/pull/3510). + ## v1.3.0 ### Added diff --git a/docs/learn/config.md b/docs/learn/config.md index 9c5e59e1da..d3f0869604 100644 --- a/docs/learn/config.md +++ b/docs/learn/config.md @@ -906,6 +906,26 @@ _Example:_ `--evnode.p2p.allowed_peers 12D3KooY...,12D3KooZ...` _Default:_ `""` (empty, allow all unless blocked) _Constant:_ `FlagP2PAllowedPeers` +### P2P Announce Addresses + +**Description:** +A comma-separated list of multiaddrs advertised to other peers (via identify, the DHT and peer discovery) instead of the addresses detected from the local network interfaces. Use this when the node runs behind NAT or in a container without host networking; otherwise it advertises loopback or Docker bridge addresses that remote peers cannot reach. When set, only these addresses are advertised. The port should be the externally reachable (published) port. + +**YAML:** + +```yaml +p2p: + announce_addresses: "/ip4/203.0.113.10/tcp/7676" +``` + +**Command-line Flag:** +`--evnode.p2p.announce_addresses ` +_Example:_ `--evnode.p2p.announce_addresses /ip4/203.0.113.10/tcp/7676,/dns4/node.example.com/tcp/7676` +_Default:_ `""` (empty, advertise the listen addresses) +_Constant:_ `FlagP2PAnnounceAddresses` + +For example, a container started with `-p 7676:7676` on a host with public IP `203.0.113.10` should set `--evnode.p2p.announce_addresses /ip4/203.0.113.10/tcp/7676`. + ## RPC Configuration (`rpc`) Settings for the Remote Procedure Call (RPC) server, which allows clients and applications to interact with the Evolve node. diff --git a/docs/reference/configuration/ev-node-config.md b/docs/reference/configuration/ev-node-config.md index 425b00c901..f6340e6658 100644 --- a/docs/reference/configuration/ev-node-config.md +++ b/docs/reference/configuration/ev-node-config.md @@ -683,6 +683,26 @@ _Example:_ `--evnode.p2p.allowed_peers 12D3KooY...,12D3KooZ...` _Default:_ `""` (empty, allow all unless blocked) _Constant:_ `FlagP2PAllowedPeers` +### P2P Announce Addresses + +**Description:** +A comma-separated list of multiaddrs advertised to other peers (via identify, the DHT and peer discovery) instead of the addresses detected from the local network interfaces. Use this when the node runs behind NAT or in a container without host networking; otherwise it advertises loopback or Docker bridge addresses that remote peers cannot reach. When set, only these addresses are advertised. The port should be the externally reachable (published) port. + +**YAML:** + +```yaml +p2p: + announce_addresses: "/ip4/203.0.113.10/tcp/7676" +``` + +**Command-line Flag:** +`--evnode.p2p.announce_addresses ` +_Example:_ `--evnode.p2p.announce_addresses /ip4/203.0.113.10/tcp/7676,/dns4/node.example.com/tcp/7676` +_Default:_ `""` (empty, advertise the listen addresses) +_Constant:_ `FlagP2PAnnounceAddresses` + +For example, a container started with `-p 7676:7676` on a host with public IP `203.0.113.10` should set `--evnode.p2p.announce_addresses /ip4/203.0.113.10/tcp/7676`. + ## RPC Configuration (`rpc`) Settings for the Remote Procedure Call (RPC) server, which allows clients and applications to interact with the Evolve node. diff --git a/pkg/config/config.go b/pkg/config/config.go index bb48a251fe..9f19d6d50b 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -120,6 +120,8 @@ const ( FlagP2PBlockedPeers = FlagPrefixEvnode + "p2p.blocked_peers" // FlagP2PAllowedPeers is a flag for specifying the P2P allowed peers FlagP2PAllowedPeers = FlagPrefixEvnode + "p2p.allowed_peers" + // FlagP2PAnnounceAddresses is a flag for specifying the P2P addresses advertised to peers + FlagP2PAnnounceAddresses = FlagPrefixEvnode + "p2p.announce_addresses" // FlagP2PDisableConnectionGater disables the P2P connection gater (no-op mode). // Enabled by default; set to false to activate peer filtering when experiencing P2P flooding. FlagP2PDisableConnectionGater = FlagPrefixEvnode + "p2p.disable_connection_gater" @@ -398,6 +400,7 @@ type P2PConfig struct { Peers string `mapstructure:"peers" yaml:"peers" comment:"Comma-separated list of peers to connect to"` BlockedPeers string `mapstructure:"blocked_peers" yaml:"blocked_peers" comment:"Comma-separated list of peer IDs to block from connecting"` AllowedPeers string `mapstructure:"allowed_peers" yaml:"allowed_peers" comment:"Comma-separated list of peer IDs to allow connections from"` + AnnounceAddresses string `mapstructure:"announce_addresses" yaml:"announce_addresses" comment:"Comma-separated list of multiaddrs advertised to peers instead of the listen addresses (e.g. /ip4/203.0.113.10/tcp/7676). Use when running behind NAT or in a container."` DisableConnectionGater bool `mapstructure:"disable_connection_gater" yaml:"disable_connection_gater" comment:"Disable the P2P connection gater (no-op mode). Set to false to enforce peer filtering when experiencing P2P flooding."` } @@ -730,6 +733,7 @@ func AddFlags(cmd *cobra.Command) { cmd.Flags().String(FlagP2PPeers, def.P2P.Peers, "Comma separated list of seed nodes to connect to") cmd.Flags().String(FlagP2PBlockedPeers, def.P2P.BlockedPeers, "Comma separated list of nodes to ignore") cmd.Flags().String(FlagP2PAllowedPeers, def.P2P.AllowedPeers, "Comma separated list of nodes to whitelist") + cmd.Flags().String(FlagP2PAnnounceAddresses, def.P2P.AnnounceAddresses, "Comma separated list of multiaddrs advertised to peers instead of the listen addresses, e.g. /ip4//tcp/7676") cmd.Flags().Bool(FlagP2PDisableConnectionGater, def.P2P.DisableConnectionGater, "Disable P2P connection gater (no-op mode); set to false to enforce peer filtering when experiencing P2P flooding") // RPC configuration flags diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 3db515b3e5..1ac8a52be6 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -168,6 +168,7 @@ func TestAddFlags(t *testing.T) { assertFlagValue(t, flags, FlagP2PPeers, DefaultConfig().P2P.Peers) assertFlagValue(t, flags, FlagP2PBlockedPeers, DefaultConfig().P2P.BlockedPeers) assertFlagValue(t, flags, FlagP2PAllowedPeers, DefaultConfig().P2P.AllowedPeers) + assertFlagValue(t, flags, FlagP2PAnnounceAddresses, DefaultConfig().P2P.AnnounceAddresses) assertFlagValue(t, flags, FlagP2PDisableConnectionGater, DefaultConfig().P2P.DisableConnectionGater) // Instrumentation flags @@ -228,7 +229,7 @@ func TestAddFlags(t *testing.T) { assertFlagValue(t, flags, FlagPruningInterval, DefaultConfig().Pruning.Interval.Duration) // Count the number of flags we're explicitly checking - expectedFlagCount := 91 // Update this number if you add more flag checks above + expectedFlagCount := 92 // Update this number if you add more flag checks above // Get the actual number of flags (both regular and persistent) actualFlagCount := 0 diff --git a/pkg/p2p/README.md b/pkg/p2p/README.md index ec653afd94..468e11987d 100644 --- a/pkg/p2p/README.md +++ b/pkg/p2p/README.md @@ -42,21 +42,23 @@ The P2P client is configured using the `P2PConfig` struct: ```go type P2PConfig struct { - ListenAddress string // Address to listen for incoming connections - Seeds string // Comma separated list of seed nodes to connect to - BlockedPeers string // Comma separated list of nodes to ignore - AllowedPeers string // Comma separated list of nodes to whitelist + ListenAddress string // Address to listen for incoming connections + Seeds string // Comma separated list of seed nodes to connect to + BlockedPeers string // Comma separated list of nodes to ignore + AllowedPeers string // Comma separated list of nodes to whitelist + AnnounceAddresses string // Comma separated list of multiaddrs advertised instead of the listen addresses } ``` ### Configuration Parameters -| Parameter | Description | Default | Example | -| ------------- | --------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------ | -| ListenAddress | The address where the node listens for incoming P2P connections | `/ip4/0.0.0.0/tcp/7676` | `/ip4/0.0.0.0/tcp/7676` | -| Seeds | Comma-separated list of seed nodes (bootstrap nodes) | "" | `/ip4/1.2.3.4/tcp/7676/p2p/12D3KooWA8EXV3KjBxEU...,/ip4/5.6.7.8/tcp/7676/p2p/12D3KooWJN9ByvD...` | -| BlockedPeers | Comma-separated list of peer IDs to block | "" | `12D3KooWA8EXV3KjBxEU...,12D3KooWJN9ByvD...` | -| AllowedPeers | Comma-separated list of peer IDs to explicitly allow | "" | `12D3KooWA8EXV3KjBxEU...,12D3KooWJN9ByvD...` | +| Parameter | Description | Default | Example | +| ----------------- | ----------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------ | +| ListenAddress | The address where the node listens for incoming P2P connections | `/ip4/0.0.0.0/tcp/7676` | `/ip4/0.0.0.0/tcp/7676` | +| Seeds | Comma-separated list of seed nodes (bootstrap nodes) | "" | `/ip4/1.2.3.4/tcp/7676/p2p/12D3KooWA8EXV3KjBxEU...,/ip4/5.6.7.8/tcp/7676/p2p/12D3KooWJN9ByvD...` | +| BlockedPeers | Comma-separated list of peer IDs to block | "" | `12D3KooWA8EXV3KjBxEU...,12D3KooWJN9ByvD...` | +| AllowedPeers | Comma-separated list of peer IDs to explicitly allow | "" | `12D3KooWA8EXV3KjBxEU...,12D3KooWJN9ByvD...` | +| AnnounceAddresses | Multiaddrs advertised to peers instead of the listen addresses (NAT, containers) | "" | `/ip4/203.0.113.10/tcp/7676` | ## libp2p Components diff --git a/pkg/p2p/client.go b/pkg/p2p/client.go index bcb4c6e7ac..6edc0cf5ad 100644 --- a/pkg/p2p/client.go +++ b/pkg/p2p/client.go @@ -353,6 +353,18 @@ func (c *Client) listen() (host.Host, error) { } opts := []libp2p.Option{libp2p.ListenAddrs(maddr), libp2p.Identity(c.privKey)} + if strings.TrimSpace(c.conf.AnnounceAddresses) != "" { + announce, err := parseMultiaddrs(c.conf.AnnounceAddresses) + if err != nil { + return nil, fmt.Errorf("invalid p2p announce address: %w", err) + } + if len(announce) == 0 { + // an empty factory result would advertise no addresses at all + return nil, fmt.Errorf("invalid p2p announce address: no multiaddr in %q", c.conf.AnnounceAddresses) + } + // replace the auto-detected interface addresses (loopback, docker bridge, ...) with the configured ones + opts = append(opts, libp2p.AddrsFactory(func([]multiaddr.Multiaddr) []multiaddr.Multiaddr { return announce })) + } if !c.conf.DisableConnectionGater { opts = append(opts, libp2p.ConnectionGater(c.gater)) } @@ -496,6 +508,23 @@ func (c *Client) parseAddrInfoList(addrInfoStr string) []peer.AddrInfo { return addrs } +// parseMultiaddrs parses a comma-separated string of multiaddrs, failing on the first invalid entry. +func parseMultiaddrs(s string) ([]multiaddr.Multiaddr, error) { + var addrs []multiaddr.Multiaddr + for _, a := range strings.Split(s, ",") { + a = strings.TrimSpace(a) + if a == "" { + continue + } + maddr, err := multiaddr.NewMultiaddr(a) + if err != nil { + return nil, fmt.Errorf("%q: %w", a, err) + } + addrs = append(addrs, maddr) + } + return addrs, nil +} + // getNamespace returns unique string identifying ORU network. // // It is used to advertise/find peers in libp2p DHT. diff --git a/pkg/p2p/client_test.go b/pkg/p2p/client_test.go index c99ef17833..2e219d9360 100644 --- a/pkg/p2p/client_test.go +++ b/pkg/p2p/client_test.go @@ -182,6 +182,46 @@ func TestClientStartup(t *testing.T) { } } +func TestAnnounceAddresses(t *testing.T) { + nodeKey, err := key.GenerateNodeKey() + require.NoError(t, err) + + newClient := func(announce string) *Client { + conf := config.P2PConfig{ListenAddress: "/ip4/127.0.0.1/tcp/0", AnnounceAddresses: announce} + client, err := NewClient(conf, nodeKey.PrivKey, dssync.MutexWrap(datastore.NewMapDatastore()), "test-chain", zerolog.Nop(), NopMetrics()) + require.NoError(t, err) + return client + } + + t.Run("announced addresses replace listen addresses", func(t *testing.T) { + client := newClient(" /ip4/203.0.113.10/tcp/7676, /dns4/node.example.com/tcp/7676 ") + h, err := client.listen() + require.NoError(t, err) + defer h.Close() + client.host = h + + // libp2p sorts the factory output, so don't depend on order + assert.ElementsMatch(t, []multiaddr.Multiaddr{ + multiaddr.StringCast("/ip4/203.0.113.10/tcp/7676"), + multiaddr.StringCast("/dns4/node.example.com/tcp/7676"), + }, h.Addrs()) + + info, err := client.GetNetworkInfo() + require.NoError(t, err) + assert.ElementsMatch(t, []string{ + "/ip4/203.0.113.10/tcp/7676/p2p/" + h.ID().String(), + "/dns4/node.example.com/tcp/7676/p2p/" + h.ID().String(), + }, info.ListenAddress) + }) + + for _, announce := range []string{"/ip4/203.0.113.10/tcp/7676,foo", " , "} { + t.Run("invalid announce address fails: "+announce, func(t *testing.T) { + _, err := newClient(announce).listen() + assert.ErrorContains(t, err, "invalid p2p announce address") + }) + } +} + func TestBootstrapping(t *testing.T) { assert := assert.New(t) logger := zerolog.Nop()