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)
1485 if (m->endpoints_v2().size() >= 1024)
1492 endpoints.
reserve(m->endpoints_v2().size());
1494 for (
auto const& tm : m->endpoints_v2())
1501 << tm.endpoint() <<
"}";
1518 if (!endpoints.
empty())
1541 <<
"Need network ledger";
1549 auto stx = std::make_shared<STTx const>(sit);
1550 uint256 txID = stx->getTransactionID();
1574 bool checkSignature =
true;
1577 if (!m->has_deferred() || !m->deferred())
1581 flags |= SF_TRUSTED;
1588 checkSignature =
false;
1601 <<
"No new transactions until synchronized";
1607 "recvTransaction->checkTransaction",
1612 if (
auto peer = weak.lock())
1613 peer->checkTransaction(flags, checkSignature, stx);
1620 <<
"Transaction invalid: " <<
strHex(m->rawtransaction());
1631 auto const itype{m->itype()};
1634 if (itype < protocol::liBASE || itype > protocol::liTS_CANDIDATE)
1635 return badData(
"Invalid ledger info type");
1640 return std::nullopt;
1643 if (itype == protocol::liTS_CANDIDATE)
1645 if (!m->has_ledgerhash())
1646 return badData(
"Invalid TX candidate set, missing TX set hash");
1649 !m->has_ledgerhash() && !m->has_ledgerseq() &&
1650 !(ltype && *ltype == protocol::ltCLOSED))
1652 return badData(
"Invalid request");
1656 if (ltype && (*ltype < protocol::ltACCEPTED || *ltype > protocol::ltCLOSED))
1657 return badData(
"Invalid ledger type");
1661 return badData(
"Invalid ledger hash");
1664 if (m->has_ledgerseq())
1666 auto const ledgerSeq{m->ledgerseq()};
1676 using namespace std::chrono_literals;
1686 if (itype != protocol::liBASE)
1688 if (m->nodeids_size() <= 0)
1689 return badData(
"Invalid ledger node IDs");
1691 for (
auto const& nodeId : m->nodeids())
1694 return badData(
"Invalid SHAMap node ID");
1699 if (m->has_querytype() && m->querytype() != protocol::qtINDIRECT)
1700 return badData(
"Invalid query type");
1703 if (m->has_querydepth())
1706 itype == protocol::liBASE)
1708 return badData(
"Invalid query depth");
1715 if (
auto peer = weak.
lock())
1716 peer->processLedgerRequest(m);
1734 if (
auto peer = weak.
lock())
1737 peer->ledgerReplayMsgHandler_.processProofPathRequest(m);
1738 if (reply.has_error())
1740 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1741 peer->charge(Resource::feeInvalidRequest);
1743 peer->charge(Resource::feeRequestNoReply);
1747 peer->send(std::make_shared<Message>(
1748 reply, protocol::mtPROOF_PATH_RESPONSE));
1783 if (
auto peer = weak.
lock())
1786 peer->ledgerReplayMsgHandler_.processReplayDeltaRequest(m);
1787 if (reply.has_error())
1789 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1790 peer->charge(Resource::feeInvalidRequest);
1792 peer->charge(Resource::feeRequestNoReply);
1796 peer->send(std::make_shared<Message>(
1797 reply, protocol::mtREPLAY_DELTA_RESPONSE));
1828 return badData(
"Invalid ledger hash");
1832 auto const ledgerSeq{m->ledgerseq()};
1833 if (m->type() == protocol::liTS_CANDIDATE)
1852 using namespace std::chrono_literals;
1863 if (m->type() < protocol::liBASE || m->type() > protocol::liTS_CANDIDATE)
1864 return badData(
"Invalid ledger info type");
1867 if (m->has_error() &&
1868 (m->error() < protocol::reNO_LEDGER ||
1869 m->error() > protocol::reBAD_REQUEST))
1871 return badData(
"Invalid reply error");
1878 "Invalid Ledger/TXset nodes " +
std::to_string(m->nodes_size()));
1882 if (m->has_requestcookie())
1886 m->clear_requestcookie();
1887 peer->send(std::make_shared<Message>(*m, protocol::mtLEDGER_DATA));
1891 JLOG(
p_journal_.
info()) <<
"Unable to route TX/ledger data reply";
1896 uint256 const ledgerHash{m->ledgerhash()};
1899 if (m->type() == protocol::liTS_CANDIDATE)
1904 if (
auto peer = weak.lock())
1906 peer->app_.getInboundTransactions().gotData(
1907 ledgerHash, peer, m);
1920 protocol::TMProposeSet&
set = *m;
1926 if ((std::clamp<std::size_t>(sig.size(), 64, 72) != sig.size()) ||
1954 uint256 const proposeHash{
set.currenttxhash()};
1955 uint256 const prevLedger{
set.previousledger()};
1967 if (
auto [added, relayed] =
1976 suppression, publicKey,
id_, protocol::mtPROPOSE_LEDGER);
1986 <<
"Proposal: Dropping untrusted (peer divergence)";
1998 <<
"Proposal: " << (isTrusted ?
"trusted" :
"untrusted");
2015 "recvPropose->checkPropose",
2017 if (
auto peer = weak.lock())
2018 peer->checkPropose(job, m,
proposal);
2027 if (!m->has_networktime())
2032 if (!
last_status_.has_newstatus() || m->has_newstatus())
2037 protocol::NodeStatus status =
last_status_.newstatus();
2039 m->set_newstatus(status);
2043 if (m->newevent() == protocol::neLOST_SYNC)
2045 bool outOfSync{
false};
2066 bool const peerChangedLedgers{
2073 if (peerChangedLedgers)
2084 if (m->has_ledgerhashprevious() &&
2095 if (peerChangedLedgers)
2105 if (m->has_firstseq() && m->has_lastseq())
2116 if (m->has_ledgerseq() &&
2126 if (m->has_newstatus())
2128 switch (m->newstatus())
2130 case protocol::nsCONNECTING:
2131 j[jss::status] =
"CONNECTING";
2133 case protocol::nsCONNECTED:
2134 j[jss::status] =
"CONNECTED";
2136 case protocol::nsMONITORING:
2137 j[jss::status] =
"MONITORING";
2139 case protocol::nsVALIDATING:
2140 j[jss::status] =
"VALIDATING";
2142 case protocol::nsSHUTTING:
2143 j[jss::status] =
"SHUTTING";
2148 if (m->has_newevent())
2150 switch (m->newevent())
2152 case protocol::neCLOSING_LEDGER:
2153 j[jss::action] =
"CLOSING_LEDGER";
2155 case protocol::neACCEPTED_LEDGER:
2156 j[jss::action] =
"ACCEPTED_LEDGER";
2158 case protocol::neSWITCHED_LEDGER:
2159 j[jss::action] =
"SWITCHED_LEDGER";
2161 case protocol::neLOST_SYNC:
2162 j[jss::action] =
"LOST_SYNC";
2167 if (m->has_ledgerseq())
2169 j[jss::ledger_index] = m->ledgerseq();
2172 if (m->has_ledgerhash())
2174 uint256 closedLedgerHash{};
2176 std::lock_guard sl(recentLock_);
2177 closedLedgerHash = closedLedgerHash_;
2179 j[jss::ledger_hash] =
to_string(closedLedgerHash);
2182 if (m->has_networktime())
2184 j[jss::date] = Json::UInt(m->networktime());
2187 if (m->has_firstseq() && m->has_lastseq())
2189 j[jss::ledger_index_min] = Json::UInt(m->firstseq());
2190 j[jss::ledger_index_max] = Json::UInt(m->lastseq());
2206 serverSeq = maxLedger_;
2212 checkTracking(serverSeq, validationSeq);
2221 if (diff < Tuning::convergedLedgerLimit)
2224 tracking_ = Tracking::converged;
2227 if ((diff > Tuning::divergedLedgerLimit) &&
2228 (tracking_.load() != Tracking::diverged))
2233 tracking_ = Tracking::diverged;
2234 trackingTime_ = clock_type::now();
2243 fee_ = Resource::feeInvalidRequest;
2247 uint256 const hash{m->hash()};
2249 if (m->status() == protocol::tsHAVE)
2253 if (
std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
2254 recentTxSets_.end())
2256 fee_ = Resource::feeUnwantedData;
2260 recentTxSets_.push_back(hash);
2265 PeerImp::onValidatorListMessage(
2275 JLOG(p_journal_.warn()) <<
"Ignored malformed " << messageType
2276 <<
" from peer " << remote_address_;
2278 fee_ = Resource::feeHighBurdenPeer;
2284 JLOG(p_journal_.debug())
2285 <<
"Received " << messageType <<
" from " << remote_address_.to_string()
2286 <<
" (" << id_ <<
")";
2288 if (!app_.getHashRouter().addSuppressionPeer(hash, id_))
2290 JLOG(p_journal_.debug())
2291 << messageType <<
": received duplicate " << messageType;
2295 fee_ = Resource::feeUnwantedData;
2299 auto const applyResult = app_.validators().applyListsAndBroadcast(
2303 remote_address_.to_string(),
2306 app_.getHashRouter(),
2309 JLOG(p_journal_.debug())
2310 <<
"Processed " << messageType <<
" version " << version <<
" from "
2311 << (applyResult.publisherKey ?
strHex(*applyResult.publisherKey)
2312 :
"unknown or invalid publisher")
2313 <<
" from " << remote_address_.to_string() <<
" (" << id_
2314 <<
") with best result " << to_string(applyResult.bestDisposition());
2317 switch (applyResult.bestDisposition())
2320 case ListDisposition::accepted:
2322 case ListDisposition::expired:
2324 case ListDisposition::pending: {
2327 assert(applyResult.publisherKey);
2328 auto const& pubKey = *applyResult.publisherKey;
2330 if (
auto const iter = publisherListSequences_.find(pubKey);
2331 iter != publisherListSequences_.end())
2333 assert(iter->second < applyResult.sequence);
2336 publisherListSequences_[pubKey] = applyResult.sequence;
2339 case ListDisposition::same_sequence:
2340 case ListDisposition::known_sequence:
2344 assert(applyResult.sequence && applyResult.publisherKey);
2346 publisherListSequences_[*applyResult.publisherKey] <=
2347 applyResult.sequence);
2352 case ListDisposition::stale:
2353 case ListDisposition::untrusted:
2354 case ListDisposition::invalid:
2355 case ListDisposition::unsupported_version:
2362 switch (applyResult.worstDisposition())
2364 case ListDisposition::accepted:
2365 case ListDisposition::expired:
2366 case ListDisposition::pending:
2369 case ListDisposition::same_sequence:
2370 case ListDisposition::known_sequence:
2374 fee_ = Resource::feeUnwantedData;
2376 case ListDisposition::stale:
2379 fee_ = Resource::feeBadData;
2381 case ListDisposition::untrusted:
2385 fee_ = Resource::feeUnwantedData;
2387 case ListDisposition::invalid:
2389 fee_ = Resource::feeInvalidSignature;
2391 case ListDisposition::unsupported_version:
2394 fee_ = Resource::feeBadData;
2401 for (
auto const& [disp, count] : applyResult.dispositions)
2406 case ListDisposition::accepted:
2407 JLOG(p_journal_.debug())
2408 <<
"Applied " << count <<
" new " << messageType
2409 <<
"(s) from peer " << remote_address_;
2412 case ListDisposition::expired:
2413 JLOG(p_journal_.debug())
2414 <<
"Applied " << count <<
" expired " << messageType
2415 <<
"(s) from peer " << remote_address_;
2418 case ListDisposition::pending:
2419 JLOG(p_journal_.debug())
2420 <<
"Processed " << count <<
" future " << messageType
2421 <<
"(s) from peer " << remote_address_;
2423 case ListDisposition::same_sequence:
2424 JLOG(p_journal_.warn())
2425 <<
"Ignored " << count <<
" " << messageType
2426 <<
"(s) with current sequence from peer "
2429 case ListDisposition::known_sequence:
2430 JLOG(p_journal_.warn())
2431 <<
"Ignored " << count <<
" " << messageType
2432 <<
"(s) with future sequence from peer " << remote_address_;
2434 case ListDisposition::stale:
2435 JLOG(p_journal_.warn())
2436 <<
"Ignored " << count <<
"stale " << messageType
2437 <<
"(s) from peer " << remote_address_;
2439 case ListDisposition::untrusted:
2440 JLOG(p_journal_.warn())
2441 <<
"Ignored " << count <<
" untrusted " << messageType
2442 <<
"(s) from peer " << remote_address_;
2444 case ListDisposition::unsupported_version:
2445 JLOG(p_journal_.warn())
2446 <<
"Ignored " << count <<
"unsupported version "
2447 << messageType <<
"(s) from peer " << remote_address_;
2449 case ListDisposition::invalid:
2450 JLOG(p_journal_.warn())
2451 <<
"Ignored " << count <<
"invalid " << messageType
2452 <<
"(s) from peer " << remote_address_;
2465 if (!supportsFeature(ProtocolFeature::ValidatorListPropagation))
2467 JLOG(p_journal_.debug())
2468 <<
"ValidatorList: received validator list from peer using "
2469 <<
"protocol version " << to_string(protocol_)
2470 <<
" which shouldn't support this feature.";
2471 fee_ = Resource::feeUnwantedData;
2474 onValidatorListMessage(
2478 ValidatorList::parseBlobs(*m));
2482 JLOG(p_journal_.warn()) <<
"ValidatorList: Exception, " << e.
what()
2483 <<
" from peer " << remote_address_;
2484 fee_ = Resource::feeBadData;
2494 if (!supportsFeature(ProtocolFeature::ValidatorList2Propagation))
2496 JLOG(p_journal_.debug())
2497 <<
"ValidatorListCollection: received validator list from peer "
2498 <<
"using protocol version " << to_string(protocol_)
2499 <<
" which shouldn't support this feature.";
2500 fee_ = Resource::feeUnwantedData;
2503 else if (m->version() < 2)
2505 JLOG(p_journal_.debug())
2506 <<
"ValidatorListCollection: received invalid validator list "
2508 << m->version() <<
" from peer using protocol version "
2509 << to_string(protocol_);
2510 fee_ = Resource::feeBadData;
2513 onValidatorListMessage(
2514 "ValidatorListCollection",
2517 ValidatorList::parseBlobs(*m));
2521 JLOG(p_journal_.warn()) <<
"ValidatorListCollection: Exception, "
2522 << e.
what() <<
" from peer " << remote_address_;
2523 fee_ = Resource::feeBadData;
2530 if (m->validation().size() < 50)
2532 JLOG(p_journal_.warn()) <<
"Validation: Too small";
2533 fee_ = Resource::feeInvalidRequest;
2539 auto const closeTime = app_.timeKeeper().closeTime();
2544 val = std::make_shared<STValidation>(
2548 app_.validatorManifests().getMasterKey(pk));
2551 val->setSeen(closeTime);
2555 app_.getValidations().parms(),
2556 app_.timeKeeper().closeTime(),
2558 val->getSeenTime()))
2560 JLOG(p_journal_.trace()) <<
"Validation: Not current";
2561 fee_ = Resource::feeUnwantedData;
2568 auto const isTrusted =
2569 app_.validators().trusted(val->getSignerPublic());
2574 if (!isTrusted && app_.config().RELAY_UNTRUSTED_VALIDATIONS == -1)
2578 if (
auto [added, relayed] =
2579 app_.getHashRouter().addSuppressionPeerWithStatus(key, id_);
2586 if (reduceRelayReady() && relayed &&
2587 (
stopwatch().now() - *relayed) < reduce_relay::IDLED)
2588 overlay_.updateSlotAndSquelch(
2589 key, val->getSignerPublic(), id_, protocol::mtVALIDATION);
2590 JLOG(p_journal_.trace()) <<
"Validation: duplicate";
2594 if (!isTrusted && (tracking_.load() == Tracking::diverged))
2596 JLOG(p_journal_.debug())
2597 <<
"Validation: dropping untrusted from diverged peer";
2599 if (isTrusted || cluster() || !app_.getFeeTrack().isLoadedLocal())
2602 app_.getJobQueue().addJob(
2604 "recvValidation->checkValidation",
2605 [weak, val, m](
Job&) {
2606 if (
auto peer = weak.
lock())
2607 peer->checkValidation(val, m);
2612 JLOG(p_journal_.debug()) <<
"Validation: Dropping UNTRUSTED (load)";
2617 JLOG(p_journal_.warn())
2618 <<
"Exception processing validation: " << e.
what();
2619 fee_ = Resource::feeInvalidRequest;
2626 protocol::TMGetObjectByHash& packet = *m;
2628 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash " << packet.type()
2629 <<
" " << packet.objects_size();
2634 if (send_queue_.size() >= Tuning::dropSendQueue)
2636 JLOG(p_journal_.debug()) <<
"GetObject: Large send queue";
2640 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2646 if (packet.type() == protocol::TMGetObjectByHash::otTRANSACTIONS)
2648 if (!txReduceRelayEnabled())
2650 JLOG(p_journal_.error())
2651 <<
"TMGetObjectByHash: tx reduce-relay is disabled";
2652 fee_ = Resource::feeInvalidRequest;
2657 app_.getJobQueue().addJob(
2659 if (
auto peer = weak.
lock())
2660 peer->doTransactions(m);
2665 fee_ = Resource::feeMediumBurdenPeer;
2667 protocol::TMGetObjectByHash reply;
2669 reply.set_query(
false);
2671 if (packet.has_seq())
2672 reply.set_seq(packet.seq());
2674 reply.set_type(packet.type());
2676 if (packet.has_ledgerhash())
2680 fee_ = Resource::feeInvalidRequest;
2684 reply.set_ledgerhash(packet.ledgerhash());
2688 for (
int i = 0; i < packet.objects_size(); ++i)
2690 auto const& obj = packet.objects(i);
2693 uint256 const hash{obj.hash()};
2696 std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0};
2697 auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)};
2700 if (
auto shardStore = app_.getShardStore())
2702 if (seq >= shardStore->earliestLedgerSeq())
2703 nodeObject = shardStore->fetchNodeObject(hash, seq);
2708 protocol::TMIndexedObject& newObj = *reply.add_objects();
2709 newObj.set_hash(hash.begin(), hash.size());
2711 &nodeObject->getData().front(),
2712 nodeObject->getData().size());
2714 if (obj.has_nodeid())
2715 newObj.set_index(obj.nodeid());
2716 if (obj.has_ledgerseq())
2717 newObj.set_ledgerseq(obj.ledgerseq());
2724 JLOG(p_journal_.trace()) <<
"GetObj: " << reply.objects_size() <<
" of "
2725 << packet.objects_size();
2726 send(std::make_shared<Message>(reply, protocol::mtGET_OBJECTS));
2733 bool progress =
false;
2735 for (
int i = 0; i < packet.objects_size(); ++i)
2737 const protocol::TMIndexedObject& obj = packet.objects(i);
2741 if (obj.has_ledgerseq())
2743 if (obj.ledgerseq() != pLSeq)
2745 if (pLDo && (pLSeq != 0))
2747 JLOG(p_journal_.debug())
2748 <<
"GetObj: Full fetch pack for " << pLSeq;
2750 pLSeq = obj.ledgerseq();
2751 pLDo = !app_.getLedgerMaster().haveLedger(pLSeq);
2755 JLOG(p_journal_.debug())
2756 <<
"GetObj: Late fetch pack for " << pLSeq;
2765 uint256 const hash{obj.hash()};
2767 app_.getLedgerMaster().addFetchPack(
2769 std::make_shared<Blob>(
2770 obj.data().begin(), obj.data().end()));
2775 if (pLDo && (pLSeq != 0))
2777 JLOG(p_journal_.debug())
2778 <<
"GetObj: Partial fetch pack for " << pLSeq;
2780 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2781 app_.getLedgerMaster().gotFetchPack(progress, pLSeq);
2788 if (!txReduceRelayEnabled())
2790 JLOG(p_journal_.error())
2791 <<
"TMHaveTransactions: tx reduce-relay is disabled";
2792 fee_ = Resource::feeInvalidRequest;
2797 app_.getJobQueue().addJob(
2799 if (
auto peer = weak.
lock())
2800 peer->handleHaveTransactions(m);
2805 PeerImp::handleHaveTransactions(
2808 protocol::TMGetObjectByHash tmBH;
2809 tmBH.set_type(protocol::TMGetObjectByHash_ObjectType_otTRANSACTIONS);
2810 tmBH.set_query(
true);
2812 JLOG(p_journal_.trace())
2813 <<
"received TMHaveTransactions " << m->hashes_size();
2819 JLOG(p_journal_.error())
2820 <<
"TMHaveTransactions with invalid hash size";
2821 fee_ = Resource::feeInvalidRequest;
2827 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2829 JLOG(p_journal_.trace()) <<
"checking transaction " << (bool)txn;
2833 JLOG(p_journal_.debug()) <<
"adding transaction to request";
2835 auto obj = tmBH.add_objects();
2836 obj->set_hash(hash.
data(), hash.
size());
2843 removeTxQueue(hash);
2847 JLOG(p_journal_.trace())
2848 <<
"transaction request object is " << tmBH.objects_size();
2850 if (tmBH.objects_size() > 0)
2851 send(std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS));
2857 if (!txReduceRelayEnabled())
2859 JLOG(p_journal_.error())
2860 <<
"TMTransactions: tx reduce-relay is disabled";
2861 fee_ = Resource::feeInvalidRequest;
2865 JLOG(p_journal_.trace())
2866 <<
"received TMTransactions " << m->transactions_size();
2868 overlay_.addTxMetrics(m->transactions_size());
2873 m->mutable_transactions(i), [](protocol::TMTransaction*) {}),
2880 using on_message_fn =
2882 if (!strand_.running_in_this_thread())
2886 (on_message_fn)&PeerImp::onMessage, shared_from_this(), m));
2888 if (!m->has_validatorpubkey())
2890 charge(Resource::feeBadData);
2893 auto validator = m->validatorpubkey();
2897 charge(Resource::feeBadData);
2903 if (!app_.validators().listed(key))
2905 charge(Resource::feeBadData);
2906 JLOG(p_journal_.debug())
2907 <<
"onMessage: TMSquelch discarding non-validator squelch "
2913 if (key == app_.getValidationPublicKey())
2915 JLOG(p_journal_.debug())
2916 <<
"onMessage: TMSquelch discarding validator's squelch " << slice;
2921 m->has_squelchduration() ? m->squelchduration() : 0;
2923 squelch_.removeSquelch(key);
2925 charge(Resource::feeBadData);
2927 JLOG(p_journal_.debug())
2928 <<
"onMessage: TMSquelch " << slice <<
" " << id() <<
" " << duration;
2940 (void)lockedRecentLock;
2942 if (
std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
2943 recentLedgers_.end())
2946 recentLedgers_.push_back(hash);
2955 if (app_.getFeeTrack().isLoadedLocal() ||
2956 (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) ||
2957 (app_.getJobQueue().getJobCount(
jtPACK) > 10))
2959 JLOG(p_journal_.info()) <<
"Too busy to make fetch pack";
2965 JLOG(p_journal_.warn()) <<
"FetchPack hash size malformed";
2966 fee_ = Resource::feeInvalidRequest;
2970 fee_ = Resource::feeHighBurdenPeer;
2972 uint256 const hash{packet->ledgerhash()};
2975 auto elapsed = UptimeClock::now();
2976 auto const pap = &app_;
2977 app_.getJobQueue().addJob(
2978 jtPACK,
"MakeFetchPack", [pap, weak, packet, hash, elapsed](
Job&) {
2979 pap->getLedgerMaster().makeFetchPack(weak, packet, hash, elapsed);
2984 PeerImp::doTransactions(
2987 protocol::TMTransactions reply;
2989 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash requesting tx "
2990 << packet->objects_size();
2992 if (packet->objects_size() > reduce_relay::MAX_TX_QUEUE_SIZE)
2994 JLOG(p_journal_.error()) <<
"doTransactions, invalid number of hashes";
2995 fee_ = Resource::feeInvalidRequest;
3001 auto const& obj = packet->objects(i);
3005 fee_ = Resource::feeInvalidRequest;
3011 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
3015 JLOG(p_journal_.error()) <<
"doTransactions, transaction not found "
3017 fee_ = Resource::feeInvalidRequest;
3022 auto tx = reply.add_transactions();
3023 auto sttx = txn->getSTransaction();
3025 tx->set_rawtransaction(s.
data(), s.
size());
3027 txn->getStatus() ==
INCLUDED ? protocol::tsCURRENT
3029 tx->set_receivetimestamp(
3030 app_.timeKeeper().now().time_since_epoch().count());
3031 tx->set_deferred(txn->getSubmitResult().queued);
3034 if (reply.transactions_size() > 0)
3035 send(std::make_shared<Message>(reply, protocol::mtTRANSACTIONS));
3039 PeerImp::checkTransaction(
3041 bool checkSignature,
3050 app_.getLedgerMaster().getValidLedgerIndex()))
3052 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3053 charge(Resource::feeUnwantedData);
3061 app_.getHashRouter(),
3063 app_.getLedgerMaster().getValidatedRules(),
3065 valid != Validity::Valid)
3067 if (!validReason.empty())
3069 JLOG(p_journal_.trace())
3070 <<
"Exception checking transaction: " << validReason;
3074 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3075 charge(Resource::feeInvalidSignature);
3082 app_.getHashRouter(), stx->getTransactionID(), Validity::Valid);
3086 auto tx = std::make_shared<Transaction>(stx, reason, app_);
3088 if (tx->getStatus() ==
INVALID)
3090 if (!reason.
empty())
3092 JLOG(p_journal_.trace())
3093 <<
"Exception checking transaction: " << reason;
3095 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3096 charge(Resource::feeInvalidSignature);
3100 bool const trusted(flags & SF_TRUSTED);
3101 app_.getOPs().processTransaction(
3102 tx, trusted,
false, NetworkOPs::FailHard::no);
3106 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3107 charge(Resource::feeBadData);
3113 PeerImp::checkPropose(
3120 JLOG(p_journal_.trace())
3121 <<
"Checking " << (isTrusted ?
"trusted" :
"UNTRUSTED") <<
" proposal";
3127 JLOG(p_journal_.warn()) <<
"Proposal fails sig check";
3128 charge(Resource::feeInvalidSignature);
3135 relay = app_.getOPs().processTrustedProposal(peerPos);
3137 relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster();
3145 auto haveMessage = app_.overlay().relay(
3147 if (reduceRelayReady() && !haveMessage.empty())
3148 overlay_.updateSlotAndSquelch(
3151 std::move(haveMessage),
3152 protocol::mtPROPOSE_LEDGER);
3157 PeerImp::checkValidation(
3161 if (!cluster() && !val->isValid())
3163 JLOG(p_journal_.debug()) <<
"Validation forwarded by peer is invalid";
3164 charge(Resource::feeInvalidRequest);
3174 auto const suppression =
3181 overlay_.relay(*packet, suppression, val->getSignerPublic());
3182 if (reduceRelayReady() && !haveMessage.empty())
3184 overlay_.updateSlotAndSquelch(
3186 val->getSignerPublic(),
3187 std::move(haveMessage),
3188 protocol::mtVALIDATION);
3194 JLOG(p_journal_.trace()) <<
"Exception processing validation";
3195 charge(Resource::feeInvalidRequest);
3209 if (p->hasTxSet(rootHash) && p.get() != skip)
3211 auto score = p->getScore(true);
3212 if (!ret || (score > retScore))
3237 if (p->hasLedger(ledgerHash, ledger) && p.get() != skip)
3239 auto score = p->getScore(true);
3240 if (!ret || (score > retScore))
3252 PeerImp::sendLedgerBase(
3254 protocol::TMLedgerData& ledgerData)
3256 JLOG(p_journal_.trace()) <<
"sendLedgerBase: Base data";
3259 addRaw(ledger->info(), s);
3262 auto const& stateMap{ledger->stateMap()};
3263 if (stateMap.getHash() != beast::zero)
3268 stateMap.serializeRoot(root);
3269 ledgerData.add_nodes()->set_nodedata(
3272 if (ledger->info().txHash != beast::zero)
3274 auto const& txMap{ledger->txMap()};
3275 if (txMap.getHash() != beast::zero)
3279 txMap.serializeRoot(root);
3280 ledgerData.add_nodes()->set_nodedata(
3287 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3294 JLOG(p_journal_.trace()) <<
"getLedger: Ledger";
3298 if (m->has_ledgerhash())
3301 uint256 const ledgerHash{m->ledgerhash()};
3302 ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash);
3305 if (m->has_ledgerseq())
3308 if (
auto shards = app_.getShardStore())
3310 if (m->ledgerseq() >= shards->earliestLedgerSeq())
3313 shards->fetchLedger(ledgerHash, m->ledgerseq());
3320 JLOG(p_journal_.trace())
3321 <<
"getLedger: Don't have ledger with hash " << ledgerHash;
3323 if (m->has_querytype() && !m->has_requestcookie())
3329 m->has_ledgerseq() ? m->ledgerseq() : 0,
3332 m->set_requestcookie(
id());
3333 peer->send(std::make_shared<Message>(
3334 *m, protocol::mtGET_LEDGER));
3335 JLOG(p_journal_.debug())
3336 <<
"getLedger: Request relayed to peer";
3340 JLOG(p_journal_.trace())
3341 <<
"getLedger: Failed to find peer to relay request";
3346 else if (m->has_ledgerseq())
3349 if (m->ledgerseq() < app_.getLedgerMaster().getEarliestFetch())
3351 JLOG(p_journal_.debug())
3352 <<
"getLedger: Early ledger sequence request";
3356 ledger = app_.getLedgerMaster().getLedgerBySeq(m->ledgerseq());
3359 JLOG(p_journal_.debug())
3360 <<
"getLedger: Don't have ledger with sequence "
3365 else if (m->has_ltype() && m->ltype() == protocol::ltCLOSED)
3367 ledger = app_.getLedgerMaster().getClosedLedger();
3373 auto const ledgerSeq{ledger->info().seq};
3374 if (m->has_ledgerseq())
3376 if (ledgerSeq != m->ledgerseq())
3379 if (!m->has_requestcookie())
3380 charge(Resource::feeInvalidRequest);
3383 JLOG(p_journal_.warn())
3384 <<
"getLedger: Invalid ledger sequence " << ledgerSeq;
3387 else if (ledgerSeq < app_.getLedgerMaster().getEarliestFetch())
3390 JLOG(p_journal_.debug())
3391 <<
"getLedger: Early ledger sequence request " << ledgerSeq;
3396 JLOG(p_journal_.warn()) <<
"getLedger: Unable to find ledger";
3405 JLOG(p_journal_.trace()) <<
"getTxSet: TX set";
3407 uint256 const txSetHash{m->ledgerhash()};
3409 app_.getInboundTransactions().getSet(txSetHash,
false)};
3412 if (m->has_querytype() && !m->has_requestcookie())
3417 m->set_requestcookie(
id());
3419 std::make_shared<Message>(*m, protocol::mtGET_LEDGER));
3420 JLOG(p_journal_.debug()) <<
"getTxSet: Request relayed";
3424 JLOG(p_journal_.debug())
3425 <<
"getTxSet: Failed to find relay peer";
3430 JLOG(p_journal_.debug()) <<
"getTxSet: Failed to find TX set";
3441 if (!m->has_requestcookie())
3442 charge(Resource::feeMediumBurdenPeer);
3446 SHAMap const* map{
nullptr};
3447 protocol::TMLedgerData ledgerData;
3448 bool fatLeaves{
true};
3449 auto const itype{m->itype()};
3451 if (itype == protocol::liTS_CANDIDATE)
3453 if (sharedMap = getTxSet(m); !sharedMap)
3455 map = sharedMap.
get();
3458 ledgerData.set_ledgerseq(0);
3459 ledgerData.set_ledgerhash(m->ledgerhash());
3460 ledgerData.set_type(protocol::liTS_CANDIDATE);
3461 if (m->has_requestcookie())
3462 ledgerData.set_requestcookie(m->requestcookie());
3469 if (send_queue_.size() >= Tuning::dropSendQueue)
3471 JLOG(p_journal_.debug())
3472 <<
"processLedgerRequest: Large send queue";
3475 if (app_.getFeeTrack().isLoadedLocal() && !cluster())
3477 JLOG(p_journal_.debug()) <<
"processLedgerRequest: Too busy";
3481 if (ledger = getLedger(m); !ledger)
3485 auto const ledgerHash{ledger->info().hash};
3486 ledgerData.set_ledgerhash(ledgerHash.begin(), ledgerHash.size());
3487 ledgerData.set_ledgerseq(ledger->info().seq);
3488 ledgerData.set_type(itype);
3489 if (m->has_requestcookie())
3490 ledgerData.set_requestcookie(m->requestcookie());
3494 case protocol::liBASE:
3495 sendLedgerBase(ledger, ledgerData);
3498 case protocol::liTX_NODE:
3499 map = &ledger->txMap();
3500 JLOG(p_journal_.trace()) <<
"processLedgerRequest: TX map hash "
3501 << to_string(map->getHash());
3504 case protocol::liAS_NODE:
3505 map = &ledger->stateMap();
3506 JLOG(p_journal_.trace())
3507 <<
"processLedgerRequest: Account state map hash "
3508 << to_string(map->getHash());
3513 JLOG(p_journal_.error())
3514 <<
"processLedgerRequest: Invalid ledger info type";
3521 JLOG(p_journal_.warn()) <<
"processLedgerRequest: Unable to find map";
3526 if (m->nodeids_size() > 0)
3528 auto const queryDepth{
3529 m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)};
3533 for (
int i = 0; i < m->nodeids_size() &&
3534 ledgerData.nodes_size() < Tuning::softMaxReplyNodes;
3543 if (map->getNodeFat(
3550 assert(nodeIds.
size() == rawNodes.
size());
3551 JLOG(p_journal_.trace())
3552 <<
"processLedgerRequest: getNodeFat got "
3553 << rawNodes.
size() <<
" nodes";
3555 auto rawNodeIter{rawNodes.
begin()};
3556 for (
auto const& nodeId : nodeIds)
3558 protocol::TMLedgerNode* node{ledgerData.add_nodes()};
3559 node->set_nodeid(nodeId.getRawString());
3561 &rawNodeIter->front(), rawNodeIter->size());
3567 JLOG(p_journal_.warn())
3568 <<
"processLedgerRequest: getNodeFat returns false";
3576 case protocol::liBASE:
3578 info =
"Ledger base";
3581 case protocol::liTX_NODE:
3585 case protocol::liAS_NODE:
3589 case protocol::liTS_CANDIDATE:
3590 info =
"TS candidate";
3598 if (!m->has_ledgerhash())
3599 info +=
", no hash specified";
3601 JLOG(p_journal_.error())
3602 <<
"processLedgerRequest: getNodeFat with nodeId "
3603 << *shaMapNodeId <<
" and ledger info type " << info
3604 <<
" throws exception: " << e.
what();
3608 JLOG(p_journal_.info())
3609 <<
"processLedgerRequest: Got request for " << m->nodeids_size()
3610 <<
" nodes at depth " << queryDepth <<
", return "
3611 << ledgerData.nodes_size() <<
" nodes";
3615 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3620 PeerImp::getScore(
bool haveItem)
const
3624 static const int spRandomMax = 9999;
3628 static const int spHaveItem = 10000;
3633 static const int spLatency = 30;
3636 static const int spNoLatency = 8000;
3641 score += spHaveItem;
3650 score -= latency->count() * spLatency;
3652 score -= spNoLatency;
3658 PeerImp::isHighLatency()
const
3661 return latency_ >= peerHighLatency;
3665 PeerImp::reduceRelayReady()
3667 if (!reduceRelayReady_)
3669 reduce_relay::epoch<std::chrono::minutes>(UptimeClock::now()) >
3670 reduce_relay::WAIT_ON_BOOTUP;
3671 return vpReduceRelayEnabled_ && reduceRelayReady_;
3677 using namespace std::chrono_literals;
3680 totalBytes_ += bytes;
3681 accumBytes_ += bytes;
3682 auto const timeElapsed = clock_type::now() - intervalStart_;
3683 auto const timeElapsedInSecs =
3684 std::chrono::duration_cast<std::chrono::seconds>(timeElapsed);
3686 if (timeElapsedInSecs >= 1s)
3688 auto const avgBytes = accumBytes_ / timeElapsedInSecs.count();
3689 rollingAvg_.push_back(avgBytes);
3691 auto const totalBytes =
3693 rollingAvgBytes_ = totalBytes / rollingAvg_.size();
3695 intervalStart_ = clock_type::now();
3701 PeerImp::Metrics::average_bytes()
const
3704 return rollingAvgBytes_;
3708 PeerImp::Metrics::total_bytes()
const