Back to Site
Loading...
Searching...
No Matches
librats::RatsClient Class Reference

RatsClient - Core peer-to-peer networking client. More...

#include <librats.h>

Inheritance diagram for librats::RatsClient:
[legend]
Collaboration diagram for librats::RatsClient:
[legend]

Public Types

using ConnectionCallback = std::function< void(socket_t, const std::string &)>
 
using BinaryDataCallback = std::function< void(socket_t, const std::string &, const std::vector< uint8_t > &)>
 
using StringDataCallback = std::function< void(socket_t, const std::string &, const std::string &)>
 
using JsonDataCallback = std::function< void(socket_t, const std::string &, const nlohmann::json &)>
 
using DisconnectCallback = std::function< void(socket_t, const std::string &)>
 
using MessageCallback = std::function< void(const std::string &, const nlohmann::json &)>
 
using SendCallback = std::function< void(bool, const std::string &)>
 
using TorrentCreationProgressCallback = std::function< void(uint32_t current_piece, uint32_t total_pieces)>
 Torrent creation progress callback type Called during piece hashing to report progress.
 
using SpiderAnnounceCallback = std::function< void(const std::string &info_hash, const std::string &peer_address)>
 Spider announce callback type Called when a peer announces they have a torrent (announce_peer request received)
 

Public Member Functions

 RatsClient (int listen_port, int max_peers=10, const std::string &bind_address="")
 Constructor.
 
 ~RatsClient ()
 Destructor.
 
bool start ()
 Start the RatsClient and begin listening for connections.
 
void stop ()
 Stop the RatsClient and close all connections.
 
void shutdown_all_threads ()
 Shutdown all background threads.
 
bool is_running () const
 Check if the client is currently running.
 
int get_listen_port () const
 
std::string get_bind_address () const
 Get the bind address being used.
 
bool connect_to_peer (const std::string &host, int port)
 Connect to a peer via direct TCP connection.
 
void disconnect_peer (socket_t socket)
 Disconnect from a specific peer.
 
void disconnect_peer_by_id (const std::string &peer_id)
 Disconnect from a peer by peer_id (preferred)
 
bool send_binary_to_peer (socket_t socket, const std::vector< uint8_t > &data, MessageDataType message_type=MessageDataType::BINARY)
 Send binary data to a specific peer (primary method)
 
bool send_string_to_peer (socket_t socket, const std::string &data)
 Send string data to a specific peer.
 
bool send_json_to_peer (socket_t socket, const nlohmann::json &data)
 Send JSON data to a specific peer.
 
bool send_binary_to_peer_id (const std::string &peer_id, const std::vector< uint8_t > &data, MessageDataType message_type=MessageDataType::BINARY)
 Send binary data to a peer by peer_id (preferred)
 
bool send_string_to_peer_id (const std::string &peer_id, const std::string &data)
 Send string data to a peer by peer_id (preferred)
 
bool send_json_to_peer_id (const std::string &peer_id, const nlohmann::json &data)
 Send JSON data to a peer by peer_id (preferred)
 
int broadcast_binary_to_peers (const std::vector< uint8_t > &data, MessageDataType message_type=MessageDataType::BINARY)
 Broadcast binary data to all connected peers (primary method)
 
int broadcast_string_to_peers (const std::string &data)
 Broadcast string data to all connected peers.
 
int broadcast_json_to_peers (const nlohmann::json &data)
 Broadcast JSON data to all connected peers.
 
int get_peer_count () const
 Get the number of currently connected peers.
 
std::string get_peer_id (socket_t socket) const
 Get peer_id for a peer by socket (preferred)
 
socket_t get_peer_socket_by_id (const std::string &peer_id) const
 Get socket for a peer by peer_id (preferred)
 
std::string get_our_peer_id () const
 Get our own peer ID.
 
std::vector< RatsPeerget_all_peers () const
 Get all connected peers.
 
std::vector< RatsPeerget_validated_peers () const
 Get all peers that have completed handshake.
 
const RatsPeerget_peer_by_id (const std::string &peer_id) const
 Get peer information by peer ID.
 
const RatsPeerget_peer_by_socket (socket_t socket) const
 Get peer information by socket.
 
int get_max_peers () const
 Get maximum number of peers.
 
void set_max_peers (int max_peers)
 Set maximum number of peers.
 
bool is_peer_limit_reached () const
 Check if peer limit has been reached.
 
void set_reconnect_enabled (bool enabled)
 Enable or disable automatic reconnection to disconnected peers.
 
bool is_reconnect_enabled () const
 Check if automatic reconnection is enabled.
 
void set_reconnect_config (const ReconnectConfig &config)
 Set reconnection configuration.
 
const ReconnectConfigget_reconnect_config () const
 Get current reconnection configuration.
 
size_t get_reconnect_queue_size () const
 Get the number of peers pending reconnection.
 
void clear_reconnect_queue ()
 Clear all pending reconnection attempts.
 
std::vector< ReconnectInfoget_reconnect_queue () const
 Get information about peers pending reconnection.
 
void set_connection_callback (ConnectionCallback callback)
 Set connection callback (called when a new peer connects)
 
void set_binary_data_callback (BinaryDataCallback callback)
 Set binary data callback (called when binary data is received)
 
void set_string_data_callback (StringDataCallback callback)
 Set string data callback (called when string data is received)
 
void set_json_data_callback (JsonDataCallback callback)
 Set JSON data callback (called when JSON data is received)
 
void set_disconnect_callback (DisconnectCallback callback)
 Set disconnect callback (called when a peer disconnects)
 
bool start_dht_discovery (int dht_port=6881)
 Start DHT discovery on specified port.
 
void stop_dht_discovery ()
 Stop DHT discovery.
 
bool find_peers_by_hash (const std::string &content_hash, std::function< void(const std::vector< std::string > &)> callback)
 Find peers by content hash using DHT.
 
bool announce_for_hash (const std::string &content_hash, uint16_t port=0, std::function< void(const std::vector< std::string > &)> callback=nullptr)
 Announce our presence for a content hash with optional peer discovery callback If callback is provided, peers discovered during DHT traversal will be returned through it.
 
bool is_dht_running () const
 Check if DHT is currently running.
 
size_t get_dht_routing_table_size () const
 Get the size of the DHT routing table.
 
bool start_mdns_discovery (const std::string &service_instance_name="", const std::map< std::string, std::string > &txt_records={})
 Start mDNS service discovery and announcement.
 
void stop_mdns_discovery ()
 Stop mDNS discovery.
 
bool is_mdns_running () const
 Check if mDNS is currently running.
 
void set_mdns_callback (std::function< void(const std::string &, int, const std::string &)> callback)
 Set mDNS service discovery callback.
 
std::vector< MdnsServiceget_mdns_services () const
 Get recently discovered mDNS services.
 
bool query_mdns_services ()
 Manually query for mDNS services.
 
void start_automatic_peer_discovery ()
 Start automatic peer discovery.
 
void stop_automatic_peer_discovery ()
 Stop automatic peer discovery.
 
bool is_automatic_discovery_running () const
 Check if automatic discovery is running.
 
std::chrono::seconds calculate_discovery_interval () const
 Calculate discovery interval based on current peer count Uses graduated scaling: more aggressive when fewer peers, less aggressive when nearly full.
 
std::string get_discovery_hash () const
 Get the discovery hash for current protocol configuration.
 
void add_ignored_address (const std::string &ip_address)
 Add an IP address to the ignore list (for blocking connections to self)
 
void set_protocol_name (const std::string &protocol_name)
 Set custom protocol name for handshakes and DHT discovery.
 
void set_protocol_version (const std::string &protocol_version)
 Set custom protocol version for handshakes.
 
std::string get_protocol_name () const
 Get current protocol name.
 
std::string get_protocol_version () const
 Get current protocol version.
 
void on (const std::string &message_type, MessageCallback callback)
 Register a persistent message handler.
 
void once (const std::string &message_type, MessageCallback callback)
 Register a one-time message handler.
 
void off (const std::string &message_type)
 Remove all handlers for a message type.
 
void send (const std::string &message_type, const nlohmann::json &data, SendCallback callback=nullptr)
 Send a message to all peers.
 
void send (const std::string &peer_id, const std::string &message_type, const nlohmann::json &data, SendCallback callback=nullptr)
 Send a message to a specific peer.
 
bool parse_json_message (const std::string &message, nlohmann::json &out_json)
 Parse a JSON message.
 
bool initialize_encryption (bool enable)
 Initialize encryption system.
 
void set_encryption_enabled (bool enabled)
 Set encryption enabled/disabled.
 
bool is_encryption_enabled () const
 Check if encryption is enabled.
 
bool is_peer_encrypted (const std::string &peer_id) const
 Check if a peer connection is encrypted.
 
bool set_noise_static_keypair (const uint8_t private_key[32])
 Set a custom static keypair for Noise Protocol If not set, a new keypair is generated automatically.
 
std::vector< uint8_t > get_noise_static_public_key () const
 Get our Noise Protocol static public key.
 
std::vector< uint8_t > get_peer_noise_public_key (const std::string &peer_id) const
 Get the remote peer's Noise static public key.
 
std::vector< uint8_t > get_peer_handshake_hash (const std::string &peer_id) const
 Get the handshake hash for a peer connection (for channel binding)
 
bool load_configuration ()
 Load configuration from files.
 
bool save_configuration ()
 Save configuration to files.
 
bool set_data_directory (const std::string &directory_path)
 Set directory where data files will be stored.
 
std::string get_data_directory () const
 Get current data directory path.
 
int load_and_reconnect_peers ()
 Load saved peers and attempt to reconnect.
 
bool load_historical_peers ()
 Load historical peers from a file.
 
bool save_historical_peers ()
 Save current peers to a historical file.
 
void clear_historical_peers ()
 Clear all historical peers.
 
std::vector< RatsPeerget_historical_peers () const
 Get all historical peers.
 
nlohmann::json get_connection_statistics () const
 Get connection statistics.
 
GossipSubget_gossipsub ()
 Get GossipSub instance for publish-subscribe messaging.
 
bool is_gossipsub_available () const
 Check if GossipSub is available.
 
bool subscribe_to_topic (const std::string &topic)
 Subscribe to a GossipSub topic.
 
bool unsubscribe_from_topic (const std::string &topic)
 Unsubscribe from a GossipSub topic.
 
bool is_subscribed_to_topic (const std::string &topic) const
 Check if subscribed to a GossipSub topic.
 
std::vector< std::string > get_subscribed_topics () const
 Get list of subscribed GossipSub topics.
 
bool publish_to_topic (const std::string &topic, const std::string &message)
 Publish a message to a GossipSub topic.
 
bool publish_json_to_topic (const std::string &topic, const nlohmann::json &message)
 Publish a JSON message to a GossipSub topic.
 
void on_topic_message (const std::string &topic, std::function< void(const std::string &, const std::string &, const std::string &)> callback)
 Set a message handler for a GossipSub topic using unified event API pattern.
 
void on_topic_json_message (const std::string &topic, std::function< void(const std::string &, const std::string &, const nlohmann::json &)> callback)
 Set a JSON message handler for a GossipSub topic using unified event API pattern.
 
void on_topic_peer_joined (const std::string &topic, std::function< void(const std::string &, const std::string &)> callback)
 Set a peer joined handler for a GossipSub topic using unified event API pattern.
 
void on_topic_peer_left (const std::string &topic, std::function< void(const std::string &, const std::string &)> callback)
 Set a peer left handler for a GossipSub topic using unified event API pattern

 
void set_topic_message_validator (const std::string &topic, std::function< ValidationResult(const std::string &, const std::string &, const std::string &)> validator)
 Set a message validator for a GossipSub topic.
 
void off_topic (const std::string &topic)
 Remove all event handlers for a GossipSub topic.
 
std::vector< std::string > get_topic_peers (const std::string &topic) const
 Get peers subscribed to a GossipSub topic.
 
std::vector< std::string > get_topic_mesh_peers (const std::string &topic) const
 Get mesh peers for a GossipSub topic.
 
nlohmann::json get_gossipsub_statistics () const
 Get GossipSub statistics.
 
bool is_gossipsub_running () const
 Check if GossipSub is running.
 
void set_console_logging_enabled (bool enabled)
 Enable or disable console logging When disabled, log messages will not be printed to stdout/stderr File logging (if enabled) will still work.
 
bool is_console_logging_enabled () const
 Check if console logging is currently enabled.
 
void set_logging_enabled (bool enabled)
 Enable or disable file logging When enabled, logs will be written to "rats.log" by default.
 
bool is_logging_enabled () const
 Check if file logging is currently enabled.
 
void set_log_file_path (const std::string &file_path)
 Set the log file path.
 
std::string get_log_file_path () const
 Get the current log file path.
 
void set_log_level (LogLevel level)
 Set the minimum log level.
 
void set_log_level (const std::string &level_str)
 Set the minimum log level using string.
 
LogLevel get_log_level () const
 Get the current log level.
 
void set_log_colors_enabled (bool enabled)
 Enable or disable colored log output.
 
bool is_log_colors_enabled () const
 Check if colored log output is enabled.
 
void set_log_timestamps_enabled (bool enabled)
 Enable or disable timestamps in log output.
 
bool is_log_timestamps_enabled () const
 Check if timestamps are enabled in log output.
 
void set_log_rotation_size (size_t max_size_bytes)
 Set log file rotation size.
 
void set_log_retention_count (int count)
 Set the number of log files to retain during rotation.
 
void set_log_rotate_on_startup (bool enabled)
 Enable or disable log rotation on application startup When enabled, the existing log file will be rotated when logging starts, so each application run gets a fresh log file.
 
bool is_log_rotate_on_startup_enabled () const
 Check if log rotation on startup is enabled.
 
void clear_log_file ()
 Clear/reset the current log file.
 
FileTransferManagerget_file_transfer_manager ()
 Get the file transfer manager instance.
 
bool is_file_transfer_available () const
 Check if file transfer is available.
 
std::string send_file (const std::string &peer_id, const std::string &file_path, const std::string &remote_filename="")
 Send a file to a peer.
 
std::string send_directory (const std::string &peer_id, const std::string &directory_path, const std::string &remote_directory_name="", bool recursive=true)
 Send an entire directory to a peer.
 
std::string request_file (const std::string &peer_id, const std::string &remote_file_path, const std::string &local_path)
 Request a file from a remote peer.
 
std::string request_directory (const std::string &peer_id, const std::string &remote_directory_path, const std::string &local_directory_path, bool recursive=true)
 Request a directory from a remote peer.
 
bool accept_file_transfer (const std::string &transfer_id, const std::string &local_path)
 Accept an incoming file transfer.
 
bool reject_file_transfer (const std::string &transfer_id, const std::string &reason="")
 Reject an incoming file transfer.
 
bool accept_directory_transfer (const std::string &transfer_id, const std::string &local_path)
 Accept an incoming directory transfer.
 
bool reject_directory_transfer (const std::string &transfer_id, const std::string &reason="")
 Reject an incoming directory transfer.
 
bool pause_file_transfer (const std::string &transfer_id)
 Pause an active file transfer.
 
bool resume_file_transfer (const std::string &transfer_id)
 Resume a paused file transfer.
 
bool cancel_file_transfer (const std::string &transfer_id)
 Cancel an active or paused file transfer.
 
std::shared_ptr< FileTransferProgressget_file_transfer_progress (const std::string &transfer_id) const
 Get file transfer progress information.
 
std::vector< std::shared_ptr< FileTransferProgress > > get_active_file_transfers () const
 Get all active file transfers.
 
nlohmann::json get_file_transfer_statistics () const
 Get file transfer statistics.
 
void set_file_transfer_config (const FileTransferConfig &config)
 Set file transfer configuration.
 
const FileTransferConfigget_file_transfer_config () const
 Get current file transfer configuration.
 
void on_file_transfer_progress (FileTransferProgressCallback callback)
 Set file transfer progress callback.
 
void on_file_transfer_completed (FileTransferCompletedCallback callback)
 Set file transfer completion callback.
 
void on_file_transfer_request (FileTransferRequestCallback callback)
 Set incoming file transfer request callback.
 
void on_directory_transfer_progress (DirectoryTransferProgressCallback callback)
 Set directory transfer progress callback.
 
void on_file_request (FileRequestCallback callback)
 Set file request callback (called when receiving file requests)
 
void on_directory_request (DirectoryRequestCallback callback)
 Set directory request callback (called when receiving directory requests)
 
IceManagerget_ice_manager ()
 Get the ICE manager instance.
 
bool is_ice_available () const
 Check if ICE is available.
 
void add_stun_server (const std::string &host, uint16_t port=STUN_DEFAULT_PORT)
 Add a STUN server for NAT traversal.
 
void add_turn_server (const std::string &host, uint16_t port, const std::string &username, const std::string &password)
 Add a TURN server for relay-based NAT traversal.
 
void clear_ice_servers ()
 Clear all ICE (STUN/TURN) servers.
 
bool gather_ice_candidates ()
 Start gathering ICE candidates This discovers our public address and generates connection candidates.
 
std::vector< IceCandidateget_ice_candidates () const
 Get our local ICE candidates Call after gathering is complete.
 
bool is_ice_gathering_complete () const
 Check if ICE candidate gathering is complete.
 
std::optional< std::pair< std::string, uint16_t > > get_public_address () const
 Get our public IP address (discovered via STUN)
 
std::optional< StunMappedAddressdiscover_public_address (const std::string &server="stun.l.google.com", uint16_t port=19302, int timeout_ms=5000)
 Perform a simple STUN binding request to discover public address This is a convenience method that doesn't require full ICE setup.
 
void add_remote_ice_candidate (const IceCandidate &candidate)
 Add a remote ICE candidate (received from peer via signaling)
 
void add_remote_ice_candidates_from_sdp (const std::vector< std::string > &sdp_lines)
 Add remote ICE candidates from SDP attribute lines.
 
void end_of_remote_ice_candidates ()
 Signal end of remote candidates (trickle ICE complete)
 
void start_ice_checks ()
 Start ICE connectivity checks.
 
IceConnectionState get_ice_connection_state () const
 Get current ICE connection state.
 
IceGatheringState get_ice_gathering_state () const
 Get ICE gathering state.
 
bool is_ice_connected () const
 Check if ICE is connected.
 
std::optional< IceCandidatePairget_ice_selected_pair () const
 Get the selected ICE candidate pair.
 
void on_ice_candidates_gathered (IceCandidatesCallback callback)
 Set callback for ICE candidates gathered.
 
void on_ice_new_candidate (IceNewCandidateCallback callback)
 Set callback for new ICE candidate (trickle ICE)
 
void on_ice_gathering_state_changed (IceGatheringStateCallback callback)
 Set callback for ICE gathering state changes.
 
void on_ice_connection_state_changed (IceConnectionStateCallback callback)
 Set callback for ICE connection state changes.
 
void on_ice_selected_pair (IceSelectedPairCallback callback)
 Set callback for ICE selected pair.
 
void set_ice_config (const IceConfig &config)
 Set ICE configuration.
 
const IceConfigget_ice_config () const
 Get current ICE configuration.
 
void close_ice ()
 Close ICE manager and release resources.
 
void restart_ice ()
 Restart ICE (re-gather candidates and restart checks)
 
StorageManager & get_storage_manager ()
 Get the storage manager instance.
 
bool is_storage_available () const
 Check if storage is available.
 
bool storage_put (const std::string &key, const std::string &value)
 Store a string value.
 
bool storage_put (const std::string &key, int64_t value)
 Store a 64-bit integer value.
 
bool storage_put (const std::string &key, double value)
 Store a double-precision floating point value.
 
bool storage_put (const std::string &key, const std::vector< uint8_t > &value)
 Store binary data.
 
bool storage_put_json (const std::string &key, const nlohmann::json &value)
 Store a JSON document.
 
std::optional< std::string > storage_get_string (const std::string &key) const
 Get a string value.
 
std::optional< int64_t > storage_get_int (const std::string &key) const
 Get a 64-bit integer value.
 
std::optional< double > storage_get_double (const std::string &key) const
 Get a double-precision floating point value.
 
std::optional< std::vector< uint8_t > > storage_get_binary (const std::string &key) const
 Get binary data.
 
std::optional< nlohmann::json > storage_get_json (const std::string &key) const
 Get a JSON document.
 
bool storage_delete (const std::string &key)
 Delete a key from storage.
 
bool storage_has (const std::string &key) const
 Check if a key exists in storage.
 
std::vector< std::string > storage_keys () const
 Get all keys in storage.
 
std::vector< std::string > storage_keys_with_prefix (const std::string &prefix) const
 Get keys matching a prefix.
 
size_t storage_size () const
 Get the number of entries in storage.
 
bool storage_request_sync ()
 Request storage sync from connected peers.
 
bool is_storage_synced () const
 Check if storage is synchronized.
 
nlohmann::json get_storage_statistics () const
 Get storage statistics.
 
void set_storage_config (const StorageConfig &config)
 Set storage configuration.
 
const StorageConfig & get_storage_config () const
 Get current storage configuration.
 
void on_storage_change (StorageChangeCallback callback)
 Set storage change callback.
 
void on_storage_sync_complete (StorageSyncCompleteCallback callback)
 Set storage sync complete callback.
 
bool enable_bittorrent (int listen_port=6881)
 Enable BitTorrent functionality.
 
void set_resume_data_path (const std::string &path)
 Set the directory for storing resume data files Resume data allows torrents to resume from where they left off.
 
void disable_bittorrent ()
 Disable BitTorrent functionality.
 
bool is_bittorrent_enabled () const
 Check if BitTorrent is enabled.
 
std::shared_ptr< TorrentDownload > add_torrent (const std::string &torrent_file, const std::string &download_path)
 Add a torrent from a file.
 
std::shared_ptr< TorrentDownload > add_torrent (const TorrentInfo &torrent_info, const std::string &download_path)
 Add a torrent from TorrentInfo.
 
std::shared_ptr< TorrentDownload > add_torrent_by_hash (const InfoHash &info_hash, const std::string &download_path)
 Add a torrent by info hash (magnet link style - uses DHT to find peers)
 
std::shared_ptr< TorrentDownload > add_torrent_by_hash (const std::string &info_hash_hex, const std::string &download_path)
 Add a torrent by info hash hex string (magnet link style - uses DHT to find peers)
 
bool remove_torrent (const InfoHash &info_hash)
 Remove a torrent by info hash.
 
std::shared_ptr< TorrentDownload > get_torrent (const InfoHash &info_hash)
 Get a torrent by info hash.
 
std::vector< std::shared_ptr< TorrentDownload > > get_all_torrents ()
 Get all active torrents.
 
size_t get_active_torrents_count () const
 Get the number of active torrents.
 
std::pair< uint64_t, uint64_t > get_bittorrent_stats () const
 Get BitTorrent statistics (downloaded and uploaded bytes)
 
void get_torrent_metadata (const InfoHash &info_hash, std::function< void(const TorrentInfo &, bool, const std::string &)> callback)
 Get torrent metadata without downloading (requires DHT to be running)
 
void get_torrent_metadata (const std::string &info_hash_hex, std::function< void(const TorrentInfo &, bool, const std::string &)> callback)
 Get torrent metadata without downloading by hex string (requires DHT to be running)
 
void get_torrent_metadata_from_peer (const InfoHash &info_hash, const std::string &peer_ip, uint16_t peer_port, std::function< void(const TorrentInfo &, bool, const std::string &)> callback)
 Get torrent metadata directly from a specific peer (fast path - no DHT search needed) This is more efficient when you already know a peer that has the torrent (e.g., from announce_peer)
 
void get_torrent_metadata_from_peer (const std::string &info_hash_hex, const std::string &peer_ip, uint16_t peer_port, std::function< void(const TorrentInfo &, bool, const std::string &)> callback)
 Get torrent metadata directly from a specific peer by hex string (fast path)
 
std::optional< TorrentInfo > create_torrent_from_path (const std::string &path, const std::vector< std::string > &trackers={}, const std::string &comment="", TorrentCreationProgressCallback progress_callback=nullptr)
 Create a torrent from a file or directory and return TorrentInfo This is a synchronous operation that reads all files to compute piece hashes.
 
std::vector< uint8_t > create_torrent_data (const std::string &path, const std::vector< std::string > &trackers={}, const std::string &comment="", TorrentCreationProgressCallback progress_callback=nullptr)
 Create a torrent from a file or directory and return raw torrent data.
 
bool create_torrent_file (const std::string &path, const std::string &output_file, const std::vector< std::string > &trackers={}, const std::string &comment="", TorrentCreationProgressCallback progress_callback=nullptr)
 Create a torrent and save it to a file.
 
std::shared_ptr< TorrentDownload > create_and_seed_torrent (const std::string &path, const std::vector< std::string > &trackers={}, const std::string &comment="", TorrentCreationProgressCallback progress_callback=nullptr)
 Create a torrent, add it to the BitTorrent client, and start seeding This combines torrent creation with immediately starting to seed it.
 
void set_spider_mode (bool enable)
 Enable spider mode on DHT In spider mode:
 
bool is_spider_mode () const
 Check if spider mode is enabled.
 
void set_spider_announce_callback (SpiderAnnounceCallback callback)
 Set callback for announce_peer requests (spider mode) Called when other peers announce they have a torrent.
 
void set_spider_ignore (bool ignore)
 Set spider ignore mode - when true, incoming requests are not processed Useful for rate limiting in spider mode.
 
bool is_spider_ignoring () const
 Check if spider ignore mode is enabled.
 
void spider_walk ()
 Trigger a single spider walk iteration Sends find_node to a random node from the spider pool Call this periodically at desired frequency to discover new nodes.
 
size_t get_spider_pool_size () const
 Get the size of the spider node pool.
 
size_t get_spider_visited_count () const
 Get the number of visited nodes in spider mode.
 
void clear_spider_state ()
 Clear spider state (pool and visited nodes) Useful for resetting the spider walk.
 
- Public Member Functions inherited from librats::ThreadManager
 ThreadManager ()
 
virtual ~ThreadManager ()
 
void add_managed_thread (std::thread &&t, const std::string &name="unnamed")
 
void cleanup_finished_threads ()
 
void shutdown_all_threads ()
 
void join_all_active_threads ()
 
size_t get_active_thread_count () const
 

Static Public Member Functions

static std::string get_rats_peer_discovery_hash ()
 Get the well-known RATS peer discovery hash.
 

Additional Inherited Members

- Protected Member Functions inherited from librats::ThreadManager
void notify_shutdown ()
 
- Protected Attributes inherited from librats::ThreadManager
std::condition_variable shutdown_cv_
 
std::mutex shutdown_mutex_
 

Detailed Description

RatsClient - Core peer-to-peer networking client.

Definition at line 208 of file librats.h.

Member Typedef Documentation

◆ BinaryDataCallback

using librats::RatsClient::BinaryDataCallback = std::function<void(socket_t, const std::string&, const std::vector<uint8_t>&)>

Definition at line 214 of file librats.h.

◆ ConnectionCallback

using librats::RatsClient::ConnectionCallback = std::function<void(socket_t, const std::string&)>

Definition at line 213 of file librats.h.

◆ DisconnectCallback

using librats::RatsClient::DisconnectCallback = std::function<void(socket_t, const std::string&)>

Definition at line 217 of file librats.h.

◆ JsonDataCallback

using librats::RatsClient::JsonDataCallback = std::function<void(socket_t, const std::string&, const nlohmann::json&)>

Definition at line 216 of file librats.h.

◆ MessageCallback

using librats::RatsClient::MessageCallback = std::function<void(const std::string&, const nlohmann::json&)>

Definition at line 218 of file librats.h.

◆ SendCallback

using librats::RatsClient::SendCallback = std::function<void(bool, const std::string&)>

Definition at line 219 of file librats.h.

◆ SpiderAnnounceCallback

using librats::RatsClient::SpiderAnnounceCallback = std::function<void(const std::string& info_hash, const std::string& peer_address)>

Spider announce callback type Called when a peer announces they have a torrent (announce_peer request received)

Parameters
info_hashThe info hash being announced (as hex string)
peer_addressThe peer that is announcing (ip:port format)

Definition at line 1882 of file librats.h.

◆ StringDataCallback

using librats::RatsClient::StringDataCallback = std::function<void(socket_t, const std::string&, const std::string&)>

Definition at line 215 of file librats.h.

◆ TorrentCreationProgressCallback

using librats::RatsClient::TorrentCreationProgressCallback = std::function<void(uint32_t current_piece, uint32_t total_pieces)>

Torrent creation progress callback type Called during piece hashing to report progress.

Parameters
current_pieceCurrent piece being hashed (0-indexed)
total_piecesTotal number of pieces

Definition at line 1809 of file librats.h.

Constructor & Destructor Documentation

◆ RatsClient()

librats::RatsClient::RatsClient ( int  listen_port,
int  max_peers = 10,
const std::string &  bind_address = "" 
)

Constructor.

Parameters
listen_portPort to listen on for incoming connections
max_peersMaximum number of concurrent peers (default: 10)
bind_addressInterface IP address to bind to (empty for all interfaces)

◆ ~RatsClient()

librats::RatsClient::~RatsClient ( )

Destructor.

Member Function Documentation

◆ accept_directory_transfer()

bool librats::RatsClient::accept_directory_transfer ( const std::string &  transfer_id,
const std::string &  local_path 
)

Accept an incoming directory transfer.

Parameters
transfer_idTransfer identifier from request
local_pathLocal path where directory should be saved
Returns
true if accepted successfully

◆ accept_file_transfer()

bool librats::RatsClient::accept_file_transfer ( const std::string &  transfer_id,
const std::string &  local_path 
)

Accept an incoming file transfer.

Parameters
transfer_idTransfer identifier from request
local_pathLocal path where file should be saved
Returns
true if accepted successfully

◆ add_ignored_address()

void librats::RatsClient::add_ignored_address ( const std::string &  ip_address)

Add an IP address to the ignore list (for blocking connections to self)

Parameters
ip_addressIP address to ignore

◆ add_remote_ice_candidate()

void librats::RatsClient::add_remote_ice_candidate ( const IceCandidate candidate)

Add a remote ICE candidate (received from peer via signaling)

Parameters
candidateRemote candidate to add

◆ add_remote_ice_candidates_from_sdp()

void librats::RatsClient::add_remote_ice_candidates_from_sdp ( const std::vector< std::string > &  sdp_lines)

Add remote ICE candidates from SDP attribute lines.

Parameters
sdp_linesVector of SDP candidate lines

◆ add_stun_server()

void librats::RatsClient::add_stun_server ( const std::string &  host,
uint16_t  port = STUN_DEFAULT_PORT 
)

Add a STUN server for NAT traversal.

Parameters
hostSTUN server hostname or IP
portSTUN server port (default: 3478)

◆ add_torrent() [1/2]

std::shared_ptr< TorrentDownload > librats::RatsClient::add_torrent ( const std::string &  torrent_file,
const std::string &  download_path 
)

Add a torrent from a file.

Parameters
torrent_filePath to the .torrent file
download_pathDirectory where files will be downloaded
Returns
Shared pointer to TorrentDownload object, or nullptr on failure

◆ add_torrent() [2/2]

std::shared_ptr< TorrentDownload > librats::RatsClient::add_torrent ( const TorrentInfo &  torrent_info,
const std::string &  download_path 
)

Add a torrent from TorrentInfo.

Parameters
torrent_infoTorrentInfo object with torrent metadata
download_pathDirectory where files will be downloaded
Returns
Shared pointer to TorrentDownload object, or nullptr on failure

◆ add_torrent_by_hash() [1/2]

std::shared_ptr< TorrentDownload > librats::RatsClient::add_torrent_by_hash ( const InfoHash info_hash,
const std::string &  download_path 
)

Add a torrent by info hash (magnet link style - uses DHT to find peers)

Parameters
info_hashInfo hash of the torrent
download_pathDirectory where files will be downloaded
Returns
Shared pointer to TorrentDownload object, or nullptr on failure
Note
Requires DHT to be running. Will discover peers via DHT.

◆ add_torrent_by_hash() [2/2]

std::shared_ptr< TorrentDownload > librats::RatsClient::add_torrent_by_hash ( const std::string &  info_hash_hex,
const std::string &  download_path 
)

Add a torrent by info hash hex string (magnet link style - uses DHT to find peers)

Parameters
info_hash_hexInfo hash as 40-character hex string
download_pathDirectory where files will be downloaded
Returns
Shared pointer to TorrentDownload object, or nullptr on failure
Note
Requires DHT to be running. Will discover peers via DHT.

◆ add_turn_server()

void librats::RatsClient::add_turn_server ( const std::string &  host,
uint16_t  port,
const std::string &  username,
const std::string &  password 
)

Add a TURN server for relay-based NAT traversal.

Parameters
hostTURN server hostname or IP
portTURN server port (default: 3478)
usernameTURN username
passwordTURN password

◆ announce_for_hash()

bool librats::RatsClient::announce_for_hash ( const std::string &  content_hash,
uint16_t  port = 0,
std::function< void(const std::vector< std::string > &)>  callback = nullptr 
)

Announce our presence for a content hash with optional peer discovery callback If callback is provided, peers discovered during DHT traversal will be returned through it.

Parameters
content_hashHash to announce for (40-character hex string)
portPort to announce (default: our listen port)
callbackOptional function to call with discovered peers during traversal
Returns
true if announced successfully

◆ broadcast_binary_to_peers()

int librats::RatsClient::broadcast_binary_to_peers ( const std::vector< uint8_t > &  data,
MessageDataType  message_type = MessageDataType::BINARY 
)

Broadcast binary data to all connected peers (primary method)

Parameters
dataBinary data to broadcast
message_typeType of message data (BINARY, STRING, JSON)
Returns
Number of peers the data was sent to

◆ broadcast_json_to_peers()

int librats::RatsClient::broadcast_json_to_peers ( const nlohmann::json &  data)

Broadcast JSON data to all connected peers.

Parameters
dataJSON data to broadcast
Returns
Number of peers the data was sent to

◆ broadcast_string_to_peers()

int librats::RatsClient::broadcast_string_to_peers ( const std::string &  data)

Broadcast string data to all connected peers.

Parameters
dataString data to broadcast
Returns
Number of peers the data was sent to

◆ calculate_discovery_interval()

std::chrono::seconds librats::RatsClient::calculate_discovery_interval ( ) const

Calculate discovery interval based on current peer count Uses graduated scaling: more aggressive when fewer peers, less aggressive when nearly full.

Returns
Discovery interval in seconds

◆ cancel_file_transfer()

bool librats::RatsClient::cancel_file_transfer ( const std::string &  transfer_id)

Cancel an active or paused file transfer.

Parameters
transfer_idTransfer to cancel
Returns
true if cancelled successfully

◆ clear_historical_peers()

void librats::RatsClient::clear_historical_peers ( )

Clear all historical peers.

◆ clear_ice_servers()

void librats::RatsClient::clear_ice_servers ( )

Clear all ICE (STUN/TURN) servers.

◆ clear_log_file()

void librats::RatsClient::clear_log_file ( )

Clear/reset the current log file.

◆ clear_reconnect_queue()

void librats::RatsClient::clear_reconnect_queue ( )

Clear all pending reconnection attempts.

◆ clear_spider_state()

void librats::RatsClient::clear_spider_state ( )

Clear spider state (pool and visited nodes) Useful for resetting the spider walk.

◆ close_ice()

void librats::RatsClient::close_ice ( )

Close ICE manager and release resources.

◆ connect_to_peer()

bool librats::RatsClient::connect_to_peer ( const std::string &  host,
int  port 
)

Connect to a peer via direct TCP connection.

Parameters
hostTarget host/IP address
portTarget port
Returns
true if connection initiated successfully

◆ create_and_seed_torrent()

std::shared_ptr< TorrentDownload > librats::RatsClient::create_and_seed_torrent ( const std::string &  path,
const std::vector< std::string > &  trackers = {},
const std::string &  comment = "",
TorrentCreationProgressCallback  progress_callback = nullptr 
)

Create a torrent, add it to the BitTorrent client, and start seeding This combines torrent creation with immediately starting to seed it.

Parameters
pathPath to file or directory
trackersOptional list of tracker URLs
commentOptional comment
progress_callbackOptional callback for progress updates
Returns
Shared pointer to TorrentDownload for the seeding torrent, or nullptr on failure
Note
Requires BitTorrent to be enabled (call enable_bittorrent() first)

◆ create_torrent_data()

std::vector< uint8_t > librats::RatsClient::create_torrent_data ( const std::string &  path,
const std::vector< std::string > &  trackers = {},
const std::string &  comment = "",
TorrentCreationProgressCallback  progress_callback = nullptr 
)

Create a torrent from a file or directory and return raw torrent data.

Parameters
pathPath to file or directory
trackersOptional list of tracker URLs
commentOptional comment
progress_callbackOptional callback for progress updates
Returns
Bencoded torrent data, or empty vector on failure

◆ create_torrent_file()

bool librats::RatsClient::create_torrent_file ( const std::string &  path,
const std::string &  output_file,
const std::vector< std::string > &  trackers = {},
const std::string &  comment = "",
TorrentCreationProgressCallback  progress_callback = nullptr 
)

Create a torrent and save it to a file.

Parameters
pathPath to file or directory
output_filePath to save the .torrent file
trackersOptional list of tracker URLs
commentOptional comment
progress_callbackOptional callback for progress updates
Returns
true if torrent was created and saved successfully

◆ create_torrent_from_path()

std::optional< TorrentInfo > librats::RatsClient::create_torrent_from_path ( const std::string &  path,
const std::vector< std::string > &  trackers = {},
const std::string &  comment = "",
TorrentCreationProgressCallback  progress_callback = nullptr 
)

Create a torrent from a file or directory and return TorrentInfo This is a synchronous operation that reads all files to compute piece hashes.

Parameters
pathPath to file or directory to create torrent from
trackersOptional list of tracker URLs
commentOptional comment
progress_callbackOptional callback for progress updates
Returns
TorrentInfo object, or nullopt on failure

◆ disable_bittorrent()

void librats::RatsClient::disable_bittorrent ( )

Disable BitTorrent functionality.

◆ disconnect_peer()

void librats::RatsClient::disconnect_peer ( socket_t  socket)

Disconnect from a specific peer.

Parameters
socketPeer socket to disconnect

◆ disconnect_peer_by_id()

void librats::RatsClient::disconnect_peer_by_id ( const std::string &  peer_id)

Disconnect from a peer by peer_id (preferred)

Parameters
peer_idPeer ID to disconnect

◆ discover_public_address()

std::optional< StunMappedAddress > librats::RatsClient::discover_public_address ( const std::string &  server = "stun.l.google.com",
uint16_t  port = 19302,
int  timeout_ms = 5000 
)

Perform a simple STUN binding request to discover public address This is a convenience method that doesn't require full ICE setup.

Parameters
serverSTUN server hostname
portSTUN server port (default: 3478)
timeout_msTimeout in milliseconds (default: 5000)
Returns
Mapped address or nullopt on failure

◆ enable_bittorrent()

bool librats::RatsClient::enable_bittorrent ( int  listen_port = 6881)

Enable BitTorrent functionality.

Parameters
listen_portPort to listen for BitTorrent connections (default: 6881)
Returns
true if BitTorrent was successfully enabled

◆ end_of_remote_ice_candidates()

void librats::RatsClient::end_of_remote_ice_candidates ( )

Signal end of remote candidates (trickle ICE complete)

◆ find_peers_by_hash()

bool librats::RatsClient::find_peers_by_hash ( const std::string &  content_hash,
std::function< void(const std::vector< std::string > &)>  callback 
)

Find peers by content hash using DHT.

Parameters
content_hashHash to search for (40-character hex string)
callbackFunction to call with discovered peers
Returns
true if search initiated successfully

◆ gather_ice_candidates()

bool librats::RatsClient::gather_ice_candidates ( )

Start gathering ICE candidates This discovers our public address and generates connection candidates.

Returns
true if gathering started successfully

◆ get_active_file_transfers()

std::vector< std::shared_ptr< FileTransferProgress > > librats::RatsClient::get_active_file_transfers ( ) const

Get all active file transfers.

Returns
Vector of transfer progress objects

◆ get_active_torrents_count()

size_t librats::RatsClient::get_active_torrents_count ( ) const

Get the number of active torrents.

Returns
Number of active torrents

◆ get_all_peers()

std::vector< RatsPeer > librats::RatsClient::get_all_peers ( ) const

Get all connected peers.

Returns
Vector of RatsPeer objects

◆ get_all_torrents()

std::vector< std::shared_ptr< TorrentDownload > > librats::RatsClient::get_all_torrents ( )

Get all active torrents.

Returns
Vector of all active torrent downloads

◆ get_bind_address()

std::string librats::RatsClient::get_bind_address ( ) const

Get the bind address being used.

Returns
Bind address (empty string if binding to all interfaces)

◆ get_bittorrent_stats()

std::pair< uint64_t, uint64_t > librats::RatsClient::get_bittorrent_stats ( ) const

Get BitTorrent statistics (downloaded and uploaded bytes)

Returns
Pair of (downloaded_bytes, uploaded_bytes)

◆ get_connection_statistics()

nlohmann::json librats::RatsClient::get_connection_statistics ( ) const

Get connection statistics.

Returns
JSON object with detailed statistics

◆ get_data_directory()

std::string librats::RatsClient::get_data_directory ( ) const

Get current data directory path.

Returns
Current data directory path

◆ get_dht_routing_table_size()

size_t librats::RatsClient::get_dht_routing_table_size ( ) const

Get the size of the DHT routing table.

Returns
Number of nodes in routing table

◆ get_discovery_hash()

std::string librats::RatsClient::get_discovery_hash ( ) const

Get the discovery hash for current protocol configuration.

Returns
Discovery hash based on current protocol name and version

◆ get_file_transfer_config()

const FileTransferConfig & librats::RatsClient::get_file_transfer_config ( ) const

Get current file transfer configuration.

Returns
Current configuration settings

◆ get_file_transfer_manager()

FileTransferManager & librats::RatsClient::get_file_transfer_manager ( )

Get the file transfer manager instance.

Returns
Reference to the file transfer manager

◆ get_file_transfer_progress()

std::shared_ptr< FileTransferProgress > librats::RatsClient::get_file_transfer_progress ( const std::string &  transfer_id) const

Get file transfer progress information.

Parameters
transfer_idTransfer to query
Returns
Progress information or nullptr if not found

◆ get_file_transfer_statistics()

nlohmann::json librats::RatsClient::get_file_transfer_statistics ( ) const

Get file transfer statistics.

Returns
JSON object with transfer statistics

◆ get_gossipsub()

GossipSub & librats::RatsClient::get_gossipsub ( )

Get GossipSub instance for publish-subscribe messaging.

Returns
Reference to GossipSub instance

◆ get_gossipsub_statistics()

nlohmann::json librats::RatsClient::get_gossipsub_statistics ( ) const

Get GossipSub statistics.

Returns
JSON object with comprehensive GossipSub statistics

◆ get_historical_peers()

std::vector< RatsPeer > librats::RatsClient::get_historical_peers ( ) const

Get all historical peers.

Returns
Vector of RatsPeer objects

◆ get_ice_candidates()

std::vector< IceCandidate > librats::RatsClient::get_ice_candidates ( ) const

Get our local ICE candidates Call after gathering is complete.

Returns
Vector of ICE candidates

◆ get_ice_config()

const IceConfig & librats::RatsClient::get_ice_config ( ) const

Get current ICE configuration.

Returns
Current ICE configuration

◆ get_ice_connection_state()

IceConnectionState librats::RatsClient::get_ice_connection_state ( ) const

Get current ICE connection state.

Returns
ICE connection state

◆ get_ice_gathering_state()

IceGatheringState librats::RatsClient::get_ice_gathering_state ( ) const

Get ICE gathering state.

Returns
ICE gathering state

◆ get_ice_manager()

IceManager & librats::RatsClient::get_ice_manager ( )

Get the ICE manager instance.

Returns
Reference to the ICE manager

◆ get_ice_selected_pair()

std::optional< IceCandidatePair > librats::RatsClient::get_ice_selected_pair ( ) const

Get the selected ICE candidate pair.

Returns
Selected candidate pair or nullopt

◆ get_listen_port()

int librats::RatsClient::get_listen_port ( ) const

◆ get_log_file_path()

std::string librats::RatsClient::get_log_file_path ( ) const

Get the current log file path.

Returns
Current log file path

◆ get_log_level()

LogLevel librats::RatsClient::get_log_level ( ) const

Get the current log level.

Returns
Current minimum log level

◆ get_max_peers()

int librats::RatsClient::get_max_peers ( ) const

Get maximum number of peers.

Returns
Maximum peer count

◆ get_mdns_services()

std::vector< MdnsService > librats::RatsClient::get_mdns_services ( ) const

Get recently discovered mDNS services.

Returns
Vector of discovered services

◆ get_noise_static_public_key()

std::vector< uint8_t > librats::RatsClient::get_noise_static_public_key ( ) const

Get our Noise Protocol static public key.

Returns
32-byte public key

◆ get_our_peer_id()

std::string librats::RatsClient::get_our_peer_id ( ) const

Get our own peer ID.

Returns
Our persistent peer ID

◆ get_peer_by_id()

const RatsPeer * librats::RatsClient::get_peer_by_id ( const std::string &  peer_id) const

Get peer information by peer ID.

Parameters
peer_idThe peer ID to look up
Returns
Pointer to RatsPeer object, or nullptr if not found

◆ get_peer_by_socket()

const RatsPeer * librats::RatsClient::get_peer_by_socket ( socket_t  socket) const

Get peer information by socket.

Parameters
socketThe socket handle to look up
Returns
Pointer to RatsPeer object, or nullptr if not found

◆ get_peer_count()

int librats::RatsClient::get_peer_count ( ) const

Get the number of currently connected peers.

Returns
Number of connected peers

◆ get_peer_handshake_hash()

std::vector< uint8_t > librats::RatsClient::get_peer_handshake_hash ( const std::string &  peer_id) const

Get the handshake hash for a peer connection (for channel binding)

Parameters
peer_idPeer ID to query
Returns
32-byte handshake hash, or empty vector if not available

◆ get_peer_id()

std::string librats::RatsClient::get_peer_id ( socket_t  socket) const

Get peer_id for a peer by socket (preferred)

Parameters
socketPeer socket
Returns
Peer ID or empty string if not found

◆ get_peer_noise_public_key()

std::vector< uint8_t > librats::RatsClient::get_peer_noise_public_key ( const std::string &  peer_id) const

Get the remote peer's Noise static public key.

Parameters
peer_idPeer ID to query
Returns
32-byte public key, or empty vector if not available

◆ get_peer_socket_by_id()

socket_t librats::RatsClient::get_peer_socket_by_id ( const std::string &  peer_id) const

Get socket for a peer by peer_id (preferred)

Parameters
peer_idPeer ID
Returns
Peer socket or INVALID_SOCKET_VALUE if not found

◆ get_protocol_name()

std::string librats::RatsClient::get_protocol_name ( ) const

Get current protocol name.

Returns
Current protocol name

◆ get_protocol_version()

std::string librats::RatsClient::get_protocol_version ( ) const

Get current protocol version.

Returns
Current protocol version

◆ get_public_address()

std::optional< std::pair< std::string, uint16_t > > librats::RatsClient::get_public_address ( ) const

Get our public IP address (discovered via STUN)

Returns
Pair of (IP, port) or nullopt if not discovered

◆ get_rats_peer_discovery_hash()

static std::string librats::RatsClient::get_rats_peer_discovery_hash ( )
static

Get the well-known RATS peer discovery hash.

Returns
Standard RATS discovery hash

◆ get_reconnect_config()

const ReconnectConfig & librats::RatsClient::get_reconnect_config ( ) const

Get current reconnection configuration.

Returns
Current reconnection configuration

◆ get_reconnect_queue()

std::vector< ReconnectInfo > librats::RatsClient::get_reconnect_queue ( ) const

Get information about peers pending reconnection.

Returns
Vector of ReconnectInfo for all pending reconnections

◆ get_reconnect_queue_size()

size_t librats::RatsClient::get_reconnect_queue_size ( ) const

Get the number of peers pending reconnection.

Returns
Number of peers in reconnection queue

◆ get_spider_pool_size()

size_t librats::RatsClient::get_spider_pool_size ( ) const

Get the size of the spider node pool.

Returns
Number of nodes in spider pool

◆ get_spider_visited_count()

size_t librats::RatsClient::get_spider_visited_count ( ) const

Get the number of visited nodes in spider mode.

Returns
Number of visited nodes

◆ get_storage_config()

const StorageConfig & librats::RatsClient::get_storage_config ( ) const

Get current storage configuration.

Returns
Current configuration settings

◆ get_storage_manager()

StorageManager & librats::RatsClient::get_storage_manager ( )

Get the storage manager instance.

Returns
Reference to the storage manager

◆ get_storage_statistics()

nlohmann::json librats::RatsClient::get_storage_statistics ( ) const

Get storage statistics.

Returns
JSON object with storage statistics

◆ get_subscribed_topics()

std::vector< std::string > librats::RatsClient::get_subscribed_topics ( ) const

Get list of subscribed GossipSub topics.

Returns
Vector of topic names

◆ get_topic_mesh_peers()

std::vector< std::string > librats::RatsClient::get_topic_mesh_peers ( const std::string &  topic) const

Get mesh peers for a GossipSub topic.

Parameters
topicTopic name
Returns
Vector of peer IDs in the mesh

◆ get_topic_peers()

std::vector< std::string > librats::RatsClient::get_topic_peers ( const std::string &  topic) const

Get peers subscribed to a GossipSub topic.

Parameters
topicTopic name
Returns
Vector of peer IDs

◆ get_torrent()

std::shared_ptr< TorrentDownload > librats::RatsClient::get_torrent ( const InfoHash info_hash)

Get a torrent by info hash.

Parameters
info_hashInfo hash of the torrent
Returns
Shared pointer to TorrentDownload object, or nullptr if not found

◆ get_torrent_metadata() [1/2]

void librats::RatsClient::get_torrent_metadata ( const InfoHash info_hash,
std::function< void(const TorrentInfo &, bool, const std::string &)>  callback 
)

Get torrent metadata without downloading (requires DHT to be running)

Parameters
info_hashInfo hash of the torrent
callbackFunction called when metadata is retrieved (torrent_info, success, error_message)
Note
This only retrieves metadata via BEP 9, it does not start downloading

◆ get_torrent_metadata() [2/2]

void librats::RatsClient::get_torrent_metadata ( const std::string &  info_hash_hex,
std::function< void(const TorrentInfo &, bool, const std::string &)>  callback 
)

Get torrent metadata without downloading by hex string (requires DHT to be running)

Parameters
info_hash_hexInfo hash as 40-character hex string
callbackFunction called when metadata is retrieved (torrent_info, success, error_message)
Note
This only retrieves metadata via BEP 9, it does not start downloading

◆ get_torrent_metadata_from_peer() [1/2]

void librats::RatsClient::get_torrent_metadata_from_peer ( const InfoHash info_hash,
const std::string &  peer_ip,
uint16_t  peer_port,
std::function< void(const TorrentInfo &, bool, const std::string &)>  callback 
)

Get torrent metadata directly from a specific peer (fast path - no DHT search needed) This is more efficient when you already know a peer that has the torrent (e.g., from announce_peer)

Parameters
info_hashInfo hash of the torrent
peer_ipIP address of the peer
peer_portPort of the peer
callbackFunction called when metadata is retrieved (torrent_info, success, error_message)
Note
This only retrieves metadata via BEP 9, it does not start downloading

◆ get_torrent_metadata_from_peer() [2/2]

void librats::RatsClient::get_torrent_metadata_from_peer ( const std::string &  info_hash_hex,
const std::string &  peer_ip,
uint16_t  peer_port,
std::function< void(const TorrentInfo &, bool, const std::string &)>  callback 
)

Get torrent metadata directly from a specific peer by hex string (fast path)

Parameters
info_hash_hexInfo hash as 40-character hex string
peer_ipIP address of the peer
peer_portPort of the peer
callbackFunction called when metadata is retrieved (torrent_info, success, error_message)
Note
This only retrieves metadata via BEP 9, it does not start downloading

◆ get_validated_peers()

std::vector< RatsPeer > librats::RatsClient::get_validated_peers ( ) const

Get all peers that have completed handshake.

Returns
Vector of RatsPeer objects with completed handshake

◆ initialize_encryption()

bool librats::RatsClient::initialize_encryption ( bool  enable)

Initialize encryption system.

Parameters
enableWhether to enable encryption
Returns
true if successful

◆ is_automatic_discovery_running()

bool librats::RatsClient::is_automatic_discovery_running ( ) const

Check if automatic discovery is running.

Returns
true if automatic discovery is running

◆ is_bittorrent_enabled()

bool librats::RatsClient::is_bittorrent_enabled ( ) const

Check if BitTorrent is enabled.

Returns
true if BitTorrent is active

◆ is_console_logging_enabled()

bool librats::RatsClient::is_console_logging_enabled ( ) const

Check if console logging is currently enabled.

Returns
true if console logging is enabled

◆ is_dht_running()

bool librats::RatsClient::is_dht_running ( ) const

Check if DHT is currently running.

Returns
true if DHT is running

◆ is_encryption_enabled()

bool librats::RatsClient::is_encryption_enabled ( ) const

Check if encryption is enabled.

Returns
true if encryption is enabled

◆ is_file_transfer_available()

bool librats::RatsClient::is_file_transfer_available ( ) const

Check if file transfer is available.

Returns
true if file transfer manager is initialized

◆ is_gossipsub_available()

bool librats::RatsClient::is_gossipsub_available ( ) const

Check if GossipSub is available.

Returns
true if GossipSub is initialized

◆ is_gossipsub_running()

bool librats::RatsClient::is_gossipsub_running ( ) const

Check if GossipSub is running.

Returns
true if GossipSub service is active

◆ is_ice_available()

bool librats::RatsClient::is_ice_available ( ) const

Check if ICE is available.

Returns
true if ICE manager is initialized

◆ is_ice_connected()

bool librats::RatsClient::is_ice_connected ( ) const

Check if ICE is connected.

Returns
true if ICE connection is established

◆ is_ice_gathering_complete()

bool librats::RatsClient::is_ice_gathering_complete ( ) const

Check if ICE candidate gathering is complete.

Returns
true if gathering is complete

◆ is_log_colors_enabled()

bool librats::RatsClient::is_log_colors_enabled ( ) const

Check if colored log output is enabled.

Returns
true if colors are enabled

◆ is_log_rotate_on_startup_enabled()

bool librats::RatsClient::is_log_rotate_on_startup_enabled ( ) const

Check if log rotation on startup is enabled.

Returns
true if rotate on startup is enabled

◆ is_log_timestamps_enabled()

bool librats::RatsClient::is_log_timestamps_enabled ( ) const

Check if timestamps are enabled in log output.

Returns
true if timestamps are enabled

◆ is_logging_enabled()

bool librats::RatsClient::is_logging_enabled ( ) const

Check if file logging is currently enabled.

Returns
true if file logging is enabled

◆ is_mdns_running()

bool librats::RatsClient::is_mdns_running ( ) const

Check if mDNS is currently running.

Returns
true if mDNS is running

◆ is_peer_encrypted()

bool librats::RatsClient::is_peer_encrypted ( const std::string &  peer_id) const

Check if a peer connection is encrypted.

Parameters
peer_idPeer ID to check
Returns
true if peer connection is encrypted

◆ is_peer_limit_reached()

bool librats::RatsClient::is_peer_limit_reached ( ) const

Check if peer limit has been reached.

Returns
true if at limit, false otherwise

◆ is_reconnect_enabled()

bool librats::RatsClient::is_reconnect_enabled ( ) const

Check if automatic reconnection is enabled.

Returns
true if auto-reconnection is enabled

◆ is_running()

bool librats::RatsClient::is_running ( ) const

Check if the client is currently running.

Returns
true if running, false otherwise

◆ is_spider_ignoring()

bool librats::RatsClient::is_spider_ignoring ( ) const

Check if spider ignore mode is enabled.

Returns
true if ignoring incoming requests

◆ is_spider_mode()

bool librats::RatsClient::is_spider_mode ( ) const

Check if spider mode is enabled.

Returns
true if spider mode is enabled

◆ is_storage_available()

bool librats::RatsClient::is_storage_available ( ) const

Check if storage is available.

Returns
true if storage manager is initialized

◆ is_storage_synced()

bool librats::RatsClient::is_storage_synced ( ) const

Check if storage is synchronized.

Returns
true if initial sync is complete

◆ is_subscribed_to_topic()

bool librats::RatsClient::is_subscribed_to_topic ( const std::string &  topic) const

Check if subscribed to a GossipSub topic.

Parameters
topicTopic name to check
Returns
true if subscribed

◆ load_and_reconnect_peers()

int librats::RatsClient::load_and_reconnect_peers ( )

Load saved peers and attempt to reconnect.

Returns
Number of connection attempts made

◆ load_configuration()

bool librats::RatsClient::load_configuration ( )

Load configuration from files.

Returns
true if successful, false otherwise

◆ load_historical_peers()

bool librats::RatsClient::load_historical_peers ( )

Load historical peers from a file.

Returns
true if successful, false otherwise

◆ off()

void librats::RatsClient::off ( const std::string &  message_type)

Remove all handlers for a message type.

Parameters
message_typeType of message to stop handling

◆ off_topic()

void librats::RatsClient::off_topic ( const std::string &  topic)

Remove all event handlers for a GossipSub topic.

Parameters
topicTopic name

◆ on()

void librats::RatsClient::on ( const std::string &  message_type,
MessageCallback  callback 
)

Register a persistent message handler.

Parameters
message_typeType of message to handle
callbackFunction to call when message is received

◆ on_directory_request()

void librats::RatsClient::on_directory_request ( DirectoryRequestCallback  callback)

Set directory request callback (called when receiving directory requests)

Parameters
callbackFunction to call when receiving directory requests

◆ on_directory_transfer_progress()

void librats::RatsClient::on_directory_transfer_progress ( DirectoryTransferProgressCallback  callback)

Set directory transfer progress callback.

Parameters
callbackFunction to call with directory transfer progress

◆ on_file_request()

void librats::RatsClient::on_file_request ( FileRequestCallback  callback)

Set file request callback (called when receiving file requests)

Parameters
callbackFunction to call when receiving file requests

◆ on_file_transfer_completed()

void librats::RatsClient::on_file_transfer_completed ( FileTransferCompletedCallback  callback)

Set file transfer completion callback.

Parameters
callbackFunction to call when transfers complete

◆ on_file_transfer_progress()

void librats::RatsClient::on_file_transfer_progress ( FileTransferProgressCallback  callback)

Set file transfer progress callback.

Parameters
callbackFunction to call with progress updates

◆ on_file_transfer_request()

void librats::RatsClient::on_file_transfer_request ( FileTransferRequestCallback  callback)

Set incoming file transfer request callback.

Parameters
callbackFunction to call when receiving transfer requests

◆ on_ice_candidates_gathered()

void librats::RatsClient::on_ice_candidates_gathered ( IceCandidatesCallback  callback)

Set callback for ICE candidates gathered.

Parameters
callbackFunction called with all candidates when gathering completes

◆ on_ice_connection_state_changed()

void librats::RatsClient::on_ice_connection_state_changed ( IceConnectionStateCallback  callback)

Set callback for ICE connection state changes.

Parameters
callbackFunction called when connection state changes

◆ on_ice_gathering_state_changed()

void librats::RatsClient::on_ice_gathering_state_changed ( IceGatheringStateCallback  callback)

Set callback for ICE gathering state changes.

Parameters
callbackFunction called when gathering state changes

◆ on_ice_new_candidate()

void librats::RatsClient::on_ice_new_candidate ( IceNewCandidateCallback  callback)

Set callback for new ICE candidate (trickle ICE)

Parameters
callbackFunction called when each new candidate is discovered

◆ on_ice_selected_pair()

void librats::RatsClient::on_ice_selected_pair ( IceSelectedPairCallback  callback)

Set callback for ICE selected pair.

Parameters
callbackFunction called when a candidate pair is selected

◆ on_storage_change()

void librats::RatsClient::on_storage_change ( StorageChangeCallback  callback)

Set storage change callback.

Parameters
callbackFunction to call when storage changes

◆ on_storage_sync_complete()

void librats::RatsClient::on_storage_sync_complete ( StorageSyncCompleteCallback  callback)

Set storage sync complete callback.

Parameters
callbackFunction to call when sync completes

◆ on_topic_json_message()

void librats::RatsClient::on_topic_json_message ( const std::string &  topic,
std::function< void(const std::string &, const std::string &, const nlohmann::json &)>  callback 
)

Set a JSON message handler for a GossipSub topic using unified event API pattern.

Parameters
topicTopic name
callbackFunction to call when JSON messages are received (peer_id, topic, json_message)

◆ on_topic_message()

void librats::RatsClient::on_topic_message ( const std::string &  topic,
std::function< void(const std::string &, const std::string &, const std::string &)>  callback 
)

Set a message handler for a GossipSub topic using unified event API pattern.

Parameters
topicTopic name
callbackFunction to call when messages are received (peer_id, topic, message_content)

◆ on_topic_peer_joined()

void librats::RatsClient::on_topic_peer_joined ( const std::string &  topic,
std::function< void(const std::string &, const std::string &)>  callback 
)

Set a peer joined handler for a GossipSub topic using unified event API pattern.

Parameters
topicTopic name
callbackFunction to call when peers join the topic

◆ on_topic_peer_left()

void librats::RatsClient::on_topic_peer_left ( const std::string &  topic,
std::function< void(const std::string &, const std::string &)>  callback 
)

Set a peer left handler for a GossipSub topic using unified event API pattern

Parameters
topicTopic name
callbackFunction to call when peers leave the topic

◆ once()

void librats::RatsClient::once ( const std::string &  message_type,
MessageCallback  callback 
)

Register a one-time message handler.

Parameters
message_typeType of message to handle
callbackFunction to call when message is received (once only)

◆ parse_json_message()

bool librats::RatsClient::parse_json_message ( const std::string &  message,
nlohmann::json &  out_json 
)

Parse a JSON message.

Parameters
messageRaw message string
out_jsonParsed JSON output
Returns
true if parsed successfully

◆ pause_file_transfer()

bool librats::RatsClient::pause_file_transfer ( const std::string &  transfer_id)

Pause an active file transfer.

Parameters
transfer_idTransfer to pause
Returns
true if paused successfully

◆ publish_json_to_topic()

bool librats::RatsClient::publish_json_to_topic ( const std::string &  topic,
const nlohmann::json &  message 
)

Publish a JSON message to a GossipSub topic.

Parameters
topicTopic to publish to
messageJSON message content
Returns
true if published successfully

◆ publish_to_topic()

bool librats::RatsClient::publish_to_topic ( const std::string &  topic,
const std::string &  message 
)

Publish a message to a GossipSub topic.

Parameters
topicTopic to publish to
messageMessage content
Returns
true if published successfully

◆ query_mdns_services()

bool librats::RatsClient::query_mdns_services ( )

Manually query for mDNS services.

Returns
true if query sent successfully

◆ reject_directory_transfer()

bool librats::RatsClient::reject_directory_transfer ( const std::string &  transfer_id,
const std::string &  reason = "" 
)

Reject an incoming directory transfer.

Parameters
transfer_idTransfer identifier from request
reasonOptional reason for rejection
Returns
true if rejected successfully

◆ reject_file_transfer()

bool librats::RatsClient::reject_file_transfer ( const std::string &  transfer_id,
const std::string &  reason = "" 
)

Reject an incoming file transfer.

Parameters
transfer_idTransfer identifier from request
reasonOptional reason for rejection
Returns
true if rejected successfully

◆ remove_torrent()

bool librats::RatsClient::remove_torrent ( const InfoHash info_hash)

Remove a torrent by info hash.

Parameters
info_hashInfo hash of the torrent to remove
Returns
true if torrent was removed successfully

◆ request_directory()

std::string librats::RatsClient::request_directory ( const std::string &  peer_id,
const std::string &  remote_directory_path,
const std::string &  local_directory_path,
bool  recursive = true 
)

Request a directory from a remote peer.

Parameters
peer_idTarget peer ID
remote_directory_pathPath to directory on remote peer
local_directory_pathLocal path where directory should be saved
recursiveWhether to include subdirectories (default: true)
Returns
Transfer ID if successful, empty string if failed

◆ request_file()

std::string librats::RatsClient::request_file ( const std::string &  peer_id,
const std::string &  remote_file_path,
const std::string &  local_path 
)

Request a file from a remote peer.

Parameters
peer_idTarget peer ID
remote_file_pathPath to file on remote peer
local_pathLocal path where file should be saved
Returns
Transfer ID if successful, empty string if failed

◆ restart_ice()

void librats::RatsClient::restart_ice ( )

Restart ICE (re-gather candidates and restart checks)

◆ resume_file_transfer()

bool librats::RatsClient::resume_file_transfer ( const std::string &  transfer_id)

Resume a paused file transfer.

Parameters
transfer_idTransfer to resume
Returns
true if resumed successfully

◆ save_configuration()

bool librats::RatsClient::save_configuration ( )

Save configuration to files.

Returns
true if successful, false otherwise

◆ save_historical_peers()

bool librats::RatsClient::save_historical_peers ( )

Save current peers to a historical file.

Returns
true if successful, false otherwise

◆ send() [1/2]

void librats::RatsClient::send ( const std::string &  message_type,
const nlohmann::json &  data,
SendCallback  callback = nullptr 
)

Send a message to all peers.

Parameters
message_typeType of message
dataMessage data
callbackOptional callback for send result

◆ send() [2/2]

void librats::RatsClient::send ( const std::string &  peer_id,
const std::string &  message_type,
const nlohmann::json &  data,
SendCallback  callback = nullptr 
)

Send a message to a specific peer.

Parameters
peer_idTarget peer ID
message_typeType of message
dataMessage data
callbackOptional callback for send result

◆ send_binary_to_peer()

bool librats::RatsClient::send_binary_to_peer ( socket_t  socket,
const std::vector< uint8_t > &  data,
MessageDataType  message_type = MessageDataType::BINARY 
)

Send binary data to a specific peer (primary method)

Parameters
socketTarget peer socket
dataBinary data to send
message_typeType of message data (BINARY, STRING, JSON)
Returns
true if sent successfully

◆ send_binary_to_peer_id()

bool librats::RatsClient::send_binary_to_peer_id ( const std::string &  peer_id,
const std::vector< uint8_t > &  data,
MessageDataType  message_type = MessageDataType::BINARY 
)

Send binary data to a peer by peer_id (preferred)

Parameters
peer_idTarget peer ID
dataBinary data to send
message_typeType of message data (BINARY, STRING, JSON)
Returns
true if sent successfully

◆ send_directory()

std::string librats::RatsClient::send_directory ( const std::string &  peer_id,
const std::string &  directory_path,
const std::string &  remote_directory_name = "",
bool  recursive = true 
)

Send an entire directory to a peer.

Parameters
peer_idTarget peer ID
directory_pathLocal directory path to send
remote_directory_nameOptional remote directory name
recursiveWhether to include subdirectories (default: true)
Returns
Transfer ID if successful, empty string if failed

◆ send_file()

std::string librats::RatsClient::send_file ( const std::string &  peer_id,
const std::string &  file_path,
const std::string &  remote_filename = "" 
)

Send a file to a peer.

Parameters
peer_idTarget peer ID
file_pathLocal file path to send
remote_filenameOptional remote filename (default: use local name)
Returns
Transfer ID if successful, empty string if failed

◆ send_json_to_peer()

bool librats::RatsClient::send_json_to_peer ( socket_t  socket,
const nlohmann::json &  data 
)

Send JSON data to a specific peer.

Parameters
socketTarget peer socket
dataJSON data to send
Returns
true if sent successfully

◆ send_json_to_peer_id()

bool librats::RatsClient::send_json_to_peer_id ( const std::string &  peer_id,
const nlohmann::json &  data 
)

Send JSON data to a peer by peer_id (preferred)

Parameters
peer_idTarget peer ID
dataJSON data to send
Returns
true if sent successfully

◆ send_string_to_peer()

bool librats::RatsClient::send_string_to_peer ( socket_t  socket,
const std::string &  data 
)

Send string data to a specific peer.

Parameters
socketTarget peer socket
dataString data to send
Returns
true if sent successfully

◆ send_string_to_peer_id()

bool librats::RatsClient::send_string_to_peer_id ( const std::string &  peer_id,
const std::string &  data 
)

Send string data to a peer by peer_id (preferred)

Parameters
peer_idTarget peer ID
dataString data to send
Returns
true if sent successfully

◆ set_binary_data_callback()

void librats::RatsClient::set_binary_data_callback ( BinaryDataCallback  callback)

Set binary data callback (called when binary data is received)

Parameters
callbackFunction to call when binary data is received

◆ set_connection_callback()

void librats::RatsClient::set_connection_callback ( ConnectionCallback  callback)

Set connection callback (called when a new peer connects)

Parameters
callbackFunction to call on new connections

◆ set_console_logging_enabled()

void librats::RatsClient::set_console_logging_enabled ( bool  enabled)

Enable or disable console logging When disabled, log messages will not be printed to stdout/stderr File logging (if enabled) will still work.

Parameters
enabledWhether to enable console logging (default: true)

◆ set_data_directory()

bool librats::RatsClient::set_data_directory ( const std::string &  directory_path)

Set directory where data files will be stored.

Parameters
directory_pathPath to directory (default: current folder)
Returns
true if directory is accessible, false otherwise

◆ set_disconnect_callback()

void librats::RatsClient::set_disconnect_callback ( DisconnectCallback  callback)

Set disconnect callback (called when a peer disconnects)

Parameters
callbackFunction to call on disconnections

◆ set_encryption_enabled()

void librats::RatsClient::set_encryption_enabled ( bool  enabled)

Set encryption enabled/disabled.

Parameters
enabledWhether encryption should be enabled

◆ set_file_transfer_config()

void librats::RatsClient::set_file_transfer_config ( const FileTransferConfig config)

Set file transfer configuration.

Parameters
configTransfer configuration settings

◆ set_ice_config()

void librats::RatsClient::set_ice_config ( const IceConfig config)

Set ICE configuration.

Parameters
configICE configuration settings

◆ set_json_data_callback()

void librats::RatsClient::set_json_data_callback ( JsonDataCallback  callback)

Set JSON data callback (called when JSON data is received)

Parameters
callbackFunction to call when JSON data is received

◆ set_log_colors_enabled()

void librats::RatsClient::set_log_colors_enabled ( bool  enabled)

Enable or disable colored log output.

Parameters
enabledWhether to enable colored output

◆ set_log_file_path()

void librats::RatsClient::set_log_file_path ( const std::string &  file_path)

Set the log file path.

Parameters
file_pathPath to the log file (default: "rats.log")

◆ set_log_level() [1/2]

void librats::RatsClient::set_log_level ( const std::string &  level_str)

Set the minimum log level using string.

Parameters
level_strLog level as string ("DEBUG", "INFO", "WARN", "ERROR")

◆ set_log_level() [2/2]

void librats::RatsClient::set_log_level ( LogLevel  level)

Set the minimum log level.

Parameters
levelMinimum log level (DEBUG=0, INFO=1, WARN=2, ERROR=3)

◆ set_log_retention_count()

void librats::RatsClient::set_log_retention_count ( int  count)

Set the number of log files to retain during rotation.

Parameters
countNumber of old log files to keep (default: 5)

◆ set_log_rotate_on_startup()

void librats::RatsClient::set_log_rotate_on_startup ( bool  enabled)

Enable or disable log rotation on application startup When enabled, the existing log file will be rotated when logging starts, so each application run gets a fresh log file.

Parameters
enabledWhether to rotate logs on startup (default: false)

◆ set_log_rotation_size()

void librats::RatsClient::set_log_rotation_size ( size_t  max_size_bytes)

Set log file rotation size.

Parameters
max_size_bytesMaximum size in bytes before log rotation (default: 10MB)

◆ set_log_timestamps_enabled()

void librats::RatsClient::set_log_timestamps_enabled ( bool  enabled)

Enable or disable timestamps in log output.

Parameters
enabledWhether to enable timestamps

◆ set_logging_enabled()

void librats::RatsClient::set_logging_enabled ( bool  enabled)

Enable or disable file logging When enabled, logs will be written to "rats.log" by default.

Parameters
enabledWhether to enable file logging

◆ set_max_peers()

void librats::RatsClient::set_max_peers ( int  max_peers)

Set maximum number of peers.

Parameters
max_peersNew maximum peer count

◆ set_mdns_callback()

void librats::RatsClient::set_mdns_callback ( std::function< void(const std::string &, int, const std::string &)>  callback)

Set mDNS service discovery callback.

Parameters
callbackFunction to call when services are discovered

◆ set_noise_static_keypair()

bool librats::RatsClient::set_noise_static_keypair ( const uint8_t  private_key[32])

Set a custom static keypair for Noise Protocol If not set, a new keypair is generated automatically.

Parameters
private_key32-byte private key
Returns
true if the keypair was set successfully

◆ set_protocol_name()

void librats::RatsClient::set_protocol_name ( const std::string &  protocol_name)

Set custom protocol name for handshakes and DHT discovery.

Parameters
protocol_nameCustom protocol name (default: "rats")

◆ set_protocol_version()

void librats::RatsClient::set_protocol_version ( const std::string &  protocol_version)

Set custom protocol version for handshakes.

Parameters
protocol_versionCustom protocol version (default: "1.0")

◆ set_reconnect_config()

void librats::RatsClient::set_reconnect_config ( const ReconnectConfig config)

Set reconnection configuration.

Parameters
configReconnection configuration settings

◆ set_reconnect_enabled()

void librats::RatsClient::set_reconnect_enabled ( bool  enabled)

Enable or disable automatic reconnection to disconnected peers.

Parameters
enabledWhether auto-reconnection should be enabled

◆ set_resume_data_path()

void librats::RatsClient::set_resume_data_path ( const std::string &  path)

Set the directory for storing resume data files Resume data allows torrents to resume from where they left off.

Should be called after enable_bittorrent() and before adding torrents.

Parameters
pathDirectory path for resume data (e.g., app data folder)

◆ set_spider_announce_callback()

void librats::RatsClient::set_spider_announce_callback ( SpiderAnnounceCallback  callback)

Set callback for announce_peer requests (spider mode) Called when other peers announce they have a torrent.

Parameters
callbackThe callback to invoke

◆ set_spider_ignore()

void librats::RatsClient::set_spider_ignore ( bool  ignore)

Set spider ignore mode - when true, incoming requests are not processed Useful for rate limiting in spider mode.

Parameters
ignoretrue to ignore incoming requests, false to process them

◆ set_spider_mode()

void librats::RatsClient::set_spider_mode ( bool  enable)

Enable spider mode on DHT In spider mode:

  • Nodes are added to routing table without ping verification
  • All announce_peer requests from other peers are collected via callback
    Parameters
    enabletrue to enable spider mode, false to disable

◆ set_storage_config()

void librats::RatsClient::set_storage_config ( const StorageConfig &  config)

Set storage configuration.

Parameters
configStorage configuration settings

◆ set_string_data_callback()

void librats::RatsClient::set_string_data_callback ( StringDataCallback  callback)

Set string data callback (called when string data is received)

Parameters
callbackFunction to call when string data is received

◆ set_topic_message_validator()

void librats::RatsClient::set_topic_message_validator ( const std::string &  topic,
std::function< ValidationResult(const std::string &, const std::string &, const std::string &)>  validator 
)

Set a message validator for a GossipSub topic.

Parameters
topicTopic name (empty for global validator)
validatorValidation function returning ACCEPT, REJECT, or IGNORE_MSG

◆ shutdown_all_threads()

void librats::RatsClient::shutdown_all_threads ( )

Shutdown all background threads.

◆ spider_walk()

void librats::RatsClient::spider_walk ( )

Trigger a single spider walk iteration Sends find_node to a random node from the spider pool Call this periodically at desired frequency to discover new nodes.

◆ start()

bool librats::RatsClient::start ( )

Start the RatsClient and begin listening for connections.

Returns
true if successful, false otherwise

◆ start_automatic_peer_discovery()

void librats::RatsClient::start_automatic_peer_discovery ( )

Start automatic peer discovery.

◆ start_dht_discovery()

bool librats::RatsClient::start_dht_discovery ( int  dht_port = 6881)

Start DHT discovery on specified port.

Parameters
dht_portPort for DHT communication (default: 6881)
Returns
true if started successfully

◆ start_ice_checks()

void librats::RatsClient::start_ice_checks ( )

Start ICE connectivity checks.

◆ start_mdns_discovery()

bool librats::RatsClient::start_mdns_discovery ( const std::string &  service_instance_name = "",
const std::map< std::string, std::string > &  txt_records = {} 
)

Start mDNS service discovery and announcement.

Parameters
service_instance_nameService instance name (optional)
txt_recordsAdditional TXT records for service announcement
Returns
true if started successfully

◆ stop()

void librats::RatsClient::stop ( )

Stop the RatsClient and close all connections.

◆ stop_automatic_peer_discovery()

void librats::RatsClient::stop_automatic_peer_discovery ( )

Stop automatic peer discovery.

◆ stop_dht_discovery()

void librats::RatsClient::stop_dht_discovery ( )

Stop DHT discovery.

◆ stop_mdns_discovery()

void librats::RatsClient::stop_mdns_discovery ( )

Stop mDNS discovery.

◆ storage_delete()

bool librats::RatsClient::storage_delete ( const std::string &  key)

Delete a key from storage.

Parameters
keyKey to delete
Returns
true if key existed and was deleted

◆ storage_get_binary()

std::optional< std::vector< uint8_t > > librats::RatsClient::storage_get_binary ( const std::string &  key) const

Get binary data.

Parameters
keyKey to retrieve
Returns
Optional containing value if found and type matches

◆ storage_get_double()

std::optional< double > librats::RatsClient::storage_get_double ( const std::string &  key) const

Get a double-precision floating point value.

Parameters
keyKey to retrieve
Returns
Optional containing value if found and type matches

◆ storage_get_int()

std::optional< int64_t > librats::RatsClient::storage_get_int ( const std::string &  key) const

Get a 64-bit integer value.

Parameters
keyKey to retrieve
Returns
Optional containing value if found and type matches

◆ storage_get_json()

std::optional< nlohmann::json > librats::RatsClient::storage_get_json ( const std::string &  key) const

Get a JSON document.

Parameters
keyKey to retrieve
Returns
Optional containing value if found and type matches

◆ storage_get_string()

std::optional< std::string > librats::RatsClient::storage_get_string ( const std::string &  key) const

Get a string value.

Parameters
keyKey to retrieve
Returns
Optional containing value if found and type matches

◆ storage_has()

bool librats::RatsClient::storage_has ( const std::string &  key) const

Check if a key exists in storage.

Parameters
keyKey to check
Returns
true if key exists

◆ storage_keys()

std::vector< std::string > librats::RatsClient::storage_keys ( ) const

Get all keys in storage.

Returns
Vector of all keys

◆ storage_keys_with_prefix()

std::vector< std::string > librats::RatsClient::storage_keys_with_prefix ( const std::string &  prefix) const

Get keys matching a prefix.

Parameters
prefixPrefix to match
Returns
Vector of matching keys

◆ storage_put() [1/4]

bool librats::RatsClient::storage_put ( const std::string &  key,
const std::string &  value 
)

Store a string value.

Parameters
keyKey to store under
valueString value to store
Returns
true if stored successfully

◆ storage_put() [2/4]

bool librats::RatsClient::storage_put ( const std::string &  key,
const std::vector< uint8_t > &  value 
)

Store binary data.

Parameters
keyKey to store under
valueBinary data to store
Returns
true if stored successfully

◆ storage_put() [3/4]

bool librats::RatsClient::storage_put ( const std::string &  key,
double  value 
)

Store a double-precision floating point value.

Parameters
keyKey to store under
valueDouble value to store
Returns
true if stored successfully

◆ storage_put() [4/4]

bool librats::RatsClient::storage_put ( const std::string &  key,
int64_t  value 
)

Store a 64-bit integer value.

Parameters
keyKey to store under
valueInteger value to store
Returns
true if stored successfully

◆ storage_put_json()

bool librats::RatsClient::storage_put_json ( const std::string &  key,
const nlohmann::json &  value 
)

Store a JSON document.

Parameters
keyKey to store under
valueJSON value to store
Returns
true if stored successfully

◆ storage_request_sync()

bool librats::RatsClient::storage_request_sync ( )

Request storage sync from connected peers.

Returns
true if sync request was sent

◆ storage_size()

size_t librats::RatsClient::storage_size ( ) const

Get the number of entries in storage.

Returns
Number of entries

◆ subscribe_to_topic()

bool librats::RatsClient::subscribe_to_topic ( const std::string &  topic)

Subscribe to a GossipSub topic.

Parameters
topicTopic name to subscribe to
Returns
true if subscription successful

◆ unsubscribe_from_topic()

bool librats::RatsClient::unsubscribe_from_topic ( const std::string &  topic)

Unsubscribe from a GossipSub topic.

Parameters
topicTopic name to unsubscribe from
Returns
true if unsubscription successful

The documentation for this class was generated from the following file: