rippled
Loading...
Searching...
No Matches
OverlayImpl.cpp
1#include <xrpld/app/misc/ValidatorList.h>
2#include <xrpld/app/misc/ValidatorSite.h>
3#include <xrpld/overlay/Cluster.h>
4#include <xrpld/overlay/detail/ConnectAttempt.h>
5#include <xrpld/overlay/detail/PeerImp.h>
6#include <xrpld/overlay/detail/TrafficCount.h>
7#include <xrpld/overlay/detail/Tuning.h>
8#include <xrpld/overlay/predicates.h>
9#include <xrpld/peerfinder/make_Manager.h>
10#include <xrpld/rpc/handlers/GetCounts.h>
11#include <xrpld/rpc/json_body.h>
12
13#include <xrpl/basics/base64.h>
14#include <xrpl/basics/make_SSLContext.h>
15#include <xrpl/basics/random.h>
16#include <xrpl/beast/core/LexicalCast.h>
17#include <xrpl/core/HashRouter.h>
18#include <xrpl/protocol/STTx.h>
19#include <xrpl/rdb/RelationalDatabase.h>
20#include <xrpl/server/NetworkOPs.h>
21#include <xrpl/server/SimpleWriter.h>
22#include <xrpl/server/Wallet.h>
23
24#include <boost/algorithm/string/predicate.hpp>
25#include <boost/asio/executor_work_guard.hpp>
26
27namespace xrpl {
28
29namespace CrawlOptions {
30enum { Disabled = 0, Overlay = (1 << 0), ServerInfo = (1 << 1), ServerCounts = (1 << 2), Unl = (1 << 3) };
31}
32
33//------------------------------------------------------------------------------
34
35OverlayImpl::Child::Child(OverlayImpl& overlay) : overlay_(overlay)
36{
37}
38
40{
41 overlay_.remove(*this);
42}
43
44//------------------------------------------------------------------------------
45
47{
48}
49
50void
52{
53 // This method is only ever called from the same strand that calls
54 // Timer::on_timer, ensuring they never execute concurrently.
55 stopping_ = true;
56 timer_.cancel();
57}
58
59void
61{
62 timer_.expires_after(std::chrono::seconds(1));
63 timer_.async_wait(
64 boost::asio::bind_executor(
65 overlay_.strand_, std::bind(&Timer::on_timer, shared_from_this(), std::placeholders::_1)));
66}
67
68void
70{
71 if (ec || stopping_)
72 {
73 if (ec && ec != boost::asio::error::operation_aborted)
74 {
75 JLOG(overlay_.journal_.error()) << "on_timer: " << ec.message();
76 }
77 return;
78 }
79
80 overlay_.m_peerFinder->once_per_second();
81 overlay_.sendEndpoints();
82 overlay_.autoConnect();
83 if (overlay_.app_.config().TX_REDUCE_RELAY_ENABLE)
84 overlay_.sendTxQueue();
85
86 if ((++overlay_.timer_count_ % Tuning::checkIdlePeers) == 0)
87 overlay_.deleteIdlePeers();
88
89 async_wait();
90}
91
92//------------------------------------------------------------------------------
93
95 Application& app,
96 Setup const& setup,
97 ServerHandler& serverHandler,
99 Resolver& resolver,
100 boost::asio::io_context& io_context,
101 BasicConfig const& config,
102 beast::insight::Collector::ptr const& collector)
103 : app_(app)
104 , io_context_(io_context)
105 , work_(std::in_place, boost::asio::make_work_guard(io_context_))
106 , strand_(boost::asio::make_strand(io_context_))
107 , setup_(setup)
108 , journal_(app_.journal("Overlay"))
109 , serverHandler_(serverHandler)
111 , m_peerFinder(PeerFinder::make_Manager(io_context, stopwatch(), app_.journal("PeerFinder"), config, collector))
112 , m_resolver(resolver)
113 , next_id_(1)
114 , timer_count_(0)
115 , slots_(app.logs(), *this, app.config())
116 , m_stats(std::bind(&OverlayImpl::collect_metrics, this), collector, [counts = m_traffic.getCounts(), collector]() {
118
119 for (auto const& pair : counts)
120 ret.emplace(pair.first, TrafficGauges(pair.second.name, collector));
121
122 return ret;
123 }())
124{
126}
127
128Handoff
130 std::unique_ptr<stream_type>&& stream_ptr,
131 http_request_type&& request,
132 endpoint_type remote_endpoint)
133{
134 auto const id = next_id_++;
135 beast::WrappedSink sink(app_.logs()["Peer"], makePrefix(id));
136 beast::Journal journal(sink);
137
138 Handoff handoff;
139 if (processRequest(request, handoff))
140 return handoff;
141 if (!isPeerUpgrade(request))
142 return handoff;
143
144 handoff.moved = true;
145
146 JLOG(journal.debug()) << "Peer connection upgrade from " << remote_endpoint;
147
148 error_code ec;
149 auto const local_endpoint(stream_ptr->next_layer().socket().local_endpoint(ec));
150 if (ec)
151 {
152 JLOG(journal.debug()) << remote_endpoint << " failed: " << ec.message();
153 return handoff;
154 }
155
157 if (consumer.disconnect(journal))
158 return handoff;
159
160 auto const [slot, result] = m_peerFinder->new_inbound_slot(
162
163 if (slot == nullptr)
164 {
165 // connection refused either IP limit exceeded or self-connect
166 handoff.moved = false;
167 JLOG(journal.debug()) << "Peer " << remote_endpoint << " refused, " << to_string(result);
168 return handoff;
169 }
170
171 // Validate HTTP request
172
173 {
174 auto const types = beast::rfc2616::split_commas(request["Connect-As"]);
175 if (std::find_if(types.begin(), types.end(), [](std::string const& s) { return boost::iequals(s, "peer"); }) ==
176 types.end())
177 {
178 handoff.moved = false;
179 handoff.response = makeRedirectResponse(slot, request, remote_endpoint.address());
180 handoff.keep_alive = beast::rfc2616::is_keep_alive(request);
181 return handoff;
182 }
183 }
184
185 auto const negotiatedVersion = negotiateProtocolVersion(request["Upgrade"]);
186 if (!negotiatedVersion)
187 {
188 m_peerFinder->on_closed(slot);
189 handoff.moved = false;
190 handoff.response =
191 makeErrorResponse(slot, request, remote_endpoint.address(), "Unable to agree on a protocol version");
192 handoff.keep_alive = false;
193 return handoff;
194 }
195
196 auto const sharedValue = makeSharedValue(*stream_ptr, journal);
197 if (!sharedValue)
198 {
199 m_peerFinder->on_closed(slot);
200 handoff.moved = false;
201 handoff.response = makeErrorResponse(slot, request, remote_endpoint.address(), "Incorrect security cookie");
202 handoff.keep_alive = false;
203 return handoff;
204 }
205
206 try
207 {
208 auto publicKey =
209 verifyHandshake(request, *sharedValue, setup_.networkID, setup_.public_ip, remote_endpoint.address(), app_);
210
211 consumer.setPublicKey(publicKey);
212
213 {
214 // The node gets a reserved slot if it is in our cluster
215 // or if it has a reservation.
216 bool const reserved =
217 static_cast<bool>(app_.cluster().member(publicKey)) || app_.peerReservations().contains(publicKey);
218 auto const result = m_peerFinder->activate(slot, publicKey, reserved);
219 if (result != PeerFinder::Result::success)
220 {
221 m_peerFinder->on_closed(slot);
222 JLOG(journal.debug()) << "Peer " << remote_endpoint << " redirected, " << to_string(result);
223 handoff.moved = false;
224 handoff.response = makeRedirectResponse(slot, request, remote_endpoint.address());
225 handoff.keep_alive = false;
226 return handoff;
227 }
228 }
229
230 auto const peer = std::make_shared<PeerImp>(
231 app_, id, slot, std::move(request), publicKey, *negotiatedVersion, consumer, std::move(stream_ptr), *this);
232 {
233 // As we are not on the strand, run() must be called
234 // while holding the lock, otherwise new I/O can be
235 // queued after a call to stop().
236 std::lock_guard<decltype(mutex_)> lock(mutex_);
237 {
238 auto const result = m_peers.emplace(peer->slot(), peer);
239 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::onHandoff : peer is inserted");
240 (void)result.second;
241 }
242 list_.emplace(peer.get(), peer);
243
244 peer->run();
245 }
246 handoff.moved = true;
247 return handoff;
248 }
249 catch (std::exception const& e)
250 {
251 JLOG(journal.debug()) << "Peer " << remote_endpoint << " fails handshake (" << e.what() << ")";
252
253 m_peerFinder->on_closed(slot);
254 handoff.moved = false;
255 handoff.response = makeErrorResponse(slot, request, remote_endpoint.address(), e.what());
256 handoff.keep_alive = false;
257 return handoff;
258 }
259}
260
261//------------------------------------------------------------------------------
262
263bool
265{
266 if (!is_upgrade(request))
267 return false;
268 auto const versions = parseProtocolVersions(request["Upgrade"]);
269 return !versions.empty();
270}
271
274{
276 ss << "[" << std::setfill('0') << std::setw(3) << id << "] ";
277 return ss.str();
278}
279
283 http_request_type const& request,
284 address_type remote_address)
285{
286 boost::beast::http::response<json_body> msg;
287 msg.version(request.version());
288 msg.result(boost::beast::http::status::service_unavailable);
289 msg.insert("Server", BuildInfo::getFullVersionString());
290 {
292 ostr << remote_address;
293 msg.insert("Remote-Address", ostr.str());
294 }
295 msg.insert("Content-Type", "application/json");
296 msg.insert(boost::beast::http::field::connection, "close");
297 msg.body() = Json::objectValue;
298 {
299 Json::Value& ips = (msg.body()["peer-ips"] = Json::arrayValue);
300 for (auto const& _ : m_peerFinder->redirect(slot))
301 ips.append(_.address.to_string());
302 }
303 msg.prepare_payload();
305}
306
310 http_request_type const& request,
311 address_type remote_address,
312 std::string text)
313{
314 boost::beast::http::response<boost::beast::http::empty_body> msg;
315 msg.version(request.version());
316 msg.result(boost::beast::http::status::bad_request);
317 msg.reason("Bad Request (" + text + ")");
318 msg.insert("Server", BuildInfo::getFullVersionString());
319 msg.insert("Remote-Address", remote_address.to_string());
320 msg.insert(boost::beast::http::field::connection, "close");
321 msg.prepare_payload();
323}
324
325//------------------------------------------------------------------------------
326
327void
329{
330 XRPL_ASSERT(work_, "xrpl::OverlayImpl::connect : work is set");
331
332 auto usage = resourceManager().newOutboundEndpoint(remote_endpoint);
333 if (usage.disconnect(journal_))
334 {
335 JLOG(journal_.info()) << "Over resource limit: " << remote_endpoint;
336 return;
337 }
338
339 auto const [slot, result] = peerFinder().new_outbound_slot(remote_endpoint);
340 if (slot == nullptr)
341 {
342 JLOG(journal_.debug()) << "Connect: No slot for " << remote_endpoint << ": " << to_string(result);
343 return;
344 }
345
347 app_,
350 usage,
352 next_id_++,
353 slot,
354 app_.journal("Peer"),
355 *this);
356
358 list_.emplace(p.get(), p);
359 p->run();
360}
361
362//------------------------------------------------------------------------------
363
364// Adds a peer that is already handshaked and active
365void
367{
368 beast::WrappedSink sink{journal_.sink(), peer->prefix()};
369 beast::Journal journal{sink};
370
372
373 {
374 auto const result = m_peers.emplace(peer->slot(), peer);
375 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer is inserted");
376 (void)result.second;
377 }
378
379 {
380 auto const result = ids_.emplace(std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer));
381 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer ID is inserted");
382 (void)result.second;
383 }
384
385 list_.emplace(peer.get(), peer);
386
387 JLOG(journal.debug()) << "activated";
388
389 // As we are not on the strand, run() must be called
390 // while holding the lock, otherwise new I/O can be
391 // queued after a call to stop().
392 peer->run();
393}
394
395void
397{
399 auto const iter = m_peers.find(slot);
400 XRPL_ASSERT(iter != m_peers.end(), "xrpl::OverlayImpl::remove : valid input");
401 m_peers.erase(iter);
402}
403
404void
406{
408 app_.config(),
409 serverHandler_.setup().overlay.port(),
410 app_.getValidationPublicKey().has_value(),
412
413 m_peerFinder->setConfig(config);
414 m_peerFinder->start();
415
416 // Populate our boot cache: if there are no entries in [ips] then we use
417 // the entries in [ips_fixed].
418 auto bootstrapIps = app_.config().IPS.empty() ? app_.config().IPS_FIXED : app_.config().IPS;
419
420 // If nothing is specified, default to several well-known high-capacity
421 // servers to serve as bootstrap:
422 if (bootstrapIps.empty())
423 {
424 // Pool of servers operated by Ripple Labs Inc. - https://ripple.com
425 bootstrapIps.push_back("r.ripple.com 51235");
426
427 // Pool of servers operated by ISRDC - https://isrdc.in
428 bootstrapIps.push_back("sahyadri.isrdc.in 51235");
429
430 // Pool of servers operated by @Xrpkuwait - https://xrpkuwait.com
431 bootstrapIps.push_back("hubs.xrpkuwait.com 51235");
432
433 // Pool of servers operated by XRPL Commons - https://xrpl-commons.org
434 bootstrapIps.push_back("hub.xrpl-commons.org 51235");
435 }
436
438 bootstrapIps, [this](std::string const& name, std::vector<beast::IP::Endpoint> const& addresses) {
440 ips.reserve(addresses.size());
441 for (auto const& addr : addresses)
442 {
443 if (addr.port() == 0)
444 ips.push_back(to_string(addr.at_port(DEFAULT_PEER_PORT)));
445 else
446 ips.push_back(to_string(addr));
447 }
448
449 std::string const base("config: ");
450 if (!ips.empty())
451 m_peerFinder->addFallbackStrings(base + name, ips);
452 });
453
454 // Add the ips_fixed from the xrpld.cfg file
456 {
459 [this](std::string const& name, std::vector<beast::IP::Endpoint> const& addresses) {
461 ips.reserve(addresses.size());
462
463 for (auto& addr : addresses)
464 {
465 if (addr.port() == 0)
466 ips.emplace_back(addr.address(), DEFAULT_PEER_PORT);
467 else
468 ips.emplace_back(addr);
469 }
470
471 if (!ips.empty())
472 m_peerFinder->addFixedPeer(name, ips);
473 });
474 }
475 auto const timer = std::make_shared<Timer>(*this);
477 list_.emplace(timer.get(), timer);
478 timer_ = timer;
479 timer->async_wait();
480}
481
482void
484{
485 boost::asio::dispatch(strand_, std::bind(&OverlayImpl::stopChildren, this));
486 {
487 std::unique_lock<decltype(mutex_)> lock(mutex_);
488 cond_.wait(lock, [this] { return list_.empty(); });
489 }
490 m_peerFinder->stop();
491}
492
493//------------------------------------------------------------------------------
494//
495// PropertyStream
496//
497//------------------------------------------------------------------------------
498
499void
501{
502 beast::PropertyStream::Set set("traffic", stream);
503 auto const stats = m_traffic.getCounts();
504 for (auto const& pair : stats)
505 {
507 item["category"] = pair.second.name;
508 item["bytes_in"] = std::to_string(pair.second.bytesIn.load());
509 item["messages_in"] = std::to_string(pair.second.messagesIn.load());
510 item["bytes_out"] = std::to_string(pair.second.bytesOut.load());
511 item["messages_out"] = std::to_string(pair.second.messagesOut.load());
512 }
513}
514
515//------------------------------------------------------------------------------
521void
523{
524 beast::WrappedSink sink{journal_.sink(), peer->prefix()};
525 beast::Journal journal{sink};
526
527 // Now track this peer
528 {
530 auto const result(ids_.emplace(std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer)));
531 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::activate : peer ID is inserted");
532 (void)result.second;
533 }
534
535 JLOG(journal.debug()) << "activated";
536
537 // We just accepted this peer so we have non-zero active peers
538 XRPL_ASSERT(size(), "xrpl::OverlayImpl::activate : nonzero peers");
539}
540
541void
547
548void
550{
551 auto const n = m->list_size();
552 auto const& journal = from->pJournal();
553
554 protocol::TMManifests relay;
555
556 for (std::size_t i = 0; i < n; ++i)
557 {
558 auto& s = m->list().Get(i).stobject();
559
560 if (auto mo = deserializeManifest(s))
561 {
562 auto const serialized = mo->serialized;
563
564 auto const result = app_.validatorManifests().applyManifest(std::move(*mo));
565
566 if (result == ManifestDisposition::accepted)
567 {
568 relay.add_list()->set_stobject(s);
569
570 // N.B.: this is important; the applyManifest call above moves
571 // the loaded Manifest out of the optional so we need to
572 // reload it here.
573 mo = deserializeManifest(serialized);
574 XRPL_ASSERT(
575 mo,
576 "xrpl::OverlayImpl::onManifests : manifest "
577 "deserialization succeeded");
578
579 app_.getOPs().pubManifest(*mo);
580
581 if (app_.validators().listed(mo->masterKey))
582 {
583 auto db = app_.getWalletDB().checkoutDb();
584 addValidatorManifest(*db, serialized);
585 }
586 }
587 }
588 else
589 {
590 JLOG(journal.debug()) << "Malformed manifest #" << i + 1 << ": " << strHex(s);
591 continue;
592 }
593 }
594
595 if (!relay.list().empty())
596 for_each([m2 = std::make_shared<Message>(relay, protocol::mtMANIFESTS)](std::shared_ptr<PeerImp>&& p) {
597 p->send(m2);
598 });
599}
600
601void
606
607void
618{
620 return ids_.size();
621}
622
623int
625{
626 return m_peerFinder->config().maxPeers;
627}
628
631{
632 using namespace std::chrono;
633 Json::Value jv;
634 auto& av = jv["active"] = Json::Value(Json::arrayValue);
635
637 auto& pv = av.append(Json::Value(Json::objectValue));
638 pv[jss::public_key] = base64_encode(sp->getNodePublic().data(), sp->getNodePublic().size());
639 pv[jss::type] = sp->slot()->inbound() ? "in" : "out";
640 pv[jss::uptime] = static_cast<std::uint32_t>(duration_cast<seconds>(sp->uptime()).count());
641 if (sp->crawl())
642 {
643 pv[jss::ip] = sp->getRemoteAddress().address().to_string();
644 if (sp->slot()->inbound())
645 {
646 if (auto port = sp->slot()->listening_port())
647 pv[jss::port] = *port;
648 }
649 else
650 {
651 pv[jss::port] = std::to_string(sp->getRemoteAddress().port());
652 }
653 }
654
655 {
656 auto version{sp->getVersion()};
657 if (!version.empty())
658 // Could move here if Json::value supported moving from strings
659 pv[jss::version] = std::string{version};
660 }
661
662 std::uint32_t minSeq, maxSeq;
663 sp->ledgerRange(minSeq, maxSeq);
664 if (minSeq != 0 || maxSeq != 0)
665 pv[jss::complete_ledgers] = std::to_string(minSeq) + "-" + std::to_string(maxSeq);
666 });
667
668 return jv;
669}
670
673{
674 bool const humanReadable = false;
675 bool const admin = false;
676 bool const counters = false;
677
678 Json::Value server_info = app_.getOPs().getServerInfo(humanReadable, admin, counters);
679
680 // Filter out some information
681 server_info.removeMember(jss::hostid);
682 server_info.removeMember(jss::load_factor_fee_escalation);
683 server_info.removeMember(jss::load_factor_fee_queue);
684 server_info.removeMember(jss::validation_quorum);
685
686 if (server_info.isMember(jss::validated_ledger))
687 {
688 Json::Value& validated_ledger = server_info[jss::validated_ledger];
689
690 validated_ledger.removeMember(jss::base_fee);
691 validated_ledger.removeMember(jss::reserve_base_xrp);
692 validated_ledger.removeMember(jss::reserve_inc_xrp);
693 }
694
695 return server_info;
696}
697
703
706{
707 Json::Value validators = app_.validators().getJson();
708
709 if (validators.isMember(jss::publisher_lists))
710 {
711 Json::Value& publisher_lists = validators[jss::publisher_lists];
712
713 for (auto& publisher : publisher_lists)
714 {
715 publisher.removeMember(jss::list);
716 }
717 }
718
719 validators.removeMember(jss::signing_keys);
720 validators.removeMember(jss::trusted_validator_keys);
721 validators.removeMember(jss::validation_quorum);
722
723 Json::Value validatorSites = app_.validatorSites().getJson();
724
725 if (validatorSites.isMember(jss::validator_sites))
726 {
727 validators[jss::validator_sites] = std::move(validatorSites[jss::validator_sites]);
728 }
729
730 return validators;
731}
732
733// Returns information on verified peers.
736{
738 for (auto const& peer : getActivePeers())
739 {
740 json.append(peer->json());
741 }
742 return json;
743}
744
745bool
747{
748 if (req.target() != "/crawl" || setup_.crawlOptions == CrawlOptions::Disabled)
749 return false;
750
751 boost::beast::http::response<json_body> msg;
752 msg.version(req.version());
753 msg.result(boost::beast::http::status::ok);
754 msg.insert("Server", BuildInfo::getFullVersionString());
755 msg.insert("Content-Type", "application/json");
756 msg.insert("Connection", "close");
757 msg.body()["version"] = Json::Value(2u);
758
760 {
761 msg.body()["overlay"] = getOverlayInfo();
762 }
764 {
765 msg.body()["server"] = getServerInfo();
766 }
768 {
769 msg.body()["counts"] = getServerCounts();
770 }
772 {
773 msg.body()["unl"] = getUnlInfo();
774 }
775
776 msg.prepare_payload();
778 return true;
779}
780
781bool
783{
784 // If the target is in the form "/vl/<validator_list_public_key>",
785 // return the most recent validator list for that key.
786 constexpr std::string_view prefix("/vl/");
787
788 if (!req.target().starts_with(prefix.data()) || !setup_.vlEnabled)
789 return false;
790
791 std::uint32_t version = 1;
792
793 boost::beast::http::response<json_body> msg;
794 msg.version(req.version());
795 msg.insert("Server", BuildInfo::getFullVersionString());
796 msg.insert("Content-Type", "application/json");
797 msg.insert("Connection", "close");
798
799 auto fail = [&msg, &handoff](auto status) {
800 msg.result(status);
801 msg.insert("Content-Length", "0");
802
803 msg.body() = Json::nullValue;
804
805 msg.prepare_payload();
807 return true;
808 };
809
810 std::string_view key = req.target().substr(prefix.size());
811
812 if (auto slash = key.find('/'); slash != std::string_view::npos)
813 {
814 auto verString = key.substr(0, slash);
815 if (!boost::conversion::try_lexical_convert(verString, version))
816 return fail(boost::beast::http::status::bad_request);
817 key = key.substr(slash + 1);
818 }
819
820 if (key.empty())
821 return fail(boost::beast::http::status::bad_request);
822
823 // find the list
824 auto vl = app_.validators().getAvailable(key, version);
825
826 if (!vl)
827 {
828 // 404 not found
829 return fail(boost::beast::http::status::not_found);
830 }
831 else if (!*vl)
832 {
833 return fail(boost::beast::http::status::bad_request);
834 }
835 else
836 {
837 msg.result(boost::beast::http::status::ok);
838
839 msg.body() = *vl;
840
841 msg.prepare_payload();
843 return true;
844 }
845}
846
847bool
849{
850 if (req.target() != "/health")
851 return false;
852 boost::beast::http::response<json_body> msg;
853 msg.version(req.version());
854 msg.insert("Server", BuildInfo::getFullVersionString());
855 msg.insert("Content-Type", "application/json");
856 msg.insert("Connection", "close");
857
858 auto info = getServerInfo();
859
860 int last_validated_ledger_age = -1;
861 if (info.isMember(jss::validated_ledger))
862 last_validated_ledger_age = info[jss::validated_ledger][jss::age].asInt();
863 bool amendment_blocked = false;
864 if (info.isMember(jss::amendment_blocked))
865 amendment_blocked = true;
866 int number_peers = info[jss::peers].asInt();
867 std::string server_state = info[jss::server_state].asString();
868 auto load_factor = info[jss::load_factor_server].asDouble() / info[jss::load_base].asDouble();
869
870 enum { healthy, warning, critical };
871 int health = healthy;
872 auto set_health = [&health](int state) {
873 if (health < state)
874 health = state;
875 };
876
877 msg.body()[jss::info] = Json::objectValue;
878 if (last_validated_ledger_age >= 7 || last_validated_ledger_age < 0)
879 {
880 msg.body()[jss::info][jss::validated_ledger] = last_validated_ledger_age;
881 if (last_validated_ledger_age < 20)
882 set_health(warning);
883 else
884 set_health(critical);
885 }
886
887 if (amendment_blocked)
888 {
889 msg.body()[jss::info][jss::amendment_blocked] = true;
890 set_health(critical);
891 }
892
893 if (number_peers <= 7)
894 {
895 msg.body()[jss::info][jss::peers] = number_peers;
896 if (number_peers != 0)
897 set_health(warning);
898 else
899 set_health(critical);
900 }
901
902 if (!(server_state == "full" || server_state == "validating" || server_state == "proposing"))
903 {
904 msg.body()[jss::info][jss::server_state] = server_state;
905 if (server_state == "syncing" || server_state == "tracking" || server_state == "connected")
906 {
907 set_health(warning);
908 }
909 else
910 set_health(critical);
911 }
912
913 if (load_factor > 100)
914 {
915 msg.body()[jss::info][jss::load_factor] = load_factor;
916 if (load_factor < 1000)
917 set_health(warning);
918 else
919 set_health(critical);
920 }
921
922 switch (health)
923 {
924 case healthy:
925 msg.result(boost::beast::http::status::ok);
926 break;
927 case warning:
928 msg.result(boost::beast::http::status::service_unavailable);
929 break;
930 case critical:
931 msg.result(boost::beast::http::status::internal_server_error);
932 break;
933 }
934
935 msg.prepare_payload();
937 return true;
938}
939
940bool
942{
943 // Take advantage of || short-circuiting
944 return processCrawl(req, handoff) || processValidatorList(req, handoff) || processHealth(req, handoff);
945}
946
949{
951 ret.reserve(size());
952
953 for_each([&ret](std::shared_ptr<PeerImp>&& sp) { ret.emplace_back(std::move(sp)); });
954
955 return ret;
956}
957
960 std::set<Peer::id_t> const& toSkip,
961 std::size_t& active,
962 std::size_t& disabled,
963 std::size_t& enabledInSkip) const
964{
967
968 active = ids_.size();
969 disabled = enabledInSkip = 0;
970 ret.reserve(ids_.size());
971
972 // NOTE The purpose of p is to delay the destruction of PeerImp
974 for (auto& [id, w] : ids_)
975 {
976 if (p = w.lock(); p != nullptr)
977 {
978 bool const reduceRelayEnabled = p->txReduceRelayEnabled();
979 // tx reduced relay feature disabled
980 if (!reduceRelayEnabled)
981 ++disabled;
982
983 if (toSkip.count(id) == 0)
984 ret.emplace_back(std::move(p));
985 else if (reduceRelayEnabled)
986 ++enabledInSkip;
987 }
988 }
989
990 return ret;
991}
992
993void
995{
996 for_each([index](std::shared_ptr<PeerImp>&& sp) { sp->checkTracking(index); });
997}
998
1001{
1002 std::lock_guard lock(mutex_);
1003 auto const iter = ids_.find(id);
1004 if (iter != ids_.end())
1005 return iter->second.lock();
1006 return {};
1007}
1008
1009// A public key hash map was not used due to the peer connect/disconnect
1010// update overhead outweighing the performance of a small set linear search.
1013{
1014 std::lock_guard lock(mutex_);
1015 // NOTE The purpose of peer is to delay the destruction of PeerImp
1017 for (auto const& e : ids_)
1018 {
1019 if (peer = e.second.lock(); peer != nullptr)
1020 {
1021 if (peer->getNodePublic() == pubKey)
1022 return peer;
1023 }
1024 }
1025 return {};
1026}
1027
1028void
1029OverlayImpl::broadcast(protocol::TMProposeSet& m)
1030{
1031 auto const sm = std::make_shared<Message>(m, protocol::mtPROPOSE_LEDGER);
1032 for_each([&](std::shared_ptr<PeerImp>&& p) { p->send(sm); });
1033}
1034
1036OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey const& validator)
1037{
1038 if (auto const toSkip = app_.getHashRouter().shouldRelay(uid))
1039 {
1040 auto const sm = std::make_shared<Message>(m, protocol::mtPROPOSE_LEDGER, validator);
1042 if (toSkip->find(p->id()) == toSkip->end())
1043 p->send(sm);
1044 });
1045 return *toSkip;
1046 }
1047 return {};
1048}
1049
1050void
1051OverlayImpl::broadcast(protocol::TMValidation& m)
1052{
1053 auto const sm = std::make_shared<Message>(m, protocol::mtVALIDATION);
1054 for_each([sm](std::shared_ptr<PeerImp>&& p) { p->send(sm); });
1055}
1056
1058OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey const& validator)
1059{
1060 if (auto const toSkip = app_.getHashRouter().shouldRelay(uid))
1061 {
1062 auto const sm = std::make_shared<Message>(m, protocol::mtVALIDATION, validator);
1064 if (toSkip->find(p->id()) == toSkip->end())
1065 p->send(sm);
1066 });
1067 return *toSkip;
1068 }
1069 return {};
1070}
1071
1074{
1076
1077 if (auto seq = app_.validatorManifests().sequence(); seq != manifestListSeq_)
1078 {
1079 protocol::TMManifests tm;
1080
1082 [&tm](std::size_t s) { tm.mutable_list()->Reserve(s); },
1083 [&tm, &hr = app_.getHashRouter()](Manifest const& manifest) {
1084 tm.add_list()->set_stobject(manifest.serialized.data(), manifest.serialized.size());
1085 hr.addSuppression(manifest.hash());
1086 });
1087
1089
1090 if (tm.list_size() != 0)
1091 manifestMessage_ = std::make_shared<Message>(tm, protocol::mtMANIFESTS);
1092
1093 manifestListSeq_ = seq;
1094 }
1095
1096 return manifestMessage_;
1097}
1098
1099void
1101 uint256 const& hash,
1103 std::set<Peer::id_t> const& toSkip)
1104{
1105 bool relay = tx.has_value();
1106 if (relay)
1107 {
1108 auto& txn = tx->get();
1109 SerialIter sit(makeSlice(txn.rawtransaction()));
1110 try
1111 {
1112 relay = !isPseudoTx(STTx{sit});
1113 }
1114 catch (std::exception const&)
1115 {
1116 // Could not construct STTx, not relaying
1117 JLOG(journal_.debug()) << "Could not construct STTx: " << hash;
1118 return;
1119 }
1120 }
1121
1122 Overlay::PeerSequence peers = {};
1123 std::size_t total = 0;
1124 std::size_t disabled = 0;
1125 std::size_t enabledInSkip = 0;
1126
1127 if (!relay)
1128 {
1130 return;
1131
1132 peers = getActivePeers(toSkip, total, disabled, enabledInSkip);
1133 JLOG(journal_.trace()) << "not relaying tx, total peers " << peers.size();
1134 for (auto const& p : peers)
1135 p->addTxQueue(hash);
1136 return;
1137 }
1138
1139 auto& txn = tx->get();
1140 auto const sm = std::make_shared<Message>(txn, protocol::mtTRANSACTION);
1141 peers = getActivePeers(toSkip, total, disabled, enabledInSkip);
1142 auto const minRelay = app_.config().TX_REDUCE_RELAY_MIN_PEERS + disabled;
1143
1144 if (!app_.config().TX_REDUCE_RELAY_ENABLE || total <= minRelay)
1145 {
1146 for (auto const& p : peers)
1147 p->send(sm);
1149 txMetrics_.addMetrics(total, toSkip.size(), 0);
1150 return;
1151 }
1152
1153 // We have more peers than the minimum (disabled + minimum enabled),
1154 // relay to all disabled and some randomly selected enabled that
1155 // do not have the transaction.
1156 auto const enabledTarget =
1157 app_.config().TX_REDUCE_RELAY_MIN_PEERS + (total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100;
1158
1159 txMetrics_.addMetrics(enabledTarget, toSkip.size(), disabled);
1160
1161 if (enabledTarget > enabledInSkip)
1162 std::shuffle(peers.begin(), peers.end(), default_prng());
1163
1164 JLOG(journal_.trace()) << "relaying tx, total peers " << peers.size() << " selected " << enabledTarget << " skip "
1165 << toSkip.size() << " disabled " << disabled;
1166
1167 // count skipped peers with the enabled feature towards the quota
1168 std::uint16_t enabledAndRelayed = enabledInSkip;
1169 for (auto const& p : peers)
1170 {
1171 // always relay to a peer with the disabled feature
1172 if (!p->txReduceRelayEnabled())
1173 {
1174 p->send(sm);
1175 }
1176 else if (enabledAndRelayed < enabledTarget)
1177 {
1178 enabledAndRelayed++;
1179 p->send(sm);
1180 }
1181 else
1182 {
1183 p->addTxQueue(hash);
1184 }
1185 }
1186}
1187
1188//------------------------------------------------------------------------------
1189
1190void
1192{
1193 std::lock_guard lock(mutex_);
1194 list_.erase(&child);
1195 if (list_.empty())
1196 cond_.notify_all();
1197}
1198
1199void
1201{
1202 // Calling list_[].second->stop() may cause list_ to be modified
1203 // (OverlayImpl::remove() may be called on this same thread). So
1204 // iterating directly over list_ to call child->stop() could lead to
1205 // undefined behavior.
1206 //
1207 // Therefore we copy all of the weak/shared ptrs out of list_ before we
1208 // start calling stop() on them. That guarantees OverlayImpl::remove()
1209 // won't be called until vector<> children leaves scope.
1211 {
1212 std::lock_guard lock(mutex_);
1213 if (!work_)
1214 return;
1216
1217 children.reserve(list_.size());
1218 for (auto const& element : list_)
1219 {
1220 children.emplace_back(element.second.lock());
1221 }
1222 } // lock released
1223
1224 for (auto const& child : children)
1225 {
1226 if (child != nullptr)
1227 child->stop();
1228 }
1229}
1230
1231void
1233{
1234 auto const result = m_peerFinder->autoconnect();
1235 for (auto addr : result)
1236 connect(addr);
1237}
1238
1239void
1241{
1242 auto const result = m_peerFinder->buildEndpointsForPeers();
1243 for (auto const& e : result)
1244 {
1246 {
1247 std::lock_guard lock(mutex_);
1248 auto const iter = m_peers.find(e.first);
1249 if (iter != m_peers.end())
1250 peer = iter->second.lock();
1251 }
1252 if (peer)
1253 peer->sendEndpoints(e.second.begin(), e.second.end());
1254 }
1255}
1256
1257void
1259{
1260 for_each([](auto const& p) {
1261 if (p->txReduceRelayEnabled())
1262 p->sendTxQueue();
1263 });
1264}
1265
1267makeSquelchMessage(PublicKey const& validator, bool squelch, uint32_t squelchDuration)
1268{
1269 protocol::TMSquelch m;
1270 m.set_squelch(squelch);
1271 m.set_validatorpubkey(validator.data(), validator.size());
1272 if (squelch)
1273 m.set_squelchduration(squelchDuration);
1274 return std::make_shared<Message>(m, protocol::mtSQUELCH);
1275}
1276
1277void
1279{
1280 if (auto peer = findPeerByShortID(id); peer)
1281 {
1282 // optimize - multiple message with different
1283 // validator might be sent to the same peer
1284 peer->send(makeSquelchMessage(validator, false, 0));
1285 }
1286}
1287
1288void
1289OverlayImpl::squelch(PublicKey const& validator, Peer::id_t id, uint32_t squelchDuration) const
1290{
1291 if (auto peer = findPeerByShortID(id); peer)
1292 {
1293 peer->send(makeSquelchMessage(validator, true, squelchDuration));
1294 }
1295}
1296
1297void
1299 uint256 const& key,
1300 PublicKey const& validator,
1301 std::set<Peer::id_t>&& peers,
1302 protocol::MessageType type)
1303{
1304 if (!slots_.baseSquelchReady())
1305 return;
1306
1307 if (!strand_.running_in_this_thread())
1308 return post(
1309 strand_,
1310 // Must capture copies of reference parameters (i.e. key, validator)
1311 [this, key = key, validator = validator, peers = std::move(peers), type]() mutable {
1312 updateSlotAndSquelch(key, validator, std::move(peers), type);
1313 });
1314
1315 for (auto id : peers)
1316 slots_.updateSlotAndSquelch(
1317 key, validator, id, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); });
1318}
1319
1320void
1322 uint256 const& key,
1323 PublicKey const& validator,
1324 Peer::id_t peer,
1325 protocol::MessageType type)
1326{
1327 if (!slots_.baseSquelchReady())
1328 return;
1329
1330 if (!strand_.running_in_this_thread())
1331 return post(
1332 strand_,
1333 // Must capture copies of reference parameters (i.e. key, validator)
1334 [this, key = key, validator = validator, peer, type]() {
1335 updateSlotAndSquelch(key, validator, peer, type);
1336 });
1337
1338 slots_.updateSlotAndSquelch(
1339 key, validator, peer, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); });
1340}
1341
1342void
1344{
1345 if (!strand_.running_in_this_thread())
1346 return post(strand_, std::bind(&OverlayImpl::deletePeer, this, id));
1347
1348 slots_.deletePeer(id, true);
1349}
1350
1351void
1353{
1354 if (!strand_.running_in_this_thread())
1355 return post(strand_, std::bind(&OverlayImpl::deleteIdlePeers, this));
1356
1357 slots_.deleteIdlePeers();
1358}
1359
1360//------------------------------------------------------------------------------
1361
1364{
1365 Overlay::Setup setup;
1366
1367 {
1368 auto const& section = config.section("overlay");
1369 setup.context = make_SSLContext("");
1370
1371 set(setup.ipLimit, "ip_limit", section);
1372 if (setup.ipLimit < 0)
1373 Throw<std::runtime_error>("Configured IP limit is invalid");
1374
1375 std::string ip;
1376 set(ip, "public_ip", section);
1377 if (!ip.empty())
1378 {
1379 boost::system::error_code ec;
1380 setup.public_ip = boost::asio::ip::make_address(ip, ec);
1381 if (ec || beast::IP::is_private(setup.public_ip))
1382 Throw<std::runtime_error>("Configured public IP is invalid");
1383 }
1384 }
1385
1386 {
1387 auto const& section = config.section("crawl");
1388 auto const& values = section.values();
1389
1390 if (values.size() > 1)
1391 {
1392 Throw<std::runtime_error>("Configured [crawl] section is invalid, too many values");
1393 }
1394
1395 bool crawlEnabled = true;
1396
1397 // Only allow "0|1" as a value
1398 if (values.size() == 1)
1399 {
1400 try
1401 {
1402 crawlEnabled = boost::lexical_cast<bool>(values.front());
1403 }
1404 catch (boost::bad_lexical_cast const&)
1405 {
1406 Throw<std::runtime_error>("Configured [crawl] section has invalid value: " + values.front());
1407 }
1408 }
1409
1410 if (crawlEnabled)
1411 {
1412 if (get<bool>(section, "overlay", true))
1413 {
1415 }
1416 if (get<bool>(section, "server", true))
1417 {
1419 }
1420 if (get<bool>(section, "counts", false))
1421 {
1423 }
1424 if (get<bool>(section, "unl", true))
1425 {
1427 }
1428 }
1429 }
1430 {
1431 auto const& section = config.section("vl");
1432
1433 set(setup.vlEnabled, "enabled", section);
1434 }
1435
1436 try
1437 {
1438 auto id = config.legacy("network_id");
1439
1440 if (!id.empty())
1441 {
1442 if (id == "main")
1443 id = "0";
1444
1445 if (id == "testnet")
1446 id = "1";
1447
1448 if (id == "devnet")
1449 id = "2";
1450
1451 setup.networkID = beast::lexicalCastThrow<std::uint32_t>(id);
1452 }
1453 }
1454 catch (...)
1455 {
1456 Throw<std::runtime_error>(
1457 "Configured [network_id] section is invalid: must be a number "
1458 "or one of the strings 'main', 'testnet' or 'devnet'.");
1459 }
1460
1461 return setup;
1462}
1463
1466 Application& app,
1467 Overlay::Setup const& setup,
1468 ServerHandler& serverHandler,
1469 Resource::Manager& resourceManager,
1470 Resolver& resolver,
1471 boost::asio::io_context& io_context,
1472 BasicConfig const& config,
1473 beast::insight::Collector::ptr const& collector)
1474{
1476 app, setup, serverHandler, resourceManager, resolver, io_context, config, collector);
1477}
1478
1479} // namespace xrpl
T begin(T... args)
T bind(T... args)
Represents a JSON value.
Definition json_value.h:130
Value & append(Value const &value)
Append value to array at the end.
Value removeMember(char const *key)
Remove and return the named member.
bool isMember(char const *key) const
Return true if the object has a member named key.
A version-independent IP address and port combination.
Definition IPEndpoint.h:18
A generic endpoint for log messages.
Definition Journal.h:40
Stream debug() const
Definition Journal.h:300
Sink & sink() const
Returns the Sink associated with this Journal.
Definition Journal.h:269
Stream info() const
Definition Journal.h:306
Stream trace() const
Severity stream access functions.
Definition Journal.h:294
std::string const & name() const
Returns the name of this source.
void add(Source &source)
Add a child source.
Wraps a Journal::Sink to prefix its output with a string.
Definition WrappedSink.h:14
virtual Config & config()=0
virtual std::optional< PublicKey const > getValidationPublicKey() const =0
Holds unparsed configuration information.
void legacy(std::string const &section, std::string value)
Set a value that is not a key/value pair.
Section & section(std::string const &name)
Returns the section with the given name.
std::optional< std::string > member(PublicKey const &node) const
Determines whether a node belongs in the cluster.
Definition Cluster.cpp:19
bool TX_REDUCE_RELAY_ENABLE
Definition Config.h:239
std::vector< std::string > IPS
Definition Config.h:124
bool standalone() const
Definition Config.h:312
std::size_t TX_RELAY_PERCENTAGE
Definition Config.h:252
bool TX_REDUCE_RELAY_METRICS
Definition Config.h:246
std::vector< std::string > IPS_FIXED
Definition Config.h:127
std::size_t TX_REDUCE_RELAY_MIN_PEERS
Definition Config.h:249
LockedSociSession checkoutDb()
std::optional< std::set< PeerShortID > > shouldRelay(uint256 const &key)
Determines whether the hashed item should be relayed.
virtual void pubManifest(Manifest const &)=0
void for_each_manifest(Function &&f) const
Invokes the callback once for every populated manifest.
Definition Manifest.h:388
ManifestDisposition applyManifest(Manifest m)
Add manifest to cache.
Definition Manifest.cpp:343
std::uint32_t sequence() const
A monotonically increasing number used to detect new manifests.
Definition Manifest.h:244
virtual Json::Value getServerInfo(bool human, bool admin, bool counters)=0
Child(OverlayImpl &overlay)
void deletePeer(Peer::id_t id)
Called when the peer is deleted.
void remove(std::shared_ptr< PeerFinder::Slot > const &slot)
std::weak_ptr< Timer > timer_
Definition OverlayImpl.h:89
boost::asio::io_context & io_context_
Definition OverlayImpl.h:84
bool processRequest(http_request_type const &req, Handoff &handoff)
Handles non-peer protocol requests.
OverlayImpl(Application &app, Setup const &setup, ServerHandler &serverHandler, Resource::Manager &resourceManager, Resolver &resolver, boost::asio::io_context &io_context, BasicConfig const &config, beast::insight::Collector::ptr const &collector)
boost::asio::ip::address address_type
Definition OverlayImpl.h:62
static bool isPeerUpgrade(http_request_type const &request)
Resource::Manager & m_resourceManager
Definition OverlayImpl.h:94
boost::system::error_code error_code
Definition OverlayImpl.h:64
bool processCrawl(http_request_type const &req, Handoff &handoff)
Handles crawl requests.
bool processHealth(http_request_type const &req, Handoff &handoff)
Handles health requests.
Json::Value getServerCounts()
Returns information about the local server's performance counters.
void activate(std::shared_ptr< PeerImp > const &peer)
Called when a peer has connected successfully This is called after the peer handshake has been comple...
Handoff onHandoff(std::unique_ptr< stream_type > &&bundle, http_request_type &&request, endpoint_type remote_endpoint) override
Conditionally accept an incoming HTTP request.
std::optional< boost::asio::executor_work_guard< boost::asio::io_context::executor_type > > work_
Definition OverlayImpl.h:85
void reportOutboundTraffic(TrafficCount::category cat, int bytes)
void for_each(UnaryFunc &&f) const
void stop() override
void connect(beast::IP::Endpoint const &remote_endpoint) override
Establish a peer connection to the specified endpoint.
std::size_t size() const override
The number of active peers on the network Active peers are only those peers that have completed the h...
ServerHandler & serverHandler_
Definition OverlayImpl.h:93
void onManifests(std::shared_ptr< protocol::TMManifests > const &m, std::shared_ptr< PeerImp > const &from)
void broadcast(protocol::TMProposeSet &m) override
Broadcast a proposal.
std::shared_ptr< Writer > makeErrorResponse(std::shared_ptr< PeerFinder::Slot > const &slot, http_request_type const &request, address_type remote_address, std::string msg)
reduce_relay::Slots< UptimeClock > slots_
hash_map< Peer::id_t, std::weak_ptr< PeerImp > > ids_
Definition OverlayImpl.h:98
void deleteIdlePeers()
Check if peers stopped relaying messages and if slots stopped receiving messages from the validator.
TrafficCount m_traffic
Definition OverlayImpl.h:96
void squelch(PublicKey const &validator, Peer::id_t const id, std::uint32_t squelchDuration) const override
Squelch handler.
void sendTxQueue()
Send once a second transactions' hashes aggregated by peers.
std::shared_ptr< Message > manifestMessage_
std::unique_ptr< PeerFinder::Manager > m_peerFinder
Definition OverlayImpl.h:95
std::optional< std::uint32_t > manifestListSeq_
void onWrite(beast::PropertyStream::Map &stream) override
Subclass override.
void add_active(std::shared_ptr< PeerImp > const &peer)
PeerFinder::Manager & peerFinder()
Application & app_
Definition OverlayImpl.h:83
std::recursive_mutex mutex_
Definition OverlayImpl.h:87
Resource::Manager & resourceManager()
beast::Journal const journal_
Definition OverlayImpl.h:92
boost::asio::ip::tcp::endpoint endpoint_type
Definition OverlayImpl.h:63
void onPeerDeactivate(Peer::id_t id)
std::mutex manifestLock_
boost::asio::strand< boost::asio::io_context::executor_type > strand_
Definition OverlayImpl.h:86
Json::Value json() override
Return diagnostics on the status of all peers.
static std::string makePrefix(std::uint32_t id)
Setup const & setup() const
std::set< Peer::id_t > relay(protocol::TMProposeSet &m, uint256 const &uid, PublicKey const &validator) override
Relay a proposal.
static bool is_upgrade(boost::beast::http::header< true, Fields > const &req)
metrics::TxMetrics txMetrics_
boost::container::flat_map< Child *, std::weak_ptr< Child > > list_
Definition OverlayImpl.h:90
int limit() override
Returns the maximum number of peers we are configured to allow.
std::condition_variable_any cond_
Definition OverlayImpl.h:88
hash_map< std::shared_ptr< PeerFinder::Slot >, std::weak_ptr< PeerImp > > m_peers
Definition OverlayImpl.h:97
std::shared_ptr< Message > getManifestsMessage()
Json::Value getUnlInfo()
Returns information about the local server's UNL.
std::shared_ptr< Peer > findPeerByPublicKey(PublicKey const &pubKey) override
Returns the peer with the matching public key, or null.
std::shared_ptr< Writer > makeRedirectResponse(std::shared_ptr< PeerFinder::Slot > const &slot, http_request_type const &request, address_type remote_address)
std::atomic< Peer::id_t > next_id_
void reportInboundTraffic(TrafficCount::category cat, int bytes)
bool processValidatorList(http_request_type const &req, Handoff &handoff)
Handles validator list requests.
void checkTracking(std::uint32_t) override
Calls the checkTracking function on each peer.
Resolver & m_resolver
Definition OverlayImpl.h:99
Json::Value getServerInfo()
Returns information about the local server.
void updateSlotAndSquelch(uint256 const &key, PublicKey const &validator, std::set< Peer::id_t > &&peers, protocol::MessageType type)
Updates message count for validator/peer.
std::shared_ptr< Peer > findPeerByShortID(Peer::id_t const &id) const override
Returns the peer with the matching short id, or null.
void start() override
PeerSequence getActivePeers() const override
Returns a sequence representing the current list of peers.
Json::Value getOverlayInfo()
Returns information about peers on the overlay network.
void unsquelch(PublicKey const &validator, Peer::id_t id) const override
Unsquelch handler.
Manages the set of connected peers.
Definition Overlay.h:29
virtual std::pair< std::shared_ptr< Slot >, Result > new_outbound_slot(beast::IP::Endpoint const &remote_endpoint)=0
Create a new outbound slot with the specified remote endpoint.
bool contains(PublicKey const &nodeId)
A public key.
Definition PublicKey.h:42
void resolve(std::vector< std::string > const &names, Handler handler)
resolve all hostnames on the list
Definition Resolver.h:36
Tracks load and resource consumption.
virtual Consumer newOutboundEndpoint(beast::IP::Endpoint const &address)=0
Create a new endpoint keyed by outbound IP address and port.
virtual Consumer newInboundEndpoint(beast::IP::Endpoint const &address)=0
Create a new endpoint keyed by inbound IP address or the forwarded IP if proxied.
std::vector< std::string > const & values() const
Returns all the values in the section.
Definition BasicConfig.h:58
void setup(Setup const &setup, beast::Journal journal)
virtual Logs & logs()=0
virtual ValidatorList & validators()=0
virtual NetworkOPs & getOPs()=0
virtual PeerReservationTable & peerReservations()=0
virtual Cluster & cluster()=0
virtual HashRouter & getHashRouter()=0
virtual DatabaseCon & getWalletDB()=0
Retrieve the "wallet database".
virtual ValidatorSite & validatorSites()=0
virtual ManifestCache & validatorManifests()=0
virtual beast::Journal journal(std::string const &name)=0
void addCount(category cat, bool inbound, int bytes)
Account for traffic associated with the given category.
auto const & getCounts() const
An up-to-date copy of all the counters.
Json::Value getJson() const
Return a JSON representation of the state of the validator list.
std::optional< Json::Value > getAvailable(std::string_view pubKey, std::optional< std::uint32_t > forceVersion={})
Returns the current valid list for the given publisher key, if available, as a Json object.
bool listed(PublicKey const &identity) const
Returns true if public key is included on any lists.
Json::Value getJson() const
Return JSON representation of configured validator sites.
T count(T... args)
T data(T... args)
T emplace_back(T... args)
T emplace(T... args)
T empty(T... args)
T end(T... args)
T find_if(T... args)
T get(T... args)
T is_same_v
T make_tuple(T... args)
@ nullValue
'null' value
Definition json_value.h:19
@ arrayValue
array value (ordered list)
Definition json_value.h:25
@ objectValue
object value (collection of name/value pairs).
Definition json_value.h:26
bool is_private(Address const &addr)
Returns true if the address is a private unroutable address.
Definition IPAddress.h:51
Result split_commas(FwdIt first, FwdIt last)
Definition rfc2616.h:174
bool is_keep_alive(boost::beast::http::message< isRequest, Body, Fields > const &m)
Definition rfc2616.h:356
STL namespace.
std::string const & getFullVersionString()
Full server version string.
Definition BuildInfo.cpp:64
@ checkIdlePeers
How often we check for idle peers (seconds)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
std::vector< ProtocolVersion > parseProtocolVersions(boost::beast::string_view const &value)
Parse a set of protocol versions.
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
std::optional< uint256 > makeSharedValue(stream_type &ssl, beast::Journal journal)
Computes a shared value based on the SSL connection state.
Stopwatch & stopwatch()
Returns an instance of a wall clock.
Definition chrono.h:93
std::string to_string(base_uint< Bits, Tag > const &a)
Definition base_uint.h:597
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:10
std::optional< ProtocolVersion > negotiateProtocolVersion(std::vector< ProtocolVersion > const &versions)
Given a list of supported protocol versions, choose the one we prefer.
boost::beast::http::request< boost::beast::http::dynamic_body > http_request_type
Definition Handoff.h:12
std::shared_ptr< boost::asio::ssl::context > make_SSLContext(std::string const &cipherList)
Create a self-signed SSL context that allows anonymous Diffie Hellman.
std::string base64_encode(std::uint8_t const *data, std::size_t len)
Json::Value getCountsJson(Application &app, int minObjectCount)
Definition GetCounts.cpp:39
void addValidatorManifest(soci::session &session, std::string const &serialized)
addValidatorManifest Saves the manifest of a validator to the database.
Definition Wallet.cpp:88
std::optional< Manifest > deserializeManifest(Slice s, beast::Journal journal)
Constructs Manifest from serialized string.
Definition Manifest.cpp:34
beast::xor_shift_engine & default_prng()
Return the default random engine.
@ manifest
Manifest.
constexpr Number squelch(Number const &x, Number const &limit) noexcept
Definition Number.h:737
std::shared_ptr< Message > makeSquelchMessage(PublicKey const &validator, bool squelch, uint32_t squelchDuration)
Overlay::Setup setup_Overlay(BasicConfig const &config)
std::enable_if_t< std::is_same< T, char >::value||std::is_same< T, unsigned char >::value, Slice > makeSlice(std::array< T, N > const &a)
Definition Slice.h:213
PublicKey verifyHandshake(boost::beast::http::fields const &headers, xrpl::uint256 const &sharedValue, std::optional< std::uint32_t > networkID, beast::IP::Address public_ip, beast::IP::Address remote, Application &app)
Validate header fields necessary for upgrading the link to the peer protocol.
bool isPseudoTx(STObject const &tx)
Check whether a transaction is a pseudo-transaction.
Definition STTx.cpp:776
std::unique_ptr< Overlay > make_Overlay(Application &app, Overlay::Setup const &setup, ServerHandler &serverHandler, Resource::Manager &resourceManager, Resolver &resolver, boost::asio::io_context &io_context, BasicConfig const &config, beast::insight::Collector::ptr const &collector)
Creates the implementation of Overlay.
@ accepted
Manifest is valid.
T piecewise_construct
T push_back(T... args)
T shuffle(T... args)
T reserve(T... args)
T reset(T... args)
T setfill(T... args)
T setw(T... args)
T size(T... args)
T str(T... args)
static boost::asio::ip::tcp::endpoint to_asio_endpoint(IP::Endpoint const &address)
static IP::Endpoint from_asio(boost::asio::ip::address const &address)
Used to indicate the result of a server connection handoff.
Definition Handoff.h:18
std::shared_ptr< Writer > response
Definition Handoff.h:27
bool keep_alive
Definition Handoff.h:24
void on_timer(error_code ec)
Timer(OverlayImpl &overlay)
std::uint32_t crawlOptions
Definition Overlay.h:51
std::optional< std::uint32_t > networkID
Definition Overlay.h:52
std::shared_ptr< boost::asio::ssl::context > context
Definition Overlay.h:48
beast::IP::Address public_ip
Definition Overlay.h:49
PeerFinder configuration settings.
static Config makeConfig(xrpl::Config const &config, std::uint16_t port, bool validationPublicKey, int ipLimit)
Make PeerFinder::Config from configuration parameters.
void addMetrics(protocol::MessageType type, std::uint32_t val)
Add protocol message metrics.
Definition TxMetrics.cpp:12
T substr(T... args)
T to_string(T... args)
T what(T... args)