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();
1079 if (m->type() == protocol::TMPing::ptPING)
1083 m->set_type(protocol::TMPing::ptPONG);
1084 send(std::make_shared<Message>(*m, protocol::mtPING));
1088 if (m->type() == protocol::TMPing::ptPONG && m->has_seq())
1098 auto const rtt = std::chrono::round<std::chrono::milliseconds>(
1123 for (
int i = 0; i < m->clusternodes().size(); ++i)
1125 protocol::TMClusterNode
const& node = m->clusternodes(i);
1128 if (node.has_nodename())
1129 name = node.nodename();
1131 auto const publicKey =
1138 auto const reportTime =
1142 *publicKey,
name, node.nodeload(), reportTime);
1146 int loadSources = m->loadsources().size();
1147 if (loadSources != 0)
1150 gossip.
items.reserve(loadSources);
1151 for (
int i = 0; i < m->loadsources().size(); ++i)
1153 protocol::TMLoadSource
const& node = m->loadsources(i);
1158 gossip.
items.push_back(item);
1171 if (status.getReportTime() >= thresh)
1172 fees.push_back(status.getLoadFee());
1177 auto const index = fees.size() / 2;
1179 clusterFee = fees[index];
1207 return badData(
"Invalid relays");
1216 auto const peerChainSz{m->peerchain_size()};
1217 if (peerChainSz > 0)
1220 return badData(
"Invalid peer chain size");
1223 return badData(
"Invalid relays and peer chain size");
1225 for (
int i = 0; i < peerChainSz; ++i)
1227 auto const slice{
makeSlice(m->peerchain(i).publickey())};
1231 return badData(
"Invalid peer public key");
1234 if (!pubKeyChain.
emplace(slice).second)
1235 return badData(
"Invalid peer public key");
1242 auto reply{shardStore->getShardInfo()->makeMessage(
app_)};
1243 if (peerChainSz > 0)
1244 *(reply.mutable_peerchain()) = m->peerchain();
1245 send(std::make_shared<Message>(reply, protocol::mtPEER_SHARD_INFO_V2));
1248 if (m->relays() == 0)
1252 if (peerChainSz == 0)
1259 m->set_relays(m->relays() - 1);
1261 std::make_shared<Message>(*m, protocol::mtGET_PEER_SHARD_INFO_V2),
1263 return pubKeyChain.
find(peer->getNodePublic()) != pubKeyChain.
end();
1275 if (curLedgerSeq >= db.earliestLedgerSeq())
1276 return db.seqToShardIndex(curLedgerSeq);
1277 return std::nullopt;
1292 auto const timestamp{
1295 if (timestamp > (now + 5s))
1296 return badData(
"Invalid timestamp");
1299 using namespace std::chrono_literals;
1300 if (timestamp < (now - 5min))
1301 return badData(
"Stale timestamp");
1303 s.
add32(m->timestamp());
1308 auto const numIncomplete{m->incomplete_size()};
1309 if (numIncomplete > 0)
1311 if (latestShardIndex && numIncomplete > *latestShardIndex)
1312 return badData(
"Invalid number of incomplete shards");
1315 for (
int i = 0; i < numIncomplete; ++i)
1317 auto const& incomplete{m->incomplete(i)};
1318 auto const shardIndex{incomplete.shardindex()};
1321 if (shardIndex < earliestShardIndex ||
1322 (latestShardIndex && shardIndex > latestShardIndex))
1324 return badData(
"Invalid incomplete shard index");
1326 s.
add32(shardIndex);
1329 auto const state{
static_cast<ShardState>(incomplete.state())};
1341 return badData(
"Invalid incomplete shard state");
1343 s.
add32(incomplete.state());
1347 if (incomplete.has_progress())
1349 progress = incomplete.progress();
1350 if (progress < 1 || progress > 100)
1351 return badData(
"Invalid incomplete shard progress");
1356 if (!
shardInfo.update(shardIndex, state, progress))
1357 return badData(
"Invalid duplicate incomplete shards");
1362 if (m->has_finalized())
1364 auto const& str{m->finalized()};
1366 return badData(
"Invalid finalized shards");
1368 if (!
shardInfo.setFinalizedFromString(str))
1369 return badData(
"Invalid finalized shard indexes");
1372 auto const numFinalized{boost::icl::length(
finalized)};
1373 if (numFinalized == 0 ||
1374 boost::icl::first(
finalized) < earliestShardIndex ||
1375 (latestShardIndex &&
1376 boost::icl::last(
finalized) > latestShardIndex))
1378 return badData(
"Invalid finalized shard indexes");
1381 if (latestShardIndex &&
1382 (numFinalized + numIncomplete) > *latestShardIndex)
1384 return badData(
"Invalid number of finalized and incomplete shards");
1387 s.
addRaw(str.data(), str.size());
1393 return badData(
"Invalid public key");
1398 return badData(
"Invalid public key");
1402 return badData(
"Invalid signature");
1405 auto const peerChainSz{m->peerchain_size()};
1406 if (peerChainSz > 0)
1410 return badData(
"Invalid peer chain size");
1418 for (
int i = 0; i < peerChainSz; ++i)
1421 slice =
makeSlice(m->peerchain(i).publickey());
1423 return badData(
"Invalid peer public key");
1426 if (!pubKeyChain.
emplace(slice).second)
1427 return badData(
"Invalid peer public key");
1432 makeSlice(m->peerchain(peerChainSz - 1).publickey()));
1435 m->mutable_peerchain()->RemoveLast();
1437 std::make_shared<Message>(*m, protocol::mtPEER_SHARD_INFO_V2));
1439 <<
"Relayed TMPeerShardInfoV2 from peer IP "
1441 << peer->getRemoteAddress().to_string();
1451 <<
"Consumed TMPeerShardInfoV2 originating from public key "
1454 << (
shardInfo.incomplete().empty() ?
"empty"
1464 else if (
shardInfo.msgTimestamp() > it->second.msgTimestamp())
1469 if (peerChainSz == 0)
1483 if (m->endpoints_v2().size() >= 1024)
1490 endpoints.
reserve(m->endpoints_v2().size());
1492 for (
auto const& tm : m->endpoints_v2())
1499 << tm.endpoint() <<
"}";
1516 if (!endpoints.
empty())
1539 <<
"Need network ledger";
1547 auto stx = std::make_shared<STTx const>(sit);
1548 uint256 txID = stx->getTransactionID();
1572 bool checkSignature =
true;
1575 if (!m->has_deferred() || !m->deferred())
1579 flags |= SF_TRUSTED;
1586 checkSignature =
false;
1593 <<
"No new transactions until synchronized";
1606 "recvTransaction->checkTransaction",
1611 if (
auto peer = weak.lock())
1612 peer->checkTransaction(flags, checkSignature, stx);
1619 <<
"Transaction invalid: " <<
strHex(m->rawtransaction());
1630 auto const itype{m->itype()};
1633 if (itype < protocol::liBASE || itype > protocol::liTS_CANDIDATE)
1634 return badData(
"Invalid ledger info type");
1639 return std::nullopt;
1642 if (itype == protocol::liTS_CANDIDATE)
1644 if (!m->has_ledgerhash())
1645 return badData(
"Invalid TX candidate set, missing TX set hash");
1648 !m->has_ledgerhash() && !m->has_ledgerseq() &&
1649 !(ltype && *ltype == protocol::ltCLOSED))
1651 return badData(
"Invalid request");
1655 if (ltype && (*ltype < protocol::ltACCEPTED || *ltype > protocol::ltCLOSED))
1656 return badData(
"Invalid ledger type");
1660 return badData(
"Invalid ledger hash");
1663 if (m->has_ledgerseq())
1665 auto const ledgerSeq{m->ledgerseq()};
1675 using namespace std::chrono_literals;
1685 if (itype != protocol::liBASE)
1687 if (m->nodeids_size() <= 0)
1688 return badData(
"Invalid ledger node IDs");
1690 for (
auto const& nodeId : m->nodeids())
1693 return badData(
"Invalid SHAMap node ID");
1698 if (m->has_querytype() && m->querytype() != protocol::qtINDIRECT)
1699 return badData(
"Invalid query type");
1702 if (m->has_querydepth())
1705 itype == protocol::liBASE)
1707 return badData(
"Invalid query depth");
1714 if (
auto peer = weak.
lock())
1715 peer->processLedgerRequest(m);
1733 if (
auto peer = weak.
lock())
1736 peer->ledgerReplayMsgHandler_.processProofPathRequest(m);
1737 if (reply.has_error())
1739 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1740 peer->charge(Resource::feeInvalidRequest);
1742 peer->charge(Resource::feeRequestNoReply);
1746 peer->send(std::make_shared<Message>(
1747 reply, protocol::mtPROOF_PATH_RESPONSE));
1782 if (
auto peer = weak.
lock())
1785 peer->ledgerReplayMsgHandler_.processReplayDeltaRequest(m);
1786 if (reply.has_error())
1788 if (reply.error() == protocol::TMReplyError::reBAD_REQUEST)
1789 peer->charge(Resource::feeInvalidRequest);
1791 peer->charge(Resource::feeRequestNoReply);
1795 peer->send(std::make_shared<Message>(
1796 reply, protocol::mtREPLAY_DELTA_RESPONSE));
1827 return badData(
"Invalid ledger hash");
1831 auto const ledgerSeq{m->ledgerseq()};
1832 if (m->type() == protocol::liTS_CANDIDATE)
1851 using namespace std::chrono_literals;
1862 if (m->type() < protocol::liBASE || m->type() > protocol::liTS_CANDIDATE)
1863 return badData(
"Invalid ledger info type");
1866 if (m->has_error() &&
1867 (m->error() < protocol::reNO_LEDGER ||
1868 m->error() > protocol::reBAD_REQUEST))
1870 return badData(
"Invalid reply error");
1877 "Invalid Ledger/TXset nodes " +
std::to_string(m->nodes_size()));
1881 if (m->has_requestcookie())
1885 m->clear_requestcookie();
1886 peer->send(std::make_shared<Message>(*m, protocol::mtLEDGER_DATA));
1890 JLOG(
p_journal_.
info()) <<
"Unable to route TX/ledger data reply";
1895 uint256 const ledgerHash{m->ledgerhash()};
1898 if (m->type() == protocol::liTS_CANDIDATE)
1902 jtTXN_DATA,
"recvPeerData", [weak, ledgerHash, m]() {
1903 if (
auto peer = weak.lock())
1905 peer->app_.getInboundTransactions().gotData(
1906 ledgerHash, peer, m);
1919 protocol::TMProposeSet&
set = *m;
1925 if ((std::clamp<std::size_t>(sig.size(), 64, 72) != sig.size()) ||
1953 uint256 const proposeHash{
set.currenttxhash()};
1954 uint256 const prevLedger{
set.previousledger()};
1966 if (
auto [added, relayed] =
1975 suppression, publicKey,
id_, protocol::mtPROPOSE_LEDGER);
1985 <<
"Proposal: Dropping untrusted (peer divergence)";
1997 <<
"Proposal: " << (isTrusted ?
"trusted" :
"untrusted");
2014 "recvPropose->checkPropose",
2016 if (
auto peer = weak.lock())
2017 peer->checkPropose(isTrusted, m,
proposal);
2026 if (!m->has_networktime())
2031 if (!
last_status_.has_newstatus() || m->has_newstatus())
2036 protocol::NodeStatus status =
last_status_.newstatus();
2038 m->set_newstatus(status);
2042 if (m->newevent() == protocol::neLOST_SYNC)
2044 bool outOfSync{
false};
2065 bool const peerChangedLedgers{
2072 if (peerChangedLedgers)
2083 if (m->has_ledgerhashprevious() &&
2094 if (peerChangedLedgers)
2104 if (m->has_firstseq() && m->has_lastseq())
2115 if (m->has_ledgerseq() &&
2125 if (m->has_newstatus())
2127 switch (m->newstatus())
2129 case protocol::nsCONNECTING:
2130 j[jss::status] =
"CONNECTING";
2132 case protocol::nsCONNECTED:
2133 j[jss::status] =
"CONNECTED";
2135 case protocol::nsMONITORING:
2136 j[jss::status] =
"MONITORING";
2138 case protocol::nsVALIDATING:
2139 j[jss::status] =
"VALIDATING";
2141 case protocol::nsSHUTTING:
2142 j[jss::status] =
"SHUTTING";
2147 if (m->has_newevent())
2149 switch (m->newevent())
2151 case protocol::neCLOSING_LEDGER:
2152 j[jss::action] =
"CLOSING_LEDGER";
2154 case protocol::neACCEPTED_LEDGER:
2155 j[jss::action] =
"ACCEPTED_LEDGER";
2157 case protocol::neSWITCHED_LEDGER:
2158 j[jss::action] =
"SWITCHED_LEDGER";
2160 case protocol::neLOST_SYNC:
2161 j[jss::action] =
"LOST_SYNC";
2166 if (m->has_ledgerseq())
2168 j[jss::ledger_index] = m->ledgerseq();
2171 if (m->has_ledgerhash())
2173 uint256 closedLedgerHash{};
2175 std::lock_guard sl(recentLock_);
2176 closedLedgerHash = closedLedgerHash_;
2178 j[jss::ledger_hash] =
to_string(closedLedgerHash);
2181 if (m->has_networktime())
2183 j[jss::date] = Json::UInt(m->networktime());
2186 if (m->has_firstseq() && m->has_lastseq())
2188 j[jss::ledger_index_min] = Json::UInt(m->firstseq());
2189 j[jss::ledger_index_max] = Json::UInt(m->lastseq());
2205 serverSeq = maxLedger_;
2211 checkTracking(serverSeq, validationSeq);
2220 if (diff < Tuning::convergedLedgerLimit)
2223 tracking_ = Tracking::converged;
2226 if ((diff > Tuning::divergedLedgerLimit) &&
2227 (tracking_.load() != Tracking::diverged))
2232 tracking_ = Tracking::diverged;
2233 trackingTime_ = clock_type::now();
2242 fee_ = Resource::feeInvalidRequest;
2246 uint256 const hash{m->hash()};
2248 if (m->status() == protocol::tsHAVE)
2252 if (
std::find(recentTxSets_.begin(), recentTxSets_.end(), hash) !=
2253 recentTxSets_.end())
2255 fee_ = Resource::feeUnwantedData;
2259 recentTxSets_.push_back(hash);
2264 PeerImp::onValidatorListMessage(
2274 JLOG(p_journal_.warn()) <<
"Ignored malformed " << messageType
2275 <<
" from peer " << remote_address_;
2277 fee_ = Resource::feeHighBurdenPeer;
2283 JLOG(p_journal_.debug())
2284 <<
"Received " << messageType <<
" from " << remote_address_.to_string()
2285 <<
" (" << id_ <<
")";
2287 if (!app_.getHashRouter().addSuppressionPeer(hash, id_))
2289 JLOG(p_journal_.debug())
2290 << messageType <<
": received duplicate " << messageType;
2294 fee_ = Resource::feeUnwantedData;
2298 auto const applyResult = app_.validators().applyListsAndBroadcast(
2302 remote_address_.to_string(),
2305 app_.getHashRouter(),
2308 JLOG(p_journal_.debug())
2309 <<
"Processed " << messageType <<
" version " << version <<
" from "
2310 << (applyResult.publisherKey ?
strHex(*applyResult.publisherKey)
2311 :
"unknown or invalid publisher")
2312 <<
" from " << remote_address_.to_string() <<
" (" << id_
2313 <<
") with best result " << to_string(applyResult.bestDisposition());
2316 switch (applyResult.bestDisposition())
2319 case ListDisposition::accepted:
2321 case ListDisposition::expired:
2323 case ListDisposition::pending: {
2326 assert(applyResult.publisherKey);
2327 auto const& pubKey = *applyResult.publisherKey;
2329 if (
auto const iter = publisherListSequences_.find(pubKey);
2330 iter != publisherListSequences_.end())
2332 assert(iter->second < applyResult.sequence);
2335 publisherListSequences_[pubKey] = applyResult.sequence;
2338 case ListDisposition::same_sequence:
2339 case ListDisposition::known_sequence:
2343 assert(applyResult.sequence && applyResult.publisherKey);
2345 publisherListSequences_[*applyResult.publisherKey] <=
2346 applyResult.sequence);
2351 case ListDisposition::stale:
2352 case ListDisposition::untrusted:
2353 case ListDisposition::invalid:
2354 case ListDisposition::unsupported_version:
2361 switch (applyResult.worstDisposition())
2363 case ListDisposition::accepted:
2364 case ListDisposition::expired:
2365 case ListDisposition::pending:
2368 case ListDisposition::same_sequence:
2369 case ListDisposition::known_sequence:
2373 fee_ = Resource::feeUnwantedData;
2375 case ListDisposition::stale:
2378 fee_ = Resource::feeBadData;
2380 case ListDisposition::untrusted:
2384 fee_ = Resource::feeUnwantedData;
2386 case ListDisposition::invalid:
2388 fee_ = Resource::feeInvalidSignature;
2390 case ListDisposition::unsupported_version:
2393 fee_ = Resource::feeBadData;
2400 for (
auto const& [disp, count] : applyResult.dispositions)
2405 case ListDisposition::accepted:
2406 JLOG(p_journal_.debug())
2407 <<
"Applied " << count <<
" new " << messageType
2408 <<
"(s) from peer " << remote_address_;
2411 case ListDisposition::expired:
2412 JLOG(p_journal_.debug())
2413 <<
"Applied " << count <<
" expired " << messageType
2414 <<
"(s) from peer " << remote_address_;
2417 case ListDisposition::pending:
2418 JLOG(p_journal_.debug())
2419 <<
"Processed " << count <<
" future " << messageType
2420 <<
"(s) from peer " << remote_address_;
2422 case ListDisposition::same_sequence:
2423 JLOG(p_journal_.warn())
2424 <<
"Ignored " << count <<
" " << messageType
2425 <<
"(s) with current sequence from peer "
2428 case ListDisposition::known_sequence:
2429 JLOG(p_journal_.warn())
2430 <<
"Ignored " << count <<
" " << messageType
2431 <<
"(s) with future sequence from peer " << remote_address_;
2433 case ListDisposition::stale:
2434 JLOG(p_journal_.warn())
2435 <<
"Ignored " << count <<
"stale " << messageType
2436 <<
"(s) from peer " << remote_address_;
2438 case ListDisposition::untrusted:
2439 JLOG(p_journal_.warn())
2440 <<
"Ignored " << count <<
" untrusted " << messageType
2441 <<
"(s) from peer " << remote_address_;
2443 case ListDisposition::unsupported_version:
2444 JLOG(p_journal_.warn())
2445 <<
"Ignored " << count <<
"unsupported version "
2446 << messageType <<
"(s) from peer " << remote_address_;
2448 case ListDisposition::invalid:
2449 JLOG(p_journal_.warn())
2450 <<
"Ignored " << count <<
"invalid " << messageType
2451 <<
"(s) from peer " << remote_address_;
2464 if (!supportsFeature(ProtocolFeature::ValidatorListPropagation))
2466 JLOG(p_journal_.debug())
2467 <<
"ValidatorList: received validator list from peer using "
2468 <<
"protocol version " << to_string(protocol_)
2469 <<
" which shouldn't support this feature.";
2470 fee_ = Resource::feeUnwantedData;
2473 onValidatorListMessage(
2477 ValidatorList::parseBlobs(*m));
2481 JLOG(p_journal_.warn()) <<
"ValidatorList: Exception, " << e.
what()
2482 <<
" from peer " << remote_address_;
2483 fee_ = Resource::feeBadData;
2493 if (!supportsFeature(ProtocolFeature::ValidatorList2Propagation))
2495 JLOG(p_journal_.debug())
2496 <<
"ValidatorListCollection: received validator list from peer "
2497 <<
"using protocol version " << to_string(protocol_)
2498 <<
" which shouldn't support this feature.";
2499 fee_ = Resource::feeUnwantedData;
2502 else if (m->version() < 2)
2504 JLOG(p_journal_.debug())
2505 <<
"ValidatorListCollection: received invalid validator list "
2507 << m->version() <<
" from peer using protocol version "
2508 << to_string(protocol_);
2509 fee_ = Resource::feeBadData;
2512 onValidatorListMessage(
2513 "ValidatorListCollection",
2516 ValidatorList::parseBlobs(*m));
2520 JLOG(p_journal_.warn()) <<
"ValidatorListCollection: Exception, "
2521 << e.
what() <<
" from peer " << remote_address_;
2522 fee_ = Resource::feeBadData;
2529 if (m->validation().size() < 50)
2531 JLOG(p_journal_.warn()) <<
"Validation: Too small";
2532 fee_ = Resource::feeInvalidRequest;
2538 auto const closeTime = app_.timeKeeper().closeTime();
2543 val = std::make_shared<STValidation>(
2547 app_.validatorManifests().getMasterKey(pk));
2550 val->setSeen(closeTime);
2554 app_.getValidations().parms(),
2555 app_.timeKeeper().closeTime(),
2557 val->getSeenTime()))
2559 JLOG(p_journal_.trace()) <<
"Validation: Not current";
2560 fee_ = Resource::feeUnwantedData;
2567 auto const isTrusted =
2568 app_.validators().trusted(val->getSignerPublic());
2573 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 <<
"Dropping untrusted validation from diverged peer";
2599 else if (isTrusted || !app_.getFeeTrack().isLoadedLocal())
2603 isTrusted ?
"Trusted validation" :
"Untrusted validation";
2608 to_string(val->getNodeID());
2615 app_.getJobQueue().addJob(
2618 [weak, val, m, key]() {
2619 if (
auto peer = weak.
lock())
2620 peer->checkValidation(val, key, m);
2625 JLOG(p_journal_.debug())
2626 <<
"Dropping untrusted validation for load";
2631 JLOG(p_journal_.warn())
2632 <<
"Exception processing validation: " << e.
what();
2633 fee_ = Resource::feeInvalidRequest;
2640 protocol::TMGetObjectByHash& packet = *m;
2642 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash " << packet.type()
2643 <<
" " << packet.objects_size();
2648 if (send_queue_.size() >= Tuning::dropSendQueue)
2650 JLOG(p_journal_.debug()) <<
"GetObject: Large send queue";
2654 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2660 if (packet.type() == protocol::TMGetObjectByHash::otTRANSACTIONS)
2662 if (!txReduceRelayEnabled())
2664 JLOG(p_journal_.error())
2665 <<
"TMGetObjectByHash: tx reduce-relay is disabled";
2666 fee_ = Resource::feeInvalidRequest;
2671 app_.getJobQueue().addJob(
2673 if (
auto peer = weak.
lock())
2674 peer->doTransactions(m);
2679 fee_ = Resource::feeMediumBurdenPeer;
2681 protocol::TMGetObjectByHash reply;
2683 reply.set_query(
false);
2685 if (packet.has_seq())
2686 reply.set_seq(packet.seq());
2688 reply.set_type(packet.type());
2690 if (packet.has_ledgerhash())
2694 fee_ = Resource::feeInvalidRequest;
2698 reply.set_ledgerhash(packet.ledgerhash());
2702 for (
int i = 0; i < packet.objects_size(); ++i)
2704 auto const& obj = packet.objects(i);
2707 uint256 const hash{obj.hash()};
2710 std::uint32_t seq{obj.has_ledgerseq() ? obj.ledgerseq() : 0};
2711 auto nodeObject{app_.getNodeStore().fetchNodeObject(hash, seq)};
2714 if (
auto shardStore = app_.getShardStore())
2716 if (seq >= shardStore->earliestLedgerSeq())
2717 nodeObject = shardStore->fetchNodeObject(hash, seq);
2722 protocol::TMIndexedObject& newObj = *reply.add_objects();
2723 newObj.set_hash(hash.begin(), hash.size());
2725 &nodeObject->getData().front(),
2726 nodeObject->getData().size());
2728 if (obj.has_nodeid())
2729 newObj.set_index(obj.nodeid());
2730 if (obj.has_ledgerseq())
2731 newObj.set_ledgerseq(obj.ledgerseq());
2738 JLOG(p_journal_.trace()) <<
"GetObj: " << reply.objects_size() <<
" of "
2739 << packet.objects_size();
2740 send(std::make_shared<Message>(reply, protocol::mtGET_OBJECTS));
2747 bool progress =
false;
2749 for (
int i = 0; i < packet.objects_size(); ++i)
2751 const protocol::TMIndexedObject& obj = packet.objects(i);
2755 if (obj.has_ledgerseq())
2757 if (obj.ledgerseq() != pLSeq)
2759 if (pLDo && (pLSeq != 0))
2761 JLOG(p_journal_.debug())
2762 <<
"GetObj: Full fetch pack for " << pLSeq;
2764 pLSeq = obj.ledgerseq();
2765 pLDo = !app_.getLedgerMaster().haveLedger(pLSeq);
2769 JLOG(p_journal_.debug())
2770 <<
"GetObj: Late fetch pack for " << pLSeq;
2779 uint256 const hash{obj.hash()};
2781 app_.getLedgerMaster().addFetchPack(
2783 std::make_shared<Blob>(
2784 obj.data().begin(), obj.data().end()));
2789 if (pLDo && (pLSeq != 0))
2791 JLOG(p_journal_.debug())
2792 <<
"GetObj: Partial fetch pack for " << pLSeq;
2794 if (packet.type() == protocol::TMGetObjectByHash::otFETCH_PACK)
2795 app_.getLedgerMaster().gotFetchPack(progress, pLSeq);
2802 if (!txReduceRelayEnabled())
2804 JLOG(p_journal_.error())
2805 <<
"TMHaveTransactions: tx reduce-relay is disabled";
2806 fee_ = Resource::feeInvalidRequest;
2811 app_.getJobQueue().addJob(
2813 if (
auto peer = weak.
lock())
2814 peer->handleHaveTransactions(m);
2819 PeerImp::handleHaveTransactions(
2822 protocol::TMGetObjectByHash tmBH;
2823 tmBH.set_type(protocol::TMGetObjectByHash_ObjectType_otTRANSACTIONS);
2824 tmBH.set_query(
true);
2826 JLOG(p_journal_.trace())
2827 <<
"received TMHaveTransactions " << m->hashes_size();
2833 JLOG(p_journal_.error())
2834 <<
"TMHaveTransactions with invalid hash size";
2835 fee_ = Resource::feeInvalidRequest;
2841 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
2843 JLOG(p_journal_.trace()) <<
"checking transaction " << (bool)txn;
2847 JLOG(p_journal_.debug()) <<
"adding transaction to request";
2849 auto obj = tmBH.add_objects();
2850 obj->set_hash(hash.
data(), hash.
size());
2857 removeTxQueue(hash);
2861 JLOG(p_journal_.trace())
2862 <<
"transaction request object is " << tmBH.objects_size();
2864 if (tmBH.objects_size() > 0)
2865 send(std::make_shared<Message>(tmBH, protocol::mtGET_OBJECTS));
2871 if (!txReduceRelayEnabled())
2873 JLOG(p_journal_.error())
2874 <<
"TMTransactions: tx reduce-relay is disabled";
2875 fee_ = Resource::feeInvalidRequest;
2879 JLOG(p_journal_.trace())
2880 <<
"received TMTransactions " << m->transactions_size();
2882 overlay_.addTxMetrics(m->transactions_size());
2887 m->mutable_transactions(i), [](protocol::TMTransaction*) {}),
2894 using on_message_fn =
2896 if (!strand_.running_in_this_thread())
2900 (on_message_fn)&PeerImp::onMessage, shared_from_this(), m));
2902 if (!m->has_validatorpubkey())
2904 charge(Resource::feeBadData);
2907 auto validator = m->validatorpubkey();
2911 charge(Resource::feeBadData);
2917 if (!app_.validators().listed(key))
2919 charge(Resource::feeBadData);
2920 JLOG(p_journal_.debug())
2921 <<
"onMessage: TMSquelch discarding non-validator squelch "
2927 if (key == app_.getValidationPublicKey())
2929 JLOG(p_journal_.debug())
2930 <<
"onMessage: TMSquelch discarding validator's squelch " << slice;
2935 m->has_squelchduration() ? m->squelchduration() : 0;
2937 squelch_.removeSquelch(key);
2939 charge(Resource::feeBadData);
2941 JLOG(p_journal_.debug())
2942 <<
"onMessage: TMSquelch " << slice <<
" " << id() <<
" " << duration;
2954 (void)lockedRecentLock;
2956 if (
std::find(recentLedgers_.begin(), recentLedgers_.end(), hash) !=
2957 recentLedgers_.end())
2960 recentLedgers_.push_back(hash);
2969 if (app_.getFeeTrack().isLoadedLocal() ||
2970 (app_.getLedgerMaster().getValidatedLedgerAge() > 40s) ||
2971 (app_.getJobQueue().getJobCount(
jtPACK) > 10))
2973 JLOG(p_journal_.info()) <<
"Too busy to make fetch pack";
2979 JLOG(p_journal_.warn()) <<
"FetchPack hash size malformed";
2980 fee_ = Resource::feeInvalidRequest;
2984 fee_ = Resource::feeHighBurdenPeer;
2986 uint256 const hash{packet->ledgerhash()};
2989 auto elapsed = UptimeClock::now();
2990 auto const pap = &app_;
2991 app_.getJobQueue().addJob(
2992 jtPACK,
"MakeFetchPack", [pap, weak, packet, hash, elapsed]() {
2993 pap->getLedgerMaster().makeFetchPack(weak, packet, hash, elapsed);
2998 PeerImp::doTransactions(
3001 protocol::TMTransactions reply;
3003 JLOG(p_journal_.trace()) <<
"received TMGetObjectByHash requesting tx "
3004 << packet->objects_size();
3006 if (packet->objects_size() > reduce_relay::MAX_TX_QUEUE_SIZE)
3008 JLOG(p_journal_.error()) <<
"doTransactions, invalid number of hashes";
3009 fee_ = Resource::feeInvalidRequest;
3015 auto const& obj = packet->objects(i);
3019 fee_ = Resource::feeInvalidRequest;
3025 auto txn = app_.getMasterTransaction().fetch_from_cache(hash);
3029 JLOG(p_journal_.error()) <<
"doTransactions, transaction not found "
3031 fee_ = Resource::feeInvalidRequest;
3036 auto tx = reply.add_transactions();
3037 auto sttx = txn->getSTransaction();
3039 tx->set_rawtransaction(s.
data(), s.
size());
3041 txn->getStatus() ==
INCLUDED ? protocol::tsCURRENT
3043 tx->set_receivetimestamp(
3044 app_.timeKeeper().now().time_since_epoch().count());
3045 tx->set_deferred(txn->getSubmitResult().queued);
3048 if (reply.transactions_size() > 0)
3049 send(std::make_shared<Message>(reply, protocol::mtTRANSACTIONS));
3053 PeerImp::checkTransaction(
3055 bool checkSignature,
3064 app_.getLedgerMaster().getValidLedgerIndex()))
3066 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3067 charge(Resource::feeUnwantedData);
3075 app_.getHashRouter(),
3077 app_.getLedgerMaster().getValidatedRules(),
3079 valid != Validity::Valid)
3081 if (!validReason.empty())
3083 JLOG(p_journal_.trace())
3084 <<
"Exception checking transaction: " << validReason;
3088 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3089 charge(Resource::feeInvalidSignature);
3096 app_.getHashRouter(), stx->getTransactionID(), Validity::Valid);
3100 auto tx = std::make_shared<Transaction>(stx, reason, app_);
3102 if (tx->getStatus() ==
INVALID)
3104 if (!reason.
empty())
3106 JLOG(p_journal_.trace())
3107 <<
"Exception checking transaction: " << reason;
3109 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3110 charge(Resource::feeInvalidSignature);
3114 bool const trusted(flags & SF_TRUSTED);
3115 app_.getOPs().processTransaction(
3116 tx, trusted,
false, NetworkOPs::FailHard::no);
3120 app_.getHashRouter().setFlags(stx->getTransactionID(), SF_BAD);
3121 charge(Resource::feeBadData);
3127 PeerImp::checkPropose(
3132 JLOG(p_journal_.trace())
3133 <<
"Checking " << (isTrusted ?
"trusted" :
"UNTRUSTED") <<
" proposal";
3139 JLOG(p_journal_.warn()) <<
"Proposal fails sig check";
3140 charge(Resource::feeInvalidSignature);
3147 relay = app_.getOPs().processTrustedProposal(peerPos);
3149 relay = app_.config().RELAY_UNTRUSTED_PROPOSALS == 1 || cluster();
3157 auto haveMessage = app_.overlay().relay(
3159 if (reduceRelayReady() && !haveMessage.empty())
3160 overlay_.updateSlotAndSquelch(
3163 std::move(haveMessage),
3164 protocol::mtPROPOSE_LEDGER);
3169 PeerImp::checkValidation(
3174 if (!val->isValid())
3176 JLOG(p_journal_.debug()) <<
"Validation forwarded by peer is invalid";
3177 charge(Resource::feeInvalidSignature);
3192 overlay_.relay(*packet, key, val->getSignerPublic());
3193 if (reduceRelayReady() && !haveMessage.empty())
3195 overlay_.updateSlotAndSquelch(
3197 val->getSignerPublic(),
3198 std::move(haveMessage),
3199 protocol::mtVALIDATION);
3205 JLOG(p_journal_.trace()) <<
"Exception processing validation";
3206 charge(Resource::feeInvalidRequest);
3220 if (p->hasTxSet(rootHash) && p.get() != skip)
3222 auto score = p->getScore(true);
3223 if (!ret || (score > retScore))
3248 if (p->hasLedger(ledgerHash, ledger) && p.get() != skip)
3250 auto score = p->getScore(true);
3251 if (!ret || (score > retScore))
3263 PeerImp::sendLedgerBase(
3265 protocol::TMLedgerData& ledgerData)
3267 JLOG(p_journal_.trace()) <<
"sendLedgerBase: Base data";
3270 addRaw(ledger->info(), s);
3273 auto const& stateMap{ledger->stateMap()};
3274 if (stateMap.getHash() != beast::zero)
3279 stateMap.serializeRoot(root);
3280 ledgerData.add_nodes()->set_nodedata(
3283 if (ledger->info().txHash != beast::zero)
3285 auto const& txMap{ledger->txMap()};
3286 if (txMap.getHash() != beast::zero)
3290 txMap.serializeRoot(root);
3291 ledgerData.add_nodes()->set_nodedata(
3298 std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA)};
3305 JLOG(p_journal_.trace()) <<
"getLedger: Ledger";
3309 if (m->has_ledgerhash())
3312 uint256 const ledgerHash{m->ledgerhash()};
3313 ledger = app_.getLedgerMaster().getLedgerByHash(ledgerHash);
3316 if (m->has_ledgerseq())
3319 if (
auto shards = app_.getShardStore())
3321 if (m->ledgerseq() >= shards->earliestLedgerSeq())
3324 shards->fetchLedger(ledgerHash, m->ledgerseq());
3331 JLOG(p_journal_.trace())
3332 <<
"getLedger: Don't have ledger with hash " << ledgerHash;
3334 if (m->has_querytype() && !m->has_requestcookie())
3340 m->has_ledgerseq() ? m->ledgerseq() : 0,
3343 m->set_requestcookie(
id());
3344 peer->send(std::make_shared<Message>(
3345 *m, protocol::mtGET_LEDGER));
3346 JLOG(p_journal_.debug())
3347 <<
"getLedger: Request relayed to peer";
3351 JLOG(p_journal_.trace())
3352 <<
"getLedger: Failed to find peer to relay request";
3357 else if (m->has_ledgerseq())
3360 if (m->ledgerseq() < app_.getLedgerMaster().getEarliestFetch())
3362 JLOG(p_journal_.debug())
3363 <<
"getLedger: Early ledger sequence request";
3367 ledger = app_.getLedgerMaster().getLedgerBySeq(m->ledgerseq());
3370 JLOG(p_journal_.debug())
3371 <<
"getLedger: Don't have ledger with sequence "
3376 else if (m->has_ltype() && m->ltype() == protocol::ltCLOSED)
3378 ledger = app_.getLedgerMaster().getClosedLedger();
3384 auto const ledgerSeq{ledger->info().seq};
3385 if (m->has_ledgerseq())
3387 if (ledgerSeq != m->ledgerseq())
3390 if (!m->has_requestcookie())
3391 charge(Resource::feeInvalidRequest);
3394 JLOG(p_journal_.warn())
3395 <<
"getLedger: Invalid ledger sequence " << ledgerSeq;
3398 else if (ledgerSeq < app_.getLedgerMaster().getEarliestFetch())
3401 JLOG(p_journal_.debug())
3402 <<
"getLedger: Early ledger sequence request " << ledgerSeq;
3407 JLOG(p_journal_.debug()) <<
"getLedger: Unable to find ledger";
3416 JLOG(p_journal_.trace()) <<
"getTxSet: TX set";
3418 uint256 const txSetHash{m->ledgerhash()};
3420 app_.getInboundTransactions().getSet(txSetHash,
false)};
3423 if (m->has_querytype() && !m->has_requestcookie())
3428 m->set_requestcookie(
id());
3430 std::make_shared<Message>(*m, protocol::mtGET_LEDGER));
3431 JLOG(p_journal_.debug()) <<
"getTxSet: Request relayed";
3435 JLOG(p_journal_.debug())
3436 <<
"getTxSet: Failed to find relay peer";
3441 JLOG(p_journal_.debug()) <<
"getTxSet: Failed to find TX set";
3452 if (!m->has_requestcookie())
3453 charge(Resource::feeMediumBurdenPeer);
3457 SHAMap const* map{
nullptr};
3458 protocol::TMLedgerData ledgerData;
3459 bool fatLeaves{
true};
3460 auto const itype{m->itype()};
3462 if (itype == protocol::liTS_CANDIDATE)
3464 if (sharedMap = getTxSet(m); !sharedMap)
3466 map = sharedMap.
get();
3469 ledgerData.set_ledgerseq(0);
3470 ledgerData.set_ledgerhash(m->ledgerhash());
3471 ledgerData.set_type(protocol::liTS_CANDIDATE);
3472 if (m->has_requestcookie())
3473 ledgerData.set_requestcookie(m->requestcookie());
3480 if (send_queue_.size() >= Tuning::dropSendQueue)
3482 JLOG(p_journal_.debug())
3483 <<
"processLedgerRequest: Large send queue";
3486 if (app_.getFeeTrack().isLoadedLocal() && !cluster())
3488 JLOG(p_journal_.debug()) <<
"processLedgerRequest: Too busy";
3492 if (ledger = getLedger(m); !ledger)
3496 auto const ledgerHash{ledger->info().hash};
3497 ledgerData.set_ledgerhash(ledgerHash.begin(), ledgerHash.size());
3498 ledgerData.set_ledgerseq(ledger->info().seq);
3499 ledgerData.set_type(itype);
3500 if (m->has_requestcookie())
3501 ledgerData.set_requestcookie(m->requestcookie());
3505 case protocol::liBASE:
3506 sendLedgerBase(ledger, ledgerData);
3509 case protocol::liTX_NODE:
3510 map = &ledger->txMap();
3511 JLOG(p_journal_.trace()) <<
"processLedgerRequest: TX map hash "
3512 << to_string(map->getHash());
3515 case protocol::liAS_NODE:
3516 map = &ledger->stateMap();
3517 JLOG(p_journal_.trace())
3518 <<
"processLedgerRequest: Account state map hash "
3519 << to_string(map->getHash());
3524 JLOG(p_journal_.error())
3525 <<
"processLedgerRequest: Invalid ledger info type";
3532 JLOG(p_journal_.warn()) <<
"processLedgerRequest: Unable to find map";
3537 if (m->nodeids_size() > 0)
3539 auto const queryDepth{
3540 m->has_querydepth() ? m->querydepth() : (isHighLatency() ? 2 : 1)};
3544 for (
int i = 0; i < m->nodeids_size() &&
3545 ledgerData.nodes_size() < Tuning::softMaxReplyNodes;
3551 data.reserve(Tuning::softMaxReplyNodes);
3555 if (map->getNodeFat(*shaMapNodeId, data, fatLeaves, queryDepth))
3557 JLOG(p_journal_.trace())
3558 <<
"processLedgerRequest: getNodeFat got "
3559 << data.size() <<
" nodes";
3561 for (
auto const& d : data)
3563 protocol::TMLedgerNode* node{ledgerData.add_nodes()};
3564 node->set_nodeid(d.first.getRawString());
3565 node->set_nodedata(d.second.data(), d.second.size());
3570 JLOG(p_journal_.warn())
3571 <<
"processLedgerRequest: getNodeFat returns false";
3579 case protocol::liBASE:
3581 info =
"Ledger base";
3584 case protocol::liTX_NODE:
3588 case protocol::liAS_NODE:
3592 case protocol::liTS_CANDIDATE:
3593 info =
"TS candidate";
3601 if (!m->has_ledgerhash())
3602 info +=
", no hash specified";
3604 JLOG(p_journal_.error())
3605 <<
"processLedgerRequest: getNodeFat with nodeId "
3606 << *shaMapNodeId <<
" and ledger info type " << info
3607 <<
" throws exception: " << e.
what();
3611 JLOG(p_journal_.info())
3612 <<
"processLedgerRequest: Got request for " << m->nodeids_size()
3613 <<
" nodes at depth " << queryDepth <<
", return "
3614 << ledgerData.nodes_size() <<
" nodes";
3617 send(std::make_shared<Message>(ledgerData, protocol::mtLEDGER_DATA));
3621 PeerImp::getScore(
bool haveItem)
const
3625 static const int spRandomMax = 9999;
3629 static const int spHaveItem = 10000;
3634 static const int spLatency = 30;
3637 static const int spNoLatency = 8000;
3642 score += spHaveItem;
3651 score -= latency->count() * spLatency;
3653 score -= spNoLatency;
3659 PeerImp::isHighLatency()
const
3662 return latency_ >= peerHighLatency;
3666 PeerImp::reduceRelayReady()
3668 if (!reduceRelayReady_)
3670 reduce_relay::epoch<std::chrono::minutes>(UptimeClock::now()) >
3671 reduce_relay::WAIT_ON_BOOTUP;
3672 return vpReduceRelayEnabled_ && reduceRelayReady_;
3678 using namespace std::chrono_literals;
3681 totalBytes_ += bytes;
3682 accumBytes_ += bytes;
3683 auto const timeElapsed = clock_type::now() - intervalStart_;
3684 auto const timeElapsedInSecs =
3685 std::chrono::duration_cast<std::chrono::seconds>(timeElapsed);
3687 if (timeElapsedInSecs >= 1s)
3689 auto const avgBytes = accumBytes_ / timeElapsedInSecs.count();
3690 rollingAvg_.push_back(avgBytes);
3692 auto const totalBytes =
3694 rollingAvgBytes_ = totalBytes / rollingAvg_.size();
3696 intervalStart_ = clock_type::now();
3702 PeerImp::Metrics::average_bytes()
const
3705 return rollingAvgBytes_;
3709 PeerImp::Metrics::total_bytes()
const