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());
648 stream_.async_shutdown(bind_executor(
658 timer_.expires_from_now(peerTimerInterval, ec);
665 timer_.async_wait(bind_executor(
695 if (ec == boost::asio::error::operation_aborted)
707 fail(
"Large send queue");
713 clock_type::duration duration;
734 fail(
"Ping Timeout");
741 protocol::TMPing message;
742 message.set_type(protocol::TMPing::ptPING);
745 send(std::make_shared<Message>(message, protocol::mtPING));
757 JLOG(
journal_.
error()) <<
"onShutdown: expected error condition";
760 if (ec != boost::asio::error::eof)
761 return fail(
"onShutdown", ec);
778 return fail(
"makeSharedValue: Unexpected failure");
799 auto write_buffer = std::make_shared<boost::beast::multi_buffer>();
812 boost::asio::async_write(
814 write_buffer->data(),
815 boost::asio::transfer_all(),
822 if (ec == boost::asio::error::operation_aborted)
825 return fail(
"onWriteResponse", ec);
826 if (write_buffer->size() == bytes_transferred)
828 return fail(
"Failed to write header");
842 return headers_[
"Server-Domain"].to_string();
884 protocol::TMGetPeerShardInfoV2 tmGPS;
886 send(std::make_shared<Message>(tmGPS, protocol::mtGET_PEER_SHARD_INFO_V2));
897 if (ec == boost::asio::error::operation_aborted)
899 if (ec == boost::asio::error::eof)
905 return fail(
"onReadMessage", ec);
908 if (bytes_transferred > 0)
909 stream <<
"onReadMessage: " << bytes_transferred <<
" bytes";
911 stream <<
"onReadMessage";
914 metrics_.recv.add_message(bytes_transferred);
926 return fail(
"onReadMessage", ec);
931 if (bytes_consumed == 0)
944 std::placeholders::_1,
945 std::placeholders::_2)));
953 if (ec == boost::asio::error::operation_aborted)
956 return fail(
"onWriteMessage", ec);
959 if (bytes_transferred > 0)
960 stream <<
"onWriteMessage: " << bytes_transferred <<
" bytes";
962 stream <<
"onWriteMessage";
965 metrics_.sent.add_message(bytes_transferred);
972 return boost::asio::async_write(
981 std::placeholders::_1,
982 std::placeholders::_2)));
987 return stream_.async_shutdown(bind_executor(
992 std::placeholders::_1)));
1022 if ((type == MessageType::mtTRANSACTION ||
1023 type == MessageType::mtHAVE_TRANSACTIONS ||
1024 type == MessageType::mtTRANSACTIONS ||
1026 category == TrafficCount::category::get_transactions ||
1028 category == TrafficCount::category::ld_tsc_get ||
1029 category == TrafficCount::category::ld_tsc_share ||
1031 category == TrafficCount::category::gl_tsc_share ||
1032 category == TrafficCount::category::gl_tsc_get) &&
1036 static_cast<MessageType
>(type),
static_cast<std::uint64_t>(size));
1038 JLOG(
journal_.
trace()) <<
"onMessageBegin: " << type <<
" " << size <<
" "
1039 << uncompressed_size <<
" " << isCompressed;
1054 auto const s = m->list_size();
1074 if (m->type() == protocol::TMPing::ptPING)
1078 m->set_type(protocol::TMPing::ptPONG);
1079 send(std::make_shared<Message>(*m, protocol::mtPING));
1083 if (m->type() == protocol::TMPing::ptPONG && m->has_seq())
1093 auto const rtt = std::chrono::round<std::chrono::milliseconds>(
1118 for (
int i = 0; i < m->clusternodes().size(); ++i)
1120 protocol::TMClusterNode
const& node = m->clusternodes(i);
1123 if (node.has_nodename())
1124 name = node.nodename();
1126 auto const publicKey =
1133 auto const reportTime =
1137 *publicKey,
name, node.nodeload(), reportTime);
1141 int loadSources = m->loadsources().size();
1142 if (loadSources != 0)
1145 gossip.
items.reserve(loadSources);
1146 for (
int i = 0; i < m->loadsources().size(); ++i)
1148 protocol::TMLoadSource
const& node = m->loadsources(i);
1153 gossip.
items.push_back(item);
1166 if (status.getReportTime() >= thresh)
1167 fees.push_back(status.getLoadFee());
1172 auto const index = fees.size() / 2;
1174 clusterFee = fees[index];
1202 return badData(
"Invalid relays");
1211 auto const peerChainSz{m->peerchain_size()};
1212 if (peerChainSz > 0)
1215 return badData(
"Invalid peer chain size");
1218 return badData(
"Invalid relays and peer chain size");
1220 for (
int i = 0; i < peerChainSz; ++i)
1222 auto const slice{
makeSlice(m->peerchain(i).publickey())};
1226 return badData(
"Invalid peer public key");
1229 if (!pubKeyChain.
emplace(slice).second)
1230 return badData(
"Invalid peer public key");
1237 auto reply{shardStore->getShardInfo()->makeMessage(
app_)};
1238 if (peerChainSz > 0)
1239 *(reply.mutable_peerchain()) = m->peerchain();
1240 send(std::make_shared<Message>(reply, protocol::mtPEER_SHARD_INFO_V2));
1243 if (m->relays() == 0)
1247 if (peerChainSz == 0)
1254 m->set_relays(m->relays() - 1);
1256 std::make_shared<Message>(*m, protocol::mtGET_PEER_SHARD_INFO_V2),
1258 return pubKeyChain.
find(peer->getNodePublic()) != pubKeyChain.
end();
1270 if (curLedgerSeq >= db.earliestLedgerSeq())
1271 return db.seqToShardIndex(curLedgerSeq);
1272 return std::nullopt;
1287 auto const timestamp{
1290 if (timestamp > (now + 5s))
1291 return badData(
"Invalid timestamp");
1294 using namespace std::chrono_literals;
1295 if (timestamp < (now - 5min))
1296 return badData(
"Stale timestamp");
1298 s.
add32(m->timestamp());
1303 auto const numIncomplete{m->incomplete_size()};
1304 if (numIncomplete > 0)
1306 if (latestShardIndex && numIncomplete > *latestShardIndex)
1307 return badData(
"Invalid number of incomplete shards");
1310 for (
int i = 0; i < numIncomplete; ++i)
1312 auto const& incomplete{m->incomplete(i)};
1313 auto const shardIndex{incomplete.shardindex()};
1316 if (shardIndex < earliestShardIndex ||
1317 (latestShardIndex && shardIndex > latestShardIndex))
1319 return badData(
"Invalid incomplete shard index");
1321 s.
add32(shardIndex);
1324 auto const state{
static_cast<ShardState>(incomplete.state())};
1336 return badData(
"Invalid incomplete shard state");
1338 s.
add32(incomplete.state());
1342 if (incomplete.has_progress())
1344 progress = incomplete.progress();
1345 if (progress < 1 || progress > 100)
1346 return badData(
"Invalid incomplete shard progress");
1351 if (!
shardInfo.update(shardIndex, state, progress))
1352 return badData(
"Invalid duplicate incomplete shards");
1357 if (m->has_finalized())
1359 auto const& str{m->finalized()};
1361 return badData(
"Invalid finalized shards");
1363 if (!
shardInfo.setFinalizedFromString(str))
1364 return badData(
"Invalid finalized shard indexes");
1367 auto const numFinalized{boost::icl::length(
finalized)};
1368 if (numFinalized == 0 ||
1369 boost::icl::first(
finalized) < earliestShardIndex ||
1370 (latestShardIndex &&
1371 boost::icl::last(
finalized) > latestShardIndex))
1373 return badData(
"Invalid finalized shard indexes");
1376 if (latestShardIndex &&
1377 (numFinalized + numIncomplete) > *latestShardIndex)
1379 return badData(
"Invalid number of finalized and incomplete shards");
1382 s.
addRaw(str.data(), str.size());
1388 return badData(
"Invalid public key");
1393 return badData(
"Invalid public key");
1397 return badData(
"Invalid signature");
1400 auto const peerChainSz{m->peerchain_size()};
1401 if (peerChainSz > 0)
1405 return badData(
"Invalid peer chain size");
1413 for (
int i = 0; i < peerChainSz; ++i)
1416 slice =
makeSlice(m->peerchain(i).publickey());
1418 return badData(
"Invalid peer public key");
1421 if (!pubKeyChain.
emplace(slice).second)
1422 return badData(
"Invalid peer public key");
1427 makeSlice(m->peerchain(peerChainSz - 1).publickey()));
1430 m->mutable_peerchain()->RemoveLast();
1432 std::make_shared<Message>(*m, protocol::mtPEER_SHARD_INFO_V2));
1434 <<
"Relayed TMPeerShardInfoV2 from peer IP "
1436 << peer->getRemoteAddress().to_string();
1446 <<
"Consumed TMPeerShardInfoV2 originating from public key "
1449 << (
shardInfo.incomplete().empty() ?
"empty"
1459 else if (
shardInfo.msgTimestamp() > it->second.msgTimestamp())
1464 if (peerChainSz == 0)
1478 if (m->endpoints_v2().size() >= 1024)
1485 endpoints.
reserve(m->endpoints_v2().size());
1487 for (
auto const& tm : m->endpoints_v2())
1494 << tm.endpoint() <<
"}";
1511 if (!endpoints.
empty())
1534 <<
"Need network ledger";
1542 auto stx = std::make_shared<STTx const>(sit);
1543 uint256 txID = stx->getTransactionID();
1567 bool checkSignature =
true;
1570 if (!m->has_deferred() || !m->deferred())
1574 flags |= SF_TRUSTED;
1581 checkSignature =
false;
1588 <<
"No new transactions until synchronized";
1601 "recvTransaction->checkTransaction",
1606 if (
auto peer = weak.lock())
1607 peer->checkTransaction(flags, checkSignature, stx);
1614 <<
"Transaction invalid: " <<
strHex(m->rawtransaction());
1625 auto const itype{m->itype()};
1628 if (itype < protocol::liBASE || itype > protocol::liTS_CANDIDATE)
1629 return badData(
"Invalid ledger info type");
1634 return std::nullopt;
1637 if (itype == protocol::liTS_CANDIDATE)
1639 if (!m->has_ledgerhash())
1640 return badData(
"Invalid TX candidate set, missing TX set hash");
1643 !m->has_ledgerhash() && !m->has_ledgerseq() &&
1644 !(ltype && *ltype == protocol::ltCLOSED))
1646 return badData(
"Invalid request");
1650 if (ltype && (*ltype < protocol::ltACCEPTED || *ltype > protocol::ltCLOSED))
1651 return badData(
"Invalid ledger type");
1655 return badData(
"Invalid ledger hash");
1658 if (m->has_ledgerseq())
1660 auto const ledgerSeq{m->ledgerseq()};
1670 using namespace std::chrono_literals;
1680 if (itype != protocol::liBASE)
1682 if (m->nodeids_size() <= 0)
1683 return badData(
"Invalid ledger node IDs");
1685 for (
auto const& nodeId : m->nodeids())
1688 return badData(
"Invalid SHAMap node ID");
1693 if (m->has_querytype() && m->querytype() != protocol::qtINDIRECT)
1694 return badData(
"Invalid query type");
1697 if (m->has_querydepth())
1700 itype == protocol::liBASE)
1702 return badData(
"Invalid query depth");
1709 if (
auto peer = weak.
lock())
1710 peer->processLedgerRequest(m);
1728 if (
auto peer = weak.
lock())
1731 peer->ledgerReplayMsgHandler_.processProofPathRequest(m);
1732 if (reply.has_error())
1734 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1735 peer->charge(Resource::feeInvalidRequest);
1737 peer->charge(Resource::feeRequestNoReply);
1741 peer->send(std::make_shared<Message>(
1742 reply, protocol::mtPROOF_PATH_RESPONSE));
1777 if (
auto peer = weak.
lock())
1780 peer->ledgerReplayMsgHandler_.processReplayDeltaRequest(m);
1781 if (reply.has_error())
1783 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1784 peer->charge(Resource::feeInvalidRequest);
1786 peer->charge(Resource::feeRequestNoReply);
1790 peer->send(std::make_shared<Message>(
1791 reply, protocol::mtREPLAY_DELTA_RESPONSE));
1822 return badData(
"Invalid ledger hash");
1826 auto const ledgerSeq{m->ledgerseq()};
1827 if (m->type() == protocol::liTS_CANDIDATE)
1846 using namespace std::chrono_literals;
1857 if (m->type() < protocol::liBASE || m->type() > protocol::liTS_CANDIDATE)
1858 return badData(
"Invalid ledger info type");
1861 if (m->has_error() &&
1862 (m->error() < protocol::reNO_LEDGER ||
1863 m->error() > protocol::reBAD_REQUEST))
1865 return badData(
"Invalid reply error");
1872 "Invalid Ledger/TXset nodes " +
std::to_string(m->nodes_size()));
1876 if (m->has_requestcookie())
1880 m->clear_requestcookie();
1881 peer->send(std::make_shared<Message>(*m, protocol::mtLEDGER_DATA));
1885 JLOG(
p_journal_.
info()) <<
"Unable to route TX/ledger data reply";
1890 uint256 const ledgerHash{m->ledgerhash()};
1893 if (m->type() == protocol::liTS_CANDIDATE)
1897 jtTXN_DATA,
"recvPeerData", [weak, ledgerHash, m]() {
1898 if (
auto peer = weak.lock())
1900 peer->app_.getInboundTransactions().gotData(
1901 ledgerHash, peer, m);
1914 protocol::TMProposeSet&
set = *m;
1920 if ((std::clamp<std::size_t>(sig.size(), 64, 72) != sig.size()) ||
1948 uint256 const proposeHash{
set.currenttxhash()};
1949 uint256 const prevLedger{
set.previousledger()};
1961 if (
auto [added, relayed] =
1970 suppression, publicKey,
id_, protocol::mtPROPOSE_LEDGER);
1980 <<
"Proposal: Dropping untrusted (peer divergence)";
1992 <<
"Proposal: " << (isTrusted ?
"trusted" :
"untrusted");
2009 "recvPropose->checkPropose",
2011 if (
auto peer = weak.lock())
2012 peer->checkPropose(isTrusted, m,
proposal);
2021 if (!m->has_networktime())
2026 if (!
last_status_.has_newstatus() || m->has_newstatus())
2031 protocol::NodeStatus status =
last_status_.newstatus();
2033 m->set_newstatus(status);
2037 if (m->newevent() == protocol::neLOST_SYNC)
2039 bool outOfSync{
false};
2060 bool const peerChangedLedgers{
2067 if (peerChangedLedgers)
2078 if (m->has_ledgerhashprevious() &&
2089 if (peerChangedLedgers)
2099 if (m->has_firstseq() && m->has_lastseq())
2110 if (m->has_ledgerseq() &&
2120 if (m->has_newstatus())
2122 switch (m->newstatus())
2124 case protocol::nsCONNECTING:
2125 j[jss::status] =
"CONNECTING";
2127 case protocol::nsCONNECTED:
2128 j[jss::status] =
"CONNECTED";
2130 case protocol::nsMONITORING:
2131 j[jss::status] =
"MONITORING";
2133 case protocol::nsVALIDATING:
2134 j[jss::status] =
"VALIDATING";
2136 case protocol::nsSHUTTING:
2137 j[jss::status] =
"SHUTTING";
2142 if (m->has_newevent())
2144 switch (m->newevent())
2146 case protocol::neCLOSING_LEDGER:
2147 j[jss::action] =
"CLOSING_LEDGER";
2149 case protocol::neACCEPTED_LEDGER:
2150 j[jss::action] =
"ACCEPTED_LEDGER";
2152 case protocol::neSWITCHED_LEDGER:
2153 j[jss::action] =
"SWITCHED_LEDGER";
2155 case protocol::neLOST_SYNC:
2156 j[jss::action] =
"LOST_SYNC";
2161 if (m->has_ledgerseq())
2163 j[jss::ledger_index] = m->ledgerseq();
2166 if (m->has_ledgerhash())
2168 uint256 closedLedgerHash{};
2170 std::lock_guard sl(recentLock_);
2171 closedLedgerHash = closedLedgerHash_;
2173 j[jss::ledger_hash] =
to_string(closedLedgerHash);
2176 if (m->has_networktime())
2178 j[jss::date] = Json::UInt(m->networktime());
2181 if (m->has_firstseq() && m->has_lastseq())
2183 j[jss::ledger_index_min] = Json::UInt(m->firstseq());
2184 j[jss::ledger_index_max] = Json::UInt(m->lastseq());
2200 serverSeq = maxLedger_;
2206 checkTracking(serverSeq, validationSeq);
2215 if (diff < Tuning::convergedLedgerLimit)
2218 tracking_ = Tracking::converged;
2221 if ((diff > Tuning::divergedLedgerLimit) &&
2222 (tracking_.load() != Tracking::diverged))
2227 tracking_ = Tracking::diverged;
2228 trackingTime_ = clock_type::now();
2237 fee_ = Resource::feeInvalidRequest;
2241 uint256 const hash{m->hash()};
2243 if (m->status() == protocol::tsHAVE)
2247 if (
std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
2248 recentTxSets_.end())
2250 fee_ = Resource::feeUnwantedData;
2254 recentTxSets_.push_back(hash);
2259 PeerImp::onValidatorListMessage(
2269 JLOG(p_journal_.warn()) <<
"Ignored malformed " << messageType
2270 <<
" from peer " << remote_address_;
2272 fee_ = Resource::feeHighBurdenPeer;
2278 JLOG(p_journal_.debug())
2279 <<
"Received " << messageType <<
" from " << remote_address_.to_string()
2280 <<
" (" << id_ <<
")";
2282 if (!app_.getHashRouter().addSuppressionPeer(hash, id_))
2284 JLOG(p_journal_.debug())
2285 << messageType <<
": received duplicate " << messageType;
2289 fee_ = Resource::feeUnwantedData;
2293 auto const applyResult = app_.validators().applyListsAndBroadcast(
2297 remote_address_.to_string(),
2300 app_.getHashRouter(),
2303 JLOG(p_journal_.debug())
2304 <<
"Processed " << messageType <<
" version " << version <<
" from "
2305 << (applyResult.publisherKey ?
strHex(*applyResult.publisherKey)
2306 :
"unknown or invalid publisher")
2307 <<
" from " << remote_address_.to_string() <<
" (" << id_
2308 <<
") with best result " << to_string(applyResult.bestDisposition());
2311 switch (applyResult.bestDisposition())
2314 case ListDisposition::accepted:
2316 case ListDisposition::expired:
2318 case ListDisposition::pending: {
2321 assert(applyResult.publisherKey);
2322 auto const& pubKey = *applyResult.publisherKey;
2324 if (
auto const iter = publisherListSequences_.find(pubKey);
2325 iter != publisherListSequences_.end())
2327 assert(iter->second < applyResult.sequence);
2330 publisherListSequences_[pubKey] = applyResult.sequence;
2333 case ListDisposition::same_sequence:
2334 case ListDisposition::known_sequence:
2338 assert(applyResult.sequence && applyResult.publisherKey);
2340 publisherListSequences_[*applyResult.publisherKey] <=
2341 applyResult.sequence);
2346 case ListDisposition::stale:
2347 case ListDisposition::untrusted:
2348 case ListDisposition::invalid:
2349 case ListDisposition::unsupported_version:
2356 switch (applyResult.worstDisposition())
2358 case ListDisposition::accepted:
2359 case ListDisposition::expired:
2360 case ListDisposition::pending:
2363 case ListDisposition::same_sequence:
2364 case ListDisposition::known_sequence:
2368 fee_ = Resource::feeUnwantedData;
2370 case ListDisposition::stale:
2373 fee_ = Resource::feeBadData;
2375 case ListDisposition::untrusted:
2379 fee_ = Resource::feeUnwantedData;
2381 case ListDisposition::invalid:
2383 fee_ = Resource::feeInvalidSignature;
2385 case ListDisposition::unsupported_version:
2388 fee_ = Resource::feeBadData;
2395 for (
auto const& [disp, count] : applyResult.dispositions)
2400 case ListDisposition::accepted:
2401 JLOG(p_journal_.debug())
2402 <<
"Applied " << count <<
" new " << messageType
2403 <<
"(s) from peer " << remote_address_;
2406 case ListDisposition::expired:
2407 JLOG(p_journal_.debug())
2408 <<
"Applied " << count <<
" expired " << messageType
2409 <<
"(s) from peer " << remote_address_;
2412 case ListDisposition::pending:
2413 JLOG(p_journal_.debug())
2414 <<
"Processed " << count <<
" future " << messageType
2415 <<
"(s) from peer " << remote_address_;
2417 case ListDisposition::same_sequence:
2418 JLOG(p_journal_.warn())
2419 <<
"Ignored " << count <<
" " << messageType
2420 <<
"(s) with current sequence from peer "
2423 case ListDisposition::known_sequence:
2424 JLOG(p_journal_.warn())
2425 <<
"Ignored " << count <<
" " << messageType
2426 <<
"(s) with future sequence from peer " << remote_address_;
2428 case ListDisposition::stale:
2429 JLOG(p_journal_.warn())
2430 <<
"Ignored " << count <<
"stale " << messageType
2431 <<
"(s) from peer " << remote_address_;
2433 case ListDisposition::untrusted:
2434 JLOG(p_journal_.warn())
2435 <<
"Ignored " << count <<
" untrusted " << messageType
2436 <<
"(s) from peer " << remote_address_;
2438 case ListDisposition::unsupported_version:
2439 JLOG(p_journal_.warn())
2440 <<
"Ignored " << count <<
"unsupported version "
2441 << messageType <<
"(s) from peer " << remote_address_;
2443 case ListDisposition::invalid:
2444 JLOG(p_journal_.warn())
2445 <<
"Ignored " << count <<
"invalid " << messageType
2446 <<
"(s) from peer " << remote_address_;
2459 if (!supportsFeature(ProtocolFeature::ValidatorListPropagation))
2461 JLOG(p_journal_.debug())
2462 <<
"ValidatorList: received validator list from peer using "
2463 <<
"protocol version " << to_string(protocol_)
2464 <<
" which shouldn't support this feature.";
2465 fee_ = Resource::feeUnwantedData;
2468 onValidatorListMessage(
2472 ValidatorList::parseBlobs(*m));
2476 JLOG(p_journal_.warn()) <<
"ValidatorList: Exception, " << e.
what()
2477 <<
" from peer " << remote_address_;
2478 fee_ = Resource::feeBadData;
2488 if (!supportsFeature(ProtocolFeature::ValidatorList2Propagation))
2490 JLOG(p_journal_.debug())
2491 <<
"ValidatorListCollection: received validator list from peer "
2492 <<
"using protocol version " << to_string(protocol_)
2493 <<
" which shouldn't support this feature.";
2494 fee_ = Resource::feeUnwantedData;
2497 else if (m->version() < 2)
2499 JLOG(p_journal_.debug())
2500 <<
"ValidatorListCollection: received invalid validator list "
2502 << m->version() <<
" from peer using protocol version "
2503 << to_string(protocol_);
2504 fee_ = Resource::feeBadData;
2507 onValidatorListMessage(
2508 "ValidatorListCollection",
2511 ValidatorList::parseBlobs(*m));
2515 JLOG(p_journal_.warn()) <<
"ValidatorListCollection: Exception, "
2516 << e.
what() <<
" from peer " << remote_address_;
2517 fee_ = Resource::feeBadData;
2524 if (m->validation().size() < 50)
2526 JLOG(p_journal_.warn()) <<
"Validation: Too small";
2527 fee_ = Resource::feeInvalidRequest;
2533 auto const closeTime = app_.timeKeeper().closeTime();
2538 val = std::make_shared<STValidation>(
2542 app_.validatorManifests().getMasterKey(pk));
2545 val->setSeen(closeTime);
2549 app_.getValidations().parms(),
2550 app_.timeKeeper().closeTime(),
2552 val->getSeenTime()))
2554 JLOG(p_journal_.trace()) <<
"Validation: Not current";
2555 fee_ = Resource::feeUnwantedData;
2562 auto const isTrusted =
2563 app_.validators().trusted(val->getSignerPublic());
2568 if (!isTrusted && app_.config().RELAY_UNTRUSTED_VALIDATIONS == -1)
2573 if (
auto [added, relayed] =
2574 app_.getHashRouter().addSuppressionPeerWithStatus(key, id_);
2581 if (reduceRelayReady() && relayed &&
2582 (
stopwatch().now() - *relayed) < reduce_relay::IDLED)
2583 overlay_.updateSlotAndSquelch(
2584 key, val->getSignerPublic(), id_, protocol::mtVALIDATION);
2585 JLOG(p_journal_.trace()) <<
"Validation: duplicate";
2589 if (!isTrusted && (tracking_.load() == Tracking::diverged))
2591 JLOG(p_journal_.debug())
2592 <<
"Dropping untrusted validation from diverged peer";
2594 else if (isTrusted || !app_.getFeeTrack().isLoadedLocal())
2598 isTrusted ?
"Trusted validation" :
"Untrusted validation";
2603 to_string(val->getNodeID());
2610 app_.getJobQueue().addJob(
2613 [weak, val, m, key]() {
2614 if (
auto peer = weak.
lock())
2615 peer->checkValidation(val, key, m);
2620 JLOG(p_journal_.debug())
2621 <<
"Dropping untrusted validation for load";
2626 JLOG(p_journal_.warn())
2627 <<
"Exception processing validation: " << e.
what();
2628 fee_ = Resource::feeInvalidRequest;
2635 protocol::TMGetObjectByHash& packet = *m;
2637 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash " << packet.type()
2638 <<
" " << packet.objects_size();
2643 if (send_queue_.size() >= Tuning::dropSendQueue)
2645 JLOG(p_journal_.debug()) <<
"GetObject: Large send queue";
2649 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2655 if (packet.type() == protocol::TMGetObjectByHash::otTRANSACTIONS)
2657 if (!txReduceRelayEnabled())
2659 JLOG(p_journal_.error())
2660 <<
"TMGetObjectByHash: tx reduce-relay is disabled";
2661 fee_ = Resource::feeInvalidRequest;
2666 app_.getJobQueue().addJob(
2668 if (
auto peer = weak.
lock())
2669 peer->doTransactions(m);
2674 fee_ = Resource::feeMediumBurdenPeer;
2676 protocol::TMGetObjectByHash reply;
2678 reply.set_query(
false);
2680 if (packet.has_seq())
2681 reply.set_seq(packet.seq());
2683 reply.set_type(packet.type());
2685 if (packet.has_ledgerhash())
2689 fee_ = Resource::feeInvalidRequest;
2693 reply.set_ledgerhash(packet.ledgerhash());
2697 for (
int i = 0; i < packet.objects_size(); ++i)
2699 auto const& obj = packet.objects(i);
2702 uint256 const hash{obj.hash()};
2705 std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0};
2706 auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)};
2709 if (
auto shardStore = app_.getShardStore())
2711 if (seq >= shardStore->earliestLedgerSeq())
2712 nodeObject = shardStore->fetchNodeObject(hash, seq);
2717 protocol::TMIndexedObject& newObj = *reply.add_objects();
2718 newObj.set_hash(hash.begin(), hash.size());
2720 &nodeObject->getData().front(),
2721 nodeObject->getData().size());
2723 if (obj.has_nodeid())
2724 newObj.set_index(obj.nodeid());
2725 if (obj.has_ledgerseq())
2726 newObj.set_ledgerseq(obj.ledgerseq());
2733 JLOG(p_journal_.trace()) <<
"GetObj: " << reply.objects_size() <<
" of "
2734 << packet.objects_size();
2735 send(std::make_shared<Message>(reply, protocol::mtGET_OBJECTS));
2742 bool progress =
false;
2744 for (
int i = 0; i < packet.objects_size(); ++i)
2746 const protocol::TMIndexedObject& obj = packet.objects(i);
2750 if (obj.has_ledgerseq())
2752 if (obj.ledgerseq() != pLSeq)
2754 if (pLDo && (pLSeq != 0))
2756 JLOG(p_journal_.debug())
2757 <<
"GetObj: Full fetch pack for " << pLSeq;
2759 pLSeq = obj.ledgerseq();
2760 pLDo = !app_.getLedgerMaster().haveLedger(pLSeq);
2764 JLOG(p_journal_.debug())
2765 <<
"GetObj: Late fetch pack for " << pLSeq;
2774 uint256 const hash{obj.hash()};
2776 app_.getLedgerMaster().addFetchPack(
2778 std::make_shared<Blob>(
2779 obj.data().begin(), obj.data().end()));
2784 if (pLDo && (pLSeq != 0))
2786 JLOG(p_journal_.debug())
2787 <<
"GetObj: Partial fetch pack for " << pLSeq;
2789 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2790 app_.getLedgerMaster().gotFetchPack(progress, pLSeq);
2797 if (!txReduceRelayEnabled())
2799 JLOG(p_journal_.error())
2800 <<
"TMHaveTransactions: tx reduce-relay is disabled";
2801 fee_ = Resource::feeInvalidRequest;
2806 app_.getJobQueue().addJob(
2808 if (
auto peer = weak.
lock())
2809 peer->handleHaveTransactions(m);
2814 PeerImp::handleHaveTransactions(
2817 protocol::TMGetObjectByHash tmBH;
2818 tmBH.set_type(protocol::TMGetObjectByHash_ObjectType_otTRANSACTIONS);
2819 tmBH.set_query(
true);
2821 JLOG(p_journal_.trace())
2822 <<
"received TMHaveTransactions " << m->hashes_size();
2828 JLOG(p_journal_.error())
2829 <<
"TMHaveTransactions with invalid hash size";
2830 fee_ = Resource::feeInvalidRequest;
2836 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2838 JLOG(p_journal_.trace()) <<
"checking transaction " << (bool)txn;
2842 JLOG(p_journal_.debug()) <<
"adding transaction to request";
2844 auto obj = tmBH.add_objects();
2845 obj->set_hash(hash.
data(), hash.
size());
2852 removeTxQueue(hash);
2856 JLOG(p_journal_.trace())
2857 <<
"transaction request object is " << tmBH.objects_size();
2859 if (tmBH.objects_size() > 0)
2860 send(std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS));
2866 if (!txReduceRelayEnabled())
2868 JLOG(p_journal_.error())
2869 <<
"TMTransactions: tx reduce-relay is disabled";
2870 fee_ = Resource::feeInvalidRequest;
2874 JLOG(p_journal_.trace())
2875 <<
"received TMTransactions " << m->transactions_size();
2877 overlay_.addTxMetrics(m->transactions_size());
2882 m->mutable_transactions(i), [](protocol::TMTransaction*) {}),
2889 using on_message_fn =
2891 if (!strand_.running_in_this_thread())
2895 (on_message_fn)&PeerImp::onMessage, shared_from_this(), m));
2897 if (!m->has_validatorpubkey())
2899 charge(Resource::feeBadData);
2902 auto validator = m->validatorpubkey();
2906 charge(Resource::feeBadData);
2912 if (!app_.validators().listed(key))
2914 charge(Resource::feeBadData);
2915 JLOG(p_journal_.debug())
2916 <<
"onMessage: TMSquelch discarding non-validator squelch "
2922 if (key == app_.getValidationPublicKey())
2924 JLOG(p_journal_.debug())
2925 <<
"onMessage: TMSquelch discarding validator's squelch " << slice;
2930 m->has_squelchduration() ? m->squelchduration() : 0;
2932 squelch_.removeSquelch(key);
2934 charge(Resource::feeBadData);
2936 JLOG(p_journal_.debug())
2937 <<
"onMessage: TMSquelch " << slice <<
" " << id() <<
" " << duration;
2949 (void)lockedRecentLock;
2951 if (
std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
2952 recentLedgers_.end())
2955 recentLedgers_.push_back(hash);
2964 if (app_.getFeeTrack().isLoadedLocal() ||
2965 (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) ||
2966 (app_.getJobQueue().getJobCount(
jtPACK) > 10))
2968 JLOG(p_journal_.info()) <<
"Too busy to make fetch pack";
2974 JLOG(p_journal_.warn()) <<
"FetchPack hash size malformed";
2975 fee_ = Resource::feeInvalidRequest;
2979 fee_ = Resource::feeHighBurdenPeer;
2981 uint256 const hash{packet->ledgerhash()};
2984 auto elapsed = UptimeClock::now();
2985 auto const pap = &app_;
2986 app_.getJobQueue().addJob(
2987 jtPACK,
"MakeFetchPack", [pap, weak, packet, hash, elapsed]() {
2988 pap->getLedgerMaster().makeFetchPack(weak, packet, hash, elapsed);
2993 PeerImp::doTransactions(
2996 protocol::TMTransactions reply;
2998 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash requesting tx "
2999 << packet->objects_size();
3001 if (packet->objects_size() > reduce_relay::MAX_TX_QUEUE_SIZE)
3003 JLOG(p_journal_.error()) <<
"doTransactions, invalid number of hashes";
3004 fee_ = Resource::feeInvalidRequest;
3010 auto const& obj = packet->objects(i);
3014 fee_ = Resource::feeInvalidRequest;
3020 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
3024 JLOG(p_journal_.error()) <<
"doTransactions, transaction not found "
3026 fee_ = Resource::feeInvalidRequest;
3031 auto tx = reply.add_transactions();
3032 auto sttx = txn->getSTransaction();
3034 tx->set_rawtransaction(s.
data(), s.
size());
3036 txn->getStatus() ==
INCLUDED ? protocol::tsCURRENT
3038 tx->set_receivetimestamp(
3039 app_.timeKeeper().now().time_since_epoch().count());
3040 tx->set_deferred(txn->getSubmitResult().queued);
3043 if (reply.transactions_size() > 0)
3044 send(std::make_shared<Message>(reply, protocol::mtTRANSACTIONS));
3048 PeerImp::checkTransaction(
3050 bool checkSignature,
3059 app_.getLedgerMaster().getValidLedgerIndex()))
3061 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3062 charge(Resource::feeUnwantedData);
3070 app_.getHashRouter(),
3072 app_.getLedgerMaster().getValidatedRules(),
3074 valid != Validity::Valid)
3076 if (!validReason.empty())
3078 JLOG(p_journal_.trace())
3079 <<
"Exception checking transaction: " << validReason;
3083 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3084 charge(Resource::feeInvalidSignature);
3091 app_.getHashRouter(), stx->getTransactionID(), Validity::Valid);
3095 auto tx = std::make_shared<Transaction>(stx, reason, app_);
3097 if (tx->getStatus() ==
INVALID)
3099 if (!reason.
empty())
3101 JLOG(p_journal_.trace())
3102 <<
"Exception checking transaction: " << reason;
3104 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3105 charge(Resource::feeInvalidSignature);
3109 bool const trusted(flags & SF_TRUSTED);
3110 app_.getOPs().processTransaction(
3111 tx, trusted,
false, NetworkOPs::FailHard::no);
3115 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3116 charge(Resource::feeBadData);
3122 PeerImp::checkPropose(
3127 JLOG(p_journal_.trace())
3128 <<
"Checking " << (isTrusted ?
"trusted" :
"UNTRUSTED") <<
" proposal";
3134 JLOG(p_journal_.warn()) <<
"Proposal fails sig check";
3135 charge(Resource::feeInvalidSignature);
3142 relay = app_.getOPs().processTrustedProposal(peerPos);
3144 relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster();
3152 auto haveMessage = app_.overlay().relay(
3154 if (reduceRelayReady() && !haveMessage.empty())
3155 overlay_.updateSlotAndSquelch(
3158 std::move(haveMessage),
3159 protocol::mtPROPOSE_LEDGER);
3164 PeerImp::checkValidation(
3169 if (!val->isValid())
3171 JLOG(p_journal_.debug()) <<
"Validation forwarded by peer is invalid";
3172 charge(Resource::feeInvalidSignature);
3187 overlay_.relay(*packet, key, val->getSignerPublic());
3188 if (reduceRelayReady() && !haveMessage.empty())
3190 overlay_.updateSlotAndSquelch(
3192 val->getSignerPublic(),
3193 std::move(haveMessage),
3194 protocol::mtVALIDATION);
3200 JLOG(p_journal_.trace()) <<
"Exception processing validation";
3201 charge(Resource::feeInvalidRequest);
3215 if (p->hasTxSet(rootHash) && p.get() != skip)
3217 auto score = p->getScore(true);
3218 if (!ret || (score > retScore))
3243 if (p->hasLedger(ledgerHash, ledger) && p.get() != skip)
3245 auto score = p->getScore(true);
3246 if (!ret || (score > retScore))
3258 PeerImp::sendLedgerBase(
3260 protocol::TMLedgerData& ledgerData)
3262 JLOG(p_journal_.trace()) <<
"sendLedgerBase: Base data";
3265 addRaw(ledger->info(), s);
3268 auto const& stateMap{ledger->stateMap()};
3269 if (stateMap.getHash() != beast::zero)
3274 stateMap.serializeRoot(root);
3275 ledgerData.add_nodes()->set_nodedata(
3278 if (ledger->info().txHash != beast::zero)
3280 auto const& txMap{ledger->txMap()};
3281 if (txMap.getHash() != beast::zero)
3285 txMap.serializeRoot(root);
3286 ledgerData.add_nodes()->set_nodedata(
3293 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3300 JLOG(p_journal_.trace()) <<
"getLedger: Ledger";
3304 if (m->has_ledgerhash())
3307 uint256 const ledgerHash{m->ledgerhash()};
3308 ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash);
3311 if (m->has_ledgerseq())
3314 if (
auto shards = app_.getShardStore())
3316 if (m->ledgerseq() >= shards->earliestLedgerSeq())
3319 shards->fetchLedger(ledgerHash, m->ledgerseq());
3326 JLOG(p_journal_.trace())
3327 <<
"getLedger: Don't have ledger with hash " << ledgerHash;
3329 if (m->has_querytype() && !m->has_requestcookie())
3335 m->has_ledgerseq() ? m->ledgerseq() : 0,
3338 m->set_requestcookie(
id());
3339 peer->send(std::make_shared<Message>(
3340 *m, protocol::mtGET_LEDGER));
3341 JLOG(p_journal_.debug())
3342 <<
"getLedger: Request relayed to peer";
3346 JLOG(p_journal_.trace())
3347 <<
"getLedger: Failed to find peer to relay request";
3352 else if (m->has_ledgerseq())
3355 if (m->ledgerseq() < app_.getLedgerMaster().getEarliestFetch())
3357 JLOG(p_journal_.debug())
3358 <<
"getLedger: Early ledger sequence request";
3362 ledger = app_.getLedgerMaster().getLedgerBySeq(m->ledgerseq());
3365 JLOG(p_journal_.debug())
3366 <<
"getLedger: Don't have ledger with sequence "
3371 else if (m->has_ltype() && m->ltype() == protocol::ltCLOSED)
3373 ledger = app_.getLedgerMaster().getClosedLedger();
3379 auto const ledgerSeq{ledger->info().seq};
3380 if (m->has_ledgerseq())
3382 if (ledgerSeq != m->ledgerseq())
3385 if (!m->has_requestcookie())
3386 charge(Resource::feeInvalidRequest);
3389 JLOG(p_journal_.warn())
3390 <<
"getLedger: Invalid ledger sequence " << ledgerSeq;
3393 else if (ledgerSeq < app_.getLedgerMaster().getEarliestFetch())
3396 JLOG(p_journal_.debug())
3397 <<
"getLedger: Early ledger sequence request " << ledgerSeq;
3402 JLOG(p_journal_.debug()) <<
"getLedger: Unable to find ledger";
3411 JLOG(p_journal_.trace()) <<
"getTxSet: TX set";
3413 uint256 const txSetHash{m->ledgerhash()};
3415 app_.getInboundTransactions().getSet(txSetHash,
false)};
3418 if (m->has_querytype() && !m->has_requestcookie())
3423 m->set_requestcookie(
id());
3425 std::make_shared<Message>(*m, protocol::mtGET_LEDGER));
3426 JLOG(p_journal_.debug()) <<
"getTxSet: Request relayed";
3430 JLOG(p_journal_.debug())
3431 <<
"getTxSet: Failed to find relay peer";
3436 JLOG(p_journal_.debug()) <<
"getTxSet: Failed to find TX set";
3447 if (!m->has_requestcookie())
3448 charge(Resource::feeMediumBurdenPeer);
3452 SHAMap const* map{
nullptr};
3453 protocol::TMLedgerData ledgerData;
3454 bool fatLeaves{
true};
3455 auto const itype{m->itype()};
3457 if (itype == protocol::liTS_CANDIDATE)
3459 if (sharedMap = getTxSet(m); !sharedMap)
3461 map = sharedMap.
get();
3464 ledgerData.set_ledgerseq(0);
3465 ledgerData.set_ledgerhash(m->ledgerhash());
3466 ledgerData.set_type(protocol::liTS_CANDIDATE);
3467 if (m->has_requestcookie())
3468 ledgerData.set_requestcookie(m->requestcookie());
3475 if (send_queue_.size() >= Tuning::dropSendQueue)
3477 JLOG(p_journal_.debug())
3478 <<
"processLedgerRequest: Large send queue";
3481 if (app_.getFeeTrack().isLoadedLocal() && !cluster())
3483 JLOG(p_journal_.debug()) <<
"processLedgerRequest: Too busy";
3487 if (ledger = getLedger(m); !ledger)
3491 auto const ledgerHash{ledger->info().hash};
3492 ledgerData.set_ledgerhash(ledgerHash.begin(), ledgerHash.size());
3493 ledgerData.set_ledgerseq(ledger->info().seq);
3494 ledgerData.set_type(itype);
3495 if (m->has_requestcookie())
3496 ledgerData.set_requestcookie(m->requestcookie());
3500 case protocol::liBASE:
3501 sendLedgerBase(ledger, ledgerData);
3504 case protocol::liTX_NODE:
3505 map = &ledger->txMap();
3506 JLOG(p_journal_.trace()) <<
"processLedgerRequest: TX map hash "
3507 << to_string(map->getHash());
3510 case protocol::liAS_NODE:
3511 map = &ledger->stateMap();
3512 JLOG(p_journal_.trace())
3513 <<
"processLedgerRequest: Account state map hash "
3514 << to_string(map->getHash());
3519 JLOG(p_journal_.error())
3520 <<
"processLedgerRequest: Invalid ledger info type";
3527 JLOG(p_journal_.warn()) <<
"processLedgerRequest: Unable to find map";
3532 if (m->nodeids_size() > 0)
3534 auto const queryDepth{
3535 m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)};
3539 for (
int i = 0; i < m->nodeids_size() &&
3540 ledgerData.nodes_size() < Tuning::softMaxReplyNodes;
3546 data.reserve(Tuning::softMaxReplyNodes);
3550 if (map->getNodeFat(*shaMapNodeId, data, fatLeaves, queryDepth))
3552 JLOG(p_journal_.trace())
3553 <<
"processLedgerRequest: getNodeFat got "
3554 << data.size() <<
" nodes";
3556 for (
auto const& d : data)
3558 protocol::TMLedgerNode* node{ledgerData.add_nodes()};
3559 node->set_nodeid(d.first.getRawString());
3560 node->set_nodedata(d.second.data(), d.second.size());
3565 JLOG(p_journal_.warn())
3566 <<
"processLedgerRequest: getNodeFat returns false";
3574 case protocol::liBASE:
3576 info =
"Ledger base";
3579 case protocol::liTX_NODE:
3583 case protocol::liAS_NODE:
3587 case protocol::liTS_CANDIDATE:
3588 info =
"TS candidate";
3596 if (!m->has_ledgerhash())
3597 info +=
", no hash specified";
3599 JLOG(p_journal_.error())
3600 <<
"processLedgerRequest: getNodeFat with nodeId "
3601 << *shaMapNodeId <<
" and ledger info type " << info
3602 <<
" throws exception: " << e.
what();
3606 JLOG(p_journal_.info())
3607 <<
"processLedgerRequest: Got request for " << m->nodeids_size()
3608 <<
" nodes at depth " << queryDepth <<
", return "
3609 << ledgerData.nodes_size() <<
" nodes";
3612 send(std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA));
3616 PeerImp::getScore(
bool haveItem)
const
3620 static const int spRandomMax = 9999;
3624 static const int spHaveItem = 10000;
3629 static const int spLatency = 30;
3632 static const int spNoLatency = 8000;
3637 score += spHaveItem;
3646 score -= latency->count() * spLatency;
3648 score -= spNoLatency;
3654 PeerImp::isHighLatency()
const
3657 return latency_ >= peerHighLatency;
3661 PeerImp::reduceRelayReady()
3663 if (!reduceRelayReady_)
3665 reduce_relay::epoch<std::chrono::minutes>(UptimeClock::now()) >
3666 reduce_relay::WAIT_ON_BOOTUP;
3667 return vpReduceRelayEnabled_ && reduceRelayReady_;
3673 using namespace std::chrono_literals;
3676 totalBytes_ += bytes;
3677 accumBytes_ += bytes;
3678 auto const timeElapsed = clock_type::now() - intervalStart_;
3679 auto const timeElapsedInSecs =
3680 std::chrono::duration_cast<std::chrono::seconds>(timeElapsed);
3682 if (timeElapsedInSecs >= 1s)
3684 auto const avgBytes = accumBytes_ / timeElapsedInSecs.count();
3685 rollingAvg_.push_back(avgBytes);
3687 auto const totalBytes =
3689 rollingAvgBytes_ = totalBytes / rollingAvg_.size();
3691 intervalStart_ = clock_type::now();
3697 PeerImp::Metrics::average_bytes()
const
3700 return rollingAvgBytes_;
3704 PeerImp::Metrics::total_bytes()
const