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