20 #include <ripple/app/consensus/RCLValidations.h>
21 #include <ripple/app/ledger/InboundLedgers.h>
22 #include <ripple/app/ledger/InboundTransactions.h>
23 #include <ripple/app/ledger/LedgerMaster.h>
24 #include <ripple/app/ledger/TransactionMaster.h>
25 #include <ripple/app/misc/HashRouter.h>
26 #include <ripple/app/misc/LoadFeeTrack.h>
27 #include <ripple/app/misc/NetworkOPs.h>
28 #include <ripple/app/misc/Transaction.h>
29 #include <ripple/app/misc/ValidatorList.h>
30 #include <ripple/app/tx/apply.h>
31 #include <ripple/basics/UptimeClock.h>
32 #include <ripple/basics/base64.h>
33 #include <ripple/basics/random.h>
34 #include <ripple/basics/safe_cast.h>
35 #include <ripple/beast/core/LexicalCast.h>
36 #include <ripple/beast/core/SemanticVersion.h>
37 #include <ripple/nodestore/DatabaseShard.h>
38 #include <ripple/overlay/Cluster.h>
39 #include <ripple/overlay/impl/PeerImp.h>
40 #include <ripple/overlay/impl/Tuning.h>
41 #include <ripple/overlay/predicates.h>
42 #include <ripple/protocol/digest.h>
44 #include <boost/algorithm/string.hpp>
45 #include <boost/algorithm/string/predicate.hpp>
46 #include <boost/beast/core/ostream.hpp>
54 using namespace std::chrono_literals;
79 , sink_(app_.journal(
"Peer"), makePrefix(id))
80 , p_sink_(app_.journal(
"Protocol"), makePrefix(id))
83 , stream_ptr_(
std::move(stream_ptr))
84 , socket_(stream_ptr_->next_layer().socket())
85 , stream_(*stream_ptr_)
86 , strand_(socket_.get_executor())
88 , remote_address_(slot->remote_endpoint())
92 , tracking_(Tracking::unknown)
93 , trackingTime_(clock_type::now())
94 , publicKey_(publicKey)
95 , lastPingTime_(clock_type::now())
96 , creationTime_(clock_type::now())
97 , squelch_(app_.journal(
"Squelch"))
101 , request_(std::move(request))
103 , compressionEnabled_(
108 app_.config().COMPRESSION)
114 app_.config().TX_REDUCE_RELAY_ENABLE))
118 app_.config().VP_REDUCE_RELAY_ENABLE))
122 app_.config().LEDGER_REPLAY))
123 , ledgerReplayMsgHandler_(app, app.getLedgerReplayer())
125 JLOG(journal_.info()) <<
"compression enabled "
126 << (compressionEnabled_ == Compressed::On)
127 <<
" vp reduce-relay enabled "
128 << vpReduceRelayEnabled_
129 <<
" tx reduce-relay enabled "
130 << txReduceRelayEnabled_ <<
" on " << remote_address_
136 const bool inCluster{
cluster()};
159 if (!
strand_.running_in_this_thread())
162 auto parseLedgerHash =
176 if (
auto const iter =
headers_.find(
"Closed-Ledger");
179 closed = parseLedgerHash(iter->value().to_string());
182 fail(
"Malformed handshake data (1)");
185 if (
auto const iter =
headers_.find(
"Previous-Ledger");
188 previous = parseLedgerHash(iter->value().to_string());
191 fail(
"Malformed handshake data (2)");
194 if (previous && !closed)
195 fail(
"Malformed handshake data (3)");
217 if (!
strand_.running_in_this_thread())
243 if (!
strand_.running_in_this_thread())
250 auto validator = m->getValidatorKey();
251 if (validator && !
squelch_.expireSquelch(*validator))
255 safe_cast<TrafficCount::category>(m->getCategory()),
273 <<
" sendq: " << sendq_size;
281 boost::asio::async_write(
290 std::placeholders::_1,
291 std::placeholders::_2)));
297 if (!
strand_.running_in_this_thread())
303 protocol::TMHaveTransactions ht;
305 ht.add_hashes(hash.data(), hash.size());
309 send(std::make_shared<Message>(ht, protocol::mtHAVE_TRANSACTIONS));
316 if (!
strand_.running_in_this_thread())
333 if (!
strand_.running_in_this_thread())
338 auto removed =
txQueue_.erase(hash);
346 strand_.running_in_this_thread())
350 fail(
"charge: Resources");
359 auto const iter =
headers_.find(
"Crawl");
362 return boost::iequals(iter->value(),
"public");
375 return headers_[
"User-Agent"].to_string();
376 return headers_[
"Server"].to_string();
388 ret[jss::inbound] =
true;
392 ret[jss::cluster] =
true;
400 ret[jss::server_domain] =
domain();
403 ret[jss::network_id] = nid;
408 ret[jss::version] = version;
419 std::chrono::duration_cast<std::chrono::seconds>(
uptime()).count());
424 if ((minSeq != 0) || (maxSeq != 0))
425 ret[jss::complete_ledgers] =
431 ret[jss::track] =
"diverged";
435 ret[jss::track] =
"unknown";
444 protocol::TMStatusChange last_status;
451 if (closedLedgerHash != beast::zero)
452 ret[jss::ledger] =
to_string(closedLedgerHash);
454 if (last_status.has_newstatus())
456 switch (last_status.newstatus())
458 case protocol::nsCONNECTING:
459 ret[jss::status] =
"connecting";
462 case protocol::nsCONNECTED:
463 ret[jss::status] =
"connected";
466 case protocol::nsMONITORING:
467 ret[jss::status] =
"monitoring";
470 case protocol::nsVALIDATING:
471 ret[jss::status] =
"validating";
474 case protocol::nsSHUTTING:
475 ret[jss::status] =
"shutting";
480 <<
"Unknown status: " << last_status.newstatus();
485 ret[jss::metrics][jss::total_bytes_recv] =
487 ret[jss::metrics][jss::total_bytes_sent] =
489 ret[jss::metrics][jss::avg_bps_recv] =
491 ret[jss::metrics][jss::avg_bps_sent] =
534 return boost::icl::contains(it->second.finalized(), shardIndex);
580 assert(
strand_.running_in_this_thread());
602 if (!
strand_.running_in_this_thread())
613 <<
" failed: " << reason;
621 assert(
strand_.running_in_this_thread());
641 assert(
strand_.running_in_this_thread());
653 stream_.async_shutdown(bind_executor(
663 timer_.expires_from_now(peerTimerInterval, ec);
670 timer_.async_wait(bind_executor(
700 if (ec == boost::asio::error::operation_aborted)
712 fail(
"Large send queue");
718 clock_type::duration duration;
739 fail(
"Ping Timeout");
746 protocol::TMPing message;
747 message.set_type(protocol::TMPing::ptPING);
750 send(std::make_shared<Message>(message, protocol::mtPING));
762 JLOG(
journal_.
error()) <<
"onShutdown: expected error condition";
765 if (ec != boost::asio::error::eof)
766 return fail(
"onShutdown", ec);
783 return fail(
"makeSharedValue: Unexpected failure");
804 auto write_buffer = std::make_shared<boost::beast::multi_buffer>();
817 boost::asio::async_write(
819 write_buffer->data(),
820 boost::asio::transfer_all(),
827 if (ec == boost::asio::error::operation_aborted)
830 return fail(
"onWriteResponse", ec);
831 if (write_buffer->size() == bytes_transferred)
833 return fail(
"Failed to write header");
847 return headers_[
"Server-Domain"].to_string();
889 protocol::TMGetPeerShardInfoV2 tmGPS;
891 send(std::make_shared<Message>(tmGPS, protocol::mtGET_PEER_SHARD_INFO_V2));
902 if (ec == boost::asio::error::operation_aborted)
904 if (ec == boost::asio::error::eof)
910 return fail(
"onReadMessage", ec);
913 if (bytes_transferred > 0)
914 stream <<
"onReadMessage: " << bytes_transferred <<
" bytes";
916 stream <<
"onReadMessage";
919 metrics_.recv.add_message(bytes_transferred);
931 return fail(
"onReadMessage", ec);
936 if (bytes_consumed == 0)
949 std::placeholders::_1,
950 std::placeholders::_2)));
958 if (ec == boost::asio::error::operation_aborted)
961 return fail(
"onWriteMessage", ec);
964 if (bytes_transferred > 0)
965 stream <<
"onWriteMessage: " << bytes_transferred <<
" bytes";
967 stream <<
"onWriteMessage";
970 metrics_.sent.add_message(bytes_transferred);
977 return boost::asio::async_write(
986 std::placeholders::_1,
987 std::placeholders::_2)));
992 return stream_.async_shutdown(bind_executor(
997 std::placeholders::_1)));
1027 if ((type == MessageType::mtTRANSACTION ||
1028 type == MessageType::mtHAVE_TRANSACTIONS ||
1029 type == MessageType::mtTRANSACTIONS ||
1031 category == TrafficCount::category::get_transactions ||
1033 category == TrafficCount::category::ld_tsc_get ||
1034 category == TrafficCount::category::ld_tsc_share ||
1036 category == TrafficCount::category::gl_tsc_share ||
1037 category == TrafficCount::category::gl_tsc_get) &&
1041 static_cast<MessageType
>(type),
static_cast<std::uint64_t>(size));
1043 JLOG(
journal_.
trace()) <<
"onMessageBegin: " << type <<
" " << size <<
" "
1044 << uncompressed_size <<
" " << isCompressed;
1059 auto const s = m->list_size();
1081 if (m->type() == protocol::TMPing::ptPING)
1085 m->set_type(protocol::TMPing::ptPONG);
1086 send(std::make_shared<Message>(*m, protocol::mtPING));
1090 if (m->type() == protocol::TMPing::ptPONG && m->has_seq())
1100 auto const rtt = std::chrono::round<std::chrono::milliseconds>(
1125 for (
int i = 0; i < m->clusternodes().size(); ++i)
1127 protocol::TMClusterNode
const& node = m->clusternodes(i);
1130 if (node.has_nodename())
1131 name = node.nodename();
1133 auto const publicKey =
1140 auto const reportTime =
1144 *publicKey,
name, node.nodeload(), reportTime);
1148 int loadSources = m->loadsources().size();
1149 if (loadSources != 0)
1152 gossip.
items.reserve(loadSources);
1153 for (
int i = 0; i < m->loadsources().size(); ++i)
1155 protocol::TMLoadSource
const& node = m->loadsources(i);
1160 gossip.
items.push_back(item);
1173 if (status.getReportTime() >= thresh)
1174 fees.push_back(status.getLoadFee());
1179 auto const index = fees.size() / 2;
1181 clusterFee = fees[index];
1209 return badData(
"Invalid relays");
1218 auto const peerChainSz{m->peerchain_size()};
1219 if (peerChainSz > 0)
1222 return badData(
"Invalid peer chain size");
1225 return badData(
"Invalid relays and peer chain size");
1227 for (
int i = 0; i < peerChainSz; ++i)
1229 auto const slice{
makeSlice(m->peerchain(i).publickey())};
1233 return badData(
"Invalid peer public key");
1236 if (!pubKeyChain.
emplace(slice).second)
1237 return badData(
"Invalid peer public key");
1244 auto reply{shardStore->getShardInfo()->makeMessage(
app_)};
1245 if (peerChainSz > 0)
1246 *(reply.mutable_peerchain()) = m->peerchain();
1247 send(std::make_shared<Message>(reply, protocol::mtPEER_SHARD_INFO_V2));
1250 if (m->relays() == 0)
1254 if (peerChainSz == 0)
1261 m->set_relays(m->relays() - 1);
1263 std::make_shared<Message>(*m, protocol::mtGET_PEER_SHARD_INFO_V2),
1265 return pubKeyChain.
find(peer->getNodePublic()) != pubKeyChain.
end();
1277 if (curLedgerSeq >= db.earliestLedgerSeq())
1278 return db.seqToShardIndex(curLedgerSeq);
1279 return std::nullopt;
1294 auto const timestamp{
1297 if (timestamp > (now + 5s))
1298 return badData(
"Invalid timestamp");
1301 using namespace std::chrono_literals;
1302 if (timestamp < (now - 5min))
1303 return badData(
"Stale timestamp");
1305 s.
add32(m->timestamp());
1310 auto const numIncomplete{m->incomplete_size()};
1311 if (numIncomplete > 0)
1313 if (latestShardIndex && numIncomplete > *latestShardIndex)
1314 return badData(
"Invalid number of incomplete shards");
1317 for (
int i = 0; i < numIncomplete; ++i)
1319 auto const& incomplete{m->incomplete(i)};
1320 auto const shardIndex{incomplete.shardindex()};
1323 if (shardIndex < earliestShardIndex ||
1324 (latestShardIndex && shardIndex > latestShardIndex))
1326 return badData(
"Invalid incomplete shard index");
1328 s.
add32(shardIndex);
1331 auto const state{
static_cast<ShardState>(incomplete.state())};
1343 return badData(
"Invalid incomplete shard state");
1345 s.
add32(incomplete.state());
1349 if (incomplete.has_progress())
1351 progress = incomplete.progress();
1352 if (progress < 1 || progress > 100)
1353 return badData(
"Invalid incomplete shard progress");
1358 if (!
shardInfo.update(shardIndex, state, progress))
1359 return badData(
"Invalid duplicate incomplete shards");
1364 if (m->has_finalized())
1366 auto const& str{m->finalized()};
1368 return badData(
"Invalid finalized shards");
1370 if (!
shardInfo.setFinalizedFromString(str))
1371 return badData(
"Invalid finalized shard indexes");
1374 auto const numFinalized{boost::icl::length(
finalized)};
1375 if (numFinalized == 0 ||
1376 boost::icl::first(
finalized) < earliestShardIndex ||
1377 (latestShardIndex &&
1378 boost::icl::last(
finalized) > latestShardIndex))
1380 return badData(
"Invalid finalized shard indexes");
1383 if (latestShardIndex &&
1384 (numFinalized + numIncomplete) > *latestShardIndex)
1386 return badData(
"Invalid number of finalized and incomplete shards");
1389 s.
addRaw(str.data(), str.size());
1395 return badData(
"Invalid public key");
1400 return badData(
"Invalid public key");
1404 return badData(
"Invalid signature");
1407 auto const peerChainSz{m->peerchain_size()};
1408 if (peerChainSz > 0)
1412 return badData(
"Invalid peer chain size");
1420 for (
int i = 0; i < peerChainSz; ++i)
1423 slice =
makeSlice(m->peerchain(i).publickey());
1425 return badData(
"Invalid peer public key");
1428 if (!pubKeyChain.
emplace(slice).second)
1429 return badData(
"Invalid peer public key");
1434 makeSlice(m->peerchain(peerChainSz - 1).publickey()));
1437 m->mutable_peerchain()->RemoveLast();
1439 std::make_shared<Message>(*m, protocol::mtPEER_SHARD_INFO_V2));
1441 <<
"Relayed TMPeerShardInfoV2 from peer IP "
1443 << peer->getRemoteAddress().to_string();
1453 <<
"Consumed TMPeerShardInfoV2 originating from public key "
1456 << (
shardInfo.incomplete().empty() ?
"empty"
1466 else if (
shardInfo.msgTimestamp() > it->second.msgTimestamp())
1471 if (peerChainSz == 0)
1484 endpoints.
reserve(m->endpoints_v2().size());
1486 for (
auto const& tm : m->endpoints_v2())
1492 << tm.endpoint() <<
"}";
1508 if (!endpoints.
empty())
1531 <<
"Need network ledger";
1539 auto stx = std::make_shared<STTx const>(sit);
1540 uint256 txID = stx->getTransactionID();
1564 bool checkSignature =
true;
1567 if (!m->has_deferred() || !m->deferred())
1571 flags |= SF_TRUSTED;
1578 checkSignature =
false;
1591 <<
"No new transactions until synchronized";
1597 "recvTransaction->checkTransaction",
1602 if (
auto peer = weak.lock())
1603 peer->checkTransaction(flags, checkSignature, stx);
1610 <<
"Transaction invalid: " <<
strHex(m->rawtransaction());
1621 auto const itype{m->itype()};
1624 if (itype < protocol::liBASE || itype > protocol::liTS_CANDIDATE)
1625 return badData(
"Invalid ledger info type");
1630 return std::nullopt;
1633 if (itype == protocol::liTS_CANDIDATE)
1635 if (!m->has_ledgerhash())
1636 return badData(
"Invalid TX candidate set, missing TX set hash");
1639 !m->has_ledgerhash() && !m->has_ledgerseq() &&
1640 !(ltype && *ltype == protocol::ltCLOSED))
1642 return badData(
"Invalid request");
1646 if (ltype && (*ltype < protocol::ltACCEPTED || *ltype > protocol::ltCLOSED))
1647 return badData(
"Invalid ledger type");
1651 return badData(
"Invalid ledger hash");
1654 if (m->has_ledgerseq())
1656 auto const ledgerSeq{m->ledgerseq()};
1666 using namespace std::chrono_literals;
1676 if (itype != protocol::liBASE)
1678 if (m->nodeids_size() <= 0)
1679 return badData(
"Invalid ledger node IDs");
1681 for (
auto const& nodeId : m->nodeids())
1684 return badData(
"Invalid SHAMap node ID");
1689 if (m->has_querytype() && m->querytype() != protocol::qtINDIRECT)
1690 return badData(
"Invalid query type");
1693 if (m->has_querydepth())
1696 itype == protocol::liBASE)
1698 return badData(
"Invalid query depth");
1705 if (
auto peer = weak.
lock())
1706 peer->processLedgerRequest(m);
1724 if (
auto peer = weak.
lock())
1727 peer->ledgerReplayMsgHandler_.processProofPathRequest(m);
1728 if (reply.has_error())
1730 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1731 peer->charge(Resource::feeInvalidRequest);
1733 peer->charge(Resource::feeRequestNoReply);
1737 peer->send(std::make_shared<Message>(
1738 reply, protocol::mtPROOF_PATH_RESPONSE));
1773 if (
auto peer = weak.
lock())
1776 peer->ledgerReplayMsgHandler_.processReplayDeltaRequest(m);
1777 if (reply.has_error())
1779 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1780 peer->charge(Resource::feeInvalidRequest);
1782 peer->charge(Resource::feeRequestNoReply);
1786 peer->send(std::make_shared<Message>(
1787 reply, protocol::mtREPLAY_DELTA_RESPONSE));
1818 return badData(
"Invalid ledger hash");
1822 auto const ledgerSeq{m->ledgerseq()};
1823 if (m->type() == protocol::liTS_CANDIDATE)
1842 using namespace std::chrono_literals;
1853 if (m->type() < protocol::liBASE || m->type() > protocol::liTS_CANDIDATE)
1854 return badData(
"Invalid ledger info type");
1857 if (m->has_error() &&
1858 (m->error() < protocol::reNO_LEDGER ||
1859 m->error() > protocol::reBAD_REQUEST))
1861 return badData(
"Invalid reply error");
1868 "Invalid Ledger/TXset nodes " +
std::to_string(m->nodes_size()));
1872 if (m->has_requestcookie())
1876 m->clear_requestcookie();
1877 peer->send(std::make_shared<Message>(*m, protocol::mtLEDGER_DATA));
1881 JLOG(
p_journal_.
info()) <<
"Unable to route TX/ledger data reply";
1886 uint256 const ledgerHash{m->ledgerhash()};
1889 if (m->type() == protocol::liTS_CANDIDATE)
1894 if (
auto peer = weak.lock())
1896 peer->app_.getInboundTransactions().gotData(
1897 ledgerHash, peer, m);
1910 protocol::TMProposeSet&
set = *m;
1916 if ((std::clamp<std::size_t>(sig.size(), 64, 72) != sig.size()) ||
1932 uint256 const proposeHash{
set.currenttxhash()};
1933 uint256 const prevLedger{
set.previousledger()};
1946 if (
auto [added, relayed] =
1955 suppression, publicKey,
id_, protocol::mtPROPOSE_LEDGER);
1967 <<
"Proposal: Dropping untrusted (peer divergence)";
1979 <<
"Proposal: " << (isTrusted ?
"trusted" :
"untrusted");
1996 "recvPropose->checkPropose",
1998 if (
auto peer = weak.lock())
1999 peer->checkPropose(job, m,
proposal);
2008 if (!m->has_networktime())
2013 if (!
last_status_.has_newstatus() || m->has_newstatus())
2018 protocol::NodeStatus status =
last_status_.newstatus();
2020 m->set_newstatus(status);
2024 if (m->newevent() == protocol::neLOST_SYNC)
2026 bool outOfSync{
false};
2047 bool const peerChangedLedgers{
2054 if (peerChangedLedgers)
2065 if (m->has_ledgerhashprevious() &&
2076 if (peerChangedLedgers)
2086 if (m->has_firstseq() && m->has_lastseq())
2097 if (m->has_ledgerseq() &&
2107 if (m->has_newstatus())
2109 switch (m->newstatus())
2111 case protocol::nsCONNECTING:
2112 j[jss::status] =
"CONNECTING";
2114 case protocol::nsCONNECTED:
2115 j[jss::status] =
"CONNECTED";
2117 case protocol::nsMONITORING:
2118 j[jss::status] =
"MONITORING";
2120 case protocol::nsVALIDATING:
2121 j[jss::status] =
"VALIDATING";
2123 case protocol::nsSHUTTING:
2124 j[jss::status] =
"SHUTTING";
2129 if (m->has_newevent())
2131 switch (m->newevent())
2133 case protocol::neCLOSING_LEDGER:
2134 j[jss::action] =
"CLOSING_LEDGER";
2136 case protocol::neACCEPTED_LEDGER:
2137 j[jss::action] =
"ACCEPTED_LEDGER";
2139 case protocol::neSWITCHED_LEDGER:
2140 j[jss::action] =
"SWITCHED_LEDGER";
2142 case protocol::neLOST_SYNC:
2143 j[jss::action] =
"LOST_SYNC";
2148 if (m->has_ledgerseq())
2150 j[jss::ledger_index] = m->ledgerseq();
2153 if (m->has_ledgerhash())
2155 uint256 closedLedgerHash{};
2157 std::lock_guard sl(recentLock_);
2158 closedLedgerHash = closedLedgerHash_;
2160 j[jss::ledger_hash] =
to_string(closedLedgerHash);
2163 if (m->has_networktime())
2165 j[jss::date] = Json::UInt(m->networktime());
2168 if (m->has_firstseq() && m->has_lastseq())
2170 j[jss::ledger_index_min] = Json::UInt(m->firstseq());
2171 j[jss::ledger_index_max] = Json::UInt(m->lastseq());
2187 serverSeq = maxLedger_;
2193 checkTracking(serverSeq, validationSeq);
2202 if (diff < Tuning::convergedLedgerLimit)
2205 tracking_ = Tracking::converged;
2208 if ((diff > Tuning::divergedLedgerLimit) &&
2209 (tracking_.load() != Tracking::diverged))
2214 tracking_ = Tracking::diverged;
2215 trackingTime_ = clock_type::now();
2224 fee_ = Resource::feeInvalidRequest;
2228 uint256 const hash{m->hash()};
2230 if (m->status() == protocol::tsHAVE)
2234 if (
std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
2235 recentTxSets_.end())
2237 fee_ = Resource::feeUnwantedData;
2241 recentTxSets_.push_back(hash);
2246 PeerImp::onValidatorListMessage(
2256 JLOG(p_journal_.warn()) <<
"Ignored malformed " << messageType
2257 <<
" from peer " << remote_address_;
2259 fee_ = Resource::feeHighBurdenPeer;
2265 JLOG(p_journal_.debug())
2266 <<
"Received " << messageType <<
" from " << remote_address_.to_string()
2267 <<
" (" << id_ <<
")";
2269 if (!app_.getHashRouter().addSuppressionPeer(hash, id_))
2271 JLOG(p_journal_.debug())
2272 << messageType <<
": received duplicate " << messageType;
2276 fee_ = Resource::feeUnwantedData;
2280 auto const applyResult = app_.validators().applyListsAndBroadcast(
2284 remote_address_.to_string(),
2287 app_.getHashRouter(),
2290 JLOG(p_journal_.debug())
2291 <<
"Processed " << messageType <<
" version " << version <<
" from "
2292 << (applyResult.publisherKey ?
strHex(*applyResult.publisherKey)
2293 :
"unknown or invalid publisher")
2294 <<
" from " << remote_address_.to_string() <<
" (" << id_
2295 <<
") with best result " << to_string(applyResult.bestDisposition());
2298 switch (applyResult.bestDisposition())
2301 case ListDisposition::accepted:
2303 case ListDisposition::expired:
2305 case ListDisposition::pending: {
2308 assert(applyResult.publisherKey);
2309 auto const& pubKey = *applyResult.publisherKey;
2311 if (
auto const iter = publisherListSequences_.find(pubKey);
2312 iter != publisherListSequences_.end())
2314 assert(iter->second < applyResult.sequence);
2317 publisherListSequences_[pubKey] = applyResult.sequence;
2320 case ListDisposition::same_sequence:
2321 case ListDisposition::known_sequence:
2325 assert(applyResult.sequence && applyResult.publisherKey);
2327 publisherListSequences_[*applyResult.publisherKey] <=
2328 applyResult.sequence);
2333 case ListDisposition::stale:
2334 case ListDisposition::untrusted:
2335 case ListDisposition::invalid:
2336 case ListDisposition::unsupported_version:
2343 switch (applyResult.worstDisposition())
2345 case ListDisposition::accepted:
2346 case ListDisposition::expired:
2347 case ListDisposition::pending:
2350 case ListDisposition::same_sequence:
2351 case ListDisposition::known_sequence:
2355 fee_ = Resource::feeUnwantedData;
2357 case ListDisposition::stale:
2360 fee_ = Resource::feeBadData;
2362 case ListDisposition::untrusted:
2366 fee_ = Resource::feeUnwantedData;
2368 case ListDisposition::invalid:
2370 fee_ = Resource::feeInvalidSignature;
2372 case ListDisposition::unsupported_version:
2375 fee_ = Resource::feeBadData;
2382 for (
auto const& [disp, count] : applyResult.dispositions)
2387 case ListDisposition::accepted:
2388 JLOG(p_journal_.debug())
2389 <<
"Applied " << count <<
" new " << messageType
2390 <<
"(s) from peer " << remote_address_;
2393 case ListDisposition::expired:
2394 JLOG(p_journal_.debug())
2395 <<
"Applied " << count <<
" expired " << messageType
2396 <<
"(s) from peer " << remote_address_;
2399 case ListDisposition::pending:
2400 JLOG(p_journal_.debug())
2401 <<
"Processed " << count <<
" future " << messageType
2402 <<
"(s) from peer " << remote_address_;
2404 case ListDisposition::same_sequence:
2405 JLOG(p_journal_.warn())
2406 <<
"Ignored " << count <<
" " << messageType
2407 <<
"(s) with current sequence from peer "
2410 case ListDisposition::known_sequence:
2411 JLOG(p_journal_.warn())
2412 <<
"Ignored " << count <<
" " << messageType
2413 <<
"(s) with future sequence from peer " << remote_address_;
2415 case ListDisposition::stale:
2416 JLOG(p_journal_.warn())
2417 <<
"Ignored " << count <<
"stale " << messageType
2418 <<
"(s) from peer " << remote_address_;
2420 case ListDisposition::untrusted:
2421 JLOG(p_journal_.warn())
2422 <<
"Ignored " << count <<
" untrusted " << messageType
2423 <<
"(s) from peer " << remote_address_;
2425 case ListDisposition::unsupported_version:
2426 JLOG(p_journal_.warn())
2427 <<
"Ignored " << count <<
"unsupported version "
2428 << messageType <<
"(s) from peer " << remote_address_;
2430 case ListDisposition::invalid:
2431 JLOG(p_journal_.warn())
2432 <<
"Ignored " << count <<
"invalid " << messageType
2433 <<
"(s) from peer " << remote_address_;
2446 if (!supportsFeature(ProtocolFeature::ValidatorListPropagation))
2448 JLOG(p_journal_.debug())
2449 <<
"ValidatorList: received validator list from peer using "
2450 <<
"protocol version " << to_string(protocol_)
2451 <<
" which shouldn't support this feature.";
2452 fee_ = Resource::feeUnwantedData;
2455 onValidatorListMessage(
2459 ValidatorList::parseBlobs(*m));
2463 JLOG(p_journal_.warn()) <<
"ValidatorList: Exception, " << e.
what()
2464 <<
" from peer " << remote_address_;
2465 fee_ = Resource::feeBadData;
2475 if (!supportsFeature(ProtocolFeature::ValidatorList2Propagation))
2477 JLOG(p_journal_.debug())
2478 <<
"ValidatorListCollection: received validator list from peer "
2479 <<
"using protocol version " << to_string(protocol_)
2480 <<
" which shouldn't support this feature.";
2481 fee_ = Resource::feeUnwantedData;
2484 else if (m->version() < 2)
2486 JLOG(p_journal_.debug())
2487 <<
"ValidatorListCollection: received invalid validator list "
2489 << m->version() <<
" from peer using protocol version "
2490 << to_string(protocol_);
2491 fee_ = Resource::feeBadData;
2494 onValidatorListMessage(
2495 "ValidatorListCollection",
2498 ValidatorList::parseBlobs(*m));
2502 JLOG(p_journal_.warn()) <<
"ValidatorListCollection: Exception, "
2503 << e.
what() <<
" from peer " << remote_address_;
2504 fee_ = Resource::feeBadData;
2511 if (m->validation().size() < 50)
2513 JLOG(p_journal_.warn()) <<
"Validation: Too small";
2514 fee_ = Resource::feeInvalidRequest;
2520 auto const closeTime = app_.timeKeeper().closeTime();
2525 val = std::make_shared<STValidation>(
2529 app_.validatorManifests().getMasterKey(pk));
2532 val->setSeen(closeTime);
2536 app_.getValidations().parms(),
2537 app_.timeKeeper().closeTime(),
2539 val->getSeenTime()))
2541 JLOG(p_journal_.trace()) <<
"Validation: Not current";
2542 fee_ = Resource::feeUnwantedData;
2547 if (
auto [added, relayed] =
2548 app_.getHashRouter().addSuppressionPeerWithStatus(key, id_);
2555 if (reduceRelayReady() && relayed &&
2556 (
stopwatch().now() - *relayed) < reduce_relay::IDLED)
2557 overlay_.updateSlotAndSquelch(
2558 key, val->getSignerPublic(), id_, protocol::mtVALIDATION);
2559 JLOG(p_journal_.trace()) <<
"Validation: duplicate";
2563 auto const isTrusted =
2564 app_.validators().trusted(val->getSignerPublic());
2566 if (!isTrusted && (tracking_.load() == Tracking::diverged))
2568 JLOG(p_journal_.debug())
2569 <<
"Validation: dropping untrusted from diverged peer";
2571 if (isTrusted || cluster() || !app_.getFeeTrack().isLoadedLocal())
2574 app_.getJobQueue().addJob(
2576 "recvValidation->checkValidation",
2577 [weak, val, m](
Job&) {
2578 if (
auto peer = weak.
lock())
2579 peer->checkValidation(val, m);
2584 JLOG(p_journal_.debug()) <<
"Validation: Dropping UNTRUSTED (load)";
2589 JLOG(p_journal_.warn())
2590 <<
"Exception processing validation: " << e.
what();
2591 fee_ = Resource::feeInvalidRequest;
2598 protocol::TMGetObjectByHash& packet = *m;
2600 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash " << packet.type()
2601 <<
" " << packet.objects_size();
2606 if (send_queue_.size() >= Tuning::dropSendQueue)
2608 JLOG(p_journal_.debug()) <<
"GetObject: Large send queue";
2612 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2618 if (packet.type() == protocol::TMGetObjectByHash::otTRANSACTIONS)
2620 if (!txReduceRelayEnabled())
2622 JLOG(p_journal_.error())
2623 <<
"TMGetObjectByHash: tx reduce-relay is disabled";
2624 fee_ = Resource::feeInvalidRequest;
2629 app_.getJobQueue().addJob(
2631 if (
auto peer = weak.
lock())
2632 peer->doTransactions(m);
2637 fee_ = Resource::feeMediumBurdenPeer;
2639 protocol::TMGetObjectByHash reply;
2641 reply.set_query(
false);
2643 if (packet.has_seq())
2644 reply.set_seq(packet.seq());
2646 reply.set_type(packet.type());
2648 if (packet.has_ledgerhash())
2652 fee_ = Resource::feeInvalidRequest;
2656 reply.set_ledgerhash(packet.ledgerhash());
2660 for (
int i = 0; i < packet.objects_size(); ++i)
2662 auto const& obj = packet.objects(i);
2665 uint256 const hash{obj.hash()};
2668 std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0};
2669 auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)};
2672 if (
auto shardStore = app_.getShardStore())
2674 if (seq >= shardStore->earliestLedgerSeq())
2675 nodeObject = shardStore->fetchNodeObject(hash, seq);
2680 protocol::TMIndexedObject& newObj = *reply.add_objects();
2681 newObj.set_hash(hash.begin(), hash.size());
2683 &nodeObject->getData().front(),
2684 nodeObject->getData().size());
2686 if (obj.has_nodeid())
2687 newObj.set_index(obj.nodeid());
2688 if (obj.has_ledgerseq())
2689 newObj.set_ledgerseq(obj.ledgerseq());
2696 JLOG(p_journal_.trace()) <<
"GetObj: " << reply.objects_size() <<
" of "
2697 << packet.objects_size();
2698 send(std::make_shared<Message>(reply, protocol::mtGET_OBJECTS));
2705 bool progress =
false;
2707 for (
int i = 0; i < packet.objects_size(); ++i)
2709 const protocol::TMIndexedObject& obj = packet.objects(i);
2713 if (obj.has_ledgerseq())
2715 if (obj.ledgerseq() != pLSeq)
2717 if (pLDo && (pLSeq != 0))
2719 JLOG(p_journal_.debug())
2720 <<
"GetObj: Full fetch pack for " << pLSeq;
2722 pLSeq = obj.ledgerseq();
2723 pLDo = !app_.getLedgerMaster().haveLedger(pLSeq);
2727 JLOG(p_journal_.debug())
2728 <<
"GetObj: Late fetch pack for " << pLSeq;
2737 uint256 const hash{obj.hash()};
2739 app_.getLedgerMaster().addFetchPack(
2741 std::make_shared<Blob>(
2742 obj.data().begin(), obj.data().end()));
2747 if (pLDo && (pLSeq != 0))
2749 JLOG(p_journal_.debug())
2750 <<
"GetObj: Partial fetch pack for " << pLSeq;
2752 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2753 app_.getLedgerMaster().gotFetchPack(progress, pLSeq);
2760 if (!txReduceRelayEnabled())
2762 JLOG(p_journal_.error())
2763 <<
"TMHaveTransactions: tx reduce-relay is disabled";
2764 fee_ = Resource::feeInvalidRequest;
2769 app_.getJobQueue().addJob(
2771 if (
auto peer = weak.
lock())
2772 peer->handleHaveTransactions(m);
2777 PeerImp::handleHaveTransactions(
2780 protocol::TMGetObjectByHash tmBH;
2781 tmBH.set_type(protocol::TMGetObjectByHash_ObjectType_otTRANSACTIONS);
2782 tmBH.set_query(
true);
2784 JLOG(p_journal_.trace())
2785 <<
"received TMHaveTransactions " << m->hashes_size();
2791 JLOG(p_journal_.error())
2792 <<
"TMHaveTransactions with invalid hash size";
2793 fee_ = Resource::feeInvalidRequest;
2799 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2801 JLOG(p_journal_.trace()) <<
"checking transaction " << (bool)txn;
2805 JLOG(p_journal_.debug()) <<
"adding transaction to request";
2807 auto obj = tmBH.add_objects();
2808 obj->set_hash(hash.
data(), hash.
size());
2815 removeTxQueue(hash);
2819 JLOG(p_journal_.trace())
2820 <<
"transaction request object is " << tmBH.objects_size();
2822 if (tmBH.objects_size() > 0)
2823 send(std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS));
2829 if (!txReduceRelayEnabled())
2831 JLOG(p_journal_.error())
2832 <<
"TMTransactions: tx reduce-relay is disabled";
2833 fee_ = Resource::feeInvalidRequest;
2837 JLOG(p_journal_.trace())
2838 <<
"received TMTransactions " << m->transactions_size();
2840 overlay_.addTxMetrics(m->transactions_size());
2845 m->mutable_transactions(i), [](protocol::TMTransaction*) {}),
2852 using on_message_fn =
2854 if (!strand_.running_in_this_thread())
2858 (on_message_fn)&PeerImp::onMessage, shared_from_this(), m));
2860 if (!m->has_validatorpubkey())
2862 charge(Resource::feeBadData);
2865 auto validator = m->validatorpubkey();
2869 charge(Resource::feeBadData);
2875 if (!app_.validators().listed(key))
2877 charge(Resource::feeBadData);
2878 JLOG(p_journal_.debug())
2879 <<
"onMessage: TMSquelch discarding non-validator squelch "
2885 if (key == app_.getValidationPublicKey())
2887 JLOG(p_journal_.debug())
2888 <<
"onMessage: TMSquelch discarding validator's squelch " << slice;
2893 m->has_squelchduration() ? m->squelchduration() : 0;
2895 squelch_.removeSquelch(key);
2897 charge(Resource::feeBadData);
2899 JLOG(p_journal_.debug())
2900 <<
"onMessage: TMSquelch " << slice <<
" " << id() <<
" " << duration;
2912 (void)lockedRecentLock;
2914 if (
std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
2915 recentLedgers_.end())
2918 recentLedgers_.push_back(hash);
2927 if (app_.getFeeTrack().isLoadedLocal() ||
2928 (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) ||
2929 (app_.getJobQueue().getJobCount(
jtPACK) > 10))
2931 JLOG(p_journal_.info()) <<
"Too busy to make fetch pack";
2937 JLOG(p_journal_.warn()) <<
"FetchPack hash size malformed";
2938 fee_ = Resource::feeInvalidRequest;
2942 fee_ = Resource::feeHighBurdenPeer;
2944 uint256 const hash{packet->ledgerhash()};
2947 auto elapsed = UptimeClock::now();
2948 auto const pap = &app_;
2949 app_.getJobQueue().addJob(
2950 jtPACK,
"MakeFetchPack", [pap, weak, packet, hash, elapsed](
Job&) {
2951 pap->getLedgerMaster().makeFetchPack(weak, packet, hash, elapsed);
2956 PeerImp::doTransactions(
2959 protocol::TMTransactions reply;
2961 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash requesting tx "
2962 << packet->objects_size();
2964 if (packet->objects_size() > reduce_relay::MAX_TX_QUEUE_SIZE)
2966 JLOG(p_journal_.error()) <<
"doTransactions, invalid number of hashes";
2967 fee_ = Resource::feeInvalidRequest;
2973 auto const& obj = packet->objects(i);
2977 fee_ = Resource::feeInvalidRequest;
2983 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2987 JLOG(p_journal_.error()) <<
"doTransactions, transaction not found "
2989 fee_ = Resource::feeInvalidRequest;
2994 auto tx = reply.add_transactions();
2995 auto sttx = txn->getSTransaction();
2997 tx->set_rawtransaction(s.
data(), s.
size());
2999 txn->getStatus() ==
INCLUDED ? protocol::tsCURRENT
3001 tx->set_receivetimestamp(
3002 app_.timeKeeper().now().time_since_epoch().count());
3003 tx->set_deferred(txn->getSubmitResult().queued);
3006 if (reply.transactions_size() > 0)
3007 send(std::make_shared<Message>(reply, protocol::mtTRANSACTIONS));
3011 PeerImp::checkTransaction(
3013 bool checkSignature,
3022 app_.getLedgerMaster().getValidLedgerIndex()))
3024 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3025 charge(Resource::feeUnwantedData);
3033 app_.getHashRouter(),
3035 app_.getLedgerMaster().getValidatedRules(),
3037 valid != Validity::Valid)
3039 if (!validReason.empty())
3041 JLOG(p_journal_.trace())
3042 <<
"Exception checking transaction: " << validReason;
3046 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3047 charge(Resource::feeInvalidSignature);
3054 app_.getHashRouter(), stx->getTransactionID(), Validity::Valid);
3058 auto tx = std::make_shared<Transaction>(stx, reason, app_);
3060 if (tx->getStatus() ==
INVALID)
3062 if (!reason.
empty())
3064 JLOG(p_journal_.trace())
3065 <<
"Exception checking transaction: " << reason;
3067 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3068 charge(Resource::feeInvalidSignature);
3072 bool const trusted(flags & SF_TRUSTED);
3073 app_.getOPs().processTransaction(
3074 tx, trusted,
false, NetworkOPs::FailHard::no);
3078 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3079 charge(Resource::feeBadData);
3085 PeerImp::checkPropose(
3092 JLOG(p_journal_.trace())
3093 <<
"Checking " << (isTrusted ?
"trusted" :
"UNTRUSTED") <<
" proposal";
3099 JLOG(p_journal_.warn()) <<
"Proposal fails sig check";
3100 charge(Resource::feeInvalidSignature);
3107 relay = app_.getOPs().processTrustedProposal(peerPos);
3109 relay = app_.config().RELAY_UNTRUSTED_PROPOSALS || cluster();
3117 auto haveMessage = app_.overlay().relay(
3119 if (reduceRelayReady() && !haveMessage.empty())
3120 overlay_.updateSlotAndSquelch(
3123 std::move(haveMessage),
3124 protocol::mtPROPOSE_LEDGER);
3129 PeerImp::checkValidation(
3133 if (!cluster() && !val->isValid())
3135 JLOG(p_journal_.debug()) <<
"Validation forwarded by peer is invalid";
3136 charge(Resource::feeInvalidRequest);
3146 auto const suppression =
3153 overlay_.relay(*packet, suppression, val->getSignerPublic());
3154 if (reduceRelayReady() && !haveMessage.empty())
3156 overlay_.updateSlotAndSquelch(
3158 val->getSignerPublic(),
3159 std::move(haveMessage),
3160 protocol::mtVALIDATION);
3166 JLOG(p_journal_.trace()) <<
"Exception processing validation";
3167 charge(Resource::feeInvalidRequest);
3181 if (p->hasTxSet(rootHash) && p.get() != skip)
3183 auto score = p->getScore(true);
3184 if (!ret || (score > retScore))
3209 if (p->hasLedger(ledgerHash, ledger) && p.get() != skip)
3211 auto score = p->getScore(true);
3212 if (!ret || (score > retScore))
3224 PeerImp::sendLedgerBase(
3226 protocol::TMLedgerData& ledgerData)
3228 JLOG(p_journal_.trace()) <<
"sendLedgerBase: Base data";
3231 addRaw(ledger->info(), s);
3234 auto const& stateMap{ledger->stateMap()};
3235 if (stateMap.getHash() != beast::zero)
3240 stateMap.serializeRoot(root);
3241 ledgerData.add_nodes()->set_nodedata(
3244 if (ledger->info().txHash != beast::zero)
3246 auto const& txMap{ledger->txMap()};
3247 if (txMap.getHash() != beast::zero)
3251 txMap.serializeRoot(root);
3252 ledgerData.add_nodes()->set_nodedata(
3259 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3266 JLOG(p_journal_.trace()) <<
"getLedger: Ledger";
3270 if (m->has_ledgerhash())
3273 uint256 const ledgerHash{m->ledgerhash()};
3274 ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash);
3277 if (m->has_ledgerseq())
3280 if (
auto shards = app_.getShardStore())
3282 if (m->ledgerseq() >= shards->earliestLedgerSeq())
3285 shards->fetchLedger(ledgerHash, m->ledgerseq());
3292 JLOG(p_journal_.trace())
3293 <<
"getLedger: Don't have ledger with hash " << ledgerHash;
3295 if (m->has_querytype() && !m->has_requestcookie())
3301 m->has_ledgerseq() ? m->ledgerseq() : 0,
3304 m->set_requestcookie(
id());
3305 peer->send(std::make_shared<Message>(
3306 *m, protocol::mtGET_LEDGER));
3307 JLOG(p_journal_.debug())
3308 <<
"getLedger: Request relayed to peer";
3312 JLOG(p_journal_.trace())
3313 <<
"getLedger: Failed to find peer to relay request";
3318 else if (m->has_ledgerseq())
3321 if (m->ledgerseq() < app_.getLedgerMaster().getEarliestFetch())
3323 JLOG(p_journal_.debug())
3324 <<
"getLedger: Early ledger sequence request";
3328 ledger = app_.getLedgerMaster().getLedgerBySeq(m->ledgerseq());
3331 JLOG(p_journal_.debug())
3332 <<
"getLedger: Don't have ledger with sequence "
3337 else if (m->has_ltype() && m->ltype() == protocol::ltCLOSED)
3339 ledger = app_.getLedgerMaster().getClosedLedger();
3345 auto const ledgerSeq{ledger->info().seq};
3346 if (m->has_ledgerseq())
3348 if (ledgerSeq != m->ledgerseq())
3351 if (!m->has_requestcookie())
3352 charge(Resource::feeInvalidRequest);
3355 JLOG(p_journal_.warn())
3356 <<
"getLedger: Invalid ledger sequence " << ledgerSeq;
3359 else if (ledgerSeq < app_.getLedgerMaster().getEarliestFetch())
3362 JLOG(p_journal_.debug())
3363 <<
"getLedger: Early ledger sequence request " << ledgerSeq;
3368 JLOG(p_journal_.warn()) <<
"getLedger: Unable to find ledger";
3377 JLOG(p_journal_.trace()) <<
"getTxSet: TX set";
3379 uint256 const txSetHash{m->ledgerhash()};
3381 app_.getInboundTransactions().getSet(txSetHash,
false)};
3384 if (m->has_querytype() && !m->has_requestcookie())
3389 m->set_requestcookie(
id());
3391 std::make_shared<Message>(*m, protocol::mtGET_LEDGER));
3392 JLOG(p_journal_.debug()) <<
"getTxSet: Request relayed";
3396 JLOG(p_journal_.debug())
3397 <<
"getTxSet: Failed to find relay peer";
3402 JLOG(p_journal_.debug()) <<
"getTxSet: Failed to find TX set";
3413 if (!m->has_requestcookie())
3414 charge(Resource::feeMediumBurdenPeer);
3418 SHAMap const* map{
nullptr};
3419 protocol::TMLedgerData ledgerData;
3420 bool fatLeaves{
true};
3421 auto const itype{m->itype()};
3423 if (itype == protocol::liTS_CANDIDATE)
3425 if (sharedMap = getTxSet(m); !sharedMap)
3427 map = sharedMap.
get();
3430 ledgerData.set_ledgerseq(0);
3431 ledgerData.set_ledgerhash(m->ledgerhash());
3432 ledgerData.set_type(protocol::liTS_CANDIDATE);
3433 if (m->has_requestcookie())
3434 ledgerData.set_requestcookie(m->requestcookie());
3441 if (send_queue_.size() >= Tuning::dropSendQueue)
3443 JLOG(p_journal_.debug())
3444 <<
"processLedgerRequest: Large send queue";
3447 if (app_.getFeeTrack().isLoadedLocal() && !cluster())
3449 JLOG(p_journal_.debug()) <<
"processLedgerRequest: Too busy";
3453 if (ledger = getLedger(m); !ledger)
3457 auto const ledgerHash{ledger->info().hash};
3458 ledgerData.set_ledgerhash(ledgerHash.begin(), ledgerHash.size());
3459 ledgerData.set_ledgerseq(ledger->info().seq);
3460 ledgerData.set_type(itype);
3461 if (m->has_requestcookie())
3462 ledgerData.set_requestcookie(m->requestcookie());
3466 case protocol::liBASE:
3467 sendLedgerBase(ledger, ledgerData);
3470 case protocol::liTX_NODE:
3471 map = &ledger->txMap();
3472 JLOG(p_journal_.trace()) <<
"processLedgerRequest: TX map hash "
3473 << to_string(map->getHash());
3476 case protocol::liAS_NODE:
3477 map = &ledger->stateMap();
3478 JLOG(p_journal_.trace())
3479 <<
"processLedgerRequest: Account state map hash "
3480 << to_string(map->getHash());
3485 JLOG(p_journal_.error())
3486 <<
"processLedgerRequest: Invalid ledger info type";
3493 JLOG(p_journal_.warn()) <<
"processLedgerRequest: Unable to find map";
3498 if (m->nodeids_size() > 0)
3500 auto const queryDepth{
3501 m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)};
3505 for (
int i = 0; i < m->nodeids_size() &&
3506 ledgerData.nodes_size() < Tuning::softMaxReplyNodes;
3515 if (map->getNodeFat(
3522 assert(nodeIds.
size() == rawNodes.
size());
3523 JLOG(p_journal_.trace())
3524 <<
"processLedgerRequest: getNodeFat got "
3525 << rawNodes.
size() <<
" nodes";
3527 auto rawNodeIter{rawNodes.
begin()};
3528 for (
auto const& nodeId : nodeIds)
3530 protocol::TMLedgerNode* node{ledgerData.add_nodes()};
3531 node->set_nodeid(nodeId.getRawString());
3533 &rawNodeIter->front(), rawNodeIter->size());
3539 JLOG(p_journal_.warn())
3540 <<
"processLedgerRequest: getNodeFat returns false";
3548 case protocol::liBASE:
3550 info =
"Ledger base";
3553 case protocol::liTX_NODE:
3557 case protocol::liAS_NODE:
3561 case protocol::liTS_CANDIDATE:
3562 info =
"TS candidate";
3570 if (!m->has_ledgerhash())
3571 info +=
", no hash specified";
3573 JLOG(p_journal_.error())
3574 <<
"processLedgerRequest: getNodeFat with nodeId "
3575 << *shaMapNodeId <<
" and ledger info type " << info
3576 <<
" throws exception: " << e.
what();
3580 JLOG(p_journal_.info())
3581 <<
"processLedgerRequest: Got request for " << m->nodeids_size()
3582 <<
" nodes at depth " << queryDepth <<
", return "
3583 << ledgerData.nodes_size() <<
" nodes";
3587 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3592 PeerImp::getScore(
bool haveItem)
const
3596 static const int spRandomMax = 9999;
3600 static const int spHaveItem = 10000;
3605 static const int spLatency = 30;
3608 static const int spNoLatency = 8000;
3613 score += spHaveItem;
3622 score -= latency->count() * spLatency;
3624 score -= spNoLatency;
3630 PeerImp::isHighLatency()
const
3633 return latency_ >= peerHighLatency;
3637 PeerImp::reduceRelayReady()
3639 if (!reduceRelayReady_)
3641 reduce_relay::epoch<std::chrono::minutes>(UptimeClock::now()) >
3642 reduce_relay::WAIT_ON_BOOTUP;
3643 return vpReduceRelayEnabled_ && reduceRelayReady_;
3649 using namespace std::chrono_literals;
3652 totalBytes_ += bytes;
3653 accumBytes_ += bytes;
3654 auto const timeElapsed = clock_type::now() - intervalStart_;
3655 auto const timeElapsedInSecs =
3656 std::chrono::duration_cast<std::chrono::seconds>(timeElapsed);
3658 if (timeElapsedInSecs >= 1s)
3660 auto const avgBytes = accumBytes_ / timeElapsedInSecs.count();
3661 rollingAvg_.push_back(avgBytes);
3663 auto const totalBytes =
3665 rollingAvgBytes_ = totalBytes / rollingAvg_.size();
3667 intervalStart_ = clock_type::now();
3673 PeerImp::Metrics::average_bytes()
const
3676 return rollingAvgBytes_;
3680 PeerImp::Metrics::total_bytes()
const