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);
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()) ||
1944 uint256 const proposeHash{
set.currenttxhash()};
1945 uint256 const prevLedger{
set.previousledger()};
1957 if (
auto [added, relayed] =
1966 suppression, publicKey,
id_, protocol::mtPROPOSE_LEDGER);
1976 <<
"Proposal: Dropping untrusted (peer divergence)";
1988 <<
"Proposal: " << (isTrusted ?
"trusted" :
"untrusted");
2005 "recvPropose->checkPropose",
2007 if (
auto peer = weak.lock())
2008 peer->checkPropose(job, m,
proposal);
2017 if (!m->has_networktime())
2022 if (!
last_status_.has_newstatus() || m->has_newstatus())
2027 protocol::NodeStatus status =
last_status_.newstatus();
2029 m->set_newstatus(status);
2033 if (m->newevent() == protocol::neLOST_SYNC)
2035 bool outOfSync{
false};
2056 bool const peerChangedLedgers{
2063 if (peerChangedLedgers)
2074 if (m->has_ledgerhashprevious() &&
2085 if (peerChangedLedgers)
2095 if (m->has_firstseq() && m->has_lastseq())
2106 if (m->has_ledgerseq() &&
2116 if (m->has_newstatus())
2118 switch (m->newstatus())
2120 case protocol::nsCONNECTING:
2121 j[jss::status] =
"CONNECTING";
2123 case protocol::nsCONNECTED:
2124 j[jss::status] =
"CONNECTED";
2126 case protocol::nsMONITORING:
2127 j[jss::status] =
"MONITORING";
2129 case protocol::nsVALIDATING:
2130 j[jss::status] =
"VALIDATING";
2132 case protocol::nsSHUTTING:
2133 j[jss::status] =
"SHUTTING";
2138 if (m->has_newevent())
2140 switch (m->newevent())
2142 case protocol::neCLOSING_LEDGER:
2143 j[jss::action] =
"CLOSING_LEDGER";
2145 case protocol::neACCEPTED_LEDGER:
2146 j[jss::action] =
"ACCEPTED_LEDGER";
2148 case protocol::neSWITCHED_LEDGER:
2149 j[jss::action] =
"SWITCHED_LEDGER";
2151 case protocol::neLOST_SYNC:
2152 j[jss::action] =
"LOST_SYNC";
2157 if (m->has_ledgerseq())
2159 j[jss::ledger_index] = m->ledgerseq();
2162 if (m->has_ledgerhash())
2164 uint256 closedLedgerHash{};
2166 std::lock_guard sl(recentLock_);
2167 closedLedgerHash = closedLedgerHash_;
2169 j[jss::ledger_hash] =
to_string(closedLedgerHash);
2172 if (m->has_networktime())
2174 j[jss::date] = Json::UInt(m->networktime());
2177 if (m->has_firstseq() && m->has_lastseq())
2179 j[jss::ledger_index_min] = Json::UInt(m->firstseq());
2180 j[jss::ledger_index_max] = Json::UInt(m->lastseq());
2196 serverSeq = maxLedger_;
2202 checkTracking(serverSeq, validationSeq);
2211 if (diff < Tuning::convergedLedgerLimit)
2214 tracking_ = Tracking::converged;
2217 if ((diff > Tuning::divergedLedgerLimit) &&
2218 (tracking_.load() != Tracking::diverged))
2223 tracking_ = Tracking::diverged;
2224 trackingTime_ = clock_type::now();
2233 fee_ = Resource::feeInvalidRequest;
2237 uint256 const hash{m->hash()};
2239 if (m->status() == protocol::tsHAVE)
2243 if (
std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
2244 recentTxSets_.end())
2246 fee_ = Resource::feeUnwantedData;
2250 recentTxSets_.push_back(hash);
2255 PeerImp::onValidatorListMessage(
2265 JLOG(p_journal_.warn()) <<
"Ignored malformed " << messageType
2266 <<
" from peer " << remote_address_;
2268 fee_ = Resource::feeHighBurdenPeer;
2274 JLOG(p_journal_.debug())
2275 <<
"Received " << messageType <<
" from " << remote_address_.to_string()
2276 <<
" (" << id_ <<
")";
2278 if (!app_.getHashRouter().addSuppressionPeer(hash, id_))
2280 JLOG(p_journal_.debug())
2281 << messageType <<
": received duplicate " << messageType;
2285 fee_ = Resource::feeUnwantedData;
2289 auto const applyResult = app_.validators().applyListsAndBroadcast(
2293 remote_address_.to_string(),
2296 app_.getHashRouter(),
2299 JLOG(p_journal_.debug())
2300 <<
"Processed " << messageType <<
" version " << version <<
" from "
2301 << (applyResult.publisherKey ?
strHex(*applyResult.publisherKey)
2302 :
"unknown or invalid publisher")
2303 <<
" from " << remote_address_.to_string() <<
" (" << id_
2304 <<
") with best result " << to_string(applyResult.bestDisposition());
2307 switch (applyResult.bestDisposition())
2310 case ListDisposition::accepted:
2312 case ListDisposition::expired:
2314 case ListDisposition::pending: {
2317 assert(applyResult.publisherKey);
2318 auto const& pubKey = *applyResult.publisherKey;
2320 if (
auto const iter = publisherListSequences_.find(pubKey);
2321 iter != publisherListSequences_.end())
2323 assert(iter->second < applyResult.sequence);
2326 publisherListSequences_[pubKey] = applyResult.sequence;
2329 case ListDisposition::same_sequence:
2330 case ListDisposition::known_sequence:
2334 assert(applyResult.sequence && applyResult.publisherKey);
2336 publisherListSequences_[*applyResult.publisherKey] <=
2337 applyResult.sequence);
2342 case ListDisposition::stale:
2343 case ListDisposition::untrusted:
2344 case ListDisposition::invalid:
2345 case ListDisposition::unsupported_version:
2352 switch (applyResult.worstDisposition())
2354 case ListDisposition::accepted:
2355 case ListDisposition::expired:
2356 case ListDisposition::pending:
2359 case ListDisposition::same_sequence:
2360 case ListDisposition::known_sequence:
2364 fee_ = Resource::feeUnwantedData;
2366 case ListDisposition::stale:
2369 fee_ = Resource::feeBadData;
2371 case ListDisposition::untrusted:
2375 fee_ = Resource::feeUnwantedData;
2377 case ListDisposition::invalid:
2379 fee_ = Resource::feeInvalidSignature;
2381 case ListDisposition::unsupported_version:
2384 fee_ = Resource::feeBadData;
2391 for (
auto const& [disp, count] : applyResult.dispositions)
2396 case ListDisposition::accepted:
2397 JLOG(p_journal_.debug())
2398 <<
"Applied " << count <<
" new " << messageType
2399 <<
"(s) from peer " << remote_address_;
2402 case ListDisposition::expired:
2403 JLOG(p_journal_.debug())
2404 <<
"Applied " << count <<
" expired " << messageType
2405 <<
"(s) from peer " << remote_address_;
2408 case ListDisposition::pending:
2409 JLOG(p_journal_.debug())
2410 <<
"Processed " << count <<
" future " << messageType
2411 <<
"(s) from peer " << remote_address_;
2413 case ListDisposition::same_sequence:
2414 JLOG(p_journal_.warn())
2415 <<
"Ignored " << count <<
" " << messageType
2416 <<
"(s) with current sequence from peer "
2419 case ListDisposition::known_sequence:
2420 JLOG(p_journal_.warn())
2421 <<
"Ignored " << count <<
" " << messageType
2422 <<
"(s) with future sequence from peer " << remote_address_;
2424 case ListDisposition::stale:
2425 JLOG(p_journal_.warn())
2426 <<
"Ignored " << count <<
"stale " << messageType
2427 <<
"(s) from peer " << remote_address_;
2429 case ListDisposition::untrusted:
2430 JLOG(p_journal_.warn())
2431 <<
"Ignored " << count <<
" untrusted " << messageType
2432 <<
"(s) from peer " << remote_address_;
2434 case ListDisposition::unsupported_version:
2435 JLOG(p_journal_.warn())
2436 <<
"Ignored " << count <<
"unsupported version "
2437 << messageType <<
"(s) from peer " << remote_address_;
2439 case ListDisposition::invalid:
2440 JLOG(p_journal_.warn())
2441 <<
"Ignored " << count <<
"invalid " << messageType
2442 <<
"(s) from peer " << remote_address_;
2455 if (!supportsFeature(ProtocolFeature::ValidatorListPropagation))
2457 JLOG(p_journal_.debug())
2458 <<
"ValidatorList: received validator list from peer using "
2459 <<
"protocol version " << to_string(protocol_)
2460 <<
" which shouldn't support this feature.";
2461 fee_ = Resource::feeUnwantedData;
2464 onValidatorListMessage(
2468 ValidatorList::parseBlobs(*m));
2472 JLOG(p_journal_.warn()) <<
"ValidatorList: Exception, " << e.
what()
2473 <<
" from peer " << remote_address_;
2474 fee_ = Resource::feeBadData;
2484 if (!supportsFeature(ProtocolFeature::ValidatorList2Propagation))
2486 JLOG(p_journal_.debug())
2487 <<
"ValidatorListCollection: received validator list from peer "
2488 <<
"using protocol version " << to_string(protocol_)
2489 <<
" which shouldn't support this feature.";
2490 fee_ = Resource::feeUnwantedData;
2493 else if (m->version() < 2)
2495 JLOG(p_journal_.debug())
2496 <<
"ValidatorListCollection: received invalid validator list "
2498 << m->version() <<
" from peer using protocol version "
2499 << to_string(protocol_);
2500 fee_ = Resource::feeBadData;
2503 onValidatorListMessage(
2504 "ValidatorListCollection",
2507 ValidatorList::parseBlobs(*m));
2511 JLOG(p_journal_.warn()) <<
"ValidatorListCollection: Exception, "
2512 << e.
what() <<
" from peer " << remote_address_;
2513 fee_ = Resource::feeBadData;
2520 if (m->validation().size() < 50)
2522 JLOG(p_journal_.warn()) <<
"Validation: Too small";
2523 fee_ = Resource::feeInvalidRequest;
2529 auto const closeTime = app_.timeKeeper().closeTime();
2534 val = std::make_shared<STValidation>(
2538 app_.validatorManifests().getMasterKey(pk));
2541 val->setSeen(closeTime);
2545 app_.getValidations().parms(),
2546 app_.timeKeeper().closeTime(),
2548 val->getSeenTime()))
2550 JLOG(p_journal_.trace()) <<
"Validation: Not current";
2551 fee_ = Resource::feeUnwantedData;
2558 auto const isTrusted =
2559 app_.validators().trusted(val->getSignerPublic());
2564 if (!isTrusted && app_.config().RELAY_UNTRUSTED_VALIDATIONS == -1)
2568 if (
auto [added, relayed] =
2569 app_.getHashRouter().addSuppressionPeerWithStatus(key, id_);
2576 if (reduceRelayReady() && relayed &&
2577 (
stopwatch().now() - *relayed) < reduce_relay::IDLED)
2578 overlay_.updateSlotAndSquelch(
2579 key, val->getSignerPublic(), id_, protocol::mtVALIDATION);
2580 JLOG(p_journal_.trace()) <<
"Validation: duplicate";
2584 if (!isTrusted && (tracking_.load() == Tracking::diverged))
2586 JLOG(p_journal_.debug())
2587 <<
"Validation: dropping untrusted from diverged peer";
2589 if (isTrusted || cluster() || !app_.getFeeTrack().isLoadedLocal())
2592 app_.getJobQueue().addJob(
2594 "recvValidation->checkValidation",
2595 [weak, val, m](
Job&) {
2596 if (
auto peer = weak.
lock())
2597 peer->checkValidation(val, m);
2602 JLOG(p_journal_.debug()) <<
"Validation: Dropping UNTRUSTED (load)";
2607 JLOG(p_journal_.warn())
2608 <<
"Exception processing validation: " << e.
what();
2609 fee_ = Resource::feeInvalidRequest;
2616 protocol::TMGetObjectByHash& packet = *m;
2618 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash " << packet.type()
2619 <<
" " << packet.objects_size();
2624 if (send_queue_.size() >= Tuning::dropSendQueue)
2626 JLOG(p_journal_.debug()) <<
"GetObject: Large send queue";
2630 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2636 if (packet.type() == protocol::TMGetObjectByHash::otTRANSACTIONS)
2638 if (!txReduceRelayEnabled())
2640 JLOG(p_journal_.error())
2641 <<
"TMGetObjectByHash: tx reduce-relay is disabled";
2642 fee_ = Resource::feeInvalidRequest;
2647 app_.getJobQueue().addJob(
2649 if (
auto peer = weak.
lock())
2650 peer->doTransactions(m);
2655 fee_ = Resource::feeMediumBurdenPeer;
2657 protocol::TMGetObjectByHash reply;
2659 reply.set_query(
false);
2661 if (packet.has_seq())
2662 reply.set_seq(packet.seq());
2664 reply.set_type(packet.type());
2666 if (packet.has_ledgerhash())
2670 fee_ = Resource::feeInvalidRequest;
2674 reply.set_ledgerhash(packet.ledgerhash());
2678 for (
int i = 0; i < packet.objects_size(); ++i)
2680 auto const& obj = packet.objects(i);
2683 uint256 const hash{obj.hash()};
2686 std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0};
2687 auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)};
2690 if (
auto shardStore = app_.getShardStore())
2692 if (seq >= shardStore->earliestLedgerSeq())
2693 nodeObject = shardStore->fetchNodeObject(hash, seq);
2698 protocol::TMIndexedObject& newObj = *reply.add_objects();
2699 newObj.set_hash(hash.begin(), hash.size());
2701 &nodeObject->getData().front(),
2702 nodeObject->getData().size());
2704 if (obj.has_nodeid())
2705 newObj.set_index(obj.nodeid());
2706 if (obj.has_ledgerseq())
2707 newObj.set_ledgerseq(obj.ledgerseq());
2714 JLOG(p_journal_.trace()) <<
"GetObj: " << reply.objects_size() <<
" of "
2715 << packet.objects_size();
2716 send(std::make_shared<Message>(reply, protocol::mtGET_OBJECTS));
2723 bool progress =
false;
2725 for (
int i = 0; i < packet.objects_size(); ++i)
2727 const protocol::TMIndexedObject& obj = packet.objects(i);
2731 if (obj.has_ledgerseq())
2733 if (obj.ledgerseq() != pLSeq)
2735 if (pLDo && (pLSeq != 0))
2737 JLOG(p_journal_.debug())
2738 <<
"GetObj: Full fetch pack for " << pLSeq;
2740 pLSeq = obj.ledgerseq();
2741 pLDo = !app_.getLedgerMaster().haveLedger(pLSeq);
2745 JLOG(p_journal_.debug())
2746 <<
"GetObj: Late fetch pack for " << pLSeq;
2755 uint256 const hash{obj.hash()};
2757 app_.getLedgerMaster().addFetchPack(
2759 std::make_shared<Blob>(
2760 obj.data().begin(), obj.data().end()));
2765 if (pLDo && (pLSeq != 0))
2767 JLOG(p_journal_.debug())
2768 <<
"GetObj: Partial fetch pack for " << pLSeq;
2770 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2771 app_.getLedgerMaster().gotFetchPack(progress, pLSeq);
2778 if (!txReduceRelayEnabled())
2780 JLOG(p_journal_.error())
2781 <<
"TMHaveTransactions: tx reduce-relay is disabled";
2782 fee_ = Resource::feeInvalidRequest;
2787 app_.getJobQueue().addJob(
2789 if (
auto peer = weak.
lock())
2790 peer->handleHaveTransactions(m);
2795 PeerImp::handleHaveTransactions(
2798 protocol::TMGetObjectByHash tmBH;
2799 tmBH.set_type(protocol::TMGetObjectByHash_ObjectType_otTRANSACTIONS);
2800 tmBH.set_query(
true);
2802 JLOG(p_journal_.trace())
2803 <<
"received TMHaveTransactions " << m->hashes_size();
2809 JLOG(p_journal_.error())
2810 <<
"TMHaveTransactions with invalid hash size";
2811 fee_ = Resource::feeInvalidRequest;
2817 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2819 JLOG(p_journal_.trace()) <<
"checking transaction " << (bool)txn;
2823 JLOG(p_journal_.debug()) <<
"adding transaction to request";
2825 auto obj = tmBH.add_objects();
2826 obj->set_hash(hash.
data(), hash.
size());
2833 removeTxQueue(hash);
2837 JLOG(p_journal_.trace())
2838 <<
"transaction request object is " << tmBH.objects_size();
2840 if (tmBH.objects_size() > 0)
2841 send(std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS));
2847 if (!txReduceRelayEnabled())
2849 JLOG(p_journal_.error())
2850 <<
"TMTransactions: tx reduce-relay is disabled";
2851 fee_ = Resource::feeInvalidRequest;
2855 JLOG(p_journal_.trace())
2856 <<
"received TMTransactions " << m->transactions_size();
2858 overlay_.addTxMetrics(m->transactions_size());
2863 m->mutable_transactions(i), [](protocol::TMTransaction*) {}),
2870 using on_message_fn =
2872 if (!strand_.running_in_this_thread())
2876 (on_message_fn)&PeerImp::onMessage, shared_from_this(), m));
2878 if (!m->has_validatorpubkey())
2880 charge(Resource::feeBadData);
2883 auto validator = m->validatorpubkey();
2887 charge(Resource::feeBadData);
2893 if (!app_.validators().listed(key))
2895 charge(Resource::feeBadData);
2896 JLOG(p_journal_.debug())
2897 <<
"onMessage: TMSquelch discarding non-validator squelch "
2903 if (key == app_.getValidationPublicKey())
2905 JLOG(p_journal_.debug())
2906 <<
"onMessage: TMSquelch discarding validator's squelch " << slice;
2911 m->has_squelchduration() ? m->squelchduration() : 0;
2913 squelch_.removeSquelch(key);
2915 charge(Resource::feeBadData);
2917 JLOG(p_journal_.debug())
2918 <<
"onMessage: TMSquelch " << slice <<
" " << id() <<
" " << duration;
2930 (void)lockedRecentLock;
2932 if (
std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
2933 recentLedgers_.end())
2936 recentLedgers_.push_back(hash);
2945 if (app_.getFeeTrack().isLoadedLocal() ||
2946 (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) ||
2947 (app_.getJobQueue().getJobCount(
jtPACK) > 10))
2949 JLOG(p_journal_.info()) <<
"Too busy to make fetch pack";
2955 JLOG(p_journal_.warn()) <<
"FetchPack hash size malformed";
2956 fee_ = Resource::feeInvalidRequest;
2960 fee_ = Resource::feeHighBurdenPeer;
2962 uint256 const hash{packet->ledgerhash()};
2965 auto elapsed = UptimeClock::now();
2966 auto const pap = &app_;
2967 app_.getJobQueue().addJob(
2968 jtPACK,
"MakeFetchPack", [pap, weak, packet, hash, elapsed](
Job&) {
2969 pap->getLedgerMaster().makeFetchPack(weak, packet, hash, elapsed);
2974 PeerImp::doTransactions(
2977 protocol::TMTransactions reply;
2979 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash requesting tx "
2980 << packet->objects_size();
2982 if (packet->objects_size() > reduce_relay::MAX_TX_QUEUE_SIZE)
2984 JLOG(p_journal_.error()) <<
"doTransactions, invalid number of hashes";
2985 fee_ = Resource::feeInvalidRequest;
2991 auto const& obj = packet->objects(i);
2995 fee_ = Resource::feeInvalidRequest;
3001 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
3005 JLOG(p_journal_.error()) <<
"doTransactions, transaction not found "
3007 fee_ = Resource::feeInvalidRequest;
3012 auto tx = reply.add_transactions();
3013 auto sttx = txn->getSTransaction();
3015 tx->set_rawtransaction(s.
data(), s.
size());
3017 txn->getStatus() ==
INCLUDED ? protocol::tsCURRENT
3019 tx->set_receivetimestamp(
3020 app_.timeKeeper().now().time_since_epoch().count());
3021 tx->set_deferred(txn->getSubmitResult().queued);
3024 if (reply.transactions_size() > 0)
3025 send(std::make_shared<Message>(reply, protocol::mtTRANSACTIONS));
3029 PeerImp::checkTransaction(
3031 bool checkSignature,
3040 app_.getLedgerMaster().getValidLedgerIndex()))
3042 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3043 charge(Resource::feeUnwantedData);
3051 app_.getHashRouter(),
3053 app_.getLedgerMaster().getValidatedRules(),
3055 valid != Validity::Valid)
3057 if (!validReason.empty())
3059 JLOG(p_journal_.trace())
3060 <<
"Exception checking transaction: " << validReason;
3064 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3065 charge(Resource::feeInvalidSignature);
3072 app_.getHashRouter(), stx->getTransactionID(), Validity::Valid);
3076 auto tx = std::make_shared<Transaction>(stx, reason, app_);
3078 if (tx->getStatus() ==
INVALID)
3080 if (!reason.
empty())
3082 JLOG(p_journal_.trace())
3083 <<
"Exception checking transaction: " << reason;
3085 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3086 charge(Resource::feeInvalidSignature);
3090 bool const trusted(flags & SF_TRUSTED);
3091 app_.getOPs().processTransaction(
3092 tx, trusted,
false, NetworkOPs::FailHard::no);
3096 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3097 charge(Resource::feeBadData);
3103 PeerImp::checkPropose(
3110 JLOG(p_journal_.trace())
3111 <<
"Checking " << (isTrusted ?
"trusted" :
"UNTRUSTED") <<
" proposal";
3117 JLOG(p_journal_.warn()) <<
"Proposal fails sig check";
3118 charge(Resource::feeInvalidSignature);
3125 relay = app_.getOPs().processTrustedProposal(peerPos);
3127 relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster();
3135 auto haveMessage = app_.overlay().relay(
3137 if (reduceRelayReady() && !haveMessage.empty())
3138 overlay_.updateSlotAndSquelch(
3141 std::move(haveMessage),
3142 protocol::mtPROPOSE_LEDGER);
3147 PeerImp::checkValidation(
3151 if (!cluster() && !val->isValid())
3153 JLOG(p_journal_.debug()) <<
"Validation forwarded by peer is invalid";
3154 charge(Resource::feeInvalidRequest);
3164 auto const suppression =
3171 overlay_.relay(*packet, suppression, val->getSignerPublic());
3172 if (reduceRelayReady() && !haveMessage.empty())
3174 overlay_.updateSlotAndSquelch(
3176 val->getSignerPublic(),
3177 std::move(haveMessage),
3178 protocol::mtVALIDATION);
3184 JLOG(p_journal_.trace()) <<
"Exception processing validation";
3185 charge(Resource::feeInvalidRequest);
3199 if (p->hasTxSet(rootHash) && p.get() != skip)
3201 auto score = p->getScore(true);
3202 if (!ret || (score > retScore))
3227 if (p->hasLedger(ledgerHash, ledger) && p.get() != skip)
3229 auto score = p->getScore(true);
3230 if (!ret || (score > retScore))
3242 PeerImp::sendLedgerBase(
3244 protocol::TMLedgerData& ledgerData)
3246 JLOG(p_journal_.trace()) <<
"sendLedgerBase: Base data";
3249 addRaw(ledger->info(), s);
3252 auto const& stateMap{ledger->stateMap()};
3253 if (stateMap.getHash() != beast::zero)
3258 stateMap.serializeRoot(root);
3259 ledgerData.add_nodes()->set_nodedata(
3262 if (ledger->info().txHash != beast::zero)
3264 auto const& txMap{ledger->txMap()};
3265 if (txMap.getHash() != beast::zero)
3269 txMap.serializeRoot(root);
3270 ledgerData.add_nodes()->set_nodedata(
3277 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3284 JLOG(p_journal_.trace()) <<
"getLedger: Ledger";
3288 if (m->has_ledgerhash())
3291 uint256 const ledgerHash{m->ledgerhash()};
3292 ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash);
3295 if (m->has_ledgerseq())
3298 if (
auto shards = app_.getShardStore())
3300 if (m->ledgerseq() >= shards->earliestLedgerSeq())
3303 shards->fetchLedger(ledgerHash, m->ledgerseq());
3310 JLOG(p_journal_.trace())
3311 <<
"getLedger: Don't have ledger with hash " << ledgerHash;
3313 if (m->has_querytype() && !m->has_requestcookie())
3319 m->has_ledgerseq() ? m->ledgerseq() : 0,
3322 m->set_requestcookie(
id());
3323 peer->send(std::make_shared<Message>(
3324 *m, protocol::mtGET_LEDGER));
3325 JLOG(p_journal_.debug())
3326 <<
"getLedger: Request relayed to peer";
3330 JLOG(p_journal_.trace())
3331 <<
"getLedger: Failed to find peer to relay request";
3336 else if (m->has_ledgerseq())
3339 if (m->ledgerseq() < app_.getLedgerMaster().getEarliestFetch())
3341 JLOG(p_journal_.debug())
3342 <<
"getLedger: Early ledger sequence request";
3346 ledger = app_.getLedgerMaster().getLedgerBySeq(m->ledgerseq());
3349 JLOG(p_journal_.debug())
3350 <<
"getLedger: Don't have ledger with sequence "
3355 else if (m->has_ltype() && m->ltype() == protocol::ltCLOSED)
3357 ledger = app_.getLedgerMaster().getClosedLedger();
3363 auto const ledgerSeq{ledger->info().seq};
3364 if (m->has_ledgerseq())
3366 if (ledgerSeq != m->ledgerseq())
3369 if (!m->has_requestcookie())
3370 charge(Resource::feeInvalidRequest);
3373 JLOG(p_journal_.warn())
3374 <<
"getLedger: Invalid ledger sequence " << ledgerSeq;
3377 else if (ledgerSeq < app_.getLedgerMaster().getEarliestFetch())
3380 JLOG(p_journal_.debug())
3381 <<
"getLedger: Early ledger sequence request " << ledgerSeq;
3386 JLOG(p_journal_.warn()) <<
"getLedger: Unable to find ledger";
3395 JLOG(p_journal_.trace()) <<
"getTxSet: TX set";
3397 uint256 const txSetHash{m->ledgerhash()};
3399 app_.getInboundTransactions().getSet(txSetHash,
false)};
3402 if (m->has_querytype() && !m->has_requestcookie())
3407 m->set_requestcookie(
id());
3409 std::make_shared<Message>(*m, protocol::mtGET_LEDGER));
3410 JLOG(p_journal_.debug()) <<
"getTxSet: Request relayed";
3414 JLOG(p_journal_.debug())
3415 <<
"getTxSet: Failed to find relay peer";
3420 JLOG(p_journal_.debug()) <<
"getTxSet: Failed to find TX set";
3431 if (!m->has_requestcookie())
3432 charge(Resource::feeMediumBurdenPeer);
3436 SHAMap const* map{
nullptr};
3437 protocol::TMLedgerData ledgerData;
3438 bool fatLeaves{
true};
3439 auto const itype{m->itype()};
3441 if (itype == protocol::liTS_CANDIDATE)
3443 if (sharedMap = getTxSet(m); !sharedMap)
3445 map = sharedMap.
get();
3448 ledgerData.set_ledgerseq(0);
3449 ledgerData.set_ledgerhash(m->ledgerhash());
3450 ledgerData.set_type(protocol::liTS_CANDIDATE);
3451 if (m->has_requestcookie())
3452 ledgerData.set_requestcookie(m->requestcookie());
3459 if (send_queue_.size() >= Tuning::dropSendQueue)
3461 JLOG(p_journal_.debug())
3462 <<
"processLedgerRequest: Large send queue";
3465 if (app_.getFeeTrack().isLoadedLocal() && !cluster())
3467 JLOG(p_journal_.debug()) <<
"processLedgerRequest: Too busy";
3471 if (ledger = getLedger(m); !ledger)
3475 auto const ledgerHash{ledger->info().hash};
3476 ledgerData.set_ledgerhash(ledgerHash.begin(), ledgerHash.size());
3477 ledgerData.set_ledgerseq(ledger->info().seq);
3478 ledgerData.set_type(itype);
3479 if (m->has_requestcookie())
3480 ledgerData.set_requestcookie(m->requestcookie());
3484 case protocol::liBASE:
3485 sendLedgerBase(ledger, ledgerData);
3488 case protocol::liTX_NODE:
3489 map = &ledger->txMap();
3490 JLOG(p_journal_.trace()) <<
"processLedgerRequest: TX map hash "
3491 << to_string(map->getHash());
3494 case protocol::liAS_NODE:
3495 map = &ledger->stateMap();
3496 JLOG(p_journal_.trace())
3497 <<
"processLedgerRequest: Account state map hash "
3498 << to_string(map->getHash());
3503 JLOG(p_journal_.error())
3504 <<
"processLedgerRequest: Invalid ledger info type";
3511 JLOG(p_journal_.warn()) <<
"processLedgerRequest: Unable to find map";
3516 if (m->nodeids_size() > 0)
3518 auto const queryDepth{
3519 m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)};
3523 for (
int i = 0; i < m->nodeids_size() &&
3524 ledgerData.nodes_size() < Tuning::softMaxReplyNodes;
3533 if (map->getNodeFat(
3540 assert(nodeIds.
size() == rawNodes.
size());
3541 JLOG(p_journal_.trace())
3542 <<
"processLedgerRequest: getNodeFat got "
3543 << rawNodes.
size() <<
" nodes";
3545 auto rawNodeIter{rawNodes.
begin()};
3546 for (
auto const& nodeId : nodeIds)
3548 protocol::TMLedgerNode* node{ledgerData.add_nodes()};
3549 node->set_nodeid(nodeId.getRawString());
3551 &rawNodeIter->front(), rawNodeIter->size());
3557 JLOG(p_journal_.warn())
3558 <<
"processLedgerRequest: getNodeFat returns false";
3566 case protocol::liBASE:
3568 info =
"Ledger base";
3571 case protocol::liTX_NODE:
3575 case protocol::liAS_NODE:
3579 case protocol::liTS_CANDIDATE:
3580 info =
"TS candidate";
3588 if (!m->has_ledgerhash())
3589 info +=
", no hash specified";
3591 JLOG(p_journal_.error())
3592 <<
"processLedgerRequest: getNodeFat with nodeId "
3593 << *shaMapNodeId <<
" and ledger info type " << info
3594 <<
" throws exception: " << e.
what();
3598 JLOG(p_journal_.info())
3599 <<
"processLedgerRequest: Got request for " << m->nodeids_size()
3600 <<
" nodes at depth " << queryDepth <<
", return "
3601 << ledgerData.nodes_size() <<
" nodes";
3605 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3610 PeerImp::getScore(
bool haveItem)
const
3614 static const int spRandomMax = 9999;
3618 static const int spHaveItem = 10000;
3623 static const int spLatency = 30;
3626 static const int spNoLatency = 8000;
3631 score += spHaveItem;
3640 score -= latency->count() * spLatency;
3642 score -= spNoLatency;
3648 PeerImp::isHighLatency()
const
3651 return latency_ >= peerHighLatency;
3655 PeerImp::reduceRelayReady()
3657 if (!reduceRelayReady_)
3659 reduce_relay::epoch<std::chrono::minutes>(UptimeClock::now()) >
3660 reduce_relay::WAIT_ON_BOOTUP;
3661 return vpReduceRelayEnabled_ && reduceRelayReady_;
3667 using namespace std::chrono_literals;
3670 totalBytes_ += bytes;
3671 accumBytes_ += bytes;
3672 auto const timeElapsed = clock_type::now() - intervalStart_;
3673 auto const timeElapsedInSecs =
3674 std::chrono::duration_cast<std::chrono::seconds>(timeElapsed);
3676 if (timeElapsedInSecs >= 1s)
3678 auto const avgBytes = accumBytes_ / timeElapsedInSecs.count();
3679 rollingAvg_.push_back(avgBytes);
3681 auto const totalBytes =
3683 rollingAvgBytes_ = totalBytes / rollingAvg_.size();
3685 intervalStart_ = clock_type::now();
3691 PeerImp::Metrics::average_bytes()
const
3694 return rollingAvgBytes_;
3698 PeerImp::Metrics::total_bytes()
const