Inside Bitcoin
Opening the selected file…
Inside Bitcoin
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) 2015-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/**6* Functionality for communicating with Tor.7*/8#ifndef BITCOIN_TORCONTROL_H9#define BITCOIN_TORCONTROL_H11#include <netaddress.h>12#include <util/fs.h>13#include <util/sock.h>14#include <util/threadinterrupt.h>16#include <cstdint>17#include <deque>18#include <functional>19#include <memory>20#include <string>21#include <thread>22#include <vector>24inline constexpr uint16_t DEFAULT_TOR_SOCKS_PORT{9050};25inline constexpr int DEFAULT_TOR_CONTROL_PORT = 9051;26extern const std::string DEFAULT_TOR_CONTROL;27inline constexpr bool DEFAULT_LISTEN_ONION = true;29/** Tor control reply code. Ref: https://spec.torproject.org/control-spec/replies.html */30inline constexpr int TOR_REPLY_OK{250};31inline constexpr int TOR_REPLY_UNRECOGNIZED{510};32inline constexpr int TOR_REPLY_SYNTAX_ERROR{512}; //!< Syntax error in command argument34CService DefaultOnionServiceTarget(uint16_t port);36/** Reply from Tor, can be single or multi-line */37class TorControlReply38{39public:40TorControlReply() { Clear(); }42int code;43std::vector<std::string> lines;45void Clear()46{47code = 0;48lines.clear();49}50};52/** Low-level handling for Tor control connection.53* Speaks the SMTP-like protocol as defined in torspec/control-spec.txt54*/55class TorControlConnection56{57public:58typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;60/** Create a new TorControlConnection.61*/62explicit TorControlConnection(CThreadInterrupt& interrupt);63~TorControlConnection();65/**66* Connect to a Tor control port.67* tor_control_center is address of the form host:port.68* Return true on success.69*/70bool Connect(const std::string& tor_control_center);72/**73* Disconnect from Tor control port.74*/75void Disconnect();77/** Send a command, register a handler for the reply.78* A trailing CRLF is automatically added.79* Return true on success.80*/81bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);83/**84* Check if the connection is established.85*/86bool IsConnected() const;88/**89* Wait for data to be available on the socket.90* @param[in] timeout Maximum time to wait91* @return true if data is available, false on timeout or error92*/93bool WaitForData(std::chrono::milliseconds timeout);95/**96* Read available data from socket and process complete replies.97* Dispatches to registered reply handlers.98* @return true if connection is still open, false if connection was closed99*/100bool ReceiveAndProcess();102private:103/** Reference to interrupt object for clean shutdown */104CThreadInterrupt& m_interrupt;105/** Socket for the connection */106std::unique_ptr<Sock> m_sock;107/** Message being received */108TorControlReply m_message;109/** Response handlers */110std::deque<ReplyHandlerCB> m_reply_handlers;111/** Buffer for incoming data */112std::string m_recv_buffer;113/** Process complete lines from the receive buffer */114bool ProcessBuffer();115};117/****** Bitcoin specific TorController implementation ********/119/** Controller that connects to Tor control socket, authenticate, then create120* and maintain an ephemeral onion service.121*/122class TorController123{124public:125TorController(const std::string& tor_control_center, const CService& target);126TorController() : m_conn(m_interrupt) {127// Used for testing only.128}129~TorController();131/** Get name of file to store private key in */132fs::path GetPrivateKeyFile();134/** Interrupt the controller thread */135void Interrupt();137/** Wait for the controller thread to exit */138void Join();139private:140CThreadInterrupt m_interrupt;141std::thread m_thread;142const std::string m_tor_control_center;143TorControlConnection m_conn;144std::string m_private_key;145std::string m_service_id;146std::atomic<bool> m_reconnect;147std::chrono::duration<double> m_reconnect_timeout;148CService m_service;149const CService m_target;150/** Cookie for SAFECOOKIE auth */151std::vector<uint8_t> m_cookie;152/** ClientNonce for SAFECOOKIE auth */153std::vector<uint8_t> m_client_nonce;155/// \anchor torcontrol156void ThreadControl();158public:159/** Callback for GETINFO net/listeners/socks result */160void get_socks_cb(TorControlConnection& conn, const TorControlReply& reply);161/** Callback for ADD_ONION result */162void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply, bool pow_was_enabled);163/** Callback for AUTHENTICATE result */164void auth_cb(TorControlConnection& conn, const TorControlReply& reply);165/** Callback for AUTHCHALLENGE result */166void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);167/** Callback for PROTOCOLINFO result */168void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);169/** Callback after successful connection */170void connected_cb(TorControlConnection& conn);171/** Callback after connection lost or failed connection attempt */172void disconnected_cb(TorControlConnection& conn);173};175#endif // BITCOIN_TORCONTROL_H
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.