What changed, and why it matters
This commit adds native I2P SAM (Simple Anonymous Messaging) protocol support to Monero, allowing the daemon to connect directly to I2P routers instead of requiring a separate SOCKS proxy. It introduces new network code, command-line options, and changes to how incoming and outgoing peer connections are established. The change is a feature addition rather than a documented security fix, but it touches low-level networking and anonymity code, so implementation flaws could affect privacy or stability.
Treat as a normal feature merge. Review the SAM parser for memory safety and protocol-state correctness, verify that `initial_data` bounds checks and SSL restrictions are enforced on all inbound paths, audit private-key file permissions and error handling, and run the new unit tests plus I2P connectivity/stress tests before release. No immediate security patch is indicated by the supplied materials.
Security signals we found
New anonymity-network integration with custom protocol parser
Pre-read data injection into connection buffer (`initial_data`) with explicit SSL-inbound rejection
Private key loaded from and saved to filesystem with owner-only permission attempt
SAM command-line argument parsing and session ID generation
Async socket lifetime management across reconnects and session sockets
No vendor security disclosure or advisory referenced in commit
Evidence from the diff
The merge commit implements I2P SAM v3.1 support: new net::sam::client and net::sam::control_socket classes handle HELLO VERSION, SESSION CREATE, DEST GENERATE, STREAM CONNECT, and STREAM ACCEPT commands; abstract_tcp_server2 is extended to accept pre-read initial_data and to hand off a connection context before the first async read; net_node gains --i2p-sam configuration, dual persistent/transient SAM sessions, and integration with the existing zone-based P2P connection logic. Unit tests cover parsing, key handling, and several accept-path edge cases. No CVE, advisory, or vendor security disclosure is present in the supplied materials.
Changed components
src/net/i2p_sam.cppsrc/net/i2p_sam.hsrc/p2p/net_node.cppsrc/p2p/net_node.hsrc/p2p/net_node.inlcontrib/epee/include/net/abstract_tcp_server2.hcontrib/epee/include/net/abstract_tcp_server2.inldocs/I2P_SAM.mdtests/unit_tests/i2p_sam.cppInspect captured patch +3237 / −22
### contrib/epee/include/net/abstract_tcp_server2.h
@@ -154,7 +154,9 @@ namespace net_utils
bool start_internal(
bool is_income,
bool is_multithreaded,
- boost::optional<network_address> real_remote
+ boost::optional<network_address> real_remote,
+ std::string initial_data = {},
+ t_connection_context* context_out = nullptr
);
struct state_t {
@@ -309,7 +311,9 @@ namespace net_utils
bool start(bool is_income, bool is_multithreaded);
// `real_remote` is the actual endpoint (if connection is to proxy, etc.)
- bool start(bool is_income, bool is_multithreaded, network_address real_remote);
+ // `initial_data`, if non-empty, is treated as already read from the socket.
+ // `context_out`, if set, is filled before the first read starts.
+ bool start(bool is_income, bool is_multithreaded, network_address real_remote, std::string initial_data = {}, t_connection_context* context_out = nullptr);
void get_context(t_connection_context& context_){context_ = get_context();}
@@ -418,7 +422,8 @@ namespace net_utils
default_remote = std::move(remote);
}
- bool add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect);
+ // `initial_data`, if non-empty, is treated as already read from `sock`.
+ bool add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect, std::string initial_data = {}, bool is_income = false);
try_connect_result_t try_connect(connection_ptr new_connection_l, const std::string& adr, const std::string& port, boost::asio::ip::tcp::socket &sock_, const boost::asio::ip::tcp::endpoint &remote_endpoint, const std::string &bind_ip, uint32_t conn_timeout, epee::net_utils::ssl_support_t ssl_support);
bool connect(const std::string& adr, const std::string& port, uint32_t conn_timeot, t_connection_context& cn, const std::string& bind_ip = "0.0.0.0", epee::net_utils::ssl_support_t ssl_support = epee::net_utils::ssl_support_t::e_ssl_support_autodetect);
template<class t_callback>
### contrib/epee/include/net/abstract_tcp_server2.inl
@@ -54,6 +54,8 @@
#include <algorithm>
#include <functional>
+#include <random>
+#include <cstring>
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "net"
@@ -931,9 +933,21 @@ namespace net_utils
bool connection<T>::start_internal(
bool is_income,
bool is_multithreaded,
- boost::optional<network_address> real_remote
+ boost::optional<network_address> real_remote,
+ std::string initial_data,
+ t_connection_context* context_out
)
{
+ if (initial_data.size() > m_state.data.read.buffer.size())
+ {
+ MERROR("initial_data (" << initial_data.size() << " bytes) exceeds read buffer size");
+ return false;
+ }
+ if (!initial_data.empty() && is_income && get_ssl_support() != epee::net_utils::ssl_support_t::e_ssl_support_disabled)
+ {
+ MERROR("initial_data is not supported for an inbound connection with SSL enabled");
+ return false;
+ }
std::unique_lock<std::mutex> guard(m_state.lock);
if (m_state.status != status_t::TERMINATED)
return false;
@@ -1021,6 +1035,9 @@ namespace net_utils
guard.lock();
m_state.protocol.wait_init = false;
m_state.protocol.initialized = true;
+ // Copy before reading starts. After that, handlers on other threads may write the context.
+ if (context_out)
+ *context_out = get_context();
// Account for this connection in the RPC limits without extending its timer.
if (m_state.status == status_t::RUNNING && m_connection_type == e_connection_type_RPC)
start_timer(duration_t{}, true);
@@ -1029,7 +1046,15 @@ namespace net_utils
else if (m_state.status == status_t::TERMINATING)
on_terminating();
else if (!is_income || !m_state.ssl.enabled)
- start_read();
+ {
+ if (initial_data.empty()) start_read();
+ else
+ {
+ // treat initial_data as already read from the socket
+ std::memcpy(m_state.data.read.buffer.data(), initial_data.data(), initial_data.size());
+ handle_read(initial_data.size());
+ }
+ }
else
start_handshake();
return true;
@@ -1099,10 +1124,12 @@ namespace net_utils
bool connection<T>::start(
bool is_income,
bool is_multithreaded,
- network_address real_remote
+ network_address real_remote,
+ std::string initial_data,
+ t_connection_context* context_out
)
{
- return start_internal(is_income, is_multithreaded, real_remote);
+ return start_internal(is_income, is_multithreaded, real_remote, std::move(initial_data), context_out);
}
template<typename T>
@@ -1715,14 +1742,13 @@ namespace net_utils
}
//---------------------------------------------------------------------------------
template<class t_protocol_handler>
- bool boosted_tcp_server<t_protocol_handler>::add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support)
+ bool boosted_tcp_server<t_protocol_handler>::add_connection(t_connection_context& out, boost::asio::ip::tcp::socket&& sock, network_address real_remote, epee::net_utils::ssl_support_t ssl_support, std::string initial_data, bool is_income)
{
if(std::addressof(get_io_context()) == std::addressof(sock.get_executor().context()))
{
connection_ptr conn(new connection<t_protocol_handler>(io_context_, std::move(sock), m_state, m_connection_type, ssl_support));
- if(conn->start(false, 1 < m_threads_count, std::move(real_remote)))
+ if(conn->start(is_income, 1 < m_threads_count, std::move(real_remote), std::move(initial_data), std::addressof(out)))
{
- conn->get_context(out);
conn->save_dbg_log();
return true;
}
### docs/I2P_SAM.md
@@ -0,0 +1,42 @@
+# I2P SAM support in Monero
+
+`monerod` supports I2P's [SAM](https://i2p.net/en/docs/api/samv3/) protocol (version 3.1) for automatically configuring and managing I2P connections. It is also possible to use I2P by means of SOCKS proxies, however this requires extra setup and can [leak metadata](https://i2p.net/en/docs/api/socks/); instead, SAM is the recommended way to use Monero over I2P.
+
+When passed to the daemon, the `--i2p-sam` argument will effectively override the `--tx-proxy` and `--anonymous-inbound` parameters for I2P to use SAM. It is worth noting that the blockchain cannot be downloaded over anonymity networks, including I2P.
+
+## Protocol parameters
+
+| Parameter | Value | Notes |
+| ---------------- | ---------------------- | ----------------------------------------------------------------------------------------- |
+| Protocol version | 3.1 | Chosen for maximum compatibility with router software |
+| Signature type | Ed25519-SHA512 | Default value; recommended by the I2P project |
+| Encryption type | MLKEM-768/ECIES-X25519 | Same reason as above; falls back to the second if the first is unavailable. Post-quantum. |
+| Stream timeout | 60 seconds | Recommended by the I2P project |
+| Tunnel quantity | 3 | Ensures consistent behavior between router implementations |
+
+At a later date, when support arrives, the signature type parameters should be updated to use post-quantum schemes (if not already the default by then).
+
+## Configuration
+
+To use SAM functionality, the I2P router's SAM bridge must first be enabled. The bridge is enabled by default in [i2pd](https://github.com/PurpleI2P/i2pd) (C++), but not in [Java I2P](https://github.com/i2p/i2p.i2p).
+
+In Java I2P, go to http://127.0.0.1:7657/configclients and start the SAM Application Bridge using the "Start" button. You may also want to enable the SAM Application Bridge by default by checking the "Run at Startup" box and clicking "Save Client Configuration".
+
+If the SAM bridge is disabled in i2pd, ensure `sam.enabled=true` is set in the `i2pd.conf` file.
+
+While default router settings will likely be sufficient for most users, the maximum bandwidth usage of the I2P router can be reduced if it is too high. See [here](https://github.com/bitcoin/bitcoin/blob/master/doc/i2p.md#bandwidth) for more information.
+
+## Private key storage
+
+The private destination key is automatically generated by the I2P router, and stored as `i2p_private_key` in the `bitmonero` data directory (by default). You will likely want to create backups of this key.
+
+## Two SAM sessions
+
+`monerod` will keep two separate SAM sessions open when both directions are enabled:
+
+- A persistent session, using the private key above, for accepting incoming connections. This session is advertised to peers as this node's reachable address.
+- A transient session, generated at startup, used only for outgoing connections at the SAM/I2P level.
+
+Either session is skipped if its direction is disabled (`0` for `max_out_connections`/`max_in_connections` in `--i2p-sam`).
+
+It is worth noting that `monerod` still announces its persistent address to peers it connects to, so the node will remain discoverable. This means a peer the node dials can still associate the transient destination it receives with the node's published address, even though the two are kept separate at the SAM protocol level.
### src/cryptonote_config.h
@@ -147,6 +147,7 @@ static_assert(CURRENCY_PROTOCOL_MAX_OBJECT_REQUEST_COUNT >= BLOCKS_SYNCHRONIZING
#define P2P_MAX_PEERS_IN_HANDSHAKE 250
#define P2P_DEFAULT_CONNECTION_TIMEOUT 5000 //5 seconds
#define P2P_DEFAULT_SOCKS_CONNECT_TIMEOUT 45 // seconds
+#define P2P_DEFAULT_I2P_SAM_CONNECT_TIMEOUT 60 // seconds
#define P2P_DEFAULT_PING_CONNECTION_TIMEOUT 2000 //2 seconds
#define P2P_DEFAULT_INVOKE_TIMEOUT 60*2*1000 //2 minutes
#define P2P_DEFAULT_HANDSHAKE_INVOKE_TIMEOUT 5000 //5 seconds
### src/net/CMakeLists.txt
@@ -27,7 +27,7 @@
# THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
set(net_sources dandelionpp.cpp error.cpp http.cpp i2p_address.cpp parse.cpp resolve.cpp
- socks.cpp socks_connect.cpp tor_address.cpp zmq.cpp)
+ socks.cpp socks_connect.cpp tor_address.cpp zmq.cpp i2p_sam.cpp)
monero_find_all_headers(net_headers "${CMAKE_CURRENT_SOURCE_DIR}")
monero_add_library(net ${net_sources} ${net_headers})
### src/net/i2p_sam.cpp
@@ -0,0 +1,919 @@
+// Copyright (c) 2018-2026, The Monero Project
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification, are
+// permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this list of
+// conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice, this list
+// of conditions and the following disclaimer in the documentation and/or other
+// materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its contributors may be
+// used to endorse or promote products derived from this software without specific
+// prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include "i2p_sam.h"
+
+#include <boost/asio/bind_executor.hpp>
+#include <boost/asio/buffer.hpp>
+#include <boost/asio/error.hpp>
+#include <boost/asio/steady_timer.hpp>
+#include <boost/asio/write.hpp>
+#include <boost/asio/read_until.hpp>
+#include <boost/asio/read.hpp>
+#include <boost/filesystem/operations.hpp>
+#include <boost/filesystem/path.hpp>
+#include <array>
+#include <cctype>
+#include <string>
+#include <fstream>
+
+#include "misc_log_ex.h"
+#include "scope_guard.h"
+#include "file_io_utils.h"
+#include "hex.h"
+#include "span.h"
+#include "string_coding.h"
+#include "common/util.h"
+#include "crypto/crypto.h"
+#include "cryptonote_config.h"
+
+#undef MONERO_DEFAULT_LOG_CATEGORY
+#define MONERO_DEFAULT_LOG_CATEGORY "net.i2p"
+
+namespace net
+{
+namespace sam
+{
+ namespace
+ {
+ struct sam_category : boost::system::error_category
+ {
+ explicit sam_category() noexcept : boost::system::error_category() {}
+
+ const char* name() const noexcept override
+ {
+ return "net::sam::error_category";
+ }
+
+ virtual std::string message(int value) const override
+ {
+ switch (sam::error(value))
+ {
+ case sam::error::cant_reach_peer:
+ return "Peer exists, but cannot be reached, or has an outdated router";
+ case sam::error::i2p_error:
+ return "Encountered a generic I2P error";
+ case sam::error::invalid_key:
+ return "Specified key is not valid";
+ case sam::error::invalid_id:
+ return "Specified ID is not valid";
+ case sam::error::timeout:
+ return "Timeout while waiting for an event";
+ case sam::error::duplicated_dest:
+ return "Specified destination is already in use";
+ case sam::error::key_not_found:
+ return "Naming system can't resolve the given name";
+ case sam::error::peer_not_found:
+ return "Peer cannot be found on the network";
+ case sam::error::leaseset_not_found:
+ return "Leaseset could not be found";
+ case sam::error::duplicated_id:
+ return "Specified session ID is already in use";
+ case sam::error::already_accepting:
+ return "Session is already accepting connections";
+ case sam::error::noversion:
+ return "I2P router doesn't support SAM version";
+ case sam::error::parse_failed:
+ return "Error while parsing response from router";
+
+ default:
+ break;
+ }
+ return "Unknown net::sam::error";
+ }
+
+ boost::system::error_condition default_error_condition(int value) const noexcept override
+ {
+ switch (sam::error(value))
+ {
+ case sam::error::cant_reach_peer:
+ case sam::error::leaseset_not_found:
+ return boost::system::errc::host_unreachable;
+ case sam::error::duplicated_dest:
+ case sam::error::duplicated_id:
+ return boost::system::errc::already_connected;
+ case sam::error::already_accepting:
+ return boost::system::errc::connection_already_in_progress;
+ case sam::error::invalid_key:
+ case sam::error::invalid_id:
+ return boost::system::errc::io_error;
+ case sam::error::timeout:
+ return boost::system::errc::timed_out;
+ case sam::error::i2p_error:
+ case sam::error::noversion:
+ return boost::system::errc::protocol_error;
+ case sam::error::parse_failed:
+ return boost::system::errc::io_error;
+ case sam::error::key_not_found:
+ case sam::error::peer_not_found:
+ return boost::system::errc::address_not_available;
+
+ default:
+ break;
+ };
+
+ return boost::system::error_condition{value, *this};
+ }
+ };
+ } // namespace
+
+ static constexpr const std::size_t MAX_LINE_LEN = 4096;
+ static constexpr const std::size_t SESSION_ID_LEN = 10;
+ static constexpr const std::chrono::seconds RECONNECT_DELAY{10};
+ static constexpr const std::chrono::seconds SESSION_CREATE_TIMEOUT{300};
+ static constexpr const std::chrono::seconds COMMAND_TIMEOUT{P2P_DEFAULT_I2P_SAM_CONNECT_TIMEOUT};
+
+ static bool has_prefix(std::string_view line, std::string_view prefix);
+
+ const boost::system::error_category& error_category() noexcept
+ {
+ static const sam_category instance{};
+ return instance;
+ }
+
+ client::client(stream_type::socket&& socket)
+ : socket_(std::move(socket))
+ , strand_(socket_.get_executor())
+ , deadline_(socket_.get_executor())
+ , state_(state::hello_version)
+ , command_timeout_(COMMAND_TIMEOUT)
+ , session_create_timeout_(SESSION_CREATE_TIMEOUT)
+ {}
+
+ control_socket::control_socket(std::string private_key, std::string data_dir, boost::asio::ip::tcp::socket&& socket, bool accept_inbound)
+ : client(std::move(socket))
+ , private_key_(accept_inbound ? std::move(private_key) : std::string{"TRANSIENT"})
+ , data_dir_(std::move(data_dir))
+ , session_socket_(socket_.get_executor())
+ , reconnect_timer_(socket_.get_executor())
+ , reconnect_delay_(RECONNECT_DELAY)
+ , accept_inbound_(accept_inbound)
+ {}
+
+ //! Strip characters that SAM bridges may include with CRLF line endings
+ static void strip_newlines(std::string& line)
+ {
+ while (!line.empty() && (line.back() == '\r' || line.back() == '\n'))
+ {
+ line.pop_back();
+ }
+ }
+
+ void client::arm_deadline(const std::chrono::steady_clock::duration timeout)
+ {
+ const auto self = shared_from_this();
+ const std::uint64_t generation = generation_;
+ const std::uint64_t op_id = ++op_id_;
+ timed_out_ = false;
+
+ deadline_.expires_after(timeout);
+ deadline_.async_wait(boost::asio::bind_executor(strand_,
+ [self, generation, op_id](boost::system::error_code ec)
+ {
+ //! Ignore canceled deadlines and completed or replaced operations.
+ if (ec || self->generation_ != generation || self->op_id_ != op_id) return;
+ self->timed_out_ = true;
+ boost::system::error_code close_ec;
+ self->socket_.close(close_ec);
+ }));
+ }
+
+ void client::async_write_command(const std::shared_ptr<client>& self)
+ {
+ client& self_ref = *self;
+ const std::uint64_t generation = self_ref.generation_;
+
+ self_ref.arm_deadline(self_ref.command_timeout_);
+ const std::uint64_t op_id = self_ref.op_id_;
+
+ boost::asio::async_write(self_ref.socket_, boost::asio::buffer(self_ref.write_buffer_),
+ boost::asio::bind_executor(self_ref.strand_,
+ [self, generation, op_id](boost::system::error_code ec, std::size_t)
+ {
+ if (self->generation_ != generation || self->op_id_ != op_id) return;
+ ++self->op_id_;
+ self->deadline_.cancel();
+ if (self->timed_out_) return self->done(make_error_code(error::timeout));
+ self->handle_write(ec);
+ }));
+ }
+
+ void client::async_read_line()
+ {
+ const auto self = shared_from_this();
+ const std::uint64_t generation = generation_;
+ const auto buffer = line_; // pin this read's buffer in case a reconnect swaps out `line_`
+
+ arm_deadline(state_ == state::session_create ? session_create_timeout_ : command_timeout_);
+ const std::uint64_t op_id = op_id_;
+
+ boost::asio::async_read_until(socket_, boost::asio::dynamic_buffer(*buffer, MAX_LINE_LEN), '\n',
+ boost::asio::bind_executor(strand_,
+ [self, generation, op_id, buffer](boost::system::error_code ec, std::size_t bytes)
+ {
+ if (self->generation_ != generation || self->op_id_ != op_id) return;
+ ++self->op_id_;
+ self->deadline_.cancel();
+ if (self->timed_out_) return self->done(make_error_code(error::timeout));
+ self->handle_read(ec, bytes);
+ }));
+ }
+
+ void client::async_read_stream_accept(std::size_t start, bool deadline_armed)
+ {
+ const std::size_t newline = line_->find('\n', start);
+ if (newline != std::string::npos) return handle_stream_accept_line(newline);
+
+ if (line_->size() >= MAX_LINE_LEN)
+ {
+ auto ec = make_error_code(error::parse_failed);
+ return done(ec);
+ }
+
+ //! No timeout until the peer's destination line starts arriving.
+ if (!deadline_armed && !line_->empty())
+ {
+ arm_deadline(command_timeout_);
+ deadline_armed = true;
+ }
+
+ const auto self = shared_from_this();
+ const std::uint64_t generation = generation_;
+ const std::uint64_t op_id = op_id_;
+ const auto buffer = line_; // pin this read's buffer in case a reconnect swaps out `line_`
+ const std::size_t next_start = buffer->size();
+
+ //! Read one byte at a time so that a pending read never consumes P2P stream data.
+ buffer->push_back('\0');
+ boost::asio::async_read(socket_, boost::asio::buffer(&buffer->back(), 1),
+ boost::asio::bind_executor(strand_,
+ [self, generation, op_id, buffer, next_start, deadline_armed](boost::system::error_code ec, std::size_t bytes)
+ {
+ if (self->generation_ != generation || self->op_id_ != op_id) return;
+ if (self->timed_out_) return self->done(make_error_code(error::timeout));
+ if (ec == boost::asio::error::operation_aborted) return;
+ if (ec) return self->done(ec);
+ if (bytes != 1) return self->done(make_error_code(error::parse_failed));
+ self->async_read_stream_accept(next_start, deadline_armed);
+ }));
+ }
+
+ void client::handle_stream_accept_line(std::size_t newline)
+ {
+ ++op_id_;
+ deadline_.cancel();
+
+ std::string line = line_->substr(0, newline);
+ line_->erase(0, newline + 1);
+ strip_newlines(line);
+
+ if (line.empty())
+ {
+ return done(make_error_code(error::parse_failed));
+ }
+
+ if (has_prefix(line, "STREAM STATUS"))
+ {
+ const auto status = parse_stream_status(line);
+ if (status) return done(status);
+ return done(make_error_code(error::parse_failed));
+ }
+
+ if (line.find(' ') != std::string::npos)
+ {
+ return done(make_error_code(error::parse_failed));
+ }
+
+ MDEBUG("SAM stream accepted data from incoming peer");
+
+ remote_peer_ = destination_to_address(line);
+ stream_accept_listening_ = false;
+ next_state({});
+ }
+
+ void client::handle_write(boost::system::error_code ec)
+ {
+ if (ec == boost::asio::error::operation_aborted) return;
+ if (ec) return done(ec);
+ async_read_line();
+ }
+
+ void client::handle_read(boost::system::error_code ec, std::size_t bytes)
+ {
+ if (ec == boost::asio::error::operation_aborted) return;
+ if (ec) return done(ec);
+
+ std::string line = line_->substr(0, bytes);
+ line_->erase(0, bytes);
+ strip_newlines(line);
+
+ auto result = parse_result(line);
+ if (result) return done(result);
+
+ next_state({});
+ }
+
+ struct client::send_hello_version
+ {
+ std::shared_ptr<client> self;
+
+ //! Value of `generation_` when the connect started.
+ std::uint64_t generation;
+
+ void operator()(boost::system::error_code ec) const
+ {
+ // `ec` is success for a connect that finished just before `async_reconnect` closed the socket.
+ if (self->generation_ != generation) return;
+ if (ec == boost::asio::error::operation_aborted) return;
+ if (ec) return self->done(ec);
+ self->set_write_buffer("HELLO VERSION MIN=3.1 MAX=3.1\n");
+ client::async_write_command(self);
+ }
+ };
+
+ static void send_session_create(const std::shared_ptr<client>& self, const std::string& id, const std::string& destination)
+ {
+ MDEBUG("Sending SESSION CREATE command with ID=" << id);
+
+ // Explicitly set a signature type for transient sessions, to prevent the router from just
+ // choosing one itself.
+ const std::string signature_type = destination == "TRANSIENT" ? " SIGNATURE_TYPE=7" : "";
+
+ /**
+ * Leaseset encryption type: MLKEM-768/ECIES-X25519
+ * Reference: https://docs.i2pd.website/en/latest/user-guide/tunnels/#leaseset
+ */
+ self->set_write_buffer("SESSION CREATE STYLE=STREAM ID=" + id + " DESTINATION=" + destination + signature_type +
+ " i2cp.leaseSetEncType=6,4 inbound.quantity=3 outbound.quantity=3\n");
+ client::async_write_command(self);
+ }
+
+ bool client::connect_and_send(std::shared_ptr<client> self_, const stream_type::endpoint& router)
+ {
+ if (!self_) return false;
+
+ client& self = *self_;
+ self.state_ = state::hello_version;
+
+ const std::uint64_t generation = self.generation_;
+ self.socket_.async_connect(router,
+ boost::asio::bind_executor(self.strand_, send_hello_version{std::move(self_), generation}));
+
+ return true;
+ }
+
+ bool control_socket::connect_and_send(std::shared_ptr<control_socket> self_, const stream_type::endpoint& router)
+ {
+ if (!self_) return false;
+ self_->router_endpoint_ = router;
+ return client::connect_and_send(std::move(self_), router);
+ }
+
+ static void send_stream_connect(const std::shared_ptr<client>& self, const std::string& session_id, const std::string& destination)
+ {
+ MDEBUG("Sending STREAM CONNECT command with ID=" << session_id);
+
+ self->set_write_buffer("STREAM CONNECT ID=" + session_id + " DESTINATION=" + destination + " SILENT=false\n");
+ client::async_write_command(self);
+ }
+
+ static void send_stream_accept(const std::shared_ptr<client>& self, const std::string& session_id)
+ {
+ self->set_write_buffer("STREAM ACCEPT ID=" + session_id + " SILENT=false\n");
+ client::async_write_command(self);
+ }
+
+ void client::next_state(boost::system::error_code ec)
+ {
+ if (ec) return done(ec);
+
+ const auto self = shared_from_this();
+
+ switch (state_)
+ {
+ case state::hello_version:
+ state_ = state::stream_connect;
+ send_stream_connect(self, session_id_, reply_buffer_);
+ return;
+
+ case state::stream_connect:
+ return done({});
+
+ default:
+ return done(make_error_code(error::parse_failed));
+ }
+ }
+
+ void control_socket::async_reconnect(const bool keep_session)
+ {
+ const auto self = shared_from_this();
+
+ reconnect_timer_.cancel();
+ deadline_.cancel();
+ ++generation_;
+
+ boost::system::error_code ec;
+ socket_.close(ec);
+ if (!keep_session)
+ {
+ session_socket_.close(ec);
+ session_established_ = false;
+ }
+
+ line_ = std::make_shared<std::string>(); // a still in-flight read may be holding the old buffer
+ stream_accept_listening_ = false;
+ state_ = state::hello_version;
+
+ const std::uint64_t generation = generation_;
+ reconnect_timer_.expires_after(reconnect_delay_);
+ reconnect_timer_.async_wait(boost::asio::bind_executor(strand_,
+ [self, this, generation](boost::system::error_code ec)
+ {
+ // `cancel()` doesn't affect a handler that already expired and is queued on the strand.
+ if (ec || generation_ != generation) return;
+ socket_ = boost::asio::ip::tcp::socket{socket_.get_executor()};
+ socket_.async_connect(router_endpoint_,
+ boost::asio::bind_executor(strand_, send_hello_version{self, generation}));
+ }));
+ }
+
+ void control_socket::reconnect_after_error()
+ {
+ if (stopped_) return;
+
+
+ // An outbound-only session has no accept loop to retry.
+ async_reconnect(accept_inbound_ && session_established_);
+ }
+
+ void control_socket::connect_now()
+ {
+ const auto self = shared_from_this();
+
+ socket_ = boost::asio::ip::tcp::socket{session_socket_.get_executor()};
+ socket_.async_connect(router_endpoint_,
+ boost::asio::bind_executor(strand_, send_hello_version{self, generation_}));
+ }
+
+ void control_socket::close_extra_sockets()
+ {
+ boost::system::error_code ec;
+ session_socket_.close(ec);
+ }
+
+ void control_socket::watch_session_socket()
+ {
+ const auto self = shared_from_this();
+
+ session_socket_.async_read_some(boost::asio::buffer(&session_watch_byte_, sizeof(session_watch_byte_)),
+ boost::asio::bind_executor(strand_,
+ [self, this](boost::system::error_code ec, std::size_t)
+ {
+ if (ec == boost::asio::error::operation_aborted) return;
+
+ MWARNING("I2P SAM session socket closed unexpectedly");
+ async_reconnect(false);
+ }));
+ }
+
+ void control_socket::next_state(boost::system::error_code ec)
+ {
+ if (ec) return done(ec);
+
+ const auto self = shared_from_this();
+
+ switch (state_)
+ {
+ case state::hello_version:
+ if (session_established_)
+ {
+ state_ = state::stream_accept;
+ send_stream_accept(self, session_id_);
+ }
+ else if (private_key_.empty())
+ {
+ state_ = state::dest_generate;
+ set_write_buffer("DEST GENERATE SIGNATURE_TYPE=7\n");
+ async_write_command(self);
+ }
+ else
+ {
+ state_ = state::session_create;
+ send_session_create(self, session_id_, private_key_);
+ }
+ return;
+
+ case state::dest_generate:
+ if (reply_buffer_.empty()) return done(make_error_code(error::parse_failed));
+ if (!save_private_key(data_dir_, reply_buffer_))
+ {
+ // Not retried; each attempt would generate a new destination and fail to save it too.
+ MERROR("Failed to save the I2P destination key; I2P SAM inbound session stopped until restart");
+ stopped_ = true;
+ return done(make_error_code(error::i2p_error));
+ }
+ private_key_ = std::move(reply_buffer_);
+
+ line_->clear();
+ state_ = state::hello_version;
+ connect_now();
+ return;
+
+ case state::session_create:
+ if (destination_handler_)
+ {
+ const net::i2p_address local = session_destination_to_address(reply_buffer_);
+ if (!local.is_unknown()) destination_handler_(local);
+ else MWARNING("Failed to derive local I2P address from SESSION STATUS destination");
+ }
+
+ session_socket_ = std::move(socket_);
+ watch_session_socket();
+ line_->clear();
+ session_established_ = true;
+
+ if (!accept_inbound_) return;
+
+ state_ = state::hello_version;
+ connect_now();
+ return;
+
+ case state::stream_accept:
+ if (stream_accept_listening_) return async_read_stream_accept();
+ // When a SAM stream is accepted, its listening socket will be turned into the
+ // communication socket with the remote peer. This means a new connection (as well as
+ // a `HELLO VERSION` handshake) will be required before another `STREAM ACCEPT` can be
+ // issued for the next peer. `done()` retrieves any leftover P2P bytes still sitting in
+ // `line_` via `take_buffered_data()`, so `line_` is already empty when it returns.
+ state_ = state::hello_version;
+ {
+ // Rearm the accept even if the peer callback throws, so a single bad
+ // callback can't leave the session unable to accept incoming peers.
+ const epee::scope_guard guard([this]{ connect_now(); });
+ done({});
+ }
+ return;
+
+ default:
+ return done(make_error_code(error::parse_failed));
+ }
+ }
+
+ boost::system::error_code get_value(std::string_view line, std::string_view key, std::string& out)
+ {
+ std::string pattern{key};
+ pattern.push_back('=');
+
+ std::size_t pos = line.find(pattern);
+ while (pos != std::string::npos && pos != 0 && line[pos - 1] != ' ')
+ pos = line.find(pattern, pos + 1);
+
+ if (pos == std::string::npos)
+ return make_error_code(error::parse_failed);
+
+ pos += pattern.length();
+
+ std::size_t end = line.find(' ', pos);
+ if (end == std::string::npos) end = line.length();
+
+ out = line.substr(pos, end - pos);
+
+ strip_newlines(out);
+
+ return {};
+ }
+
+ boost::system::error_code parse_result_code(std::string_view line)
+ {
+ std::string result;
+
+ if (get_value(line, "RESULT", result)) return make_error_code(error::parse_failed);
+ if (result == "OK") return {};
+
+ if (result == "CANT_REACH_PEER") return make_error_code(error::cant_reach_peer);
+ if (result == "I2P_ERROR") return make_error_code(error::i2p_error);
+ if (result == "INVALID_KEY") return make_error_code(error::invalid_key);
+ if (result == "INVALID_ID") return make_error_code(error::invalid_id);
+ if (result == "TIMEOUT") return make_error_code(error::timeout);
+ if (result == "DUPLICATED_DEST") return make_error_code(error::duplicated_dest);
+ if (result == "DUPLICATED_ID") return make_error_code(error::duplicated_id);
+ if (result == "KEY_NOT_FOUND") return make_error_code(error::key_not_found);
+ if (result == "PEER_NOT_FOUND") return make_error_code(error::peer_not_found);
+ if (result == "LEASESET_NOT_FOUND") return make_error_code(error::leaseset_not_found);
+ if (result == "ALREADY_ACCEPTING") return make_error_code(error::already_accepting);
+ if (result == "NOVERSION") return make_error_code(error::noversion);
+
+ return make_error_code(error::parse_failed);
+ }
+
+ static bool has_prefix(std::string_view line, std::string_view prefix)
+ {
+ if (line.compare(0, prefix.size(), prefix) != 0) return false;
+ return line.size() == prefix.size() || line[prefix.size()] == ' ';
+ }
+
+ boost::system::error_code parse_hello_reply(std::string_view line)
+ {
+ if (!has_prefix(line, "HELLO REPLY")) return make_error_code(error::parse_failed);
+ return parse_result_code(line);
+ }
+
+ boost::system::error_code parse_session_status(std::string_view line, std::string& destination)
+ {
+ if (!has_prefix(line, "SESSION STATUS")) return make_error_code(error::parse_failed);
+
+ const auto ec = parse_result_code(line);
+ if (ec) return ec;
+
+ if (get_value(line, "DESTINATION", destination)) return make_error_code(error::parse_failed);
+ return {};
+ }
+
+ boost::system::error_code parse_stream_status(std::string_view line)
+ {
+ if (!has_prefix(line, "STREAM STATUS")) return make_error_code(error::parse_failed);
+ return parse_result_code(line);
+ }
+
+ boost::system::error_code parse_dest_reply(std::string_view line, std::string& private_key)
+ {
+ if (!has_prefix(line, "DEST REPLY")) return make_error_code(error::parse_failed);
+ if (!get_value(line, "PRIV", private_key) && !private_key.empty()) return {};
+
+ // No usable `PRIV` means an error reply. Never return success here, even for `RESULT=OK`.
+ private_key.clear();
+ const auto ec = parse_result_code(line);
+ return ec ? ec : make_error_code(error::parse_failed);
+ }
+
+ boost::system::error_code client::parse_result(std::string_view line)
+ {
+ switch (state_)
+ {
+ case state::hello_version:
+ return parse_hello_reply(line);
+
+ case state::dest_generate:
+ return parse_dest_reply(line, reply_buffer_);
+
+ case state::session_create:
+ {
+ const auto ec = parse_session_status(line, reply_buffer_);
+ if (ec) return ec;
+
+ MDEBUG("Created session with DESTINATION=" << reply_buffer_.substr(0, 25) << "...");
+ return {};
+ }
+
+ case state::stream_connect:
+ {
+ const auto ec = parse_stream_status(line);
+ if (ec) return ec;
+
+ MDEBUG("I2P SAM stream established to " << remote_peer_.str());
+ return {};
+ }
+
+ case state::stream_accept:
+ {
+ const auto ec = parse_stream_status(line);
+ if (ec) return ec;
+
+ stream_accept_listening_ = true;
+ return {};
+ }
+
+ default:
+ return make_error_code(error::parse_failed);
+ }
+ }
+
+ void client::set_session_id(const std::string& id)
+ {
+ session_id_ = sanitize_private_key(id);
+ }
+
+ bool client::set_connect_command(const net::i2p_address& address)
+ {
+ if (address.is_unknown()) return false;
+
+ remote_peer_ = address;
+ reply_buffer_ = address.host_str();
+
+ return true;
+ }
+
+ void client::async_close::operator()()
+ {
+ if (self_)
+ {
+ const std::shared_ptr<client> self = std::move(self_);
+ boost::asio::dispatch(self->strand_, [self]()
+ {
+ if (self->socket_.is_open())
+ {
+ boost::system::error_code ec_;
+ self->socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec_);
+ self->socket_.close(ec_);
+ }
+ self->close_extra_sockets();
+ });
+ }
+ }
+
+ std::string sanitize_private_key(const std::string& key)
+ {
+ std::string result;
+ result.reserve(key.size());
+ for (std::size_t i = 0; i < key.size(); ++i)
+ {
+ if (!std::isspace(static_cast<unsigned char>(key[i])))
+ result.push_back(key[i]);
+ }
+
+ return result;
+ }
+
+ static std::string key_file_path(const std::string& data_dir)
+ {
+ return (boost::filesystem::path(data_dir) / "i2p_private_key").string();
+ }
+
+ bool private_key_from_file(const std::string& data_dir, std::string& private_key)
+ {
+ const std::string key_path = key_file_path(data_dir);
+
+ if (!epee::file_io_utils::is_file_exist(key_path))
+ {
+ private_key.clear();
+ return true;
+ }
+
+ std::string loaded_key{};
+ if (!epee::file_io_utils::load_file_to_string(key_path, loaded_key))
+ {
+ MERROR("Failed to load I2P destination key from " << key_path);
+ return false;
+ }
+
+ private_key = sanitize_private_key(loaded_key);
+
+ MINFO("Read I2P destination key from file (" << key_path << "), length=" << private_key.size());
+ return true;
+ }
+
+ bool save_private_key(const std::string& data_dir, const std::string& private_key)
+ {
+ const std::string key_path = key_file_path(data_dir);
+
+ if (!epee::file_io_utils::is_file_exist(key_path))
+ std::ofstream{key_path, std::ios_base::binary | std::ios_base::out};
+
+ boost::system::error_code ec;
+ boost::filesystem::permissions(key_path, boost::filesystem::owner_read | boost::filesystem::owner_write, ec);
+ if (ec)
+ {
+ MERROR("Failed to set permissions for I2P destination key file: " << ec.message());
+ boost::filesystem::remove(key_path, ec);
+ return false;
+ }
+
+ if (!epee::file_io_utils::save_string_to_file(key_path, private_key))
+ {
+ MERROR("Failed to save I2P destination key to " << key_path);
+ return false;
+ }
+
+ MINFO("Saved I2P destination key to " << key_path);
+ return true;
+ }
+
+ std::string random_session_id()
+ {
+ static_assert(SESSION_ID_LEN % 2 == 0, "SESSION_ID_LEN must be even");
+ std::array<std::uint8_t, SESSION_ID_LEN / 2> result{{}};
+ crypto::rand(result.size(), result.data());
+ return epee::to_hex::string(epee::to_span(result));
+ }
+
+ std::string swap_base64(std::string_view in)
+ {
+ std::string out;
+ out.resize(in.size());
+
+ for (std::size_t i = 0; i < in.size(); ++i)
+ {
+ switch (in[i])
+ {
+ case '-':
+ out[i] = '+';
+ break;
+ case '~':
+ out[i] = '/';
+ break;
+ case '+':
+ out[i] = '-';
+ break;
+ case '/':
+ out[i] = '~';
+ break;
+
+ default:
+ out[i] = in[i];
+ break;
+ }
+ }
+ return out;
+ }
+
+ //! @return The Base32 address whose host is the SHA-256 digest of `binary`.
+ static net::i2p_address hash_destination(std::string_view binary)
+ {
+ if (binary.empty()) return net::i2p_address::unknown();
+
+ static_assert(sizeof(crypto::hash) == 32, "I2P Base32 destination encoding assumes a 32-byte SHA-256 digest");
+ crypto::hash digest{};
+ if (!tools::sha256sum(reinterpret_cast<const std::uint8_t*>(binary.data()), binary.size(), digest))
+ return net::i2p_address::unknown();
+
+ static constexpr const char base32_alphabet[] = "abcdefghijklmnopqrstuvwxyz234567";
+
+ std::string host;
+ host.reserve(net::i2p_address::buffer_size());
+
+ std::uint32_t buffer = 0;
+ std::size_t bits = 0;
+ for (std::size_t i = 0; i < sizeof(digest.data); ++i)
+ {
+ buffer = (buffer << 8) | static_cast<unsigned char>(digest.data[i]);
+ bits += 8;
+ while (bits >= 5)
+ {
+ bits -= 5;
+ host.push_back(base32_alphabet[(buffer >> bits) & 0x1F]);
+ }
+ }
+ if (bits > 0) host.push_back(base32_alphabet[(buffer << (5 - bits)) & 0x1F]);
+
+ host.append(".b32.i2p");
+
+ const auto address = net::i2p_address::make(host);
+ if (!address) return net::i2p_address::unknown();
+
+ return *address;
+ }
+
+ net::i2p_address destination_to_address(std::string_view destination)
+ {
+ return hash_destination(epee::string_encoding::base64_decode(swap_base64(destination)));
+ }
+
+ net::i2p_address session_destination_to_address(std::string_view private_destination)
+ {
+ /**
+ * I2P destination binary layout: 256-byte public key + 128-byte signing
+ * public key + 3-byte certificate header, followed by `cert_len` bytes
+ * of the certificate payload. `CERT_LEN_POS` is the offset of that
+ * 2-byte length field, and `DEST_LEN_BASE` (256 + 128 + 3) is the
+ * destination size when the certificate payload is empty.
+ */
+ static constexpr const std::size_t DEST_LEN_BASE = 387;
+ static constexpr const std::size_t CERT_LEN_POS = 385;
+
+ const std::string binary = epee::string_encoding::base64_decode(swap_base64(private_destination));
+ if (binary.size() < CERT_LEN_POS + 2) return net::i2p_address::unknown();
+
+ const auto* data = reinterpret_cast<const std::uint8_t*>(binary.data());
+ const std::size_t cert_len = (std::size_t{data[CERT_LEN_POS]} << 8) | data[CERT_LEN_POS + 1];
+ const std::size_t dest_len = DEST_LEN_BASE + cert_len;
+ if (binary.size() < dest_len) return net::i2p_address::unknown();
+
+ return hash_destination({binary.data(), dest_len});
+ }
+} // namespace sam
+} // namespace net
### src/net/i2p_sam.h
@@ -0,0 +1,435 @@
+// Copyright (c) 2018-2026, The Monero Project
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification, are
+// permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this list of
+// conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice, this list
+// of conditions and the following disclaimer in the documentation and/or other
+// materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its contributors may be
+// used to endorse or promote products derived from this software without specific
+// prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#pragma once
+
+#include <boost/asio/ip/tcp.hpp>
+#include <boost/asio/strand.hpp>
+#include <boost/system/error_code.hpp>
+#include <boost/asio/steady_timer.hpp>
+#include <atomic>
+#include <functional>
+#include <memory>
+#include <utility>
+#include <cstdint>
+#include <string>
+#include <string_view>
+#include <chrono>
+
+#include "net/i2p_address.h"
+#include "net/parse.h"
+#include "net/net_utils_base.h"
+
+namespace net
+{
+namespace sam
+{
+ /**
+ * Possible SAM protocol errors. Defined here:
+ * https://i2p.net/en/docs/api/samv3/
+ */
+ enum class error : int
+ {
+ cant_reach_peer = 1, ///< Peer exists, but cannot be reached
+ i2p_error, ///< A generic I2P error
+ invalid_key, ///< Specified key is not valid
+ invalid_id, ///< Invalid stream ID
+ timeout, ///< Timeout while waiting for an event
+ duplicated_dest, ///< Specified destination is already in use
+ key_not_found, ///< Naming system couldn't resolve the given name
+ peer_not_found, ///< Peer couldn't be found on the network
+ leaseset_not_found, ///< Leaseset couldn't be found
+ duplicated_id, ///< Session ID is already in use
+ already_accepting, ///< There is already a pending `STREAM ACCEPT` for this session
+ noversion, ///< I2P router does not support SAM version
+
+ parse_failed ///< Parse failed (not a standard SAM error code)
+ };
+
+ //! @return boost::system::error_category for net::sam namespace
+ const boost::system::error_category& error_category() noexcept;
+
+ //! @return net::sam::error as a boost::system::error_code.
+ inline boost::system::error_code make_error_code(error value) noexcept
+ {
+ return boost::system::error_code{int(value), sam::error_category()};
+ }
+
+ //! States of the SAM connection process.
+ enum class state : std::uint8_t
+ {
+ hello_version,
+ dest_generate,
+ session_create,
+ stream_accept,
+ stream_connect
+ };
+
+ //! Base class for a connection to a network peer over I2P.
+ class client : public std::enable_shared_from_this<client>
+ {
+ protected:
+ boost::asio::ip::tcp::socket socket_;
+ const boost::asio::strand<boost::asio::ip::tcp::socket::executor_type> strand_;
+
+ //! Timeout for the pending read or write.
+ boost::asio::steady_timer deadline_;
+
+ //! Bumped on reconnect so a completion from an abandoned attempt can be ignored.
+ std::uint64_t generation_{0};
+
+ //! Bumped when a deadline is armed or its operation completes, so stale callbacks are ignored.
+ std::uint64_t op_id_{0};
+
+ /**
+ * Set by an expired `deadline_`; `done()` is deferred to the operation's own completion
+ * handler, since closing the socket doesn't guarantee the operation has stopped using its buffer.
+ */
+ bool timed_out_{false};
+
+ /**
+ * Held by `shared_ptr` so a reconnect can give the client a fresh buffer without
+ * invalidating one a still in-flight (composed) read is holding onto.
+ */
+ std::shared_ptr<std::string> line_{std::make_shared<std::string>()};
+ std::string write_buffer_;
+
+ //! Buffer used for whatever string value the current `state_` parameter needs.
+ std::string reply_buffer_;
+
+ //! A randomly-generated global SAM session ID.
+ std::string session_id_;
+
+ //! I2P network address of the remote peer (if applicable).
+ net::i2p_address remote_peer_;
+
+ bool stream_accept_listening_{false};
+
+ //! Current state of the connection process.
+ state state_;
+
+ //! Reply timeouts: one for most commands, plus a longer one for `SESSION CREATE` (tunnel setup can take minutes).
+ std::chrono::steady_clock::duration command_timeout_;
+ std::chrono::steady_clock::duration session_create_timeout_;
+
+ public:
+ using stream_type = boost::asio::ip::tcp;
+
+ //! Invoked after `send` function completes or fails.
+ virtual void done(boost::system::error_code error) = 0;
+
+ struct send_hello_version;
+
+ /**
+ * Socket ownership is passed into this.
+ * Does not have to be in connected state.
+ */
+ explicit client(stream_type::socket&& socket);
+
+ client(const client&) = delete;
+ virtual ~client() = default;
+ client& operator=(const client&) = delete;
+
+ //! @return Ownership of the client socket object.
+ [[nodiscard]] stream_type::socket take_socket() noexcept
+ {
+ return stream_type::socket{std::move(socket_)};
+ }
+
+ //! Only called from `done()`, when no read is in flight.
+ [[nodiscard]] std::string take_buffered_data() noexcept
+ {
+ return std::exchange(*line_, std::string{});
+ }
+
+ //! @return Address of the remote I2P peer.
+ const net::i2p_address& remote_address() const noexcept { return remote_peer_; }
+
+ [[nodiscard]] bool set_connect_command(const net::i2p_address& address);
+
+ //! Sets the SAM session ID used in later commands. Strips whitespace, since embedded
+ //! spaces or newlines would otherwise let `id` inject extra SAM command parameters.
+ void set_session_id(const std::string& id);
+
+ //! Sets the raw command sent by the next `async_write_command` call.
+ void set_write_buffer(std::string in) noexcept { write_buffer_ = std::move(in); }
+
+ //! Overrides the default command and `SESSION CREATE` timeouts. Call before `connect_and_send`.
+ void set_timeouts(std::chrono::steady_clock::duration command, std::chrono::steady_clock::duration session_create) noexcept
+ {
+ command_timeout_ = command;
+ session_create_timeout_ = session_create;
+ }
+
+ [[nodiscard]] static bool connect_and_send(std::shared_ptr<client> self_, const stream_type::endpoint& router);
+
+ /*! Callback for closing socket. Thread-safe with `*send` functions;
+ never blocks (uses strands). Only ever invoked via `close_on_exit`
+ (NOP if `self_` is null), so it takes no arguments. */
+ struct async_close
+ {
+ std::shared_ptr<client> self_;
+ void operator()();
+ };
+
+ //! Calls `async_close` on `self` at destruction. NOP if `nullptr`.
+ struct close_on_exit
+ {
+ std::shared_ptr<client> self;
+ ~close_on_exit() { async_close{std::move(self)}(); }
+ };
+
+ static void async_write_command(const std::shared_ptr<client>& self);
+ void handle_write(boost::system::error_code ec);
+ void handle_read(boost::system::error_code ec, std::size_t bytes);
+
+ protected:
+ /**
+ * The response to `STREAM ACCEPT` is unique in that the router will send the peer's
+ * Base64 destination as a single line, and then start sending that peer's stream data
+ * immediately after. This means that some of the P2P data can get pulled into the line
+ * being parsed. The prior `STREAM STATUS` read can also over-read into `line_`, so
+ * `line_` may already contain the destination line (or more) before any byte is read here.
+ * `deadline_` is only armed once the destination line starts arriving.
+ */
+ void async_read_stream_accept(std::size_t start = 0, bool deadline_armed = false);
+
+ //! Closes `socket_` if the current operation exceeds `timeout`.
+ void arm_deadline(std::chrono::steady_clock::duration timeout);
+
+ private:
+ virtual void next_state(boost::system::error_code ec);
+
+ //! Closes any sockets a derived class owns besides `socket_`. NOP here; called by `async_close`.
+ virtual void close_extra_sockets() {}
+
+ void async_read_line();
+
+ //! Parses the STREAM ACCEPT reply line ending at index `newline` in `line_`, then erases it from `line_`.
+ void handle_stream_accept_line(std::size_t newline);
+
+ //! Parse response from router to get error code
+ boost::system::error_code parse_result(std::string_view line);
+ };
+
+ //! A connection to an I2P router's SAM bridge.
+ class control_socket : public client
+ {
+ //! Our private destination key; generated or retrieved from a file.
+ std::string private_key_;
+
+ //! Directory used to store the private destination key from `DEST GENERATE`.
+ const std::string data_dir_;
+
+ //! The local SAM bridge endpoint, stored so we can reconnect for `STREAM ACCEPT`.
+ boost::asio::ip::tcp::endpoint router_endpoint_;
+
+ //! Keeps the `SESSION CREATE` socket alive while we open a second connection.
+ boost::asio::ip::tcp::socket session_socket_;
+
+ /**
+ * Shared by every `async_reconnect` call so that at most one reconnect chain is
+ * ever in flight. Without this, a router restart can drop `socket_` and `session_socket_`
+ * at nearly the same time, arming two independent timers that later race each other's
+ * move-assignment into `socket_`.
+ */
+ boost::asio::steady_timer reconnect_timer_;
+
+ std::uint8_t session_watch_byte_{0};
+
+ //! Delay before each reconnect attempt.
+ std::chrono::steady_clock::duration reconnect_delay_;
+
+ //! Set when the generated key can't be saved. Stops `reconnect_after_error` from retrying.
+ bool stopped_{false};
+
+ //! True after `SESSION CREATE` completes; read from outside the strand, so it's atomic.
+ std::atomic<bool> session_established_{false};
+
+ std::function<void(const net::i2p_address&)> destination_handler_;
+
+ //! False for an outbound-only session; skips `STREAM ACCEPT` entirely.
+ const bool accept_inbound_;
+
+ void next_state(boost::system::error_code ec) override;
+
+ //! Closes `session_socket_`, canceling the pending read of `watch_session_socket`.
+ void close_extra_sockets() override;
+
+ void watch_session_socket();
+
+ /**
+ * Recreates `socket_` and connects it to `router_endpoint_`, which starts the
+ * connection over again using `HELLO VERSION`. SAM requires a new connection after
+ * `SESSION CREATE` and after `STREAM ACCEPT` (when completed); the same is done after
+ * `DEST GENERATE` for simplicity.
+ */
+ void connect_now();
+
+ public:
+ //! Reconnects after a delay; `keep_session` retries only the accept connection.
+ void async_reconnect(bool keep_session);
+
+ /**
+ * Retries the accept connection if a session has already been created; otherwise, falls
+ * back to a full async reconnect.
+ */
+ void reconnect_after_error();
+
+ void set_destination_handler(std::function<void(const net::i2p_address&)> handler) noexcept { destination_handler_ = std::move(handler); }
+
+ bool session_established() const noexcept { return session_established_; }
+
+ //! Overrides the default reconnect delay. Call before `connect_and_send`.
+ void set_reconnect_delay(std::chrono::steady_clock::duration delay) noexcept { reconnect_delay_ = delay; }
+
+ /**
+ * Socket ownership is passed into this. Does not have to be in connected state.
+ * `accept_inbound=false` ignores `private_key`/`data_dir`, uses `DESTINATION=TRANSIENT`,
+ * and never sends `STREAM ACCEPT`.
+ */
+ explicit control_socket(std::string private_key, std::string data_dir, boost::asio::ip::tcp::socket&& socket, bool accept_inbound = true);
+
+ [[nodiscard]] static bool connect_and_send(std::shared_ptr<control_socket> self_, const boost::asio::ip::tcp::endpoint& router);
+ };
+
+ /**
+ * @brief Removes whitespace and newlines from a saved private key file.
+ * @param key The raw key contents of the saved file.
+ * @return The sanitized key.
+ */
+ [[nodiscard]] std::string sanitize_private_key(const std::string& key);
+
+ /**
+ * @brief Loads the private I2P destination key from a file, if one exists.
+ * @param data_dir The directory to use for loading/storing the key file.
+ * @param private_key Set to the loaded key, or left empty if none exists.
+ * @return `false` if the key file exists but could not be read.
+ */
+ [[nodiscard]] bool private_key_from_file(const std::string& data_dir, std::string& private_key);
+
+ /**
+ * @brief Generates a random SAM session ID.
+ * @return A string consisting of 10 random hex characters.
+ */
+ std::string random_session_id();
+
+ /**
+ * @brief Swaps between standard Base64 and I2P-style Base64.
+ * @param in The string to convert between Base64 variants.
+ * @return The converted string.
+ */
+ [[nodiscard]] std::string swap_base64(std::string_view in);
+
+ /**
+ * @brief Derives the public Base32 I2P address from a full Base64-encoded destination.
+ * @param destination The destination string, encoded in I2P-style Base64.
+ * @return The address derived from the destination.
+ */
+ net::i2p_address destination_to_address(std::string_view destination);
+
+ /**
+ * @brief Derives the public Base32 I2P address from a private destination.
+ * @param private_destination The private destination, encoded in I2P-style Base64.
+ * @return The address derived from the destination.
+ */
+ net::i2p_address session_destination_to_address(std::string_view private_destination);
+
+ [[nodiscard]] boost::system::error_code get_value(std::string_view line, std::string_view key, std::string& out);
+ [[nodiscard]] boost::system::error_code parse_result_code(std::string_view line);
+
+ [[nodiscard]] boost::system::error_code parse_hello_reply(std::string_view line);
+ [[nodiscard]] boost::system::error_code parse_session_status(std::string_view line, std::string& destination);
+ [[nodiscard]] boost::system::error_code parse_stream_status(std::string_view line);
+ [[nodiscard]] boost::system::error_code parse_dest_reply(std::string_view line, std::string& private_key);
+
+ [[nodiscard]] bool save_private_key(const std::string& data_dir, const std::string& private_key);
+
+ template<typename Handler>
+ class connect_client : public client
+ {
+ Handler handler_;
+
+ virtual void done(boost::system::error_code error) override
+ {
+ handler_(error, take_socket(), take_buffered_data());
+ }
+
+ public:
+ explicit connect_client(stream_type::socket&& router, Handler&& handler)
+ : client(std::move(router))
+ , handler_(std::move(handler))
+ {}
+
+ virtual ~connect_client() override {}
+ };
+
+ template<typename Handler>
+ inline std::shared_ptr<client> make_connect_client(client::stream_type::socket&& router, Handler handler)
+ {
+ return std::make_shared<connect_client<Handler>>(std::move(router), std::move(handler));
+ }
+//----------------------------------------------------------------------------------------------------
+ template<typename Handler>
+ class control_client : public control_socket
+ {
+ Handler handler_;
+
+ virtual void done(boost::system::error_code error) override
+ {
+ handler_(error, take_socket(), remote_address(), take_buffered_data());
+ if (error) reconnect_after_error();
+ }
+
+ public:
+ explicit control_client(std::string private_key, std::string data_dir, boost::asio::ip::tcp::socket&& router, Handler&& handler, bool accept_inbound = true)
+ : control_socket(std::move(private_key), std::move(data_dir), std::move(router), accept_inbound)
+ , handler_(std::move(handler))
+ {}
+
+ virtual ~control_client() override {}
+ };
+
+ template<typename Handler>
+ inline std::shared_ptr<control_socket> make_control_client(std::string private_key, std::string data_dir, boost::asio::ip::tcp::socket&& router, Handler handler, bool accept_inbound = true)
+ {
+ return std::make_shared<control_client<Handler>>(std::move(private_key), std::move(data_dir), std::move(router), std::move(handler), accept_inbound);
+ }
+} // namespace sam
+} // namespace net
+
+namespace boost
+{
+namespace system
+{
+ template<>
+ struct is_error_code_enum<net::sam::error>
+ : true_type
+ {};
+} // namespace system
+} // namespace boost
### src/p2p/net_node.cpp
@@ -37,6 +37,7 @@
#include <boost/utility/string_ref.hpp>
#include <chrono>
#include <utility>
+#include <tuple>
#include "common/command_line.h"
#include "cryptonote_core/cryptonote_core.h"
@@ -54,6 +55,7 @@ namespace
{
constexpr const boost::chrono::milliseconds future_poll_interval{500};
constexpr const std::chrono::seconds socks_connect_timeout{P2P_DEFAULT_SOCKS_CONNECT_TIMEOUT};
+ constexpr const std::chrono::seconds sam_connect_timeout{P2P_DEFAULT_I2P_SAM_CONNECT_TIMEOUT};
std::int64_t get_max_connections(const boost::iterator_range<boost::string_ref::const_iterator> value) noexcept
{
@@ -67,6 +69,17 @@ namespace
return 0;
}
+ boost::optional<std::int64_t> get_i2p_sam_max_connections(const boost::iterator_range<boost::string_ref::const_iterator> value)
+ {
+ if (value.empty())
+ return std::int64_t{-1};
+
+ std::uint32_t out = 0;
+ if (!epee::string_tools::get_xtype_from_string(out, std::string{value.begin(), value.end()}))
+ return boost::none;
+ return std::int64_t{out};
+ }
+
bool start_socks(std::shared_ptr<net::socks::client> client, const net::socks::endpoint& proxy, const epee::net_utils::network_address& remote)
{
CHECK_AND_ASSERT_MES(client != nullptr, false, "Unexpected null client");
@@ -100,6 +113,13 @@ namespace
CHECK_AND_ASSERT_MES(sent, false, "Unexpected failure to init socks client");
return true;
}
+
+ [[nodiscard]] bool start_sam(std::shared_ptr<net::sam::client> client, const boost::asio::ip::tcp::endpoint& router, const net::i2p_address& remote)
+ {
+ CHECK_AND_ASSERT_MES(client != nullptr, false, "Unexpected null client");
+ if (!client->set_connect_command(remote)) return false;
+ return net::sam::client::connect_and_send(std::move(client), router);
+ }
}
namespace nodetool
@@ -142,6 +162,7 @@ namespace nodetool
const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_seed_node = {"seed-node", "Connect to a node to retrieve peer addresses, and disconnect"};
const command_line::arg_descriptor<std::vector<std::string> > arg_tx_proxy = {"tx-proxy", "Send local txes through proxy: <network-type>,[socks5://[user:pass@]]<socks-ip:port>[,max_connections][,disable_noise] i.e. \"tor,127.0.0.1:9050,100,disable_noise\""};
const command_line::arg_descriptor<std::vector<std::string> > arg_anonymous_inbound = {"anonymous-inbound", "<hidden-service-address>,<[bind-ip:]port>[,max_connections] i.e. \"x.onion,127.0.0.1:18083,100\""};
+ const command_line::arg_descriptor<std::string> arg_i2p_sam = {"i2p-sam", "Use I2P router's SAM bridge for proxying network traffic: <router-ip:sam-port>[,max_out_connections[,max_in_connections]] i.e. \"127.0.0.1:7656,32,0\" (0 disables that direction). Inbound keeps a persistent I2P key in the data directory, and its address is announced to peers"};
const command_line::arg_descriptor<std::string> arg_ban_list = {"ban-list", "Specify ban list file, one IP address per line"};
const command_line::arg_descriptor<bool> arg_p2p_hide_my_port = {"hide-my-port", "Do not announce yourself as peerlist candidate", false, true};
const command_line::arg_descriptor<bool> arg_no_sync = {"no-sync", "Don't synchronize the blockchain with other peers", false};
@@ -298,6 +319,39 @@ namespace nodetool
return inbounds;
}
+ boost::optional<i2p_sam_config> get_i2p_sam_config(const boost::program_options::variables_map& vm)
+ {
+ i2p_sam_config out{};
+
+ const std::string arg = command_line::get_arg(vm, arg_i2p_sam);
+ const boost::string_ref arg_ref{arg};
+
+ auto next = boost::algorithm::make_split_iterator(arg_ref, boost::algorithm::first_finder(","));
+ CHECK_AND_ASSERT_MES(!next.eof() && !next->empty(), boost::none, "No ip:port given for --" << arg_i2p_sam.name);
+ out.endpoint = std::string{next->begin(), next->size()};
+
+ ++next;
+ for (unsigned int count = 0; !next.eof(); ++count, ++next)
+ {
+ if (2 <= count)
+ {
+ MERROR("Too many ',' characters given to --" << arg_i2p_sam.name);
+ return boost::none;
+ }
+
+ const auto max_connections = get_i2p_sam_max_connections(*next);
+ if (!max_connections)
+ {
+ MERROR("Invalid max connections given to --" << arg_i2p_sam.name);
+ return boost::none;
+ }
+
+ (count == 0 ? out.max_out_connections : out.max_in_connections) = *max_connections;
+ }
+
+ return out;
+ }
+
bool is_filtered_command(const epee::net_utils::network_address& address, int command)
{
switch (command)
@@ -376,4 +430,66 @@ namespace nodetool
return boost::none;
}
+
+ boost::optional<std::pair<boost::asio::ip::tcp::socket, std::string>>
+ sam_connect_internal(const std::atomic<bool>& stop_signal, boost::asio::io_context& service, const boost::asio::ip::tcp::endpoint& router, const net::i2p_address& remote, const std::string& session_id)
+ {
+ using socket_type = net::sam::client::stream_type::socket;
+ using client_result = std::tuple<boost::system::error_code, socket_type, std::string>;
+
+ struct notify
+ {
+ boost::promise<client_result> sam_promise;
+
+ void operator()(boost::system::error_code error, socket_type&& sock, std::string&& initial_data)
+ {
+ sam_promise.set_value(std::make_tuple(error, std::move(sock), std::move(initial_data)));
+ }
+ };
+
+ net::sam::client::close_on_exit close_client{};
+ boost::unique_future<client_result> sam_result{};
+ {
+ boost::promise<client_result> sam_promise{};
+ sam_result = sam_promise.get_future();
+
+ auto client = net::sam::make_connect_client(
+ boost::asio::ip::tcp::socket{service}, notify{std::move(sam_promise)}
+ );
+ close_client.self = client;
+
+ client->set_session_id(session_id);
+
+ if (!start_sam(std::move(client), router, remote))
+ return boost::none;
+ }
+
+ const auto start = std::chrono::steady_clock::now();
+ while (sam_result.wait_for(future_poll_interval) == boost::future_status::timeout)
+ {
+ if (sam_connect_timeout < std::chrono::steady_clock::now() - start)
+ {
+ MERROR("Timeout on SAM connect (" << router << " to " << remote.str() << ")");
+ return boost::none;
+ }
+
+ if (stop_signal) return boost::none;
+ }
+
+ try
+ {
+ auto result = sam_result.get();
+ const auto& error = std::get<0>(result);
+ if (!error)
+ {
+ close_client.self.reset();
+ return {std::make_pair(std::move(std::get<1>(result)), std::move(std::get<2>(result)))};
+ }
+
+ MERROR("Failed to make SAM connection to " << remote.str() << " (via " << router << "): " << error.message());
+ }
+ catch (const boost::broken_promise&) {}
+
+ return boost::none;
+ }
}
### src/p2p/net_node.h
@@ -57,6 +57,7 @@
#include "net/enums.h"
#include "net/parse.h"
#include "common/command_line.h"
+#include "net/i2p_sam.h"
PUSH_WARNINGS
DISABLE_VS_WARNINGS(4355)
@@ -95,15 +96,31 @@ namespace nodetool
epee::net_utils::network_address default_remote;
};
+ struct i2p_sam_config
+ {
+ i2p_sam_config()
+ : endpoint(),
+ max_out_connections(-1),
+ max_in_connections(-1)
+ {}
+
+ std::string endpoint;
+ std::int64_t max_out_connections;
+ std::int64_t max_in_connections;
+ };
+
boost::optional<std::vector<proxy>> get_proxies(const boost::program_options::variables_map& vm);
boost::optional<std::vector<anonymous_inbound>> get_anonymous_inbounds(const boost::program_options::variables_map& vm);
+ boost::optional<i2p_sam_config> get_i2p_sam_config(const boost::program_options::variables_map& vm);
//! \return True if `command` is filtered (ignored/dropped) for `address`
bool is_filtered_command(epee::net_utils::network_address const& address, int command);
// hides boost::future and chrono stuff from mondo template file
boost::optional<boost::asio::ip::tcp::socket>
socks_connect_internal(const std::atomic<bool>& stop_signal, boost::asio::io_context& service, const net::socks::endpoint& proxy, const epee::net_utils::network_address& remote);
+ [[nodiscard]] boost::optional<std::pair<boost::asio::ip::tcp::socket, std::string>>
+ sam_connect_internal(const std::atomic<bool>& stop_signal, boost::asio::io_context& service, const boost::asio::ip::tcp::endpoint& router, const net::i2p_address& remote, const std::string& session_id);
template<class base_type>
@@ -167,7 +184,6 @@ namespace nodetool
m_port(),
m_port_ipv6(),
m_notifier(),
- m_our_address(),
m_peerlist(),
m_config{},
m_proxy_address(),
@@ -189,7 +205,6 @@ namespace nodetool
m_port(),
m_port_ipv6(),
m_notifier(),
- m_our_address(),
m_peerlist(),
m_config{},
m_proxy_address(),
@@ -210,17 +225,42 @@ namespace nodetool
std::string m_port;
std::string m_port_ipv6;
cryptonote::levin::notify m_notifier;
- epee::net_utils::network_address m_our_address; // in anonymity networks
peerlist_manager m_peerlist;
config m_config;
net::socks::endpoint m_proxy_address;
+
+ std::string m_sam_session_id;
+ boost::asio::ip::tcp::endpoint m_sam_router_endpoint;
+ std::shared_ptr<net::sam::control_socket> m_sam_control_socket;
+
+ std::string m_sam_outbound_session_id;
+ std::shared_ptr<net::sam::control_socket> m_sam_outbound_control_socket;
+
std::atomic<unsigned int> m_current_number_of_out_peers;
std::atomic<unsigned int> m_current_number_of_in_peers;
boost::shared_mutex m_seed_nodes_lock;
bool m_can_pingback;
bool m_seed_nodes_initialized;
+ /* `m_our_address` is set from the I2P SAM control socket's strand after the destination
+ is established, which races with reads from other threads once the zone's io_context
+ is running; all access goes through lock-guarded accessors. */
+ epee::net_utils::network_address get_our_address() const
+ {
+ CRITICAL_REGION_LOCAL(m_our_address_lock);
+ return m_our_address;
+ }
+
+ void set_our_address(epee::net_utils::network_address address)
+ {
+ CRITICAL_REGION_LOCAL(m_our_address_lock);
+ m_our_address = std::move(address);
+ }
+
private:
+ epee::net_utils::network_address m_our_address; // in anonymity networks
+ mutable epee::critical_section m_our_address_lock;
+
void set_config_defaults() noexcept
{
// at this moment we have a hardcoded config
@@ -456,6 +496,7 @@ namespace nodetool
static boost::optional<p2p_connection_context> public_connect(network_zone&, epee::net_utils::network_address const&, epee::net_utils::ssl_support_t);
static boost::optional<p2p_connection_context> socks_connect(network_zone&, epee::net_utils::network_address const&, epee::net_utils::ssl_support_t);
+ static boost::optional<p2p_connection_context> sam_connect(network_zone&, const epee::net_utils::network_address&, epee::net_utils::ssl_support_t);
/* A `std::map` provides constant iterators and key/value pointers even with
@@ -505,6 +546,7 @@ namespace nodetool
extern const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_add_exclusive_node;
extern const command_line::arg_descriptor<std::vector<std::string> > arg_p2p_seed_node;
extern const command_line::arg_descriptor<std::vector<std::string> > arg_tx_proxy;
+ extern const command_line::arg_descriptor<std::string> arg_i2p_sam;
extern const command_line::arg_descriptor<std::vector<std::string> > arg_anonymous_inbound;
extern const command_line::arg_descriptor<std::string> arg_ban_list;
extern const command_line::arg_descriptor<bool> arg_p2p_hide_my_port;
### src/p2p/net_node.inl
@@ -208,6 +208,7 @@ namespace nodetool
command_line::add_arg(desc, arg_p2p_add_exclusive_node);
command_line::add_arg(desc, arg_p2p_seed_node);
command_line::add_arg(desc, arg_tx_proxy);
+ command_line::add_arg(desc, arg_i2p_sam);
command_line::add_arg(desc, arg_anonymous_inbound);
command_line::add_arg(desc, arg_ban_list);
command_line::add_arg(desc, arg_p2p_hide_my_port);
@@ -717,12 +718,152 @@ namespace nodetool
epee::byte_slice noise = nullptr;
+
+ bool sam_outbound_disabled = false;
+ bool use_i2p_sam = command_line::has_arg(vm, arg_i2p_sam) && !command_line::is_arg_defaulted(vm, arg_i2p_sam);
+ if (use_i2p_sam && m_offline)
+ {
+ MWARNING("running in offline mode; --" << arg_i2p_sam.name << " ignored");
+ use_i2p_sam = false;
+ }
+
+ if (use_i2p_sam)
+ {
+ auto sam_config = get_i2p_sam_config(vm);
+ if (!sam_config) return false;
+
+ sam_outbound_disabled = sam_config->max_out_connections == 0;
+
+ const auto sam_endpoint = net::get_tcp_endpoint(sam_config->endpoint);
+ CHECK_AND_ASSERT_MES(sam_endpoint, false, "Failed to parse I2P router endpoint: " << sam_config->endpoint << " - " << sam_endpoint.error().message());
+
+ network_zone& i2p_sam_zone = add_zone(epee::net_utils::zone::i2p);
+ i2p_sam_zone.m_connect = &sam_connect;
+ i2p_sam_zone.m_sam_router_endpoint = *sam_endpoint;
+ // Needed for the ban check and in-peer limit in `start_internal`. `init()` only sets these for zones with a bind address.
+ i2p_sam_zone.m_net_server.set_connection_filter(this);
+ i2p_sam_zone.m_net_server.set_connection_limit(this);
+
+ const std::string data_dir = command_line::get_arg(vm, cryptonote::arg_data_dir);
+
+ if (sam_config->max_in_connections != 0)
+ {
+ auto handler = [this](boost::system::error_code ec, boost::asio::ip::tcp::socket socket, net::i2p_address remote, std::string initial_data)
+ {
+ if (ec)
+ {
+ MWARNING("I2P SAM inbound session error: " << ec.message());
+ return;
+ }
+
+ if (!is_remote_host_allowed(remote) || is_host_limit(remote))
+ {
+ MDEBUG("Rejected I2P SAM connection from " << remote.str());
+ boost::system::error_code close_ec;
+ socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, close_ec);
+ socket.close(close_ec);
+ return;
+ }
+
+ p2p_connection_context context{};
+ network_zone& i2p_sam_zone = m_network_zones.at(epee::net_utils::zone::i2p);
+ if (!i2p_sam_zone.m_net_server.add_connection(context, std::move(socket), remote,
+ epee::net_utils::ssl_support_t::e_ssl_support_disabled,
+ std::move(initial_data), true))
+ {
+ MWARNING("Failed to add I2P SAM connection");
+ return;
+ }
+ MDEBUG("Added I2P SAM connection");
+ };
+
+ std::string private_key{};
+ CHECK_AND_ASSERT_MES(net::sam::private_key_from_file(data_dir, private_key), false, "Failed to load I2P destination key");
+
+ const std::string session_id = net::sam::random_session_id();
+
+ i2p_sam_zone.m_sam_control_socket = net::sam::make_control_client(
+ private_key,
+ data_dir,
+ net::sam::client::stream_type::socket{i2p_sam_zone.m_net_server.get_io_context()},
+ handler
+ );
+ i2p_sam_zone.m_sam_session_id = session_id;
+ i2p_sam_zone.m_sam_control_socket->set_session_id(session_id);
+
+ i2p_sam_zone.m_sam_control_socket->set_destination_handler(
+ [this](const net::i2p_address& local)
+ {
+ network_zone& i2p_sam_zone = m_network_zones.at(epee::net_utils::zone::i2p);
+
+ if (i2p_sam_zone.get_our_address().get_zone() != epee::net_utils::zone::i2p)
+ i2p_sam_zone.set_our_address(local);
+ MINFO("I2P SAM destination established: " << local.str());
+ });
+
+ MDEBUG("Attempting to start SAM control socket");
+
+ CHECK_AND_ASSERT_MES(
+ net::sam::control_socket::connect_and_send(i2p_sam_zone.m_sam_control_socket, i2p_sam_zone.m_sam_router_endpoint),
+ false, "Failed to init I2P SAM control socket");
+ }
+
+ if (sam_config->max_out_connections != 0)
+ {
+ auto outbound_handler = [](boost::system::error_code ec, boost::asio::ip::tcp::socket, net::i2p_address, std::string)
+ {
+ if (ec) MWARNING("I2P SAM outbound session error: " << ec.message());
+ };
+
+ const std::string outbound_session_id = net::sam::random_session_id();
+
+ i2p_sam_zone.m_sam_outbound_control_socket = net::sam::make_control_client(
+ std::string{}, // ignored; an outbound-only session always uses DESTINATION=TRANSIENT
+ std::string{}, // unused for an outbound-only session
+ net::sam::client::stream_type::socket{i2p_sam_zone.m_net_server.get_io_context()},
+ outbound_handler,
+ /*accept_inbound=*/false
+ );
+ i2p_sam_zone.m_sam_outbound_session_id = outbound_session_id;
+ i2p_sam_zone.m_sam_outbound_control_socket->set_session_id(outbound_session_id);
+
+ MDEBUG("Attempting to start outbound-only I2P SAM session");
+
+ CHECK_AND_ASSERT_MES(
+ net::sam::control_socket::connect_and_send(i2p_sam_zone.m_sam_outbound_control_socket, i2p_sam_zone.m_sam_router_endpoint),
+ false, "Failed to init outbound-only I2P SAM session");
+ }
+
+ noise = epee::levin::make_noise_notify(CRYPTONOTE_NOISE_BYTES);
+ i2p_sam_zone.m_notifier = cryptonote::levin::notify{
+ i2p_sam_zone.m_net_server.get_io_context(),
+ i2p_sam_zone.m_net_server.get_config_shared(),
+ noise.clone(),
+ epee::net_utils::zone::i2p,
+ true,
+ m_payload_handler.get_core()
+ };
+
+ if (!set_max_out_peers(i2p_sam_zone, sam_config->max_out_connections))
+ return false;
+ else
+ m_payload_handler.set_max_out_peers(epee::net_utils::zone::i2p, sam_config->max_out_connections); // same as the `--tx-proxy` path
+
+ if (!set_max_in_peers(i2p_sam_zone, sam_config->max_in_connections)) return false;
+ }
+
auto proxies = get_proxies(vm);
if (!proxies)
return false;
for (auto& proxy : *proxies)
{
+ if (use_i2p_sam && proxy.zone == epee::net_utils::zone::i2p)
+ {
+ MWARNING("Listed --" << arg_tx_proxy.name << " with " << epee::net_utils::zone_to_string(proxy.zone) << " but --" << arg_i2p_sam.name << " is set; ignoring it");
+ continue;
+ }
+
network_zone& zone = add_zone(proxy.zone);
if (zone.m_connect != nullptr)
{
@@ -754,20 +895,33 @@ namespace nodetool
for (const auto& zone : m_network_zones)
{
- if (zone.second.m_connect == nullptr)
+ if (!m_offline && zone.second.m_connect == nullptr)
{
- MERROR("Set outgoing peer for " << epee::net_utils::zone_to_string(zone.first) << " but did not set --" << arg_tx_proxy.name);
+ MERROR("Set outgoing peer for " << epee::net_utils::zone_to_string(zone.first) << " but did not set --" << arg_tx_proxy.name << " or --" << arg_i2p_sam.name);
return false;
}
}
+ if (sam_outbound_disabled && m_network_zones.size() <= 2)
+ {
+ MERROR("--" << arg_i2p_sam.name << " has outbound disabled (0) but no --" << arg_tx_proxy.name <<
+ " is set for another network; local txes would be silently dropped instead of relayed");
+ return false;
+ }
+
auto inbounds = get_anonymous_inbounds(vm);
if (!inbounds)
return false;
const std::size_t tx_relay_zones = m_network_zones.size();
for (auto& inbound : *inbounds)
{
+ if (use_i2p_sam && inbound.our_address.get_zone() == epee::net_utils::zone::i2p)
+ {
+ MWARNING("Listed --" << arg_anonymous_inbound.name << " with " << epee::net_utils::zone_to_string(inbound.our_address.get_zone()) << " but --" << arg_i2p_sam.name << " is set; ignoring it");
+ continue;
+ }
+
network_zone& zone = add_zone(inbound.our_address.get_zone());
if (!zone.m_bind_ip.empty())
@@ -785,7 +939,7 @@ namespace nodetool
zone.m_bind_ip = std::move(inbound.local_ip);
zone.m_port = std::move(inbound.local_port);
zone.m_net_server.set_default_remote(std::move(inbound.default_remote));
- zone.m_our_address = std::move(inbound.our_address);
+ zone.set_our_address(std::move(inbound.our_address));
if (!set_max_in_peers(zone, inbound.max_connections))
return false;
@@ -1553,7 +1707,7 @@ namespace nodetool
if (should_skip_connect_address(na, m_use_ipv6))
return false;
- if (zone.m_our_address == na)
+ if (zone.get_our_address() == na)
return false;
if (zone.m_current_number_of_out_peers == zone.m_config.m_net_config.max_out_connection_count) // out peers limit
@@ -1907,7 +2061,7 @@ namespace nodetool
peerid_to_string(candidate.id) << " " << candidate.adr.str() << ", pruning seed " << epee::string_tools::to_string_hex(candidate.pruning_seed) <<
" (stripe " << next_needed_pruning_stripe << " needed), in loop pass " << outer_loop_count);
- if (zone.m_our_address == candidate.adr)
+ if (zone.get_our_address() == candidate.adr)
// It's ourselves, obviously don't take that
continue;
@@ -2030,6 +2184,12 @@ namespace nodetool
bool one_succeeded = false;
for(auto& zone : m_network_zones)
{
+ if (zone.second.m_sam_outbound_control_socket && !zone.second.m_sam_outbound_control_socket->session_established())
+ {
+ MDEBUG("I2P SAM session not yet established; skipping connection attempts for now");
+ continue;
+ }
+
size_t start_conn_count = get_outgoing_connections_count(zone.second);
if(!zone.second.m_peerlist.get_white_peers_count() && !connect_to_seed(zone.first))
{
@@ -2658,7 +2818,7 @@ namespace nodetool
network_zone& zone = m_network_zones.at(zone_type);
//will add self to peerlist if in same zone as outgoing later in this function
- const bool outgoing_to_same_zone = !context.m_is_income && zone.m_our_address.get_zone() == zone_type;
+ const bool outgoing_to_same_zone = !context.m_is_income && zone.get_our_address().get_zone() == zone_type;
const uint32_t max_peerlist_size = P2P_DEFAULT_PEERS_IN_HANDSHAKE - (outgoing_to_same_zone ? 1 : 0);
std::vector<peerlist_entry> local_peerlist_new;
@@ -2677,7 +2837,7 @@ namespace nodetool
{
local_peerlist_new.insert(
local_peerlist_new.begin() + crypto::rand_range(std::size_t(0), local_peerlist_new.size()),
- peerlist_entry{zone.m_our_address, zone.m_config.m_peer_id, 0}
+ peerlist_entry{zone.get_our_address(), zone.m_config.m_peer_id, 0}
);
}
@@ -3083,6 +3243,14 @@ namespace nodetool
if (zone.second.m_connect == nullptr)
continue;
+ if (zone.second.m_connect == &sam_connect &&
+ (!zone.second.m_sam_outbound_control_socket ||
+ !zone.second.m_sam_outbound_control_socket->session_established()))
+ {
+ MDEBUG("I2P SAM outbound session unavailable; skipping gray peerlist housekeeping for now");
+ continue;
+ }
+
peerlist_entry pe{};
if (!zone.second.m_peerlist.get_random_gray_peer(pe))
continue;
@@ -3161,6 +3329,41 @@ namespace nodetool
return boost::none;
}
+ template<typename t_payload_net_handler>
+ boost::optional<p2p_connection_context_t<typename t_payload_net_handler::connection_context>>
+ node_server<t_payload_net_handler>::sam_connect(network_zone& zone, const epee::net_utils::network_address& remote, epee::net_utils::ssl_support_t ssl_support)
+ {
+ if (remote.get_type_id() != net::i2p_address::get_type_id())
+ return boost::none;
+
+ if (!zone.m_sam_outbound_control_socket || !zone.m_sam_outbound_control_socket->session_established())
+ {
+ MDEBUG("I2P SAM session not yet established, dropping connection to " << remote.str());
+ return boost::none;
+ }
+
+ const net::i2p_address& i2p_addr = remote.as<net::i2p_address>();
+ auto result = sam_connect_internal(zone.m_net_server.get_stop_signal(), zone.m_net_server.get_io_context(), zone.m_sam_router_endpoint, i2p_addr, zone.m_sam_outbound_session_id);
+
+ // The inbound session may have set our address while this connect was pending, after the pre-dial self-checks ran.
+ if (result && zone.get_our_address() == remote)
+ {
+ MDEBUG("Dropping I2P SAM connection to our own address " << remote.str());
+ boost::system::error_code ec;
+ result->first.close(ec);
+ return boost::none;
+ }
+
+ if (result) // if no error
+ {
+ p2p_connection_context context{};
+ if (zone.m_net_server.add_connection(context, std::move(result->first), remote, ssl_support, std::move(result->second)))
+ return {std::move(context)};
+ }
+ MWARNING("Failed to add I2P SAM connection");
+ return boost::none;
+ }
+
template<typename t_payload_net_handler>
boost::optional<p2p_connection_context_t<typename t_payload_net_handler::connection_context>>
node_server<t_payload_net_handler>::public_connect(network_zone& zone, epee::net_utils::network_address const& na, epee::net_utils::ssl_support_t ssl_support)
### tests/unit_tests/CMakeLists.txt
@@ -107,7 +107,8 @@ set(unit_tests_sources
aligned.cpp
rpc_version_str.cpp
x25519.cpp
- zmq_rpc.cpp)
+ zmq_rpc.cpp
+ i2p_sam.cpp)
set(unit_tests_headers
unit_tests_utils.h)
### tests/unit_tests/i2p_sam.cpp
@@ -0,0 +1,1424 @@
+// Copyright (c) 2026, The Monero Project
+//
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without modification, are
+// permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this list of
+// conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice, this list
+// of conditions and the following disclaimer in the documentation and/or other
+// materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its contributors may be
+// used to endorse or promote products derived from this software without specific
+// prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#include <gtest/gtest.h>
+#include <boost/asio.hpp>
+#include <boost/filesystem.hpp>
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <functional>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <utility>
+#include <vector>
+
+#include "net/i2p_sam.h"
+#include "string_coding.h"
+#include "file_io_utils.h"
+
+namespace
+{
+ using boost::asio::ip::tcp;
+
+ std::string encode_i2p_base64(const std::string& binary)
+ {
+ return net::sam::swap_base64(epee::string_encoding::base64_encode(binary));
+ }
+
+ std::string make_destination_bytes(std::uint16_t cert_len, unsigned char fill = 0x11)
+ {
+ std::string bytes(std::size_t{387} + cert_len, static_cast<char>(fill));
+ bytes[384] = static_cast<char>(cert_len ? 5 : 0); // KeyCertificate iff there's a payload
+ bytes[385] = static_cast<char>((cert_len >> 8) & 0xFF);
+ bytes[386] = static_cast<char>(cert_len & 0xFF);
+ return bytes;
+ }
+
+ struct fake_sam_router
+ {
+ enum class accept_response
+ {
+ peer_destination_then_raw_bytes,
+ peer_destination_split_then_raw_bytes,
+ peer_destination_and_raw_bytes_same_write,
+ stream_status_destination_and_raw_bytes_same_write,
+ late_stream_status_error,
+ peer_destination_line_too_long,
+ eof_before_peer_destination_line,
+ empty_peer_destination_line,
+ second_stream_status_ok,
+ peer_destination_with_ports,
+ };
+
+ boost::asio::io_context& io;
+ tcp::acceptor acceptor;
+
+ std::shared_ptr<tcp::socket> session_socket;
+ std::shared_ptr<tcp::socket> accept_socket;
+
+ std::string session_buffer;
+ std::string accept_buffer;
+
+ accept_response response;
+
+ //! Set when the client's `STREAM ACCEPT` arrives and when the scripted reply is written.
+ //! Tests assert both, to make sure they reached the case they cover.
+ bool stream_accept_seen = false;
+ bool accept_response_sent = false;
+
+ explicit fake_sam_router(
+ boost::asio::io_context& io_,
+ accept_response response_ = accept_response::peer_destination_then_raw_bytes
+ )
+ : io(io_)
+ , acceptor(
+ io_,
+ tcp::endpoint{boost::asio::ip::make_address("127.0.0.1"), 0}
+ )
+ , session_socket(std::make_shared<tcp::socket>(io_))
+ , accept_socket(std::make_shared<tcp::socket>(io_))
+ , response(response_)
+ {}
+
+ tcp::endpoint endpoint() const
+ {
+ return acceptor.local_endpoint();
+ }
+
+ template<typename Handler>
+ void read_line(
+ const std::shared_ptr<tcp::socket>& socket,
+ std::string& buffer,
+ Handler handler
+ )
+ {
+ boost::asio::async_read_until(
+ *socket,
+ boost::asio::dynamic_buffer(buffer),
+ '\n',
+ [socket, &buffer, handler = std::move(handler)]
+ (boost::system::error_code ec, std::size_t bytes) mutable
+ {
+ ASSERT_FALSE(ec) << ec.message();
+
+ std::string line = buffer.substr(0, bytes);
+ buffer.erase(0, bytes);
+
+ handler(std::move(line));
+ });
+ }
+
+ template<typename Handler>
+ void write(
+ const std::shared_ptr<tcp::socket>& socket,
+ std::string message,
+ Handler handler
+ )
+ {
+ auto data = std::make_shared<std::string>(std::move(message));
+
+ boost::asio::async_write(
+ *socket,
+ boost::asio::buffer(*data),
+ [socket, data, handler = std::move(handler)]
+ (boost::system::error_code ec, std::size_t) mutable
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ handler();
+ });
+ }
+
+ void write(
+ const std::shared_ptr<tcp::socket>& socket,
+ std::string message
+ )
+ {
+ auto data = std::make_shared<std::string>(std::move(message));
+
+ boost::asio::async_write(
+ *socket,
+ boost::asio::buffer(*data),
+ [socket, data](boost::system::error_code ec, std::size_t)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ });
+ }
+
+ void start()
+ {
+ accept_session_create_socket();
+ }
+
+ void accept_session_create_socket()
+ {
+ acceptor.async_accept(
+ *session_socket,
+ [this](boost::system::error_code ec)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+
+ // Client should send HELLO first.
+ read_line(
+ session_socket,
+ session_buffer,
+ [this](std::string hello)
+ {
+ EXPECT_EQ(hello, "HELLO VERSION MIN=3.1 MAX=3.1\n");
+
+ write(
+ session_socket,
+ "HELLO REPLY RESULT=OK VERSION=3.1\n",
+ [this]()
+ {
+ read_session_create();
+ });
+ });
+ });
+ }
+
+ void read_session_create()
+ {
+ read_line(
+ session_socket,
+ session_buffer,
+ [this](std::string session_create)
+ {
+ EXPECT_NE(
+ session_create.find("SESSION CREATE STYLE=STREAM ID=abcdefghij "),
+ std::string::npos
+ );
+
+ EXPECT_NE(
+ session_create.find("DESTINATION=FAKE_PRIVATE_KEY"),
+ std::string::npos
+ );
+
+ EXPECT_NE(
+ session_create.find("i2cp.leaseSetEncType=6,4"),
+ std::string::npos
+ );
+
+ // After SESSION CREATE succeeds, the client reconnects and opens the accept socket.
+ write(
+ session_socket,
+ "SESSION STATUS RESULT=OK DESTINATION=FAKE_PRIVATE_KEY\n",
+ [this]()
+ {
+ accept_stream_accept_socket();
+ });
+ });
+ }
+
+ void accept_stream_accept_socket()
+ {
+ acceptor.async_accept(
+ *accept_socket,
+ [this](boost::system::error_code ec)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+
+ // New socket also starts with HELLO.
+ read_line(
+ accept_socket,
+ accept_buffer,
+ [this](std::string hello)
+ {
+ EXPECT_EQ(hello, "HELLO VERSION MIN=3.1 MAX=3.1\n");
+
+ write(
+ accept_socket,
+ "HELLO REPLY RESULT=OK VERSION=3.1\n",
+ [this]()
+ {
+ read_stream_accept();
+ });
+ });
+ });
+ }
+
+ void read_stream_accept()
+ {
+ read_line(
+ accept_socket,
+ accept_buffer,
+ [this](std::string stream_accept)
+ {
+ EXPECT_EQ(stream_accept, "STREAM ACCEPT ID=abcdefghij SILENT=false\n");
+ stream_accept_seen = (stream_accept == "STREAM ACCEPT ID=abcdefghij SILENT=false\n");
+
+ if (response == accept_response::stream_status_destination_and_raw_bytes_same_write)
+ {
+ accept_response_sent = true;
+ // Combine the STREAM STATUS line, destination line, and raw P2P bytes into a
+ // single write, so they can arrive in the same underlying socket read. This is
+ // the over-read the byte-at-a-time destination reader cannot protect against,
+ // since it happens while parsing the STREAM STATUS line itself.
+ write(
+ accept_socket,
+ "STREAM STATUS RESULT=OK\nPEER_BASE64_DESTINATION\nraw-peer-bytes-without-newline"
+ );
+ return;
+ }
+
+ // First SAM status response: accept command is now pending.
+ write(
+ accept_socket,
+ "STREAM STATUS RESULT=OK\n",
+ [this]()
+ {
+ write_accept_response();
+ });
+ });
+ }
+
+ void write_accept_response()
+ {
+ accept_response_sent = true;
+ switch (response)
+ {
+ case accept_response::peer_destination_then_raw_bytes:
+ // Second line per SAMv3 spec with SILENT=false:
+ // peer public destination line, then raw stream bytes.
+ //
+ // This line should be consumed by the SAM layer.
+ write(
+ accept_socket,
+ "PEER_BASE64_DESTINATION\n",
+ [this]()
+ {
+ // These bytes should NOT be consumed by the SAM parser.
+ // No newline on purpose. A buggy read_until('\n') can hang or
+ // overread/corrupt data.
+ write(accept_socket, "raw-peer-bytes-without-newline");
+ });
+ return;
+
+ case accept_response::peer_destination_split_then_raw_bytes:
+ write(
+ accept_socket,
+ "PEER_",
+ [this]()
+ {
+ write(
+ accept_socket,
+ "BASE64_",
+ [this]()
+ {
+ write(
+ accept_socket,
+ "DESTINATION\n",
+ [this]()
+ {
+ write(accept_socket, "raw-peer-bytes-without-newline");
+ });
+ });
+ });
+ return;
+
+ case accept_response::peer_destination_and_raw_bytes_same_write:
+ write(
+ accept_socket,
+ "PEER_BASE64_DESTINATION\nraw-peer-bytes-without-newline"
+ );
+ return;
+
+ case accept_response::late_stream_status_error:
+ write(
+ accept_socket,
+ "STREAM STATUS RESULT=I2P_ERROR MESSAGE=router-restarted\n"
+ );
+ return;
+
+ case accept_response::peer_destination_line_too_long:
+ write(accept_socket, std::string(4096, 'A') + "\n");
+ return;
+
+ case accept_response::eof_before_peer_destination_line:
+ {
+ boost::system::error_code ignored;
+ accept_socket->shutdown(tcp::socket::shutdown_both, ignored);
+ accept_socket->close(ignored);
+ return;
+ }
+
+ case accept_response::empty_peer_destination_line:
+ write(accept_socket, "\n");
+ return;
+
+ case accept_response::second_stream_status_ok:
+ write(accept_socket, "STREAM STATUS RESULT=OK\n");
+ return;
+
+ case accept_response::peer_destination_with_ports:
+ write(accept_socket, "PEER_BASE64_DESTINATION FROM_PORT=1 TO_PORT=2\n");
+ return;
+
+ case accept_response::stream_status_destination_and_raw_bytes_same_write:
+ return;
+ }
+ }
+ };
+
+ // TCP gives no message-boundary guarantee, so the raw peer bytes may have already been
+ // pulled into `handed_off_data` by the SAM parser's over-read instead of sitting on the
+ // socket. Combine both, and bound the socket read so a coalesced write can't hang the test.
+ void expect_handed_off_raw_peer_bytes(
+ tcp::socket& socket, const std::string& handed_off_data,
+ const std::string& expected = "raw-peer-bytes-without-newline")
+ {
+ ASSERT_TRUE(socket.is_open());
+ ASSERT_LE(handed_off_data.size(), expected.size());
+
+ std::string received = handed_off_data;
+ boost::system::error_code non_blocking_ec;
+ socket.non_blocking(true, non_blocking_ec);
+ ASSERT_FALSE(non_blocking_ec) << non_blocking_ec.message();
+
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds{3};
+ std::array<char, 64> buffer{};
+ while (received.size() < expected.size() && std::chrono::steady_clock::now() < deadline)
+ {
+ boost::system::error_code read_ec;
+ const std::size_t n = socket.read_some(boost::asio::buffer(buffer), read_ec);
+ if (!read_ec)
+ received.append(buffer.data(), n);
+ else if (read_ec == boost::asio::error::would_block || read_ec == boost::asio::error::try_again)
+ std::this_thread::sleep_for(std::chrono::milliseconds{10});
+ else
+ ASSERT_FALSE(read_ec) << read_ec.message();
+ }
+
+ EXPECT_EQ(received, expected);
+ }
+
+ template<typename Verify>
+ void run_control_socket_accept(
+ fake_sam_router::accept_response response,
+ Verify verify
+ )
+ {
+ boost::asio::io_context io;
+
+ fake_sam_router router{io, response};
+
+ bool handler_called = false;
+ boost::system::error_code handler_ec;
+ tcp::socket handed_off_socket{io};
+ std::string handed_off_data;
+
+ auto client = net::sam::make_control_client(
+ "FAKE_PRIVATE_KEY",
+ "",
+ tcp::socket{io},
+ [&](boost::system::error_code ec, tcp::socket socket, net::i2p_address, std::string leftover)
+ {
+ handler_called = true;
+ handler_ec = ec;
+ handed_off_socket = std::move(socket);
+ handed_off_data = std::move(leftover);
+ io.stop();
+ });
+
+ client->set_session_id("abcdefghij");
+
+ router.start();
+
+ ASSERT_TRUE(
+ net::sam::control_socket::connect_and_send(client, router.endpoint())
+ );
+
+ boost::asio::steady_timer deadline{io};
+ deadline.expires_after(std::chrono::seconds{3});
+ deadline.async_wait(
+ [&](boost::system::error_code ec)
+ {
+ if (!ec)
+ io.stop();
+ });
+
+ io.run();
+
+ EXPECT_TRUE(router.stream_accept_seen);
+ EXPECT_TRUE(router.accept_response_sent);
+ verify(handler_called, handler_ec, handed_off_socket, handed_off_data);
+ }
+
+ constexpr const char fake_b32_dest[] = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrst.b32.i2p";
+
+ struct fake_connect_router
+ {
+ boost::asio::io_context& io;
+ tcp::acceptor acceptor;
+ std::shared_ptr<tcp::socket> socket;
+ std::string buffer;
+
+ explicit fake_connect_router(boost::asio::io_context& io_)
+ : io(io_)
+ , acceptor(io_, tcp::endpoint{boost::asio::ip::make_address("127.0.0.1"), 0})
+ , socket(std::make_shared<tcp::socket>(io_))
+ {}
+
+ tcp::endpoint endpoint() const { return acceptor.local_endpoint(); }
+
+ template<typename Handler>
+ void read_line(Handler handler)
+ {
+ boost::asio::async_read_until(
+ *socket, boost::asio::dynamic_buffer(buffer), '\n',
+ [this, handler = std::move(handler)](boost::system::error_code ec, std::size_t bytes) mutable
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ std::string line = buffer.substr(0, bytes);
+ buffer.erase(0, bytes);
+ handler(std::move(line));
+ });
+ }
+
+ void write(std::string message)
+ {
+ auto data = std::make_shared<std::string>(std::move(message));
+ boost::asio::async_write(
+ *socket, boost::asio::buffer(*data),
+ [socket = socket, data](boost::system::error_code ec, std::size_t) { ASSERT_FALSE(ec) << ec.message(); });
+ }
+
+ void start()
+ {
+ acceptor.async_accept(*socket, [this](boost::system::error_code ec)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ read_line([this](std::string hello)
+ {
+ EXPECT_EQ(hello, "HELLO VERSION MIN=3.1 MAX=3.1\n");
+ write("HELLO REPLY RESULT=OK VERSION=3.1\n");
+ read_line([this](std::string stream_connect)
+ {
+ EXPECT_EQ(stream_connect, std::string("STREAM CONNECT ID=abcdefghij DESTINATION=") + fake_b32_dest + " SILENT=false\n");
+ write("STREAM STATUS RESULT=OK\nhello-from-peer");
+ });
+ });
+ });
+ }
+ };
+}
+
+TEST(i2p_sam, control_socket_accept_hands_off_after_peer_destination_line)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::peer_destination_then_raw_bytes,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket& handed_off_socket, const std::string& handed_off_data)
+ {
+ ASSERT_TRUE(handler_called);
+ ASSERT_FALSE(handler_ec) << handler_ec.message();
+ expect_handed_off_raw_peer_bytes(handed_off_socket, handed_off_data);
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_reports_late_stream_status_error)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::late_stream_status_error,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_EQ(handler_ec, net::sam::make_error_code(net::sam::error::i2p_error));
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_handles_split_peer_destination_line)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::peer_destination_split_then_raw_bytes,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket& handed_off_socket, const std::string& handed_off_data)
+ {
+ ASSERT_TRUE(handler_called);
+ ASSERT_FALSE(handler_ec) << handler_ec.message();
+ expect_handed_off_raw_peer_bytes(handed_off_socket, handed_off_data);
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_leaves_same_write_raw_peer_bytes_unread)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::peer_destination_and_raw_bytes_same_write,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket& handed_off_socket, const std::string& handed_off_data)
+ {
+ ASSERT_TRUE(handler_called);
+ ASSERT_FALSE(handler_ec) << handler_ec.message();
+ expect_handed_off_raw_peer_bytes(handed_off_socket, handed_off_data);
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_rejects_too_long_peer_destination_line)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::peer_destination_line_too_long,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_EQ(handler_ec, net::sam::make_error_code(net::sam::error::parse_failed));
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_reports_eof_before_peer_destination_line)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::eof_before_peer_destination_line,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_TRUE(handler_ec);
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_rejects_empty_peer_destination_line)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::empty_peer_destination_line,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_EQ(handler_ec, net::sam::make_error_code(net::sam::error::parse_failed));
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_rejects_second_stream_status_ok)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::second_stream_status_ok,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_TRUE(handler_ec);
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_rejects_peer_destination_with_sam32_ports)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::peer_destination_with_ports,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket&, const std::string&)
+ {
+ ASSERT_TRUE(handler_called);
+ EXPECT_EQ(handler_ec, net::sam::make_error_code(net::sam::error::parse_failed));
+ });
+}
+
+TEST(i2p_sam, control_socket_accept_hands_off_buffered_data_when_status_and_destination_arrive_together)
+{
+ run_control_socket_accept(
+ fake_sam_router::accept_response::stream_status_destination_and_raw_bytes_same_write,
+ [](bool handler_called, boost::system::error_code handler_ec, tcp::socket& handed_off_socket, const std::string& handed_off_data)
+ {
+ ASSERT_TRUE(handler_called);
+ ASSERT_FALSE(handler_ec) << handler_ec.message();
+ expect_handed_off_raw_peer_bytes(handed_off_socket, handed_off_data);
+ });
+}
+
+TEST(i2p_sam, control_socket_outbound_only_uses_transient_destination_and_never_accepts)
+{
+ boost::asio::io_context io;
+ tcp::acceptor acceptor{io, tcp::endpoint{boost::asio::ip::make_address("127.0.0.1"), 0}};
+ auto first_socket = std::make_shared<tcp::socket>(io);
+ auto second_socket = std::make_shared<tcp::socket>(io);
+ std::string buffer;
+ bool second_connection_seen = false;
+ bool handler_called = false;
+
+ auto client = net::sam::make_control_client(
+ "unused-private-key",
+ "unused-data-dir",
+ tcp::socket{io},
+ [&](boost::system::error_code, tcp::socket, net::i2p_address, std::string)
+ {
+ handler_called = true;
+ },
+ /*accept_inbound=*/false
+ );
+ client->set_session_id("outbound01");
+
+ acceptor.async_accept(*first_socket, [&](boost::system::error_code ec)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+
+ boost::asio::async_read_until(*first_socket, boost::asio::dynamic_buffer(buffer), '\n',
+ [&](boost::system::error_code ec, std::size_t bytes)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ const std::string hello = buffer.substr(0, bytes);
+ buffer.erase(0, bytes);
+ EXPECT_EQ(hello, "HELLO VERSION MIN=3.1 MAX=3.1\n");
+
+ static const std::string hello_reply = "HELLO REPLY RESULT=OK VERSION=3.1\n";
+ boost::asio::async_write(*first_socket, boost::asio::buffer(hello_reply),
+ [&](boost::system::error_code ec, std::size_t)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+
+ // If `DEST GENERATE` were sent first (as the persistent/inbound session does when
+ // it has no key yet), this line would be that instead of `SESSION CREATE`.
+ boost::asio::async_read_until(*first_socket, boost::asio::dynamic_buffer(buffer), '\n',
+ [&](boost::system::error_code ec, std::size_t bytes)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ const std::string session_create = buffer.substr(0, bytes);
+ buffer.erase(0, bytes);
+
+ EXPECT_NE(session_create.find("SESSION CREATE STYLE=STREAM ID=outbound01 "), std::string::npos);
+ EXPECT_NE(session_create.find("DESTINATION=TRANSIENT"), std::string::npos);
+ EXPECT_NE(session_create.find("SIGNATURE_TYPE=7"), std::string::npos);
+
+ static const std::string status = "SESSION STATUS RESULT=OK DESTINATION=FAKE\n";
+ boost::asio::async_write(*first_socket, boost::asio::buffer(status),
+ [&](boost::system::error_code ec, std::size_t)
+ {
+ ASSERT_FALSE(ec) << ec.message();
+ // An outbound-only session should never reconnect toward `STREAM ACCEPT`.
+ acceptor.async_accept(*second_socket, [&](boost::system::error_code ec)
+ {
+ if (!ec) second_connection_seen = true;
+ });
+ });
+ });
+ });
+ });
+ });
+
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, acceptor.local_endpoint()));
+
+ boost::asio::steady_timer deadline{io};
+ deadline.expires_after(std::chrono::milliseconds{300});
+ deadline.async_wait([&](boost::system::error_code ec) { if (!ec) io.stop(); });
+
+ io.run();
+
+ EXPECT_FALSE(handler_called);
+ EXPECT_FALSE(second_connection_seen);
+ EXPECT_TRUE(client->session_established());
+}
+
+TEST(i2p_sam, get_value_ok)
+{
+ const std::string message = "HELLO REPLY RESULT=OK VERSION=3.1";
+ std::string out{};
+ auto ec = net::sam::get_value(message, "RESULT", out);
+ EXPECT_FALSE(ec);
+ EXPECT_EQ(out, "OK");
+
+ const std::string message2 = "HELLO REPLY RESULT=OK VERSION=3.1\n";
+ std::string out2{};
+ auto ec2 = net::sam::get_value(message2, "RESULT", out2);
+ EXPECT_FALSE(ec2);
+ EXPECT_EQ(out2, "OK");
+
+ const std::string message3 = "NAMING REPLY NAME=foobar\r\n";
+ std::string out3{};
+ auto ec3 = net::sam::get_value(message3, "NAME", out3);
+ EXPECT_FALSE(ec3);
+ EXPECT_EQ(out3, "foobar");
+}
+
+TEST(i2p_sam, get_value_error)
+{
+ // Nonexistent key
+ const std::string message = "HELLO REPLY RESULT=OK VERSION=3.1";
+ std::string out{};
+ auto ec = net::sam::get_value(message, "NAME", out);
+ EXPECT_TRUE(ec);
+
+ // Nonexistent value
+ const std::string message2 = "HELLO REPLY RESULT=OK VERSION=3.1";
+ std::string out2{};
+ auto ec2 = net::sam::get_value(message2, "HELLO", out2);
+ EXPECT_TRUE(ec2);
+}
+
+TEST(i2p_sam, get_value_at_start_of_line)
+{
+ std::string out;
+ auto ec = net::sam::get_value("RESULT=OK", "RESULT", out);
+
+ EXPECT_FALSE(ec);
+ EXPECT_EQ(out, "OK");
+}
+
+TEST(i2p_sam, get_value_after_space)
+{
+ std::string out;
+ auto ec = net::sam::get_value("FOO RESULT=OKAY", "RESULT", out);
+
+ EXPECT_FALSE(ec);
+ EXPECT_EQ(out, "OKAY");
+}
+
+TEST(i2p_sam, get_value_empty_value)
+{
+ std::string out = "unchanged";
+ auto ec = net::sam::get_value("RESULT=", "RESULT", out);
+
+ EXPECT_FALSE(ec);
+ EXPECT_EQ(out, "");
+}
+
+TEST(i2p_sam, get_value_does_not_match_key_inside_value)
+{
+ std::string out;
+ auto ec = net::sam::get_value("MESSAGE=BAD_RESULT=OK", "RESULT", out);
+
+ EXPECT_TRUE(ec);
+ EXPECT_EQ(ec, net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, sanitize_private_key_strips_surrounding_whitespace)
+{
+ EXPECT_EQ(net::sam::sanitize_private_key("abc123\n"), "abc123");
+ EXPECT_EQ(net::sam::sanitize_private_key("abc123\r\n"), "abc123");
+ EXPECT_EQ(net::sam::sanitize_private_key(" abc123\t"), "abc123");
+ EXPECT_EQ(net::sam::sanitize_private_key("\n\r abc1 23 \r\n"), "abc123");
+}
+
+TEST(i2p_sam, sanitize_private_key_strips_interior_whitespace)
+{
+ EXPECT_EQ(net::sam::sanitize_private_key("abc\n123\ndef"), "abc123def");
+ EXPECT_EQ(net::sam::sanitize_private_key("abc 123\tdef"), "abc123def");
+}
+
+TEST(i2p_sam, sanitize_private_key_unchanged_and_empty)
+{
+ EXPECT_EQ(net::sam::sanitize_private_key("abc123"), "abc123");
+ EXPECT_EQ(net::sam::sanitize_private_key(""), "");
+ EXPECT_EQ(net::sam::sanitize_private_key(" \r \n\t"), "");
+}
+
+TEST(i2p_sam, parse_result_code)
+{
+ EXPECT_FALSE(net::sam::parse_result_code("RESULT=OK"));
+
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=I2P_ERROR"), net::sam::make_error_code(net::sam::error::i2p_error));
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=TIMEOUT"), net::sam::make_error_code(net::sam::error::timeout));
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=NOVERSION"), net::sam::make_error_code(net::sam::error::noversion));
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=DUPLICATED_ID"), net::sam::make_error_code(net::sam::error::duplicated_id));
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=ALREADY_ACCEPTING"), net::sam::make_error_code(net::sam::error::already_accepting));
+
+ EXPECT_EQ(net::sam::parse_result_code("RESULT=AAAAAA121212"), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_EQ(net::sam::parse_result_code("HELLO REPLY VERSION=3.1"), net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, parse_hello_reply)
+{
+ EXPECT_FALSE(net::sam::parse_hello_reply("HELLO REPLY RESULT=OK VERSION=3.1"));
+
+ EXPECT_EQ(net::sam::parse_hello_reply("STREAM STATUS RESULT=OK"), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_EQ(net::sam::parse_hello_reply("RESULT=OK"), net::sam::make_error_code(net::sam::error::parse_failed));
+
+ EXPECT_EQ(net::sam::parse_hello_reply("HELLO REPLYX RESULT=OK"), net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, parse_session_status)
+{
+ std::string destination;
+ EXPECT_FALSE(net::sam::parse_session_status("SESSION STATUS RESULT=OK DESTINATION=abc", destination));
+ EXPECT_EQ(destination, "abc");
+
+ std::string ignored;
+ EXPECT_EQ(net::sam::parse_session_status("SESSION STATUS RESULT=I2P_ERROR DESTINATION=abc", ignored), net::sam::make_error_code(net::sam::error::i2p_error));
+
+ EXPECT_EQ(net::sam::parse_session_status("HELLO REPLY RESULT=OK", ignored), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_EQ(net::sam::parse_session_status("SESSION STATUSX RESULT=OK DESTINATION=abc", ignored), net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, parse_stream_status)
+{
+ EXPECT_FALSE(net::sam::parse_stream_status("STREAM STATUS RESULT=OK"));
+
+ EXPECT_EQ(net::sam::parse_stream_status("STREAM STATUS RESULT=CANT_REACH_PEER"), net::sam::make_error_code(net::sam::error::cant_reach_peer));
+
+ EXPECT_EQ(net::sam::parse_stream_status("SESSION STATUS RESULT=OK"), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_EQ(net::sam::parse_stream_status("STREAM STATUSX RESULT=OK"), net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, parse_dest_reply)
+{
+ std::string priv;
+ EXPECT_FALSE(net::sam::parse_dest_reply("DEST REPLY PUB=abc PRIV=def", priv));
+ EXPECT_EQ(priv, "def");
+
+ std::string priv_empty;
+ EXPECT_EQ(net::sam::parse_dest_reply("DEST REPLY PUB=abc PRIV=", priv_empty), net::sam::make_error_code(net::sam::error::parse_failed));
+
+ std::string priv_err;
+ EXPECT_EQ(net::sam::parse_dest_reply("DEST REPLY RESULT=I2P_ERROR MESSAGE=foo", priv_err), net::sam::make_error_code(net::sam::error::i2p_error));
+
+ // `RESULT=OK` without a usable key is not success.
+ std::string priv_ok_missing;
+ EXPECT_EQ(net::sam::parse_dest_reply("DEST REPLY PUB=abc RESULT=OK", priv_ok_missing), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_TRUE(priv_ok_missing.empty());
+
+ std::string priv_ok_empty;
+ EXPECT_EQ(net::sam::parse_dest_reply("DEST REPLY PUB=abc PRIV= RESULT=OK", priv_ok_empty), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_TRUE(priv_ok_empty.empty());
+
+ std::string priv_wrong;
+ EXPECT_EQ(net::sam::parse_dest_reply("HELLO REPLY RESULT=OK", priv_wrong), net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_EQ(net::sam::parse_dest_reply("DEST REPLYX PUB=abc PRIV=def", priv_wrong), net::sam::make_error_code(net::sam::error::parse_failed));
+}
+
+TEST(i2p_sam, random_session_id)
+{
+ const std::string id = net::sam::random_session_id();
+ EXPECT_TRUE(id.length() == 10);
+ EXPECT_FALSE(id.empty());
+}
+
+TEST(i2p_sam, get_value_duplicate_key_returns_first_value)
+{
+ std::string out;
+ auto ec = net::sam::get_value("RESULT=OK RESULT=I2P_ERROR", "RESULT", out);
+
+ EXPECT_FALSE(ec);
+ EXPECT_EQ(out, "OK");
+}
+
+TEST(i2p_sam, destination_to_address_rejects_empty_input)
+{
+ EXPECT_TRUE(net::sam::destination_to_address("").is_unknown());
+}
+
+TEST(i2p_sam, destination_to_address_is_deterministic_and_content_dependent)
+{
+ const std::string dest_a = make_destination_bytes(0, 0x11);
+ const std::string dest_b = make_destination_bytes(0, 0x22);
+
+ const auto addr_a1 = net::sam::destination_to_address(encode_i2p_base64(dest_a));
+ const auto addr_a2 = net::sam::destination_to_address(encode_i2p_base64(dest_a));
+ const auto addr_b = net::sam::destination_to_address(encode_i2p_base64(dest_b));
+
+ EXPECT_FALSE(addr_a1.is_unknown());
+ EXPECT_EQ(addr_a1, addr_a2);
+ EXPECT_NE(addr_a1, addr_b);
+}
+
+TEST(i2p_sam, session_destination_to_address_ignores_appended_private_keys)
+{
+ const std::string dest = make_destination_bytes(0);
+ const std::string private_keys(64, char(0x99));
+
+ const auto from_bare_dest = net::sam::destination_to_address(encode_i2p_base64(dest));
+ const auto from_private_destination =
+ net::sam::session_destination_to_address(encode_i2p_base64(dest + private_keys));
+
+ ASSERT_FALSE(from_bare_dest.is_unknown());
+ EXPECT_EQ(from_bare_dest, from_private_destination);
+
+ // Hashing the whole private destination (the prior bug) must give a different address.
+ const auto from_whole_blob = net::sam::destination_to_address(encode_i2p_base64(dest + private_keys));
+ EXPECT_NE(from_bare_dest, from_whole_blob);
+}
+
+TEST(i2p_sam, session_destination_to_address_respects_nonzero_certificate_length)
+{
+ const std::string dest = make_destination_bytes(4);
+ const std::string private_keys(96, char(0x77));
+
+ const auto from_bare_dest = net::sam::destination_to_address(encode_i2p_base64(dest));
+ const auto from_private_destination =
+ net::sam::session_destination_to_address(encode_i2p_base64(dest + private_keys));
+
+ ASSERT_FALSE(from_bare_dest.is_unknown());
+ EXPECT_EQ(from_bare_dest, from_private_destination);
+}
+
+TEST(i2p_sam, session_destination_to_address_rejects_too_short_input)
+{
+ EXPECT_TRUE(net::sam::session_destination_to_address(encode_i2p_base64(std::string(386, 'a'))).is_unknown());
+ EXPECT_FALSE(net::sam::session_destination_to_address(encode_i2p_base64(make_destination_bytes(0))).is_unknown());
+}
+
+TEST(i2p_sam, session_destination_to_address_rejects_certificate_length_past_end)
+{
+ std::string dest = make_destination_bytes(0);
+ dest[385] = char(0x27);
+ dest[386] = char(0x10); // Certificate claims 10000 bytes that are not actually present.
+
+ EXPECT_TRUE(net::sam::session_destination_to_address(encode_i2p_base64(dest)).is_unknown());
+}
+
+TEST(i2p_sam, connect_client_forwards_buffered_peer_bytes)
+{
+ boost::asio::io_context io;
+
+ fake_connect_router router{io};
+
+ bool handler_called = false;
+ boost::system::error_code handler_ec;
+ tcp::socket handed_off_socket{io};
+ std::string handed_off_data;
+
+ auto client = net::sam::make_connect_client(
+ tcp::socket{io},
+ [&](boost::system::error_code ec, tcp::socket socket, std::string leftover)
+ {
+ handler_called = true;
+ handler_ec = ec;
+ handed_off_socket = std::move(socket);
+ handed_off_data = std::move(leftover);
+ io.stop();
+ });
+
+ client->set_session_id("abcdefghij");
+
+ const auto address = net::i2p_address::make(fake_b32_dest);
+ ASSERT_TRUE(address);
+ ASSERT_TRUE(client->set_connect_command(*address));
+
+ router.start();
+
+ ASSERT_TRUE(net::sam::client::connect_and_send(client, router.endpoint()));
+
+ boost::asio::steady_timer deadline{io};
+ deadline.expires_after(std::chrono::seconds{3});
+ deadline.async_wait([&](boost::system::error_code ec) { if (!ec) io.stop(); });
+
+ io.run();
+
+ ASSERT_TRUE(handler_called);
+ ASSERT_FALSE(handler_ec) << handler_ec.message();
+ expect_handed_off_raw_peer_bytes(handed_off_socket, handed_off_data, "hello-from-peer");
+}
+
+TEST(i2p_sam, save_private_key_creates_file_with_owner_only_permissions)
+{
+ const boost::filesystem::path dir = boost::filesystem::temp_directory_path() /
+ boost::filesystem::unique_path("i2p_sam_test-%%%%-%%%%-%%%%-%%%%");
+ boost::filesystem::create_directories(dir);
+
+ ASSERT_TRUE(net::sam::save_private_key(dir.string(), "FAKE_PRIVATE_KEY"));
+
+ const boost::filesystem::path key_path = dir / "i2p_private_key";
+ boost::system::error_code ec;
+
+#ifndef _WIN32
+ const auto perms = boost::filesystem::status(key_path, ec).permissions();
+ ASSERT_FALSE(ec) << ec.message();
+
+ EXPECT_EQ(boost::filesystem::perms::owner_read | boost::filesystem::perms::owner_write,
+ perms & (boost::filesystem::perms::group_all | boost::filesystem::perms::others_all | boost::filesystem::perms::owner_all));
+#endif
+
+ std::string loaded;
+ ASSERT_TRUE(epee::file_io_utils::load_file_to_string(key_path.string(), loaded));
+ EXPECT_EQ("FAKE_PRIVATE_KEY", loaded);
+
+ boost::filesystem::remove_all(dir, ec);
+}
+
+namespace
+{
+ //! Fake SAM bridge for the reconnect and timeout tests. Records every line received; replies are scripted per test.
+ struct scripted_router
+ {
+ struct connection
+ {
+ explicit connection(boost::asio::io_context& io) : socket(io) {}
+ tcp::socket socket;
+ std::string buffer;
+ std::vector<std::string> lines;
+ };
+ using connection_ptr = std::shared_ptr<connection>;
+ using on_line_t = std::function<void(scripted_router&, const connection_ptr&, const std::string&)>;
+
+ boost::asio::io_context& io;
+ tcp::acceptor acceptor;
+ std::vector<connection_ptr> connections;
+ on_line_t on_line;
+ std::mutex* lock = nullptr; //!< set when tests read the router's state from another thread
+
+ scripted_router(boost::asio::io_context& io_, on_line_t on_line_)
+ : io(io_)
+ , acceptor(io_, tcp::endpoint{boost::asio::ip::make_address("127.0.0.1"), 0})
+ , on_line(std::move(on_line_))
+ {}
+
+ tcp::endpoint endpoint() const { return acceptor.local_endpoint(); }
+
+ void start() { accept_next(); }
+
+ void accept_next()
+ {
+ auto conn = std::make_shared<connection>(io);
+ acceptor.async_accept(conn->socket, [this, conn](boost::system::error_code ec)
+ {
+ if (ec) return;
+ {
+ std::unique_lock<std::mutex> guard;
+ if (lock) guard = std::unique_lock<std::mutex>{*lock};
+ connections.push_back(conn);
+ }
+ read_next(conn);
+ accept_next();
+ });
+ }
+
+ void read_next(const connection_ptr& conn)
+ {
+ boost::asio::async_read_until(conn->socket, boost::asio::dynamic_buffer(conn->buffer), '\n',
+ [this, conn](boost::system::error_code ec, std::size_t bytes)
+ {
+ if (ec) return; // the client closed or abandoned this connection
+ std::string line = conn->buffer.substr(0, bytes - 1);
+ conn->buffer.erase(0, bytes);
+ {
+ std::unique_lock<std::mutex> guard;
+ if (lock) guard = std::unique_lock<std::mutex>{*lock};
+ conn->lines.push_back(line);
+ }
+ on_line(*this, conn, line);
+ read_next(conn);
+ });
+ }
+
+ static void close(const connection_ptr& conn)
+ {
+ boost::system::error_code ignored;
+ conn->socket.shutdown(tcp::socket::shutdown_both, ignored);
+ conn->socket.close(ignored);
+ }
+
+ static void reply(const connection_ptr& conn, std::string message, bool close_after = false)
+ {
+ auto data = std::make_shared<std::string>(std::move(message));
+ boost::asio::async_write(conn->socket, boost::asio::buffer(*data),
+ [conn, data, close_after](boost::system::error_code, std::size_t)
+ {
+ if (close_after) close(conn);
+ });
+ }
+
+ //! Replies to `HELLO VERSION`. Returns false for any other line.
+ static bool answer_hello(const connection_ptr& conn, const std::string& line)
+ {
+ if (line.rfind("HELLO VERSION", 0) != 0) return false;
+ reply(conn, "HELLO REPLY RESULT=OK VERSION=3.1\n");
+ return true;
+ }
+
+ std::size_t count(const std::string& prefix) const
+ {
+ std::size_t n = 0;
+ for (const auto& conn : connections)
+ n += std::count_if(conn->lines.begin(), conn->lines.end(),
+ [&](const std::string& line) { return line.rfind(prefix, 0) == 0; });
+ return n;
+ }
+ };
+
+ constexpr std::chrono::milliseconds short_delay{20};
+
+ //! Runs `io` until `done()` is true or `limit` passes.
+ void run_until(boost::asio::io_context& io, const std::function<bool()>& done, std::chrono::milliseconds limit = std::chrono::seconds{5})
+ {
+ const auto end = std::chrono::steady_clock::now() + limit;
+ while (!done() && std::chrono::steady_clock::now() < end)
+ io.run_for(std::chrono::milliseconds{5});
+ }
+
+ void run_for(boost::asio::io_context& io, std::chrono::milliseconds duration)
+ {
+ run_until(io, []{ return false; }, duration);
+ }
+
+ struct handler_log
+ {
+ std::vector<boost::system::error_code> errors;
+ std::size_t calls = 0;
+ };
+
+ std::shared_ptr<net::sam::control_socket> make_test_control_client(
+ boost::asio::io_context& io, handler_log& log, std::string private_key = "FAKE_PRIVATE_KEY", std::string data_dir = "")
+ {
+ auto client = net::sam::make_control_client(
+ std::move(private_key), std::move(data_dir), tcp::socket{io},
+ [&log](boost::system::error_code ec, tcp::socket, net::i2p_address, std::string)
+ {
+ ++log.calls;
+ if (ec) log.errors.push_back(ec);
+ });
+ client->set_session_id("abcdefghij");
+ client->set_timeouts(std::chrono::seconds{2}, std::chrono::seconds{2});
+ client->set_reconnect_delay(short_delay);
+ return client;
+ }
+
+ boost::filesystem::path make_temp_dir()
+ {
+ const boost::filesystem::path dir = boost::filesystem::temp_directory_path() /
+ boost::filesystem::unique_path("i2p_sam_test-%%%%-%%%%-%%%%-%%%%");
+ boost::filesystem::create_directories(dir);
+ return dir;
+ }
+
+ void run_connect_until_timeout(scripted_router::on_line_t on_line, const std::string& expected_last_command)
+ {
+ boost::asio::io_context io;
+ scripted_router router{io, std::move(on_line)};
+ router.start();
+
+ bool called = false;
+ boost::system::error_code result;
+ auto client = net::sam::make_connect_client(tcp::socket{io},
+ [&](boost::system::error_code ec, tcp::socket, std::string)
+ {
+ called = true;
+ result = ec;
+ });
+ client->set_session_id("abcdefghij");
+ client->set_timeouts(short_delay * 5, short_delay * 5);
+
+ const auto address = net::i2p_address::make(fake_b32_dest);
+ ASSERT_TRUE(address);
+ ASSERT_TRUE(client->set_connect_command(*address));
+ ASSERT_TRUE(net::sam::client::connect_and_send(client, router.endpoint()));
+
+ run_until(io, [&]{ return called; });
+
+ ASSERT_TRUE(called);
+ EXPECT_EQ(result, net::sam::make_error_code(net::sam::error::timeout));
+ EXPECT_EQ(router.count(expected_last_command), 1u);
+ }
+}
+
+TEST(i2p_sam, connect_client_times_out_when_hello_reply_never_arrives)
+{
+ run_connect_until_timeout(
+ [](scripted_router&, const scripted_router::connection_ptr&, const std::string&) {},
+ "HELLO VERSION");
+}
+
+TEST(i2p_sam, connect_client_times_out_when_stream_status_never_arrives)
+{
+ run_connect_until_timeout(
+ [](scripted_router&, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ scripted_router::answer_hello(conn, line); // and never answer STREAM CONNECT
+ },
+ "STREAM CONNECT");
+}
+
+TEST(i2p_sam, control_socket_retries_accept_without_recreating_session)
+{
+ boost::asio::io_context io;
+ scripted_router router{io, [](scripted_router& r, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ if (scripted_router::answer_hello(conn, line)) return;
+ if (line.rfind("SESSION CREATE", 0) == 0)
+ scripted_router::reply(conn, "SESSION STATUS RESULT=OK DESTINATION=FAKE_PRIVATE_KEY\n");
+ else if (line.rfind("STREAM ACCEPT", 0) == 0)
+ scripted_router::reply(conn, r.count("STREAM ACCEPT") == 1 ? "STREAM STATUS RESULT=I2P_ERROR\n" : "STREAM STATUS RESULT=OK\n");
+ }};
+ router.start();
+
+ handler_log log;
+ auto client = make_test_control_client(io, log);
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, router.endpoint()));
+
+ run_until(io, [&]{ return router.count("STREAM ACCEPT") >= 2; });
+
+ EXPECT_EQ(router.count("STREAM ACCEPT"), 2u);
+ EXPECT_EQ(router.count("SESSION CREATE"), 1u); // the session survived the failed accept
+ ASSERT_EQ(log.errors.size(), 1u);
+ EXPECT_EQ(log.errors[0], net::sam::make_error_code(net::sam::error::i2p_error));
+ EXPECT_TRUE(client->session_established());
+}
+
+TEST(i2p_sam, control_socket_recreates_session_after_session_socket_drops)
+{
+ boost::asio::io_context io;
+ scripted_router router{io, [](scripted_router& r, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ if (scripted_router::answer_hello(conn, line)) return;
+ if (line.rfind("SESSION CREATE", 0) == 0)
+ {
+ EXPECT_NE(line.find("ID=abcdefghij "), std::string::npos);
+ scripted_router::reply(conn, "SESSION STATUS RESULT=OK DESTINATION=FAKE_PRIVATE_KEY\n");
+ }
+ else if (line.rfind("STREAM ACCEPT", 0) == 0)
+ {
+ scripted_router::reply(conn, "STREAM STATUS RESULT=OK\n");
+ if (r.count("STREAM ACCEPT") == 1)
+ {
+ // Simulate a router restart: drop the session while an accept is pending.
+ for (const auto& c : r.connections)
+ if (!c->lines.empty() && c->lines.back().rfind("SESSION CREATE", 0) == 0)
+ scripted_router::close(c);
+ }
+ }
+ }};
+ router.start();
+
+ handler_log log;
+ auto client = make_test_control_client(io, log);
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, router.endpoint()));
+
+ run_until(io, [&]{ return router.count("STREAM ACCEPT") >= 2; });
+
+ EXPECT_EQ(router.count("SESSION CREATE"), 2u);
+ EXPECT_EQ(router.count("STREAM ACCEPT"), 2u);
+ // The abandoned accept is stale and must not be reported as an error.
+ EXPECT_EQ(log.calls, 0u);
+ EXPECT_TRUE(client->session_established());
+}
+
+TEST(i2p_sam, control_socket_ignores_stale_connect_after_session_drops)
+{
+ // The router drops each session right after SESSION STATUS, while the client is connecting
+ // its accept socket. A connect that finishes just before the reconnect closes the socket must
+ // not write HELLO to it ("Bad file descriptor"). The router and client run on separate threads
+ // to let the session EOF and the connect completion arrive in either order.
+ boost::asio::io_context router_io;
+ std::mutex router_lock; // guards `router.connections` and their `lines`
+ scripted_router router{router_io, [&](scripted_router&, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ if (scripted_router::answer_hello(conn, line)) return;
+ if (line.rfind("SESSION CREATE", 0) == 0)
+ scripted_router::reply(conn, "SESSION STATUS RESULT=OK DESTINATION=FAKE_PRIVATE_KEY\n", /*close_after=*/true);
+ else if (line.rfind("STREAM ACCEPT", 0) == 0)
+ scripted_router::reply(conn, "STREAM STATUS RESULT=OK\n");
+ }};
+ router.lock = &router_lock;
+ router.start();
+ std::thread router_thread{[&]{ router_io.run(); }};
+
+ boost::asio::io_context io;
+ std::mutex log_lock;
+ std::vector<boost::system::error_code> errors;
+ auto client = net::sam::make_control_client("FAKE_PRIVATE_KEY", "", tcp::socket{io},
+ [&](boost::system::error_code ec, tcp::socket, net::i2p_address, std::string)
+ {
+ const std::lock_guard<std::mutex> guard{log_lock};
+ errors.push_back(ec);
+ });
+ client->set_session_id("abcdefghij");
+ client->set_reconnect_delay(std::chrono::milliseconds{1});
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, router.endpoint()));
+
+ auto work = boost::asio::make_work_guard(io);
+ std::vector<std::thread> client_threads;
+ for (int i = 0; i < 4; ++i)
+ client_threads.emplace_back([&]{ io.run(); });
+
+ constexpr std::size_t cycles = 200;
+ const auto end = std::chrono::steady_clock::now() + std::chrono::seconds{30};
+ while (std::chrono::steady_clock::now() < end)
+ {
+ {
+ const std::lock_guard<std::mutex> guard{router_lock};
+ if (router.count("SESSION CREATE") >= cycles) break;
+ }
+ std::this_thread::sleep_for(std::chrono::milliseconds{5});
+ }
+
+ net::sam::client::async_close{client}();
+ work.reset();
+ io.stop();
+ for (auto& thread : client_threads)
+ thread.join();
+ router_io.stop();
+ router_thread.join();
+
+ const std::lock_guard<std::mutex> guard{router_lock};
+ EXPECT_GE(router.count("SESSION CREATE"), cycles);
+ for (const auto& error : errors)
+ ADD_FAILURE() << "stale connect chain reported: " << error.message();
+ for (const auto& conn : router.connections)
+ if (!conn->lines.empty())
+ EXPECT_EQ(conn->lines.front().rfind("HELLO VERSION", 0), 0u);
+}
+
+TEST(i2p_sam, control_socket_stops_when_generated_key_cannot_be_saved)
+{
+ boost::asio::io_context io;
+ scripted_router router{io, [](scripted_router&, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ if (scripted_router::answer_hello(conn, line)) return;
+ if (line.rfind("DEST GENERATE", 0) == 0)
+ scripted_router::reply(conn, "DEST REPLY PUB=FAKE_PUBLIC_KEY PRIV=FAKE_PRIVATE_KEY\n");
+ }};
+ router.start();
+
+ const boost::filesystem::path dir = make_temp_dir();
+ handler_log log;
+ auto client = make_test_control_client(io, log, "", (dir / "missing").string()); // not creatable
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, router.endpoint()));
+
+ run_until(io, [&]{ return log.calls > 0; });
+ run_for(io, short_delay * 10); // several reconnect delays; no retry expected
+
+ EXPECT_EQ(router.count("DEST GENERATE"), 1u);
+ EXPECT_EQ(router.count("SESSION CREATE"), 0u);
+ ASSERT_EQ(log.errors.size(), 1u);
+ EXPECT_EQ(log.errors[0], net::sam::make_error_code(net::sam::error::i2p_error));
+ EXPECT_FALSE(client->session_established());
+
+ boost::system::error_code ec;
+ boost::filesystem::remove_all(dir, ec);
+}
+
+TEST(i2p_sam, control_socket_waits_before_retrying_dest_reply_without_key)
+{
+ // Regression test: `RESULT=OK` without `PRIV` was treated as success with an empty key,
+ // and the client resent `DEST GENERATE` in a tight loop.
+ boost::asio::io_context io;
+ scripted_router router{io, [](scripted_router&, const scripted_router::connection_ptr& conn, const std::string& line)
+ {
+ if (scripted_router::answer_hello(conn, line)) return;
+ if (line.rfind("DEST GENERATE", 0) == 0)
+ scripted_router::reply(conn, "DEST REPLY PUB=FAKE_PUBLIC_KEY RESULT=OK\n");
+ }};
+ router.start();
+
+ const boost::filesystem::path dir = make_temp_dir();
+ handler_log log;
+ auto client = make_test_control_client(io, log, "", dir.string());
+ client->set_reconnect_delay(std::chrono::milliseconds{200});
+ ASSERT_TRUE(net::sam::control_socket::connect_and_send(client, router.endpoint()));
+
+ run_for(io, std::chrono::milliseconds{300});
+
+ EXPECT_GE(router.count("DEST GENERATE"), 1u);
+ EXPECT_LE(router.count("DEST GENERATE"), 2u); // one per reconnect delay, not a tight loop
+ ASSERT_FALSE(log.errors.empty());
+ EXPECT_EQ(log.errors[0], net::sam::make_error_code(net::sam::error::parse_failed));
+ EXPECT_FALSE(boost::filesystem::exists(dir / "i2p_private_key"));
+
+ boost::system::error_code ec;
+ boost::filesystem::remove_all(dir, ec);
+}
### utils/fish/monerod.fish
@@ -68,6 +68,7 @@ complete -c monerod -l add-exclusive-node -r -d "Specify list of peers to connec
complete -c monerod -l seed-node -r -d "Connect to a node to retrieve peer addresses, and disconnect"
complete -c monerod -l tx-proxy -r -d "Send local txes through proxy: <network-type>,<socks-ip:port>[,max_connections][,disable_noise] i.e. \"tor,127.0.0.1:9050,100,disable_noise\""
complete -c monerod -l anonymous-inbound -r -d "<hidden-service-address>,<[bind-ip:]port>[,max_connections] i.e. \"x.onion,127.0.0.1:18083,100\""
+complete -c monerod -l i2p-sam -r -d "Use I2P router's SAM bridge for proxying network traffic: <router-ip:sam-port>[,max_out_connections[,max_in_connections]] i.e. \"127.0.0.1:7656,32,0\" (0 disables that direction)"
complete -c monerod -l ban-list -r -F -d "Specify ban list file, one IP address per line"
complete -c monerod -l hide-my-port -d "Do not announce yourself as peerlist candidate"
complete -c monerod -l no-sync -d "Don't synchronize the blockchain with other peers"Why this scored 31/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.