rippled
Loading...
Searching...
No Matches
OverlayImpl.cpp
1#include <xrpld/app/misc/HashRouter.h>
2#include <xrpld/app/misc/NetworkOPs.h>
3#include <xrpld/app/misc/ValidatorList.h>
4#include <xrpld/app/misc/ValidatorSite.h>
5#include <xrpld/app/rdb/RelationalDatabase.h>
6#include <xrpld/app/rdb/Wallet.h>
7#include <xrpld/overlay/Cluster.h>
8#include <xrpld/overlay/detail/ConnectAttempt.h>
9#include <xrpld/overlay/detail/PeerImp.h>
10#include <xrpld/overlay/detail/TrafficCount.h>
11#include <xrpld/overlay/detail/Tuning.h>
12#include <xrpld/overlay/predicates.h>
13#include <xrpld/peerfinder/make_Manager.h>
14#include <xrpld/rpc/handlers/GetCounts.h>
15#include <xrpld/rpc/json_body.h>
16
17#include <xrpl/basics/base64.h>
18#include <xrpl/basics/make_SSLContext.h>
19#include <xrpl/basics/random.h>
20#include <xrpl/beast/core/LexicalCast.h>
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/server/SimpleWriter.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(boost::asio::bind_executor(
64 overlay_.strand_, std::bind(&Timer::on_timer, shared_from_this(), std::placeholders::_1)));
65}
66
67void
69{
70 if (ec || stopping_)
71 {
72 if (ec && ec != boost::asio::error::operation_aborted)
73 {
74 JLOG(overlay_.journal_.error()) << "on_timer: " << ec.message();
75 }
76 return;
77 }
78
79 overlay_.m_peerFinder->once_per_second();
80 overlay_.sendEndpoints();
81 overlay_.autoConnect();
82 if (overlay_.app_.config().TX_REDUCE_RELAY_ENABLE)
83 overlay_.sendTxQueue();
84
85 if ((++overlay_.timer_count_ % Tuning::checkIdlePeers) == 0)
86 overlay_.deleteIdlePeers();
87
88 async_wait();
89}
90
91//------------------------------------------------------------------------------
92
94 Application& app,
95 Setup const& setup,
96 ServerHandler& serverHandler,
98 Resolver& resolver,
99 boost::asio::io_context& io_context,
100 BasicConfig const& config,
101 beast::insight::Collector::ptr const& collector)
102 : app_(app)
103 , io_context_(io_context)
104 , work_(std::in_place, boost::asio::make_work_guard(io_context_))
105 , strand_(boost::asio::make_strand(io_context_))
106 , setup_(setup)
107 , journal_(app_.journal("Overlay"))
108 , serverHandler_(serverHandler)
110 , m_peerFinder(PeerFinder::make_Manager(io_context, stopwatch(), app_.journal("PeerFinder"), config, collector))
111 , m_resolver(resolver)
112 , next_id_(1)
113 , timer_count_(0)
114 , slots_(app.logs(), *this, app.config())
115 , m_stats(std::bind(&OverlayImpl::collect_metrics, this), collector, [counts = m_traffic.getCounts(), collector]() {
117
118 for (auto const& pair : counts)
119 ret.emplace(pair.first, TrafficGauges(pair.second.name, collector));
120
121 return ret;
122 }())
123{
125}
126
127Handoff
129 std::unique_ptr<stream_type>&& stream_ptr,
130 http_request_type&& request,
131 endpoint_type remote_endpoint)
132{
133 auto const id = next_id_++;
134 beast::WrappedSink sink(app_.logs()["Peer"], makePrefix(id));
135 beast::Journal journal(sink);
136
137 Handoff handoff;
138 if (processRequest(request, handoff))
139 return handoff;
140 if (!isPeerUpgrade(request))
141 return handoff;
142
143 handoff.moved = true;
144
145 JLOG(journal.debug()) << "Peer connection upgrade from " << remote_endpoint;
146
147 error_code ec;
148 auto const local_endpoint(stream_ptr->next_layer().socket().local_endpoint(ec));
149 if (ec)
150 {
151 JLOG(journal.debug()) << remote_endpoint << " failed: " << ec.message();
152 return handoff;
153 }
154
156 if (consumer.disconnect(journal))
157 return handoff;
158
159 auto const [slot, result] = m_peerFinder->new_inbound_slot(
161
162 if (slot == nullptr)
163 {
164 // connection refused either IP limit exceeded or self-connect
165 handoff.moved = false;
166 JLOG(journal.debug()) << "Peer " << remote_endpoint << " refused, " << to_string(result);
167 return handoff;
168 }
169
170 // Validate HTTP request
171
172 {
173 auto const types = beast::rfc2616::split_commas(request["Connect-As"]);
174 if (std::find_if(types.begin(), types.end(), [](std::string const& s) { return boost::iequals(s, "peer"); }) ==
175 types.end())
176 {
177 handoff.moved = false;
178 handoff.response = makeRedirectResponse(slot, request, remote_endpoint.address());
179 handoff.keep_alive = beast::rfc2616::is_keep_alive(request);
180 return handoff;
181 }
182 }
183
184 auto const negotiatedVersion = negotiateProtocolVersion(request["Upgrade"]);
185 if (!negotiatedVersion)
186 {
187 m_peerFinder->on_closed(slot);
188 handoff.moved = false;
189 handoff.response =
190 makeErrorResponse(slot, request, remote_endpoint.address(), "Unable to agree on a protocol version");
191 handoff.keep_alive = false;
192 return handoff;
193 }
194
195 auto const sharedValue = makeSharedValue(*stream_ptr, journal);
196 if (!sharedValue)
197 {
198 m_peerFinder->on_closed(slot);
199 handoff.moved = false;
200 handoff.response = makeErrorResponse(slot, request, remote_endpoint.address(), "Incorrect security cookie");
201 handoff.keep_alive = false;
202 return handoff;
203 }
204
205 try
206 {
207 auto publicKey =
208 verifyHandshake(request, *sharedValue, setup_.networkID, setup_.public_ip, remote_endpoint.address(), app_);
209
210 consumer.setPublicKey(publicKey);
211
212 {
213 // The node gets a reserved slot if it is in our cluster
214 // or if it has a reservation.
215 bool const reserved =
216 static_cast<bool>(app_.cluster().member(publicKey)) || app_.peerReservations().contains(publicKey);
217 auto const result = m_peerFinder->activate(slot, publicKey, reserved);
218 if (result != PeerFinder::Result::success)
219 {
220 m_peerFinder->on_closed(slot);
221 JLOG(journal.debug()) << "Peer " << remote_endpoint << " redirected, " << to_string(result);
222 handoff.moved = false;
223 handoff.response = makeRedirectResponse(slot, request, remote_endpoint.address());
224 handoff.keep_alive = false;
225 return handoff;
226 }
227 }
228
229 auto const peer = std::make_shared<PeerImp>(
230 app_, id, slot, std::move(request), publicKey, *negotiatedVersion, consumer, std::move(stream_ptr), *this);
231 {
232 // As we are not on the strand, run() must be called
233 // while holding the lock, otherwise new I/O can be
234 // queued after a call to stop().
235 std::lock_guard<decltype(mutex_)> lock(mutex_);
236 {
237 auto const result = m_peers.emplace(peer->slot(), peer);
238 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::onHandoff : peer is inserted");
239 (void)result.second;
240 }
241 list_.emplace(peer.get(), peer);
242
243 peer->run();
244 }
245 handoff.moved = true;
246 return handoff;
247 }
248 catch (std::exception const& e)
249 {
250 JLOG(journal.debug()) << "Peer " << remote_endpoint << " fails handshake (" << e.what() << ")";
251
252 m_peerFinder->on_closed(slot);
253 handoff.moved = false;
254 handoff.response = makeErrorResponse(slot, request, remote_endpoint.address(), e.what());
255 handoff.keep_alive = false;
256 return handoff;
257 }
258}
259
260//------------------------------------------------------------------------------
261
262bool
264{
265 if (!is_upgrade(request))
266 return false;
267 auto const versions = parseProtocolVersions(request["Upgrade"]);
268 return !versions.empty();
269}
270
273{
275 ss << "[" << std::setfill('0') << std::setw(3) << id << "] ";
276 return ss.str();
277}
278
282 http_request_type const& request,
283 address_type remote_address)
284{
285 boost::beast::http::response<json_body> msg;
286 msg.version(request.version());
287 msg.result(boost::beast::http::status::service_unavailable);
288 msg.insert("Server", BuildInfo::getFullVersionString());
289 {
291 ostr << remote_address;
292 msg.insert("Remote-Address", ostr.str());
293 }
294 msg.insert("Content-Type", "application/json");
295 msg.insert(boost::beast::http::field::connection, "close");
296 msg.body() = Json::objectValue;
297 {
298 Json::Value& ips = (msg.body()["peer-ips"] = Json::arrayValue);
299 for (auto const& _ : m_peerFinder->redirect(slot))
300 ips.append(_.address.to_string());
301 }
302 msg.prepare_payload();
304}
305
309 http_request_type const& request,
310 address_type remote_address,
311 std::string text)
312{
313 boost::beast::http::response<boost::beast::http::empty_body> msg;
314 msg.version(request.version());
315 msg.result(boost::beast::http::status::bad_request);
316 msg.reason("Bad Request (" + text + ")");
317 msg.insert("Server", BuildInfo::getFullVersionString());
318 msg.insert("Remote-Address", remote_address.to_string());
319 msg.insert(boost::beast::http::field::connection, "close");
320 msg.prepare_payload();
322}
323
324//------------------------------------------------------------------------------
325
326void
328{
329 XRPL_ASSERT(work_, "xrpl::OverlayImpl::connect : work is set");
330
331 auto usage = resourceManager().newOutboundEndpoint(remote_endpoint);
332 if (usage.disconnect(journal_))
333 {
334 JLOG(journal_.info()) << "Over resource limit: " << remote_endpoint;
335 return;
336 }
337
338 auto const [slot, result] = peerFinder().new_outbound_slot(remote_endpoint);
339 if (slot == nullptr)
340 {
341 JLOG(journal_.debug()) << "Connect: No slot for " << remote_endpoint << ": " << to_string(result);
342 return;
343 }
344
346 app_,
349 usage,
351 next_id_++,
352 slot,
353 app_.journal("Peer"),
354 *this);
355
357 list_.emplace(p.get(), p);
358 p->run();
359}
360
361//------------------------------------------------------------------------------
362
363// Adds a peer that is already handshaked and active
364void
366{
367 beast::WrappedSink sink{journal_.sink(), peer->prefix()};
368 beast::Journal journal{sink};
369
371
372 {
373 auto const result = m_peers.emplace(peer->slot(), peer);
374 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer is inserted");
375 (void)result.second;
376 }
377
378 {
379 auto const result = ids_.emplace(std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer));
380 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::add_active : peer ID is inserted");
381 (void)result.second;
382 }
383
384 list_.emplace(peer.get(), peer);
385
386 JLOG(journal.debug()) << "activated";
387
388 // As we are not on the strand, run() must be called
389 // while holding the lock, otherwise new I/O can be
390 // queued after a call to stop().
391 peer->run();
392}
393
394void
396{
398 auto const iter = m_peers.find(slot);
399 XRPL_ASSERT(iter != m_peers.end(), "xrpl::OverlayImpl::remove : valid input");
400 m_peers.erase(iter);
401}
402
403void
405{
407 app_.config(),
408 serverHandler_.setup().overlay.port(),
409 app_.getValidationPublicKey().has_value(),
411
412 m_peerFinder->setConfig(config);
413 m_peerFinder->start();
414
415 // Populate our boot cache: if there are no entries in [ips] then we use
416 // the entries in [ips_fixed].
417 auto bootstrapIps = app_.config().IPS.empty() ? app_.config().IPS_FIXED : app_.config().IPS;
418
419 // If nothing is specified, default to several well-known high-capacity
420 // servers to serve as bootstrap:
421 if (bootstrapIps.empty())
422 {
423 // Pool of servers operated by Ripple Labs Inc. - https://ripple.com
424 bootstrapIps.push_back("r.ripple.com 51235");
425
426 // Pool of servers operated by ISRDC - https://isrdc.in
427 bootstrapIps.push_back("sahyadri.isrdc.in 51235");
428
429 // Pool of servers operated by @Xrpkuwait - https://xrpkuwait.com
430 bootstrapIps.push_back("hubs.xrpkuwait.com 51235");
431
432 // Pool of servers operated by XRPL Commons - https://xrpl-commons.org
433 bootstrapIps.push_back("hub.xrpl-commons.org 51235");
434 }
435
437 bootstrapIps, [this](std::string const& name, std::vector<beast::IP::Endpoint> const& addresses) {
439 ips.reserve(addresses.size());
440 for (auto const& addr : addresses)
441 {
442 if (addr.port() == 0)
443 ips.push_back(to_string(addr.at_port(DEFAULT_PEER_PORT)));
444 else
445 ips.push_back(to_string(addr));
446 }
447
448 std::string const base("config: ");
449 if (!ips.empty())
450 m_peerFinder->addFallbackStrings(base + name, ips);
451 });
452
453 // Add the ips_fixed from the xrpld.cfg file
455 {
458 [this](std::string const& name, std::vector<beast::IP::Endpoint> const& addresses) {
460 ips.reserve(addresses.size());
461
462 for (auto& addr : addresses)
463 {
464 if (addr.port() == 0)
465 ips.emplace_back(addr.address(), DEFAULT_PEER_PORT);
466 else
467 ips.emplace_back(addr);
468 }
469
470 if (!ips.empty())
471 m_peerFinder->addFixedPeer(name, ips);
472 });
473 }
474 auto const timer = std::make_shared<Timer>(*this);
476 list_.emplace(timer.get(), timer);
477 timer_ = timer;
478 timer->async_wait();
479}
480
481void
483{
484 boost::asio::dispatch(strand_, std::bind(&OverlayImpl::stopChildren, this));
485 {
486 std::unique_lock<decltype(mutex_)> lock(mutex_);
487 cond_.wait(lock, [this] { return list_.empty(); });
488 }
489 m_peerFinder->stop();
490}
491
492//------------------------------------------------------------------------------
493//
494// PropertyStream
495//
496//------------------------------------------------------------------------------
497
498void
500{
501 beast::PropertyStream::Set set("traffic", stream);
502 auto const stats = m_traffic.getCounts();
503 for (auto const& pair : stats)
504 {
506 item["category"] = pair.second.name;
507 item["bytes_in"] = std::to_string(pair.second.bytesIn.load());
508 item["messages_in"] = std::to_string(pair.second.messagesIn.load());
509 item["bytes_out"] = std::to_string(pair.second.bytesOut.load());
510 item["messages_out"] = std::to_string(pair.second.messagesOut.load());
511 }
512}
513
514//------------------------------------------------------------------------------
520void
522{
523 beast::WrappedSink sink{journal_.sink(), peer->prefix()};
524 beast::Journal journal{sink};
525
526 // Now track this peer
527 {
529 auto const result(ids_.emplace(std::piecewise_construct, std::make_tuple(peer->id()), std::make_tuple(peer)));
530 XRPL_ASSERT(result.second, "xrpl::OverlayImpl::activate : peer ID is inserted");
531 (void)result.second;
532 }
533
534 JLOG(journal.debug()) << "activated";
535
536 // We just accepted this peer so we have non-zero active peers
537 XRPL_ASSERT(size(), "xrpl::OverlayImpl::activate : nonzero peers");
538}
539
540void
546
547void
549{
550 auto const n = m->list_size();
551 auto const& journal = from->pJournal();
552
553 protocol::TMManifests relay;
554
555 for (std::size_t i = 0; i < n; ++i)
556 {
557 auto& s = m->list().Get(i).stobject();
558
559 if (auto mo = deserializeManifest(s))
560 {
561 auto const serialized = mo->serialized;
562
563 auto const result = app_.validatorManifests().applyManifest(std::move(*mo));
564
565 if (result == ManifestDisposition::accepted)
566 {
567 relay.add_list()->set_stobject(s);
568
569 // N.B.: this is important; the applyManifest call above moves
570 // the loaded Manifest out of the optional so we need to
571 // reload it here.
572 mo = deserializeManifest(serialized);
573 XRPL_ASSERT(
574 mo,
575 "xrpl::OverlayImpl::onManifests : manifest "
576 "deserialization succeeded");
577
578 app_.getOPs().pubManifest(*mo);
579
580 if (app_.validators().listed(mo->masterKey))
581 {
582 auto db = app_.getWalletDB().checkoutDb();
583 addValidatorManifest(*db, serialized);
584 }
585 }
586 }
587 else
588 {
589 JLOG(journal.debug()) << "Malformed manifest #" << i + 1 << ": " << strHex(s);
590 continue;
591 }
592 }
593
594 if (!relay.list().empty())
595 for_each([m2 = std::make_shared<Message>(relay, protocol::mtMANIFESTS)](std::shared_ptr<PeerImp>&& p) {
596 p->send(m2);
597 });
598}
599
600void
605
606void
617{
619 return ids_.size();
620}
621
622int
624{
625 return m_peerFinder->config().maxPeers;
626}
627
630{
631 using namespace std::chrono;
632 Json::Value jv;
633 auto& av = jv["active"] = Json::Value(Json::arrayValue);
634
636 auto& pv = av.append(Json::Value(Json::objectValue));
637 pv[jss::public_key] = base64_encode(sp->getNodePublic().data(), sp->getNodePublic().size());
638 pv[jss::type] = sp->slot()->inbound() ? "in" : "out";
639 pv[jss::uptime] = static_cast<std::uint32_t>(duration_cast<seconds>(sp->uptime()).count());
640 if (sp->crawl())
641 {
642 pv[jss::ip] = sp->getRemoteAddress().address().to_string();
643 if (sp->slot()->inbound())
644 {
645 if (auto port = sp->slot()->listening_port())
646 pv[jss::port] = *port;
647 }
648 else
649 {
650 pv[jss::port] = std::to_string(sp->getRemoteAddress().port());
651 }
652 }
653
654 {
655 auto version{sp->getVersion()};
656 if (!version.empty())
657 // Could move here if Json::value supported moving from strings
658 pv[jss::version] = std::string{version};
659 }
660
661 std::uint32_t minSeq, maxSeq;
662 sp->ledgerRange(minSeq, maxSeq);
663 if (minSeq != 0 || maxSeq != 0)
664 pv[jss::complete_ledgers] = std::to_string(minSeq) + "-" + std::to_string(maxSeq);
665 });
666
667 return jv;
668}
669
672{
673 bool const humanReadable = false;
674 bool const admin = false;
675 bool const counters = false;
676
677 Json::Value server_info = app_.getOPs().getServerInfo(humanReadable, admin, counters);
678
679 // Filter out some information
680 server_info.removeMember(jss::hostid);
681 server_info.removeMember(jss::load_factor_fee_escalation);
682 server_info.removeMember(jss::load_factor_fee_queue);
683 server_info.removeMember(jss::validation_quorum);
684
685 if (server_info.isMember(jss::validated_ledger))
686 {
687 Json::Value& validated_ledger = server_info[jss::validated_ledger];
688
689 validated_ledger.removeMember(jss::base_fee);
690 validated_ledger.removeMember(jss::reserve_base_xrp);
691 validated_ledger.removeMember(jss::reserve_inc_xrp);
692 }
693
694 return server_info;
695}
696
702
705{
706 Json::Value validators = app_.validators().getJson();
707
708 if (validators.isMember(jss::publisher_lists))
709 {
710 Json::Value& publisher_lists = validators[jss::publisher_lists];
711
712 for (auto& publisher : publisher_lists)
713 {
714 publisher.removeMember(jss::list);
715 }
716 }
717
718 validators.removeMember(jss::signing_keys);
719 validators.removeMember(jss::trusted_validator_keys);
720 validators.removeMember(jss::validation_quorum);
721
722 Json::Value validatorSites = app_.validatorSites().getJson();
723
724 if (validatorSites.isMember(jss::validator_sites))
725 {
726 validators[jss::validator_sites] = std::move(validatorSites[jss::validator_sites]);
727 }
728
729 return validators;
730}
731
732// Returns information on verified peers.
735{
737 for (auto const& peer : getActivePeers())
738 {
739 json.append(peer->json());
740 }
741 return json;
742}
743
744bool
746{
747 if (req.target() != "/crawl" || setup_.crawlOptions == CrawlOptions::Disabled)
748 return false;
749
750 boost::beast::http::response<json_body> msg;
751 msg.version(req.version());
752 msg.result(boost::beast::http::status::ok);
753 msg.insert("Server", BuildInfo::getFullVersionString());
754 msg.insert("Content-Type", "application/json");
755 msg.insert("Connection", "close");
756 msg.body()["version"] = Json::Value(2u);
757
759 {
760 msg.body()["overlay"] = getOverlayInfo();
761 }
763 {
764 msg.body()["server"] = getServerInfo();
765 }
767 {
768 msg.body()["counts"] = getServerCounts();
769 }
771 {
772 msg.body()["unl"] = getUnlInfo();
773 }
774
775 msg.prepare_payload();
777 return true;
778}
779
780bool
782{
783 // If the target is in the form "/vl/<validator_list_public_key>",
784 // return the most recent validator list for that key.
785 constexpr std::string_view prefix("/vl/");
786
787 if (!req.target().starts_with(prefix.data()) || !setup_.vlEnabled)
788 return false;
789
790 std::uint32_t version = 1;
791
792 boost::beast::http::response<json_body> msg;
793 msg.version(req.version());
794 msg.insert("Server", BuildInfo::getFullVersionString());
795 msg.insert("Content-Type", "application/json");
796 msg.insert("Connection", "close");
797
798 auto fail = [&msg, &handoff](auto status) {
799 msg.result(status);
800 msg.insert("Content-Length", "0");
801
802 msg.body() = Json::nullValue;
803
804 msg.prepare_payload();
806 return true;
807 };
808
809 std::string_view key = req.target().substr(prefix.size());
810
811 if (auto slash = key.find('/'); slash != std::string_view::npos)
812 {
813 auto verString = key.substr(0, slash);
814 if (!boost::conversion::try_lexical_convert(verString, version))
815 return fail(boost::beast::http::status::bad_request);
816 key = key.substr(slash + 1);
817 }
818
819 if (key.empty())
820 return fail(boost::beast::http::status::bad_request);
821
822 // find the list
823 auto vl = app_.validators().getAvailable(key, version);
824
825 if (!vl)
826 {
827 // 404 not found
828 return fail(boost::beast::http::status::not_found);
829 }
830 else if (!*vl)
831 {
832 return fail(boost::beast::http::status::bad_request);
833 }
834 else
835 {
836 msg.result(boost::beast::http::status::ok);
837
838 msg.body() = *vl;
839
840 msg.prepare_payload();
842 return true;
843 }
844}
845
846bool
848{
849 if (req.target() != "/health")
850 return false;
851 boost::beast::http::response<json_body> msg;
852 msg.version(req.version());
853 msg.insert("Server", BuildInfo::getFullVersionString());
854 msg.insert("Content-Type", "application/json");
855 msg.insert("Connection", "close");
856
857 auto info = getServerInfo();
858
859 int last_validated_ledger_age = -1;
860 if (info.isMember(jss::validated_ledger))
861 last_validated_ledger_age = info[jss::validated_ledger][jss::age].asInt();
862 bool amendment_blocked = false;
863 if (info.isMember(jss::amendment_blocked))
864 amendment_blocked = true;
865 int number_peers = info[jss::peers].asInt();
866 std::string server_state = info[jss::server_state].asString();
867 auto load_factor = info[jss::load_factor_server].asDouble() / info[jss::load_base].asDouble();
868
869 enum { healthy, warning, critical };
870 int health = healthy;
871 auto set_health = [&health](int state) {
872 if (health < state)
873 health = state;
874 };
875
876 msg.body()[jss::info] = Json::objectValue;
877 if (last_validated_ledger_age >= 7 || last_validated_ledger_age < 0)
878 {
879 msg.body()[jss::info][jss::validated_ledger] = last_validated_ledger_age;
880 if (last_validated_ledger_age < 20)
881 set_health(warning);
882 else
883 set_health(critical);
884 }
885
886 if (amendment_blocked)
887 {
888 msg.body()[jss::info][jss::amendment_blocked] = true;
889 set_health(critical);
890 }
891
892 if (number_peers <= 7)
893 {
894 msg.body()[jss::info][jss::peers] = number_peers;
895 if (number_peers != 0)
896 set_health(warning);
897 else
898 set_health(critical);
899 }
900
901 if (!(server_state == "full" || server_state == "validating" || server_state == "proposing"))
902 {
903 msg.body()[jss::info][jss::server_state] = server_state;
904 if (server_state == "syncing" || server_state == "tracking" || server_state == "connected")
905 {
906 set_health(warning);
907 }
908 else
909 set_health(critical);
910 }
911
912 if (load_factor > 100)
913 {
914 msg.body()[jss::info][jss::load_factor] = load_factor;
915 if (load_factor < 1000)
916 set_health(warning);
917 else
918 set_health(critical);
919 }
920
921 switch (health)
922 {
923 case healthy:
924 msg.result(boost::beast::http::status::ok);
925 break;
926 case warning:
927 msg.result(boost::beast::http::status::service_unavailable);
928 break;
929 case critical:
930 msg.result(boost::beast::http::status::internal_server_error);
931 break;
932 }
933
934 msg.prepare_payload();
936 return true;
937}
938
939bool
941{
942 // Take advantage of || short-circuiting
943 return processCrawl(req, handoff) || processValidatorList(req, handoff) || processHealth(req, handoff);
944}
945
948{
950 ret.reserve(size());
951
952 for_each([&ret](std::shared_ptr<PeerImp>&& sp) { ret.emplace_back(std::move(sp)); });
953
954 return ret;
955}
956
959 std::set<Peer::id_t> const& toSkip,
960 std::size_t& active,
961 std::size_t& disabled,
962 std::size_t& enabledInSkip) const
963{
966
967 active = ids_.size();
968 disabled = enabledInSkip = 0;
969 ret.reserve(ids_.size());
970
971 // NOTE The purpose of p is to delay the destruction of PeerImp
973 for (auto& [id, w] : ids_)
974 {
975 if (p = w.lock(); p != nullptr)
976 {
977 bool const reduceRelayEnabled = p->txReduceRelayEnabled();
978 // tx reduced relay feature disabled
979 if (!reduceRelayEnabled)
980 ++disabled;
981
982 if (toSkip.count(id) == 0)
983 ret.emplace_back(std::move(p));
984 else if (reduceRelayEnabled)
985 ++enabledInSkip;
986 }
987 }
988
989 return ret;
990}
991
992void
994{
995 for_each([index](std::shared_ptr<PeerImp>&& sp) { sp->checkTracking(index); });
996}
997
1000{
1001 std::lock_guard lock(mutex_);
1002 auto const iter = ids_.find(id);
1003 if (iter != ids_.end())
1004 return iter->second.lock();
1005 return {};
1006}
1007
1008// A public key hash map was not used due to the peer connect/disconnect
1009// update overhead outweighing the performance of a small set linear search.
1012{
1013 std::lock_guard lock(mutex_);
1014 // NOTE The purpose of peer is to delay the destruction of PeerImp
1016 for (auto const& e : ids_)
1017 {
1018 if (peer = e.second.lock(); peer != nullptr)
1019 {
1020 if (peer->getNodePublic() == pubKey)
1021 return peer;
1022 }
1023 }
1024 return {};
1025}
1026
1027void
1028OverlayImpl::broadcast(protocol::TMProposeSet& m)
1029{
1030 auto const sm = std::make_shared<Message>(m, protocol::mtPROPOSE_LEDGER);
1031 for_each([&](std::shared_ptr<PeerImp>&& p) { p->send(sm); });
1032}
1033
1035OverlayImpl::relay(protocol::TMProposeSet& m, uint256 const& uid, PublicKey const& validator)
1036{
1037 if (auto const toSkip = app_.getHashRouter().shouldRelay(uid))
1038 {
1039 auto const sm = std::make_shared<Message>(m, protocol::mtPROPOSE_LEDGER, validator);
1041 if (toSkip->find(p->id()) == toSkip->end())
1042 p->send(sm);
1043 });
1044 return *toSkip;
1045 }
1046 return {};
1047}
1048
1049void
1050OverlayImpl::broadcast(protocol::TMValidation& m)
1051{
1052 auto const sm = std::make_shared<Message>(m, protocol::mtVALIDATION);
1053 for_each([sm](std::shared_ptr<PeerImp>&& p) { p->send(sm); });
1054}
1055
1057OverlayImpl::relay(protocol::TMValidation& m, uint256 const& uid, PublicKey const& validator)
1058{
1059 if (auto const toSkip = app_.getHashRouter().shouldRelay(uid))
1060 {
1061 auto const sm = std::make_shared<Message>(m, protocol::mtVALIDATION, validator);
1063 if (toSkip->find(p->id()) == toSkip->end())
1064 p->send(sm);
1065 });
1066 return *toSkip;
1067 }
1068 return {};
1069}
1070
1073{
1075
1076 if (auto seq = app_.validatorManifests().sequence(); seq != manifestListSeq_)
1077 {
1078 protocol::TMManifests tm;
1079
1081 [&tm](std::size_t s) { tm.mutable_list()->Reserve(s); },
1082 [&tm, &hr = app_.getHashRouter()](Manifest const& manifest) {
1083 tm.add_list()->set_stobject(manifest.serialized.data(), manifest.serialized.size());
1084 hr.addSuppression(manifest.hash());
1085 });
1086
1088
1089 if (tm.list_size() != 0)
1090 manifestMessage_ = std::make_shared<Message>(tm, protocol::mtMANIFESTS);
1091
1092 manifestListSeq_ = seq;
1093 }
1094
1095 return manifestMessage_;
1096}
1097
1098void
1100 uint256 const& hash,
1102 std::set<Peer::id_t> const& toSkip)
1103{
1104 bool relay = tx.has_value();
1105 if (relay)
1106 {
1107 auto& txn = tx->get();
1108 SerialIter sit(makeSlice(txn.rawtransaction()));
1109 try
1110 {
1111 relay = !isPseudoTx(STTx{sit});
1112 }
1113 catch (std::exception const&)
1114 {
1115 // Could not construct STTx, not relaying
1116 JLOG(journal_.debug()) << "Could not construct STTx: " << hash;
1117 return;
1118 }
1119 }
1120
1121 Overlay::PeerSequence peers = {};
1122 std::size_t total = 0;
1123 std::size_t disabled = 0;
1124 std::size_t enabledInSkip = 0;
1125
1126 if (!relay)
1127 {
1129 return;
1130
1131 peers = getActivePeers(toSkip, total, disabled, enabledInSkip);
1132 JLOG(journal_.trace()) << "not relaying tx, total peers " << peers.size();
1133 for (auto const& p : peers)
1134 p->addTxQueue(hash);
1135 return;
1136 }
1137
1138 auto& txn = tx->get();
1139 auto const sm = std::make_shared<Message>(txn, protocol::mtTRANSACTION);
1140 peers = getActivePeers(toSkip, total, disabled, enabledInSkip);
1141 auto const minRelay = app_.config().TX_REDUCE_RELAY_MIN_PEERS + disabled;
1142
1143 if (!app_.config().TX_REDUCE_RELAY_ENABLE || total <= minRelay)
1144 {
1145 for (auto const& p : peers)
1146 p->send(sm);
1148 txMetrics_.addMetrics(total, toSkip.size(), 0);
1149 return;
1150 }
1151
1152 // We have more peers than the minimum (disabled + minimum enabled),
1153 // relay to all disabled and some randomly selected enabled that
1154 // do not have the transaction.
1155 auto const enabledTarget =
1156 app_.config().TX_REDUCE_RELAY_MIN_PEERS + (total - minRelay) * app_.config().TX_RELAY_PERCENTAGE / 100;
1157
1158 txMetrics_.addMetrics(enabledTarget, toSkip.size(), disabled);
1159
1160 if (enabledTarget > enabledInSkip)
1161 std::shuffle(peers.begin(), peers.end(), default_prng());
1162
1163 JLOG(journal_.trace()) << "relaying tx, total peers " << peers.size() << " selected " << enabledTarget << " skip "
1164 << toSkip.size() << " disabled " << disabled;
1165
1166 // count skipped peers with the enabled feature towards the quota
1167 std::uint16_t enabledAndRelayed = enabledInSkip;
1168 for (auto const& p : peers)
1169 {
1170 // always relay to a peer with the disabled feature
1171 if (!p->txReduceRelayEnabled())
1172 {
1173 p->send(sm);
1174 }
1175 else if (enabledAndRelayed < enabledTarget)
1176 {
1177 enabledAndRelayed++;
1178 p->send(sm);
1179 }
1180 else
1181 {
1182 p->addTxQueue(hash);
1183 }
1184 }
1185}
1186
1187//------------------------------------------------------------------------------
1188
1189void
1191{
1192 std::lock_guard lock(mutex_);
1193 list_.erase(&child);
1194 if (list_.empty())
1195 cond_.notify_all();
1196}
1197
1198void
1200{
1201 // Calling list_[].second->stop() may cause list_ to be modified
1202 // (OverlayImpl::remove() may be called on this same thread). So
1203 // iterating directly over list_ to call child->stop() could lead to
1204 // undefined behavior.
1205 //
1206 // Therefore we copy all of the weak/shared ptrs out of list_ before we
1207 // start calling stop() on them. That guarantees OverlayImpl::remove()
1208 // won't be called until vector<> children leaves scope.
1210 {
1211 std::lock_guard lock(mutex_);
1212 if (!work_)
1213 return;
1215
1216 children.reserve(list_.size());
1217 for (auto const& element : list_)
1218 {
1219 children.emplace_back(element.second.lock());
1220 }
1221 } // lock released
1222
1223 for (auto const& child : children)
1224 {
1225 if (child != nullptr)
1226 child->stop();
1227 }
1228}
1229
1230void
1232{
1233 auto const result = m_peerFinder->autoconnect();
1234 for (auto addr : result)
1235 connect(addr);
1236}
1237
1238void
1240{
1241 auto const result = m_peerFinder->buildEndpointsForPeers();
1242 for (auto const& e : result)
1243 {
1245 {
1246 std::lock_guard lock(mutex_);
1247 auto const iter = m_peers.find(e.first);
1248 if (iter != m_peers.end())
1249 peer = iter->second.lock();
1250 }
1251 if (peer)
1252 peer->sendEndpoints(e.second.begin(), e.second.end());
1253 }
1254}
1255
1256void
1258{
1259 for_each([](auto const& p) {
1260 if (p->txReduceRelayEnabled())
1261 p->sendTxQueue();
1262 });
1263}
1264
1266makeSquelchMessage(PublicKey const& validator, bool squelch, uint32_t squelchDuration)
1267{
1268 protocol::TMSquelch m;
1269 m.set_squelch(squelch);
1270 m.set_validatorpubkey(validator.data(), validator.size());
1271 if (squelch)
1272 m.set_squelchduration(squelchDuration);
1273 return std::make_shared<Message>(m, protocol::mtSQUELCH);
1274}
1275
1276void
1278{
1279 if (auto peer = findPeerByShortID(id); peer)
1280 {
1281 // optimize - multiple message with different
1282 // validator might be sent to the same peer
1283 peer->send(makeSquelchMessage(validator, false, 0));
1284 }
1285}
1286
1287void
1288OverlayImpl::squelch(PublicKey const& validator, Peer::id_t id, uint32_t squelchDuration) const
1289{
1290 if (auto peer = findPeerByShortID(id); peer)
1291 {
1292 peer->send(makeSquelchMessage(validator, true, squelchDuration));
1293 }
1294}
1295
1296void
1298 uint256 const& key,
1299 PublicKey const& validator,
1300 std::set<Peer::id_t>&& peers,
1301 protocol::MessageType type)
1302{
1303 if (!slots_.baseSquelchReady())
1304 return;
1305
1306 if (!strand_.running_in_this_thread())
1307 return post(
1308 strand_,
1309 // Must capture copies of reference parameters (i.e. key, validator)
1310 [this, key = key, validator = validator, peers = std::move(peers), type]() mutable {
1311 updateSlotAndSquelch(key, validator, std::move(peers), type);
1312 });
1313
1314 for (auto id : peers)
1315 slots_.updateSlotAndSquelch(
1316 key, validator, id, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); });
1317}
1318
1319void
1321 uint256 const& key,
1322 PublicKey const& validator,
1323 Peer::id_t peer,
1324 protocol::MessageType type)
1325{
1326 if (!slots_.baseSquelchReady())
1327 return;
1328
1329 if (!strand_.running_in_this_thread())
1330 return post(
1331 strand_,
1332 // Must capture copies of reference parameters (i.e. key, validator)
1333 [this, key = key, validator = validator, peer, type]() {
1334 updateSlotAndSquelch(key, validator, peer, type);
1335 });
1336
1337 slots_.updateSlotAndSquelch(
1338 key, validator, peer, type, [&]() { reportInboundTraffic(TrafficCount::squelch_ignored, 0); });
1339}
1340
1341void
1343{
1344 if (!strand_.running_in_this_thread())
1345 return post(strand_, std::bind(&OverlayImpl::deletePeer, this, id));
1346
1347 slots_.deletePeer(id, true);
1348}
1349
1350void
1352{
1353 if (!strand_.running_in_this_thread())
1354 return post(strand_, std::bind(&OverlayImpl::deleteIdlePeers, this));
1355
1356 slots_.deleteIdlePeers();
1357}
1358
1359//------------------------------------------------------------------------------
1360
1363{
1364 Overlay::Setup setup;
1365
1366 {
1367 auto const& section = config.section("overlay");
1368 setup.context = make_SSLContext("");
1369
1370 set(setup.ipLimit, "ip_limit", section);
1371 if (setup.ipLimit < 0)
1372 Throw<std::runtime_error>("Configured IP limit is invalid");
1373
1374 std::string ip;
1375 set(ip, "public_ip", section);
1376 if (!ip.empty())
1377 {
1378 boost::system::error_code ec;
1379 setup.public_ip = boost::asio::ip::make_address(ip, ec);
1380 if (ec || beast::IP::is_private(setup.public_ip))
1381 Throw<std::runtime_error>("Configured public IP is invalid");
1382 }
1383 }
1384
1385 {
1386 auto const& section = config.section("crawl");
1387 auto const& values = section.values();
1388
1389 if (values.size() > 1)
1390 {
1391 Throw<std::runtime_error>("Configured [crawl] section is invalid, too many values");
1392 }
1393
1394 bool crawlEnabled = true;
1395
1396 // Only allow "0|1" as a value
1397 if (values.size() == 1)
1398 {
1399 try
1400 {
1401 crawlEnabled = boost::lexical_cast<bool>(values.front());
1402 }
1403 catch (boost::bad_lexical_cast const&)
1404 {
1405 Throw<std::runtime_error>("Configured [crawl] section has invalid value: " + values.front());
1406 }
1407 }
1408
1409 if (crawlEnabled)
1410 {
1411 if (get<bool>(section, "overlay", true))
1412 {
1414 }
1415 if (get<bool>(section, "server", true))
1416 {
1418 }
1419 if (get<bool>(section, "counts", false))
1420 {
1422 }
1423 if (get<bool>(section, "unl", true))
1424 {
1426 }
1427 }
1428 }
1429 {
1430 auto const& section = config.section("vl");
1431
1432 set(setup.vlEnabled, "enabled", section);
1433 }
1434
1435 try
1436 {
1437 auto id = config.legacy("network_id");
1438
1439 if (!id.empty())
1440 {
1441 if (id == "main")
1442 id = "0";
1443
1444 if (id == "testnet")
1445 id = "1";
1446
1447 if (id == "devnet")
1448 id = "2";
1449
1450 setup.networkID = beast::lexicalCastThrow<std::uint32_t>(id);
1451 }
1452 }
1453 catch (...)
1454 {
1455 Throw<std::runtime_error>(
1456 "Configured [network_id] section is invalid: must be a number "
1457 "or one of the strings 'main', 'testnet' or 'devnet'.");
1458 }
1459
1460 return setup;
1461}
1462
1465 Application& app,
1466 Overlay::Setup const& setup,
1467 ServerHandler& serverHandler,
1468 Resource::Manager& resourceManager,
1469 Resolver& resolver,
1470 boost::asio::io_context& io_context,
1471 BasicConfig const& config,
1472 beast::insight::Collector::ptr const& collector)
1473{
1475 app, setup, serverHandler, resourceManager, resolver, io_context, config, collector);
1476}
1477
1478} // 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 beast::Journal journal(std::string const &name)=0
virtual DatabaseCon & getWalletDB()=0
Retrieve the "wallet database".
virtual std::optional< PublicKey const > getValidationPublicKey() const =0
virtual Logs & logs()=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:238
std::vector< std::string > IPS
Definition Config.h:122
bool standalone() const
Definition Config.h:311
std::size_t TX_RELAY_PERCENTAGE
Definition Config.h:251
bool TX_REDUCE_RELAY_METRICS
Definition Config.h:245
std::vector< std::string > IPS_FIXED
Definition Config.h:125
std::size_t TX_REDUCE_RELAY_MIN_PEERS
Definition Config.h:248
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:344
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 ValidatorList & validators()=0
virtual NetworkOPs & getOPs()=0
virtual PeerReservationTable & peerReservations()=0
virtual Cluster & cluster()=0
virtual HashRouter & getHashRouter()=0
virtual ValidatorSite & validatorSites()=0
virtual ManifestCache & validatorManifests()=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.
void addValidatorManifest(soci::session &session, std::string const &serialized)
addValidatorManifest Saves the manifest of a validator to the database.
Definition Wallet.cpp:87
std::string base64_encode(std::uint8_t const *data, std::size_t len)
Json::Value getCountsJson(Application &app, int minObjectCount)
Definition GetCounts.cpp:39
std::optional< Manifest > deserializeManifest(Slice s, beast::Journal journal)
Constructs Manifest from serialized string.
Definition Manifest.cpp:35
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)