Back to Site
Loading...
Searching...
No Matches
peer_exchange.h
Go to the documentation of this file.
1#pragma once
2
49#include "librats/util/rats_export.h"
51#include "librats/peer/peer.h"
54
55#include <atomic>
56#include <chrono>
57#include <cstdint>
58#include <mutex>
59#include <string>
60#include <unordered_map>
61#include <vector>
62
63namespace librats {
64
65class ServiceRegistry;
66struct HolePunchService;
67
68class RATS_API PeerExchange final : public Subsystem {
69public:
70 struct Config {
71 size_t max_addresses_per_response = 32;
72 size_t request_max = 32;
73 bool request_on_connect = true;
74 bool public_only = false;
75 std::chrono::milliseconds dial_cooldown{std::chrono::minutes(5)};
76 size_t max_recent_dials = 4096;
77
84 size_t peer_target = 0;
85
88 bool punch_on_dial_failure = true;
91 std::chrono::milliseconds punch_window{std::chrono::seconds(30)};
93 size_t max_pending_dials = 512;
94 };
95
97 explicit PeerExchange(Config config);
98 ~PeerExchange() override;
99
100 void attach(NodeContext& ctx) override;
101 void start() override;
102 void stop() override;
103
104private:
105 void on_connected(const Peer& peer);
106 void handle(const Peer& peer, ByteView payload);
107 void handle_request(const Peer& requester, uint16_t max);
108 void handle_response(ByteView body);
110 void on_dial_failed(const Address& address);
111
112 const Address* pick_shareable(const std::vector<Address>& addrs) const;
113 bool should_dial(const Address& addr);
116 void remember_dial(const Address& addr, const PeerId& id);
117
118 Config config_;
119 PeerNetwork* network_ = nullptr;
120 ServiceRegistry* services_ = nullptr;
123 std::atomic<HolePunchService*> punch_{nullptr};
124 std::atomic<bool> running_{false};
125
126 struct PendingDial {
127 PeerId id;
128 std::chrono::steady_clock::time_point started;
129 };
130
131 std::mutex mutex_;
132 std::unordered_map<Address, std::chrono::steady_clock::time_point> recent_dials_;
133 std::unordered_map<Address, PendingDial> pending_dials_;
134};
135
136} // namespace librats
A dialable transport endpoint: a numeric IP + port.
Non-owning view over a contiguous run of bytes.
Definition bytes.h:27
void stop() override
PeerExchange(Config config)
~PeerExchange() override
void attach(NodeContext &ctx) override
void start() override
A pluggable network subsystem.
Definition node.h:73
A lightweight handle to a connected peer.
Self-certifying peer identity.
The narrow contract a subsystem needs from the node — and nothing more.