Adds a new opt-in -randomizep2pport mode that selects a non-default clearnet P2P listening port on first startup, persists it to the dynamic settings file, and reuses it on later restarts.
The feature is independent from fixed -port usage. -randomizep2pport and -port are mutually exclusive: users can either let Bitcoin Core manage a randomized persisted P2P port, or explicitly choose one with -port, but not both.
Behavior
- Adds
-randomizep2pport=1. - Selects a listening port from
49152-65534when no randomized port has been persisted yet. - Persists the selected port in
settings.jsonas a hidden network-specific setting. - Reuses the persisted randomized port on later restarts.
- Rejects reserved Bitcoin P2P ports, test-chain default P2P ports, bad ports, and ports outside the randomized range for randomized local listening or advertised ports.
- Rejects using
-randomizep2pporttogether with-port. - If the first generated candidate is unavailable during initial selection, tries another candidate instead of failing immediately.
- If the persisted randomized port is unavailable on restart, fails startup instead of silently selecting a new port.
- Keeps remote peer ports unrestricted, so connections to existing peers on
8333and other advertised ports continue to work. - Keeps
Params().GetDefaultPort(),CConnman::GetDefaultPort(), DNS seed behavior, addrman behavior, and chain params unchanged.
Notes
This is best-effort on the public P2P network. Bitcoin Core can listen on and advertise the randomized port, but remote peers still need to learn that port through address relay, RPC, manual configuration, or external discovery before they can connect.
This does not change outbound compatibility with the existing network: nodes can still connect to legacy peers using 8333.
Onion/I2P behavior is unchanged.
Tests
cmake --build build --target bitcoind -j2cmake --build build --target test_bitcoin -j2build/bin/test_bitcoin --run_test=net_teststest/functional/feature_randomize_p2p_port.py --configfile build/test/config.ini