Inside Bitcoin
Opening the selected file…
Opening the selected file…
The code behind the network, with room to understand it.
Release published 2026-10-28 · Snapshot fetched 2026-11-01. Latest stable release at fetch time; development branches and Git history are excluded. Only the selected code window and visible folders load here.
1// Copyright (c) 2011-present The Bitcoin Core developers2// Distributed under the MIT software license, see the accompanying3// file COPYING or http://www.opensource.org/licenses/mit-license.php.5#include <mapport.h>7#include <clientversion.h>8#include <common/netif.h>9#include <common/pcp.h>10#include <common/system.h>11#include <net.h>12#include <netaddress.h>13#include <netbase.h>14#include <random.h>15#include <util/log.h>16#include <util/thread.h>17#include <util/threadinterrupt.h>19#include <atomic>20#include <cassert>21#include <chrono>22#include <functional>23#include <string>24#include <thread>26static CThreadInterrupt g_mapport_interrupt;27static std::thread g_mapport_thread;29using namespace std::chrono_literals;30static constexpr auto PORT_MAPPING_REANNOUNCE_PERIOD{20min};31static constexpr auto PORT_MAPPING_RETRY_PERIOD{5min};33static void ProcessPCP()34{35// The same nonce is used for all mappings, this is allowed by the spec, and simplifies keeping track of them.36PCPMappingNonce pcp_nonce;37GetRandBytes(pcp_nonce);39bool ret = false;40bool no_resources = false;41const uint16_t private_port = GetListenPort();42// Multiply the reannounce period by two, as we'll try to renew approximately halfway.43const uint32_t requested_lifetime = std::chrono::seconds(PORT_MAPPING_REANNOUNCE_PERIOD * 2).count();44uint32_t actual_lifetime = 0;45std::chrono::milliseconds sleep_time;47// Local functor to handle result from PCP/NATPMP mapping.48auto handle_mapping = [&](std::variant<MappingResult, MappingError> &res) -> void {49if (MappingResult* mapping = std::get_if<MappingResult>(&res)) {50LogInfo("portmap: Added mapping %s", mapping->ToString());51AddLocal(mapping->external, LOCAL_MAPPED);52ret = true;53actual_lifetime = std::min(actual_lifetime, mapping->lifetime);54} else if (MappingError *err = std::get_if<MappingError>(&res)) {55// Detailed error will already have been logged internally in respective Portmap function.56if (*err == MappingError::NO_RESOURCES) {57no_resources = true;58}59}60};62do {63actual_lifetime = requested_lifetime;64no_resources = false; // Set to true if there was any "no resources" error.65ret = false; // Set to true if any mapping succeeds.67// IPv468std::optional<CNetAddr> gateway4 = QueryDefaultGateway(NET_IPV4);69if (!gateway4) {70LogDebug(BCLog::NET, "portmap: Could not determine IPv4 default gateway\n");71} else {72LogDebug(BCLog::NET, "portmap: gateway [IPv4]: %s\n", gateway4->ToStringAddr());74// Open a port mapping on whatever local address we have toward the gateway.75struct in_addr inaddr_any;76inaddr_any.s_addr = htonl(INADDR_ANY);77auto res = PCPRequestPortMap(pcp_nonce, *gateway4, CNetAddr(inaddr_any), private_port, requested_lifetime, g_mapport_interrupt);78MappingError* pcp_err = std::get_if<MappingError>(&res);79if (pcp_err && *pcp_err == MappingError::UNSUPP_VERSION) {80LogDebug(BCLog::NET, "portmap: Got unsupported PCP version response, falling back to NAT-PMP\n");81res = NATPMPRequestPortMap(*gateway4, private_port, requested_lifetime, g_mapport_interrupt);82}83handle_mapping(res);84}86// IPv687std::optional<CNetAddr> gateway6 = QueryDefaultGateway(NET_IPV6);88if (!gateway6) {89LogDebug(BCLog::NET, "portmap: Could not determine IPv6 default gateway\n");90} else {91LogDebug(BCLog::NET, "portmap: gateway [IPv6]: %s\n", gateway6->ToStringAddr());93// Try to open pinholes for all routable local IPv6 addresses.94for (const auto &addr: GetLocalAddresses()) {95if (!addr.IsRoutable() || !addr.IsIPv6()) continue;96auto res = PCPRequestPortMap(pcp_nonce, *gateway6, addr, private_port, requested_lifetime, g_mapport_interrupt);97handle_mapping(res);98}99}101// Log message if we got NO_RESOURCES.102if (no_resources) {103LogWarning("portmap: At least one mapping failed because of a NO_RESOURCES error. This usually indicates that the port is already used on the router. If this is the only instance of bitcoin running on the network, this will resolve itself automatically. Otherwise, you might want to choose a different P2P port to prevent this conflict.\n");104}106// Sanity-check returned lifetime.107if (actual_lifetime < 30) {108LogWarning("portmap: Got impossibly short mapping lifetime of %d seconds\n", actual_lifetime);109return;110}111// RFC6887 11.2.1 recommends that clients send their first renewal packet at a time chosen with uniform random112// distribution in the range 1/2 to 5/8 of expiration time.113std::chrono::seconds sleep_time_min(actual_lifetime / 2);114std::chrono::seconds sleep_time_max(actual_lifetime * 5 / 8);115sleep_time = sleep_time_min + FastRandomContext().randrange<std::chrono::milliseconds>(sleep_time_max - sleep_time_min);116} while (ret && g_mapport_interrupt.sleep_for(sleep_time));118// We don't delete the mappings when the thread is interrupted because this would add additional complexity, so119// we rather just choose a fairly short expiry time.120}122/// \anchor mapport123static void ThreadMapPort()124{125do {126ProcessPCP();127} while (g_mapport_interrupt.sleep_for(PORT_MAPPING_RETRY_PERIOD));128}130void StartThreadMapPort()131{132if (!g_mapport_thread.joinable()) {133assert(!g_mapport_interrupt);134g_mapport_thread = std::thread(&util::TraceThread, "mapport", &ThreadMapPort);135}136}138void StartMapPort(bool enable)139{140if (enable) {141StartThreadMapPort();142} else {143InterruptMapPort();144StopMapPort();145}146}148void InterruptMapPort()149{150if (g_mapport_thread.joinable()) {151g_mapport_interrupt();152}153}155void StopMapPort()156{157if (g_mapport_thread.joinable()) {158g_mapport_thread.join();159g_mapport_interrupt.reset();160}161}
Independent explanations by MyBitcoinExplorer. Not affiliated with or endorsed by Bitcoin Core. Guides are educational and do not replace the source or its tests.
Bitcoin Core source © its contributors, distributed under the MIT license. Original notices and bundled third-party licenses are retained in the source tree.