20 #include <ripple/app/consensus/RCLConsensus.h>
21 #include <ripple/app/consensus/RCLValidations.h>
22 #include <ripple/app/ledger/AcceptedLedger.h>
23 #include <ripple/app/ledger/InboundLedgers.h>
24 #include <ripple/app/ledger/LedgerMaster.h>
25 #include <ripple/app/ledger/LedgerToJson.h>
26 #include <ripple/app/ledger/LocalTxs.h>
27 #include <ripple/app/ledger/OpenLedger.h>
28 #include <ripple/app/ledger/OrderBookDB.h>
29 #include <ripple/app/ledger/TransactionMaster.h>
30 #include <ripple/app/main/LoadManager.h>
31 #include <ripple/app/misc/AmendmentTable.h>
32 #include <ripple/app/misc/HashRouter.h>
33 #include <ripple/app/misc/LoadFeeTrack.h>
34 #include <ripple/app/misc/NetworkOPs.h>
35 #include <ripple/app/misc/Transaction.h>
36 #include <ripple/app/misc/TxQ.h>
37 #include <ripple/app/misc/ValidatorKeys.h>
38 #include <ripple/app/misc/ValidatorList.h>
39 #include <ripple/app/misc/impl/AccountTxPaging.h>
40 #include <ripple/app/rdb/backend/PostgresDatabase.h>
41 #include <ripple/app/rdb/backend/SQLiteDatabase.h>
42 #include <ripple/app/reporting/ReportingETL.h>
43 #include <ripple/app/tx/apply.h>
44 #include <ripple/basics/PerfLog.h>
45 #include <ripple/basics/SubmitSync.h>
46 #include <ripple/basics/UptimeClock.h>
47 #include <ripple/basics/mulDiv.h>
48 #include <ripple/basics/safe_cast.h>
49 #include <ripple/beast/rfc2616.h>
50 #include <ripple/beast/utility/rngfill.h>
51 #include <ripple/consensus/Consensus.h>
52 #include <ripple/consensus/ConsensusParms.h>
53 #include <ripple/crypto/RFC1751.h>
54 #include <ripple/crypto/csprng.h>
55 #include <ripple/json/to_string.h>
56 #include <ripple/net/RPCErr.h>
57 #include <ripple/nodestore/DatabaseShard.h>
58 #include <ripple/overlay/Cluster.h>
59 #include <ripple/overlay/Overlay.h>
60 #include <ripple/overlay/predicates.h>
61 #include <ripple/protocol/BuildInfo.h>
62 #include <ripple/protocol/Feature.h>
63 #include <ripple/protocol/STParsedJSON.h>
64 #include <ripple/resource/Fees.h>
65 #include <ripple/resource/ResourceManager.h>
66 #include <ripple/rpc/BookChanges.h>
67 #include <ripple/rpc/DeliveredAmount.h>
68 #include <ripple/rpc/ServerHandler.h>
69 #include <ripple/rpc/impl/RPCHelpers.h>
70 #include <boost/asio/ip/host_name.hpp>
71 #include <boost/asio/steady_timer.hpp>
147 std::chrono::steady_clock::time_point
start_ =
208 return !(*
this != b);
227 boost::asio::io_service& io_svc,
242 app_.logs().journal(
"FeeVote")),
245 app.getInboundTransactions(),
246 beast::get_abstract_clock<
std::chrono::steady_clock>(),
248 app_.logs().journal(
"LedgerConsensus"))
396 getServerInfo(
bool human,
bool admin,
bool counters)
override;
423 TER result)
override;
466 bool historyOnly)
override;
472 bool historyOnly)
override;
540 boost::system::error_code ec;
545 <<
"NetworkOPs: heartbeatTimer cancel error: "
554 <<
"NetworkOPs: clusterTimer cancel error: "
563 <<
"NetworkOPs: accountHistoryTxTimer cancel error: "
572 <<
"NetworkOPs: batchApplyTimer cancel error: "
577 using namespace std::chrono_literals;
587 boost::asio::steady_timer& timer,
602 const STTx& transaction,
768 template <
class Handler>
770 Handler
const& handler,
772 :
hook(collector->make_hook(handler))
775 "Disconnected_duration"))
778 "Connected_duration"))
780 collector->make_gauge(
"State_Accounting",
"Syncing_duration"))
783 "Tracking_duration"))
785 collector->make_gauge(
"State_Accounting",
"Full_duration"))
788 "Disconnected_transitions"))
791 "Connected_transitions"))
794 "Syncing_transitions"))
797 "Tracking_transitions"))
799 collector->make_gauge(
"State_Accounting",
"Full_transitions"))
828 {
"disconnected",
"connected",
"syncing",
"tracking",
"full"}};
890 static std::string const hostname = boost::asio::ip::host_name();
897 static std::string const shroudedHostId = [
this]() {
903 return shroudedHostId;
918 boost::asio::steady_timer& timer,
925 [
this, onExpire, onError](boost::system::error_code
const& e) {
926 if ((e.value() == boost::system::errc::success) &&
927 (!m_job_queue.isStopped()))
932 if (e.value() != boost::system::errc::success &&
933 e.value() != boost::asio::error::operation_aborted)
936 JLOG(m_journal.error())
937 <<
"Timer got error '" << e.message()
938 <<
"'. Restarting timer.";
943 timer.expires_from_now(expiry_time);
944 timer.async_wait(std::move(*optionalCountedHandler));
980 using namespace std::chrono_literals;
996 JLOG(
m_journal.
debug()) <<
"Scheduling AccountHistory job for account "
998 using namespace std::chrono_literals;
1009 using namespace std::chrono_literals;
1014 auto constexpr batchInterval = 100ms;
1028 jtBATCH,
"transactionBatch", [
this]() {
1029 transactionBatch(false);
1061 <<
"Node count (" << numPeers <<
") has fallen "
1077 <<
"Node count (" << numPeers <<
") is sufficient.";
1106 using namespace std::chrono_literals;
1123 protocol::TMCluster cluster;
1125 protocol::TMClusterNode& n = *cluster.add_clusternodes();
1130 n.set_nodename(node.
name());
1134 for (
auto& item : gossip.
items)
1136 protocol::TMLoadSource& node = *cluster.add_loadsources();
1138 node.set_cost(item.balance);
1141 std::make_shared<Message>(cluster, protocol::mtCLUSTER),
1161 return "validating";
1180 auto const txid = trans->getTransactionID();
1183 if ((flags & SF_BAD) != 0)
1185 JLOG(
m_journal.
warn()) <<
"Submitted transaction cached bad";
1200 <<
"Submitted transaction invalid: " << reason;
1207 <<
"Exception checking transaction " << txid <<
": " << ex.
what();
1214 auto tx = std::make_shared<Transaction>(trans, reason,
app_);
1234 if ((newFlags & SF_BAD) != 0)
1237 JLOG(
m_journal.
warn()) << transaction->getID() <<
": cached bad!\n";
1238 transaction->setStatus(
INVALID);
1249 *transaction->getSTransaction(),
1257 JLOG(
m_journal.
trace()) <<
"Transaction has bad signature: " << reason;
1258 transaction->setStatus(
INVALID);
1268 if (!transaction->getApplying())
1270 transaction->setApplying();
1286 }
while (transaction->getApplying());
1295 transaction = std::make_shared<Transaction>(*transaction);
1301 lock, [&transaction] {
return !transaction->getApplying(); });
1339 bool changed =
false;
1357 app_, view, e.transaction->getSTransaction(), flags, j);
1358 e.result = result.first;
1359 e.applied = result.second;
1360 changed = changed || result.second;
1370 validatedLedgerIndex = l->info().seq;
1375 e.transaction->clearSubmitResult();
1380 newOL, e.transaction->getSTransaction(), e.result);
1381 e.transaction->setApplied();
1384 e.transaction->setResult(e.result);
1397 <<
"TransactionResult: " << token <<
": " << human;
1402 bool addLocal = e.local;
1407 <<
"Transaction is now included in open ledger";
1408 e.transaction->setStatus(
INCLUDED);
1410 auto const& txCur = e.transaction->getSTransaction();
1416 auto t = std::make_shared<Transaction>(trans, reason,
app_);
1425 e.transaction->setStatus(
OBSOLETE);
1430 <<
"Transaction is likely to claim a"
1431 <<
" fee, but is queued until fee drops";
1433 e.transaction->setStatus(
HELD);
1438 e.transaction->setQueued();
1439 e.transaction->setKept();
1447 <<
"Transaction should be held: " << e.result;
1448 e.transaction->setStatus(
HELD);
1450 e.transaction->setKept();
1456 <<
"Status other than success " << e.result;
1457 e.transaction->setStatus(
INVALID);
1460 auto const enforceFailHard =
1463 if (addLocal && !enforceFailHard)
1467 e.transaction->getSTransaction());
1468 e.transaction->setKept();
1482 protocol::TMTransaction tx;
1485 e.transaction->getSTransaction()->add(s);
1486 tx.set_rawtransaction(s.
data(), s.
size());
1487 tx.set_status(protocol::tsCURRENT);
1488 tx.set_receivetimestamp(
1493 e.transaction->setBroadcast();
1497 if (validatedLedgerIndex)
1499 auto [fee, accountSeq, availableSeq] =
1501 *newOL, e.transaction->getSTransaction());
1502 e.transaction->setCurrentLedgerState(
1503 *validatedLedgerIndex, fee, accountSeq, availableSeq);
1511 e.transaction->clearApplying();
1513 if (!submit_held.
empty())
1518 for (
auto& e : submit_held)
1545 for (
auto const& uDirEntry : sleNode->getFieldV256(
sfIndexes))
1550 switch (sleCur->getType())
1553 if (!jvObjects.
isMember(jss::offers))
1554 jvObjects[jss::offers] =
1557 jvObjects[jss::offers].
append(
1562 if (!jvObjects.
isMember(jss::ripple_lines))
1564 jvObjects[jss::ripple_lines] =
1568 jvObjects[jss::ripple_lines].
append(
1663 JLOG(
m_journal.
trace()) <<
"NetworkOPsImp::checkLastClosedLedger";
1670 uint256 closedLedger = ourClosed->info().hash;
1671 uint256 prevClosedLedger = ourClosed->info().parentHash;
1680 <<
"ValidationTrie " <<
Json::Compact(validations.getJsonTrie());
1684 peerCounts[closedLedger] = 0;
1686 peerCounts[closedLedger]++;
1688 for (
auto& peer : peerList)
1690 uint256 peerLedger = peer->getClosedLedgerHash();
1693 ++peerCounts[peerLedger];
1696 for (
auto const& it : peerCounts)
1697 JLOG(
m_journal.
debug()) <<
"L: " << it.first <<
" n=" << it.second;
1699 uint256 preferredLCL = validations.getPreferredLCL(
1704 bool switchLedgers = preferredLCL != closedLedger;
1706 closedLedger = preferredLCL;
1708 if (switchLedgers && (closedLedger == prevClosedLedger))
1711 JLOG(
m_journal.
info()) <<
"We won't switch to our own previous ledger";
1712 networkClosed = ourClosed->info().hash;
1713 switchLedgers =
false;
1717 networkClosed = closedLedger;
1736 networkClosed = ourClosed->info().hash;
1740 JLOG(
m_journal.
warn()) <<
"We are not running on the consensus ledger";
1766 <<
"JUMP last closed ledger to " << newLCL->info().hash;
1802 protocol::TMStatusChange s;
1803 s.set_newevent(protocol::neSWITCHED_LEDGER);
1804 s.set_ledgerseq(newLCL->info().seq);
1806 s.set_ledgerhashprevious(
1807 newLCL->info().parentHash.begin(), newLCL->info().parentHash.size());
1808 s.set_ledgerhash(newLCL->info().hash.begin(), newLCL->info().hash.size());
1811 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
1821 JLOG(
m_journal.
info()) <<
"Consensus time for #" << closingInfo.seq
1822 <<
" with LCL " << closingInfo.parentHash;
1831 JLOG(
m_journal.
warn()) <<
"Don't have LCL, going to tracking";
1838 assert(prevLedger->info().hash == closingInfo.parentHash);
1840 closingInfo.parentHash ==
1847 closingInfo.parentCloseTime,
1852 if (!changes.
added.empty() || !changes.
removed.empty())
1892 protocol::TMHaveTransactionSet msg;
1893 msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8);
1894 msg.set_status(protocol::tsHAVE);
1896 send_always(std::make_shared<Message>(msg, protocol::mtHAVE_SET)));
1910 if (it && (it->getClosedLedgerHash() == deadLedger))
1921 if (networkClosed.
isZero())
1950 2 *
current->info().closeTimeResolution))
1978 jvObj[jss::type] =
"manifestReceived";
1981 jvObj[jss::signing_key] =
1985 jvObj[jss::signature] =
strHex(*sig);
1988 jvObj[jss::domain] = mo.
domain;
1994 if (
auto p = i->second.lock())
1996 p->send(jvObj,
true);
2012 , loadBaseServer{loadFeeTrack.getLoadBase()}
2014 , em{std::move(escalationMetrics)}
2024 em.has_value() != b.
em.has_value())
2030 em->minProcessingFeeLevel != b.
em->minProcessingFeeLevel ||
2031 em->openLedgerFeeLevel != b.
em->openLedgerFeeLevel ||
2032 em->referenceFeeLevel != b.
em->referenceFeeLevel);
2065 jvObj[jss::type] =
"serverStatus";
2067 jvObj[jss::load_base] = f.loadBaseServer;
2068 jvObj[jss::load_factor_server] = f.loadFactorServer;
2069 jvObj[jss::base_fee] = f.baseFee.jsonClipped();
2074 safe_cast<std::uint64_t>(f.loadFactorServer),
2076 f.em->openLedgerFeeLevel,
2078 f.em->referenceFeeLevel)
2081 jvObj[jss::load_factor] =
trunc32(loadFactor);
2082 jvObj[jss::load_factor_fee_escalation] =
2083 f.em->openLedgerFeeLevel.jsonClipped();
2084 jvObj[jss::load_factor_fee_queue] =
2085 f.em->minProcessingFeeLevel.jsonClipped();
2086 jvObj[jss::load_factor_fee_reference] =
2087 f.em->referenceFeeLevel.jsonClipped();
2090 jvObj[jss::load_factor] = f.loadFactorServer;
2104 p->send(jvObj,
true);
2121 if (!streamMap.empty())
2124 jvObj[jss::type] =
"consensusPhase";
2125 jvObj[jss::consensus] =
to_string(phase);
2127 for (
auto i = streamMap.begin(); i != streamMap.end();)
2129 if (
auto p = i->second.lock())
2131 p->send(jvObj,
true);
2136 i = streamMap.erase(i);
2152 auto const signerPublic = val->getSignerPublic();
2154 jvObj[jss::type] =
"validationReceived";
2155 jvObj[jss::validation_public_key] =
2157 jvObj[jss::ledger_hash] =
to_string(val->getLedgerHash());
2158 jvObj[jss::signature] =
strHex(val->getSignature());
2159 jvObj[jss::full] = val->isFull();
2160 jvObj[jss::flags] = val->getFlags();
2162 jvObj[jss::data] =
strHex(val->getSerializer().slice());
2167 if (
auto cookie = (*val)[~
sfCookie])
2171 jvObj[jss::validated_hash] =
strHex(*hash);
2173 auto const masterKey =
2176 if (masterKey != signerPublic)
2180 jvObj[jss::ledger_index] =
to_string(*seq);
2185 for (
auto const& amendment : val->getFieldV256(
sfAmendments))
2190 jvObj[jss::close_time] = *closeTime;
2192 if (
auto const loadFee = (*val)[~
sfLoadFee])
2193 jvObj[jss::load_fee] = *loadFee;
2195 if (
auto const baseFee = val->at(~
sfBaseFee))
2196 jvObj[jss::base_fee] =
static_cast<double>(*baseFee);
2199 jvObj[jss::reserve_base] = *reserveBase;
2202 jvObj[jss::reserve_inc] = *reserveInc;
2207 baseFeeXRP && baseFeeXRP->native())
2208 jvObj[jss::base_fee] = baseFeeXRP->xrp().jsonClipped();
2211 reserveBaseXRP && reserveBaseXRP->native())
2212 jvObj[jss::reserve_base] = reserveBaseXRP->xrp().jsonClipped();
2215 reserveIncXRP && reserveIncXRP->native())
2216 jvObj[jss::reserve_inc] = reserveIncXRP->xrp().jsonClipped();
2221 if (
auto p = i->second.lock())
2223 p->send(jvObj,
true);
2243 jvObj[jss::type] =
"peerStatusChange";
2252 p->send(jvObj,
true);
2266 using namespace std::chrono_literals;
2298 <<
"recvValidation " << val->getLedgerHash() <<
" from " << source;
2328 "This server is amendment blocked, and must be updated to be "
2329 "able to stay in sync with the network.";
2336 "This server has an expired validator list. validators.txt "
2337 "may be incorrectly configured or some [validator_list_sites] "
2338 "may be unreachable.";
2345 "One or more unsupported amendments have reached majority. "
2346 "Upgrade to the latest version before they are activated "
2347 "to avoid being amendment blocked.";
2348 if (
auto const expected =
2352 d[jss::expected_date] = expected->time_since_epoch().count();
2353 d[jss::expected_date_UTC] =
to_string(*expected);
2357 if (warnings.size())
2358 info[jss::warnings] = std::move(warnings);
2373 info[jss::time] =
to_string(std::chrono::floor<std::chrono::microseconds>(
2377 info[jss::network_ledger] =
"waiting";
2379 info[jss::validation_quorum] =
2387 info[jss::node_size] =
"tiny";
2390 info[jss::node_size] =
"small";
2393 info[jss::node_size] =
"medium";
2396 info[jss::node_size] =
"large";
2399 info[jss::node_size] =
"huge";
2408 info[jss::validator_list_expires] =
2409 safe_cast<Json::UInt>(when->time_since_epoch().count());
2411 info[jss::validator_list_expires] = 0;
2421 if (*when == TimeKeeper::time_point::max())
2423 x[jss::expiration] =
"never";
2424 x[jss::status] =
"active";
2431 x[jss::status] =
"active";
2433 x[jss::status] =
"expired";
2438 x[jss::status] =
"unknown";
2439 x[jss::expiration] =
"unknown";
2443 info[jss::io_latency_ms] =
2450 info[jss::pubkey_validator] =
toBase58(
2455 info[jss::pubkey_validator] =
"none";
2468 info[jss::counters][jss::nodestore] = nodestore;
2472 info[jss::pubkey_node] =
2478 info[jss::amendment_blocked] =
true;
2493 lastClose[jss::converge_time_s] =
2498 lastClose[jss::converge_time] =
2502 info[jss::last_close] = lastClose;
2512 info[jss::network_id] =
static_cast<Json::UInt>(*netid);
2514 auto const escalationMetrics =
2522 auto const loadFactorFeeEscalation =
2524 escalationMetrics.openLedgerFeeLevel,
2526 escalationMetrics.referenceFeeLevel)
2530 safe_cast<std::uint64_t>(loadFactorServer),
2531 loadFactorFeeEscalation);
2535 info[jss::load_base] = loadBaseServer;
2536 info[jss::load_factor] =
trunc32(loadFactor);
2537 info[jss::load_factor_server] = loadFactorServer;
2544 info[jss::load_factor_fee_escalation] =
2545 escalationMetrics.openLedgerFeeLevel.jsonClipped();
2546 info[jss::load_factor_fee_queue] =
2547 escalationMetrics.minProcessingFeeLevel.jsonClipped();
2548 info[jss::load_factor_fee_reference] =
2549 escalationMetrics.referenceFeeLevel.jsonClipped();
2553 info[jss::load_factor] =
2554 static_cast<double>(loadFactor) / loadBaseServer;
2556 if (loadFactorServer != loadFactor)
2557 info[jss::load_factor_server] =
2558 static_cast<double>(loadFactorServer) / loadBaseServer;
2563 if (fee != loadBaseServer)
2564 info[jss::load_factor_local] =
2565 static_cast<double>(fee) / loadBaseServer;
2567 if (fee != loadBaseServer)
2568 info[jss::load_factor_net] =
2569 static_cast<double>(fee) / loadBaseServer;
2571 if (fee != loadBaseServer)
2572 info[jss::load_factor_cluster] =
2573 static_cast<double>(fee) / loadBaseServer;
2575 if (escalationMetrics.openLedgerFeeLevel !=
2576 escalationMetrics.referenceFeeLevel &&
2577 (admin || loadFactorFeeEscalation != loadFactor))
2578 info[jss::load_factor_fee_escalation] =
2579 escalationMetrics.openLedgerFeeLevel.decimalFromReference(
2580 escalationMetrics.referenceFeeLevel);
2581 if (escalationMetrics.minProcessingFeeLevel !=
2582 escalationMetrics.referenceFeeLevel)
2583 info[jss::load_factor_fee_queue] =
2584 escalationMetrics.minProcessingFeeLevel
2585 .decimalFromReference(
2586 escalationMetrics.referenceFeeLevel);
2600 XRPAmount const baseFee = lpClosed->fees().base;
2602 l[jss::seq] =
Json::UInt(lpClosed->info().seq);
2603 l[jss::hash] =
to_string(lpClosed->info().hash);
2608 l[jss::reserve_base] =
2609 lpClosed->fees().accountReserve(0).jsonClipped();
2610 l[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped();
2612 lpClosed->info().closeTime.time_since_epoch().count());
2617 l[jss::reserve_base_xrp] =
2618 lpClosed->fees().accountReserve(0).decimalXRP();
2619 l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP();
2622 std::abs(closeOffset.count()) >= 60)
2623 l[jss::close_time_offset] =
2626 #if RIPPLED_REPORTING
2636 Json::UInt(age < highAgeThreshold ? age.count() : 0);
2640 auto lCloseTime = lpClosed->info().closeTime;
2642 if (lCloseTime <= closeTime)
2644 using namespace std::chrono_literals;
2645 auto age = closeTime - lCloseTime;
2647 Json::UInt(age < highAgeThreshold ? age.count() : 0);
2654 info[jss::validated_ledger] = l;
2656 info[jss::closed_ledger] = l;
2660 info[jss::published_ledger] =
"none";
2661 else if (lpPublished->info().seq != lpClosed->info().seq)
2662 info[jss::published_ledger] = lpPublished->info().seq;
2669 info[jss::jq_trans_overflow] =
2671 info[jss::peer_disconnects] =
2673 info[jss::peer_disconnects_resources] =
2683 "http",
"https",
"peer",
"ws",
"ws2",
"wss",
"wss2"};
2691 !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() &&
2692 port.admin_user.empty() && port.admin_password.empty()))
2706 for (
auto const& p : proto)
2707 jv[jss::protocol].append(p);
2714 auto const optPort = grpcSection.
get(
"port");
2715 if (optPort && grpcSection.get(
"ip"))
2718 jv[jss::port] = *optPort;
2720 jv[jss::protocol].append(
"grpc");
2723 info[jss::ports] = std::move(ports);
2759 p->send(jvObj,
true);
2778 if (jvObj[jss::validated].asBool())
2790 p->send(jvObj,
true);
2811 if (
auto p = i->second.lock())
2813 p->send(jvObj,
true);
2831 if (
auto p = i->second.lock())
2833 p->send(jvObj,
true);
2846 for (
auto& jv : jvObj)
2852 else if (jv.isString())
2876 if (jvObj.
isMember(jss::transaction))
2885 << __func__ <<
" : "
2886 <<
"error parsing json for accounts affected";
2895 for (
auto const& affectedAccount : accounts)
2900 auto it = simiIt->second.begin();
2902 while (it != simiIt->second.end())
2913 it = simiIt->second.erase(it);
2920 <<
" iProposed=" << iProposed;
2922 if (!notify.
empty())
2925 isrListener->send(jvObj,
true);
2939 alpAccepted = std::make_shared<AcceptedLedger>(lpAccepted,
app_);
2941 lpAccepted->info().hash, alpAccepted);
2944 assert(alpAccepted->getLedger().
get() == lpAccepted.
get());
2948 <<
"Publishing ledger " << lpAccepted->info().seq <<
" "
2949 << lpAccepted->info().hash;
2957 jvObj[jss::type] =
"ledgerClosed";
2958 jvObj[jss::ledger_index] = lpAccepted->info().seq;
2959 jvObj[jss::ledger_hash] =
to_string(lpAccepted->info().hash);
2961 lpAccepted->info().closeTime.time_since_epoch().count());
2965 jvObj[jss::fee_base] = lpAccepted->fees().base.jsonClipped();
2966 jvObj[jss::reserve_base] =
2967 lpAccepted->fees().accountReserve(0).jsonClipped();
2968 jvObj[jss::reserve_inc] =
2969 lpAccepted->fees().increment.jsonClipped();
2971 jvObj[jss::txn_count] =
Json::UInt(alpAccepted->size());
2975 jvObj[jss::validated_ledgers] =
2985 p->send(jvObj,
true);
3003 p->send(jvObj,
true);
3012 static bool firstTime =
true;
3019 for (
auto& inner : outer.second)
3021 auto& subInfo = inner.second;
3022 if (subInfo.index_->separationLedgerSeq_ == 0)
3025 alpAccepted->getLedger(), subInfo);
3034 for (
auto const& accTx : *alpAccepted)
3038 lpAccepted, *accTx, accTx == *(--alpAccepted->end()));
3067 "reportConsensusStateChange->pubConsensus",
3086 const STTx& transaction,
3097 jvObj[jss::type] =
"transaction";
3102 jvObj[jss::ledger_index] = ledger->info().seq;
3103 jvObj[jss::ledger_hash] =
to_string(ledger->info().hash);
3104 jvObj[jss::transaction][jss::date] =
3105 ledger->info().closeTime.time_since_epoch().count();
3106 jvObj[jss::validated] =
true;
3112 jvObj[jss::validated] =
false;
3113 jvObj[jss::ledger_current_index] = ledger->info().seq;
3116 jvObj[jss::status] = validated ?
"closed" :
"proposed";
3117 jvObj[jss::engine_result] = sToken;
3118 jvObj[jss::engine_result_code] = result;
3119 jvObj[jss::engine_result_message] = sHuman;
3127 if (account != amount.issue().account)
3135 jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText();
3148 auto const& stTxn = transaction.
getTxn();
3154 auto const& meta = transaction.
getMeta();
3169 p->send(jvObj,
true);
3184 p->send(jvObj,
true);
3209 auto const currLedgerSeq = ledger->seq();
3216 for (
auto const& affectedAccount : transaction.
getAffected())
3221 auto it = simiIt->second.begin();
3223 while (it != simiIt->second.end())
3234 it = simiIt->second.erase(it);
3241 auto it = simiIt->second.begin();
3242 while (it != simiIt->second.end())
3253 it = simiIt->second.erase(it);
3260 auto& subs = histoIt->second;
3261 auto it = subs.begin();
3262 while (it != subs.end())
3265 if (currLedgerSeq <= info.index_->separationLedgerSeq_)
3279 it = subs.erase(it);
3290 <<
"pubAccountTransaction: "
3291 <<
"proposed=" << iProposed <<
", accepted=" << iAccepted;
3293 if (!notify.
empty() || !accountHistoryNotify.
empty())
3295 auto const& stTxn = transaction.
getTxn();
3301 auto const& meta = transaction.
getMeta();
3308 isrListener->send(jvObj,
true);
3311 jvObj[jss::account_history_boundary] =
true;
3313 assert(!jvObj.
isMember(jss::account_history_tx_stream));
3314 for (
auto& info : accountHistoryNotify)
3316 auto& index = info.index_;
3317 if (index->forwardTxIndex_ == 0 && !index->haveHistorical_)
3318 jvObj[jss::account_history_tx_first] =
true;
3319 jvObj[jss::account_history_tx_index] = index->forwardTxIndex_++;
3320 info.sink_->send(jvObj,
true);
3345 for (
auto const& affectedAccount : tx->getMentionedAccounts())
3350 auto it = simiIt->second.begin();
3352 while (it != simiIt->second.end())
3363 it = simiIt->second.erase(it);
3370 JLOG(
m_journal.
trace()) <<
"pubProposedAccountTransaction: " << iProposed;
3372 if (!notify.
empty() || !accountHistoryNotify.
empty())
3377 isrListener->send(jvObj,
true);
3379 assert(!jvObj.
isMember(jss::account_history_tx_stream));
3380 for (
auto& info : accountHistoryNotify)
3382 auto& index = info.index_;
3383 if (index->forwardTxIndex_ == 0 && !index->haveHistorical_)
3384 jvObj[jss::account_history_tx_first] =
true;
3385 jvObj[jss::account_history_tx_index] = index->forwardTxIndex_++;
3386 info.sink_->send(jvObj,
true);
3403 for (
auto const& naAccountID : vnaAccountIDs)
3406 <<
"subAccount: account: " <<
toBase58(naAccountID);
3408 isrListener->insertSubAccountInfo(naAccountID, rt);
3413 for (
auto const& naAccountID : vnaAccountIDs)
3415 auto simIterator = subMap.
find(naAccountID);
3416 if (simIterator == subMap.
end())
3420 usisElement[isrListener->getSeq()] = isrListener;
3422 subMap.
insert(simIterator, make_pair(naAccountID, usisElement));
3427 simIterator->second[isrListener->getSeq()] = isrListener;
3438 for (
auto const& naAccountID : vnaAccountIDs)
3441 isrListener->deleteSubAccountInfo(naAccountID, rt);
3458 for (
auto const& naAccountID : vnaAccountIDs)
3460 auto simIterator = subMap.
find(naAccountID);
3462 if (simIterator != subMap.
end())
3465 simIterator->second.erase(uSeq);
3467 if (simIterator->second.empty())
3470 subMap.
erase(simIterator);
3479 enum DatabaseType { Postgres, Sqlite, None };
3480 static const auto databaseType = [&]() -> DatabaseType {
3481 #ifdef RIPPLED_REPORTING
3488 return DatabaseType::Postgres;
3490 return DatabaseType::None;
3498 return DatabaseType::Sqlite;
3500 return DatabaseType::None;
3507 return DatabaseType::Sqlite;
3509 return DatabaseType::None;
3513 if (databaseType == DatabaseType::None)
3516 <<
"AccountHistory job for account "
3528 "AccountHistoryTxStream",
3529 [
this, dbType = databaseType, subInfo]() {
3530 auto const& accountId = subInfo.
index_->accountId_;
3531 auto& lastLedgerSeq = subInfo.
index_->historyLastLedgerSeq_;
3532 auto& txHistoryIndex = subInfo.
index_->historyTxIndex_;
3535 <<
"AccountHistory job for account " <<
toBase58(accountId)
3536 <<
" started. lastLedgerSeq=" << lastLedgerSeq;
3546 auto stx = tx->getSTransaction();
3547 if (stx->getAccountID(
sfAccount) == accountId &&
3548 stx->getSeqProxy().value() == 1)
3552 for (
auto& node : meta->getNodes())
3559 if (
auto inner =
dynamic_cast<const STObject*
>(
3564 inner->getAccountID(
sfAccount) == accountId)
3576 bool unsubscribe) ->
bool {
3579 sptr->send(jvObj,
true);
3605 auto [txResult, status] = db->getAccountTx(args);
3609 <<
"AccountHistory job for account "
3611 <<
" getAccountTx failed";
3616 std::get_if<RelationalDatabase::AccountTxs>(
3617 &txResult.transactions);
3625 <<
"AccountHistory job for account "
3627 <<
" getAccountTx wrong data";
3635 accountId, minLedger, maxLedger, marker, 0,
true};
3636 return db->newestAccountTxPage(options);
3648 while (lastLedgerSeq >= 2 && !subInfo.
index_->stopHistorical_)
3650 int feeChargeCount = 0;
3659 <<
"AccountHistory job for account "
3660 <<
toBase58(accountId) <<
" no InfoSub. Fee charged "
3661 << feeChargeCount <<
" times.";
3666 auto startLedgerSeq =
3667 (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2);
3669 <<
"AccountHistory job for account " <<
toBase58(accountId)
3670 <<
", working on ledger range [" << startLedgerSeq <<
","
3671 << lastLedgerSeq <<
"]";
3673 auto haveRange = [&]() ->
bool {
3676 auto haveSomeValidatedLedgers =
3678 validatedMin, validatedMax);
3680 return haveSomeValidatedLedgers &&
3681 validatedMin <= startLedgerSeq &&
3682 lastLedgerSeq <= validatedMax;
3688 <<
"AccountHistory reschedule job for account "
3689 <<
toBase58(accountId) <<
", incomplete ledger range ["
3690 << startLedgerSeq <<
"," << lastLedgerSeq <<
"]";
3696 while (!subInfo.
index_->stopHistorical_)
3699 getMoreTxns(startLedgerSeq, lastLedgerSeq, marker);
3703 <<
"AccountHistory job for account "
3704 <<
toBase58(accountId) <<
" getMoreTxns failed.";
3709 auto const& txns = dbResult->first;
3710 marker = dbResult->second;
3711 size_t num_txns = txns.size();
3712 for (
size_t i = 0; i < num_txns; ++i)
3714 auto const& [tx, meta] = txns[i];
3719 <<
"AccountHistory job for account "
3720 <<
toBase58(accountId) <<
" empty tx or meta.";
3730 <<
"AccountHistory job for account "
3731 <<
toBase58(accountId) <<
" no ledger.";
3736 tx->getSTransaction();
3740 <<
"AccountHistory job for account "
3742 <<
" getSTransaction failed.";
3747 *stTxn, meta->getResultTER(),
true, curTxLedger);
3749 jvTx[jss::account_history_tx_index] = txHistoryIndex--;
3751 if (i + 1 == num_txns ||
3752 txns[i + 1].first->getLedger() != tx->getLedger())
3753 jvTx[jss::account_history_boundary] =
true;
3756 jvTx[jss::meta], *curTxLedger, stTxn, *meta);
3757 if (isFirstTx(tx, meta))
3759 jvTx[jss::account_history_tx_first] =
true;
3763 <<
"AccountHistory job for account "
3765 <<
" done, found last tx.";
3777 <<
"AccountHistory job for account "
3779 <<
" paging, marker=" << marker->ledgerSeq <<
":"
3788 if (!subInfo.
index_->stopHistorical_)
3790 lastLedgerSeq = startLedgerSeq - 1;
3791 if (lastLedgerSeq <= 1)
3794 <<
"AccountHistory job for account "
3796 <<
" done, reached genesis ledger.";
3809 subInfo.
index_->separationLedgerSeq_ = ledger->seq();
3810 auto const& accountId = subInfo.
index_->accountId_;
3812 if (!ledger->exists(accountKeylet))
3815 <<
"subAccountHistoryStart, no account " <<
toBase58(accountId)
3816 <<
", no need to add AccountHistory job.";
3821 if (
auto const sleAcct = ledger->read(accountKeylet); sleAcct)
3826 <<
"subAccountHistoryStart, genesis account "
3828 <<
" does not have tx, no need to add AccountHistory job.";
3838 subInfo.
index_->historyLastLedgerSeq_ = ledger->seq();
3839 subInfo.
index_->haveHistorical_ =
true;
3842 <<
"subAccountHistoryStart, add AccountHistory job: accountId="
3843 <<
toBase58(accountId) <<
", currentLedgerSeq=" << ledger->seq();
3853 if (!isrListener->insertSubAccountHistory(accountId))
3856 <<
"subAccountHistory, already subscribed to account "
3863 isrListener, std::make_shared<SubAccountHistoryIndex>(accountId)};
3868 inner.
emplace(isrListener->getSeq(), ahi);
3874 simIterator->second.emplace(isrListener->getSeq(), ahi);
3888 <<
"subAccountHistory, no validated ledger yet, delay start";
3901 isrListener->deleteSubAccountHistory(account);
3915 auto& subInfoMap = simIterator->second;
3916 auto subInfoIter = subInfoMap.find(seq);
3917 if (subInfoIter != subInfoMap.end())
3919 subInfoIter->second.index_->stopHistorical_ =
true;
3924 simIterator->second.erase(seq);
3925 if (simIterator->second.empty())
3931 <<
"unsubAccountHistory, account " <<
toBase58(account)
3932 <<
", historyOnly = " << (historyOnly ?
"true" :
"false");
3940 listeners->addSubscriber(isrListener);
3950 listeners->removeSubscriber(uSeq);
3964 Throw<std::runtime_error>(
3965 "Operation only possible in STANDALONE mode.");
3980 jvResult[jss::ledger_index] = lpClosed->info().seq;
3981 jvResult[jss::ledger_hash] =
to_string(lpClosed->info().hash);
3983 lpClosed->info().closeTime.time_since_epoch().count());
3986 jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped();
3987 jvResult[jss::reserve_base] =
3988 lpClosed->fees().accountReserve(0).jsonClipped();
3989 jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped();
3994 jvResult[jss::validated_ledgers] =
4000 .emplace(isrListener->getSeq(), isrListener)
4010 .emplace(isrListener->getSeq(), isrListener)
4036 .emplace(isrListener->getSeq(), isrListener)
4064 jvResult[jss::random] =
to_string(uRandom);
4066 jvResult[jss::load_base] = feeTrack.getLoadBase();
4067 jvResult[jss::load_factor] = feeTrack.getLoadFactor();
4068 jvResult[jss::hostid] =
getHostId(admin);
4069 jvResult[jss::pubkey_node] =
4074 .emplace(isrListener->getSeq(), isrListener)
4092 .emplace(isrListener->getSeq(), isrListener)
4110 .emplace(isrListener->getSeq(), isrListener)
4128 .emplace(isrListener->getSeq(), isrListener)
4152 .emplace(isrListener->getSeq(), isrListener)
4170 .emplace(isrListener->getSeq(), isrListener)
4218 if (map.find(pInfo->getSeq()) != map.end())
4225 #ifndef USE_NEW_BOOK_PAGE
4236 unsigned int iLimit,
4246 uint256 uTipIndex = uBookBase;
4250 stream <<
"getBookPage:" << book;
4251 stream <<
"getBookPage: uBookBase=" << uBookBase;
4252 stream <<
"getBookPage: uBookEnd=" << uBookEnd;
4253 stream <<
"getBookPage: uTipIndex=" << uTipIndex;
4262 bool bDirectAdvance =
true;
4266 unsigned int uBookEntry;
4272 while (!bDone && iLimit-- > 0)
4276 bDirectAdvance =
false;
4280 auto const ledgerIndex = view.
succ(uTipIndex, uBookEnd);
4284 sleOfferDir.
reset();
4293 uTipIndex = sleOfferDir->key();
4296 cdirFirst(view, uTipIndex, sleOfferDir, uBookEntry, offerIndex);
4299 <<
"getBookPage: uTipIndex=" << uTipIndex;
4301 <<
"getBookPage: offerIndex=" << offerIndex;
4311 auto const uOfferOwnerID = sleOffer->getAccountID(
sfAccount);
4312 auto const& saTakerGets = sleOffer->getFieldAmount(
sfTakerGets);
4313 auto const& saTakerPays = sleOffer->getFieldAmount(
sfTakerPays);
4315 bool firstOwnerOffer(
true);
4321 saOwnerFunds = saTakerGets;
4323 else if (bGlobalFreeze)
4331 auto umBalanceEntry = umBalance.
find(uOfferOwnerID);
4332 if (umBalanceEntry != umBalance.
end())
4336 saOwnerFunds = umBalanceEntry->second;
4337 firstOwnerOffer =
false;
4351 if (saOwnerFunds < beast::zero)
4355 saOwnerFunds.
clear();
4363 STAmount saOwnerFundsLimit = saOwnerFunds;
4375 saOwnerFundsLimit =
divide(saOwnerFunds, offerRate);
4378 if (saOwnerFundsLimit >= saTakerGets)
4381 saTakerGetsFunded = saTakerGets;
4387 saTakerGetsFunded = saOwnerFundsLimit;
4389 saTakerGetsFunded.
setJson(jvOffer[jss::taker_gets_funded]);
4393 saTakerGetsFunded, saDirRate, saTakerPays.
issue()))
4394 .setJson(jvOffer[jss::taker_pays_funded]);
4400 saOwnerFunds,
multiply(saTakerGetsFunded, offerRate));
4402 umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays;
4406 jvOf[jss::quality] = saDirRate.
getText();
4408 if (firstOwnerOffer)
4409 jvOf[jss::owner_funds] = saOwnerFunds.
getText();
4416 if (!
cdirNext(view, uTipIndex, sleOfferDir, uBookEntry, offerIndex))
4418 bDirectAdvance =
true;
4423 <<
"getBookPage: offerIndex=" << offerIndex;
4443 unsigned int iLimit,
4451 MetaView lesActive(lpLedger,
tapNONE,
true);
4452 OrderBookIterator obIterator(lesActive, book);
4456 const bool bGlobalFreeze = lesActive.isGlobalFrozen(book.
out.
account) ||
4457 lesActive.isGlobalFrozen(book.
in.
account);
4459 while (iLimit-- > 0 && obIterator.nextOffer())
4464 auto const uOfferOwnerID = sleOffer->getAccountID(
sfAccount);
4465 auto const& saTakerGets = sleOffer->getFieldAmount(
sfTakerGets);
4466 auto const& saTakerPays = sleOffer->getFieldAmount(
sfTakerPays);
4467 STAmount saDirRate = obIterator.getCurrentRate();
4473 saOwnerFunds = saTakerGets;
4475 else if (bGlobalFreeze)
4483 auto umBalanceEntry = umBalance.
find(uOfferOwnerID);
4485 if (umBalanceEntry != umBalance.
end())
4489 saOwnerFunds = umBalanceEntry->second;
4495 saOwnerFunds = lesActive.accountHolds(
4501 if (saOwnerFunds.isNegative())
4505 saOwnerFunds.zero();
4512 STAmount saTakerGetsFunded;
4513 STAmount saOwnerFundsLimit = saOwnerFunds;
4525 saOwnerFundsLimit =
divide(saOwnerFunds, offerRate);
4528 if (saOwnerFundsLimit >= saTakerGets)
4531 saTakerGetsFunded = saTakerGets;
4536 saTakerGetsFunded = saOwnerFundsLimit;
4538 saTakerGetsFunded.setJson(jvOffer[jss::taker_gets_funded]);
4544 multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue()))
4545 .setJson(jvOffer[jss::taker_pays_funded]);
4548 STAmount saOwnerPays = (
parityRate == offerRate)
4551 saOwnerFunds,
multiply(saTakerGetsFunded, offerRate));
4553 umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays;
4555 if (!saOwnerFunds.isZero() || uOfferOwnerID == uTakerID)
4559 jvOf[jss::quality] = saDirRate.
getText();
4574 auto const current = std::chrono::duration_cast<std::chrono::microseconds>(
4614 ++counters_[
static_cast<std::size_t>(om)].transitions;
4616 counters_[
static_cast<std::size_t>(om)].transitions == 1)
4618 initialSyncUs_ = std::chrono::duration_cast<std::chrono::microseconds>(
4619 now - processStart_)
4623 std::chrono::duration_cast<std::chrono::microseconds>(now - start_);
4632 auto [counters, mode, start, initialSync] = getCounterData();
4633 auto const current = std::chrono::duration_cast<std::chrono::microseconds>(
4643 auto& state = obj[jss::state_accounting][
states_[i]];
4644 state[jss::transitions] =
std::to_string(counters[i].transitions);
4645 state[jss::duration_us] =
std::to_string(counters[i].dur.count());
4649 obj[jss::initial_sync_duration_us] =
std::to_string(initialSync);
4664 boost::asio::io_service& io_svc,
4668 return std::make_unique<NetworkOPsImp>(
void forwardManifest(Json::Value const &jvObj) override
bool unsubValidations(std::uint64_t uListener) override
beast::insight::Hook hook
TxType getTxnType() const
bool subValidations(InfoSub::ref ispListener) override
void processHeartbeatTimer()
Provides server functionality for clients.
const SF_UINT64 sfIndexNext
std::uint32_t historyLastLedgerSeq_
bool getValidatedRange(std::uint32_t &minVal, std::uint32_t &maxVal)
ConsensusPhase phase() const
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
void mapComplete(std::shared_ptr< SHAMap > const &map, bool fromAcquire) override
Rate transferRate(ReadView const &view, AccountID const &issuer)
bool cdirNext(ReadView const &view, uint256 const &root, std::shared_ptr< SLE const > &page, unsigned int &index, uint256 &entry)
Returns the next entry in the directory, advancing the index.
bool unsubConsensus(std::uint64_t uListener) override
std::string domain
The domain, if one was specified in the manifest; empty otherwise.
virtual OrderBookDB & getOrderBookDB()=0
void setTimerDelay(std::optional< std::chrono::milliseconds > td=std::nullopt)
A peer's signed, proposed position for use in RCLConsensus.
@ ledgerMaster
ledger master data for signing
bool processTrustedProposal(RCLCxPeerPos proposal) override
void setAccountHistoryJobTimer(SubAccountHistoryInfoWeak subInfo)
const SF_AMOUNT sfBaseFeeDrops
virtual Json::Value getInfo()=0
void stateAccounting(Json::Value &obj) override
SubmitSync
Possible values for defining synchronous behavior of the transaction submission API.
const SF_UINT32 sfReserveBase
virtual Cluster & cluster()=0
std::shared_ptr< ReadView const > getPublishedLedger()
std::optional< Dest > mulDiv(Source1 value, Dest mul, Source2 div)
const uint256 featureXRPFees
virtual TaggedCache< uint256, AcceptedLedger > & getAcceptedLedgerCache()=0
std::shared_ptr< OpenView const > current() const
Returns a view to the current open ledger.
ServerFeeSummary mLastFeeSummary
PublicKey localPublicKey() const
Returns local validator public key.
const std::chrono::steady_clock::time_point processStart_
@ proposing
We are normal participant in consensus and propose our position.
boost::asio::steady_timer heartbeatTimer_
PublicKey getMasterKey(PublicKey const &pk) const
Returns ephemeral signing key's master public key.
Json::Value getJson(bool full) const
const std::size_t minPeerCount_
Json::Value rpcError(int iError)
Represents a transfer rate.
void setStateTimer() override
Called to initially start our timers.
void startRound(NetClock::time_point const &now, RCLCxLedger::ID const &prevLgrId, RCLCxLedger const &prevLgr, hash_set< NodeID > const &nowUntrusted, hash_set< NodeID > const &nowTrusted)
Adjust the set of trusted validators and kick-off the next round of consensus.
void json(Json::Value &obj) const
Output state counters in JSON format.
Stream trace() const
Severity stream access functions.
const SF_UINT32 sfLedgerSequence
std::shared_ptr< STTx const > const & getTxn() const
void pubAccountTransaction(std::shared_ptr< ReadView const > const &ledger, AcceptedLedgerTx const &transaction, bool last)
Issue const & issue() const
int getFlags(uint256 const &key)
const Charge feeMediumBurdenRPC
Changes in trusted nodes after updating validator list.
Data format for exchanging consumption information across peers.
void setAmendmentWarned() override
void pubManifest(Manifest const &) override
bool subPeerStatus(InfoSub::ref ispListener) override
DispatchState mDispatchState
@ arrayValue
array value (ordered list)
void setBatchApplyTimer() override
std::pair< TER, bool > apply(Application &app, OpenView &view, std::shared_ptr< STTx const > const &tx, ApplyFlags flags, beast::Journal j)
Add a new transaction to the open ledger, hold it in the queue, or reject it.
virtual std::uint64_t getJqTransOverflow() const =0
SubInfoMapType mSubRTAccount
std::atomic< bool > amendmentWarned_
static const std::array< char const *, 5 > states_
const SF_UINT32 sfSequence
@ wrongLedger
We have the wrong ledger and are attempting to acquire it.
LedgerIndex getValidLedgerIndex()
virtual AmendmentTable & getAmendmentTable()=0
void setMode(OperatingMode om) override
std::string const & name() const
Writable ledger view that accumulates state and tx changes.
Decorator for streaming out compact json.
uint256 getBookBase(Book const &book)
std::chrono::microseconds dur
PublicKey signingKey
The ephemeral key associated with this manifest.
void pubProposedAccountTransaction(std::shared_ptr< ReadView const > const &ledger, std::shared_ptr< STTx const > const &transaction, TER result)
bool isUNLBlocked() override
std::string serialized
The manifest in serialized form.
void trustChanged(hash_set< NodeID > const &added, hash_set< NodeID > const &removed)
Update trust status of validations.
void setNeedNetworkLedger() override
bool tryRemoveRpcSub(std::string const &strUrl) override
PublicKey masterKey
The master key associated with this manifest.
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j)
bool empty() const noexcept
std::string getText() const override
bool recvValidation(std::shared_ptr< STValidation > const &val, std::string const &source) override
T back_inserter(T... args)
void setNegativeUNL(hash_set< PublicKey > const &negUnl)
set the Negative UNL with validators' master public keys
std::string getHostId(bool forAdmin)
void gotTxSet(NetClock::time_point const &now, RCLTxSet const &txSet)
void forwardProposedTransaction(Json::Value const &jvObj) override
QuorumKeys getQuorumKeys() const
Get the quorum and all of the trusted keys.
boost::asio::steady_timer batchApplyTimer_
This timer is for applying transaction batches.
virtual void trustChanged(hash_set< PublicKey > const &allTrusted)=0
csprng_engine & crypto_prng()
The default cryptographically secure PRNG.
Keylet offer(AccountID const &id, std::uint32_t seq) noexcept
An offer from an account.
Rules getValidatedRules()
Json::Value getJson(int c=0)
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
beast::insight::Gauge disconnected_duration
constexpr auto muldiv_max
void switchLCL(std::shared_ptr< Ledger const > const &lastClosed)
Keylet child(uint256 const &key) noexcept
Any item that can be in an owner dir.
void consensusViewChange() override
Json::Value computeBookChanges(std::shared_ptr< L const > const &lpAccepted)
std::chrono::seconds closeOffset() const
StateAccounting accounting_
std::chrono::milliseconds ledgerGRANULARITY
How often we check state or change positions.
void unsubAccountHistoryInternal(std::uint64_t seq, AccountID const &account, bool historyOnly) override
virtual NodeStore::DatabaseShard * getShardStore()=0
const SF_UINT32 sfCloseTime
std::shared_ptr< SubAccountHistoryIndex > index_
std::shared_ptr< Ledger const > getLedgerByHash(uint256 const &hash)
void timerEntry(NetClock::time_point const &now)
virtual std::size_t size() const =0
Returns the number of active peers.
void apply(std::unique_lock< std::mutex > &batchLock)
Attempt to apply transactions and post-process based on the results.
bool addJob(JobType type, std::string const &name, JobHandler &&jobHandler)
Adds a job to the JobQueue.
std::unique_ptr< NetworkOPs > make_NetworkOPs(Application &app, NetworkOPs::clock_type &clock, bool standalone, std::size_t minPeerCount, bool startvalid, JobQueue &job_queue, LedgerMaster &ledgerMaster, ValidatorKeys const &validatorKeys, boost::asio::io_service &io_svc, beast::Journal journal, beast::insight::Collector::ptr const &collector)
beast::insight::Gauge syncing_transitions
std::uint32_t getLoadBase() const
std::atomic< bool > unlBlocked_
SubAccountHistoryIndex(AccountID const &accountId)
uint256 getQualityNext(uint256 const &uBase)
virtual TimeKeeper & timeKeeper()=0
virtual MutexType & getMasterMutex()=0
void forwardProposedAccountTransaction(Json::Value const &jvObj) override
virtual OpenLedger & openLedger()=0
void pubLedger(std::shared_ptr< ReadView const > const &lpAccepted) override
bool update(PublicKey const &identity, std::string name, std::uint32_t loadFee=0, NetClock::time_point reportTime=NetClock::time_point{})
Store information about the state of a cluster node.
void switchLastClosedLedger(std::shared_ptr< Ledger const > const &newLCL)
void setUNLBlocked() override
Structure returned by TxQ::getMetrics, expressed in reference fee level units.
Wraps a ledger instance for use in generic Validations LedgerTrie.
void accept(Application &app, Rules const &rules, std::shared_ptr< Ledger const > const &ledger, OrderedTxs const &locals, bool retriesFirst, OrderedTxs &retries, ApplyFlags flags, std::string const &suffix="", modify_type const &f={})
Accept a new ledger.
time_point closeTime() const
Returns the predicted close time, in network time.
const Rate parityRate(QUALITY_ONE)
A transfer rate signifying a 1:1 exchange.
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
Validator keys and manifest as set in configuration file.
virtual InboundLedgers & getInboundLedgers()=0
virtual LoadFeeTrack & getFeeTrack()=0
constexpr static std::size_t size()
std::string getCompleteLedgers()
@ ltDIR_NODE
A ledger object which contains a list of object identifiers.
Sends a message to all peers.
@ SYNCING
fallen slightly behind
void processClusterTimer()
bool unsubTransactions(std::uint64_t uListener) override
void const * data() const noexcept
const SF_VECTOR256 sfIndexes
void simulate(NetClock::time_point const &now, std::optional< std::chrono::milliseconds > consensusDelay)
virtual Gossip exportConsumers()=0
Extract packaged consumer information for export.
std::recursive_mutex & peekMutex()
std::uint32_t loadFactorServer
STAmount divide(STAmount const &amount, Rate const &rate)
~NetworkOPsImp() override
std::uint32_t getRemoteFee() const
const SF_UINT256 sfValidatedHash
std::optional< std::chrono::milliseconds > getTimerDelay() const
Integers of any length that is a multiple of 32-bits.
const SF_AMOUNT sfTakerPays
static void getAccounts(Json::Value const &jvObj, std::vector< AccountID > &accounts)
Manages the generic consensus algorithm for use by the RCL.
@ warnRPC_AMENDMENT_BLOCKED
T time_since_epoch(T... args)
bool isGlobalFrozen(ReadView const &view, AccountID const &issuer)
beast::insight::Gauge syncing_duration
bool isAmendmentBlocked() override
InfoSub::pointer addRpcSub(std::string const &strUrl, InfoSub::ref) override
void forwardValidation(Json::Value const &jvObj) override
@ ltOFFER
A ledger object which describes an offer on the DEX.
Value & append(const Value &value)
Append value to array at the end.
virtual ReportingETL & getReportingETL()=0
@ DISCONNECTED
not ready to process requests
void clearAmendmentWarned() override
void setJson(Json::Value &) const
void subAccountHistoryStart(std::shared_ptr< ReadView const > const &ledger, SubAccountHistoryInfoWeak &subInfo)
void processTxn(std::shared_ptr< ReadView const > const &ledger, const AcceptedLedgerTx &alTx, Json::Value const &jvObj)
virtual std::chrono::milliseconds getIOLatency()=0
Json::Value getOwnerInfo(std::shared_ptr< ReadView const > lpLedger, AccountID const &account) override
const SF_UINT64 sfServerVersion
std::pair< Validity, std::string > checkValidity(HashRouter &router, STTx const &tx, Rules const &rules, Config const &config)
Checks transaction signature and local checks.
void reportFeeChange() override
std::uint32_t getLocalFee() const
@ CONNECTED
convinced we are talking to the network
std::uint64_t transitions
virtual LoadManager & getLoadManager()=0
std::shared_ptr< InfoSub > pointer
@ objectValue
object value (collection of name/value pairs).
constexpr double decimalXRP() const
const SF_UINT32 sfLoadFee
virtual LedgerMaster & getLedgerMaster()=0
void addAccountHistoryJob(SubAccountHistoryInfoWeak subInfo)
bool isBlocked() override
virtual std::shared_ptr< Ledger const > acquire(uint256 const &hash, std::uint32_t seq, InboundLedger::Reason)=0
Keylet account(AccountID const &id) noexcept
AccountID root.
bool peerProposal(NetClock::time_point const &now, RCLCxPeerPos const &newProposal)
@ TRACKING
convinced we agree with the network
std::uint32_t separationLedgerSeq_
AccountID getAccountID(SField const &field) const
const SF_UINT32 sfReserveIncrement
void setTimer(boost::asio::steady_timer &timer, std::chrono::milliseconds const &expiry_time, std::function< void()> onExpire, std::function< void()> onError)
DispatchState
Synchronization states for transaction batches.
virtual Config & config()=0
Select all peers (except optional excluded) that are in our cluster.
std::chrono::steady_clock::time_point start_
hash_set< NodeID > removed
Represents a set of transactions in RCLConsensus.
Keylet page(uint256 const &key, std::uint64_t index) noexcept
A page in a directory.
void endConsensus() override
std::optional< AccountTxMarker > marker
TrustChanges updateTrusted(hash_set< NodeID > const &seenValidators, NetClock::time_point closeTime, NetworkOPs &ops, Overlay &overlay, HashRouter &hashRouter)
Update trusted nodes.
AccountID calcAccountID(PublicKey const &pk)
void unsubAccount(InfoSub::ref ispListener, hash_set< AccountID > const &vnaAccountIDs, bool rt) override
virtual RelationalDatabase & getRelationalDatabase()=0
virtual std::pair< PublicKey, SecretKey > const & nodeIdentity()=0
bool canBeCurrent(std::shared_ptr< Ledger const > const &ledger)
Check the sequence number and parent close time of a ledger against our clock and last validated ledg...
bool unsubRTTransactions(std::uint64_t uListener) override
Manages the current fee schedule.
std::optional< Blob > getSignature() const
Returns manifest signature.
virtual JobQueue & getJobQueue()=0
bool subManifests(InfoSub::ref ispListener) override
A transaction that is in a closed ledger.
virtual std::optional< NetClock::time_point > firstUnsupportedExpected() const =0
std::vector< Item > items
const std::shared_ptr< Transaction > transaction
void clearUNLBlocked() override
FeeAndSeq getTxRequiredFeeAndSeq(OpenView const &view, std::shared_ptr< STTx const > const &tx) const
Returns minimum required fee for tx and two sequences: first vaild sequence for this account in curre...
Server fees published on server subscription.
std::unique_ptr< LocalTxs > m_localTX
NetworkOPsImp(Application &app, NetworkOPs::clock_type &clock, bool standalone, std::size_t minPeerCount, bool start_valid, JobQueue &job_queue, LedgerMaster &ledgerMaster, ValidatorKeys const &validatorKeys, boost::asio::io_service &io_svc, beast::Journal journal, beast::insight::Collector::ptr const &collector)
ConsensusPhase
Phases of consensus for a single ledger round.
@ warnRPC_EXPIRED_VALIDATOR_LIST
bool isCompatible(ReadView const &, beast::Journal::Stream, char const *reason)
std::string const & getVersionString()
Server version.
const SF_AMOUNT sfTakerGets
bool subBookChanges(InfoSub::ref ispListener) override
FeeSetup setup_FeeVote(Section const §ion)
std::shared_ptr< Ledger const > getLedgerBySeq(std::uint32_t index)
ConsensusMode mode() const
boost::container::flat_set< AccountID > const & getAffected() const
virtual PeerSequence getActivePeers() const =0
Returns a sequence representing the current list of peers.
decltype(counters_) counters
beast::insight::Gauge tracking_duration
@ warnRPC_UNSUPPORTED_MAJORITY
bool subTransactions(InfoSub::ref ispListener) override
@ current
This was a new validation and was added.
The role of a ClosureCounter is to assist in shutdown by letting callers wait for the completion of c...
std::array< Counters, 5 > counters_
bool isMember(const char *key) const
Return true if the object has a member named key.
bool unsubLedger(std::uint64_t uListener) override
A generic endpoint for log messages.
bool isAmendmentWarned() override
virtual RCLValidations & getValidations()=0
virtual std::set< Peer::id_t > relay(protocol::TMProposeSet &m, uint256 const &uid, PublicKey const &validator)=0
Relay a proposal.
std::atomic< bool > needNetworkLedger_
virtual std::optional< key_type > succ(key_type const &key, std::optional< key_type > const &last=std::nullopt) const =0
Return the key of the next state item.
std::optional< std::set< PeerShortID > > shouldRelay(uint256 const &key)
Determines whether the hashed item should be relayed.
void addHeldTransaction(std::shared_ptr< Transaction > const &trans)
Blob getMasterSignature() const
Returns manifest master key signature.
void foreach(Function f) const
Visit every active peer.
ServerFeeSummary()=default
std::uint32_t getClusterFee() const
ClosedInterval< T > range(T low, T high)
Create a closed range interval.
virtual PublicKey const & getValidationPublicKey() const =0
void pubValidation(std::shared_ptr< STValidation > const &val) override
STAmount amountFromQuality(std::uint64_t rate)
BookListeners::pointer makeBookListeners(Book const &)
void processClosedLedger(Application &app, ReadView const &view, bool timeLeap)
Update fee metrics and clean up the queue in preparation for the next ledger.
const SF_AMOUNT sfReserveIncrementDrops
void subAccount(InfoSub::ref ispListener, hash_set< AccountID > const &vnaAccountIDs, bool rt) override
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< ReadView const > getCurrentLedger()
time_point now() const override
Returns the current time, using the server's clock.
ConsensusParms const & parms() const
std::size_t size() const
The number of nodes in the cluster list.
decltype(initialSyncUs_) initialSyncUs
Json::Value getJson(JsonOptions options) const override
const SF_AMOUNT sfReserveBaseDrops
static constexpr std::uint32_t FEE_UNITS_DEPRECATED
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
@ ttOFFER_CREATE
This transaction type creates an offer to trade one asset for another.
std::int32_t historyTxIndex_
Transaction with input flags and results to be applied in batches.
virtual ValidatorList & validators()=0
A metric for measuring an integral value.
bool isNeedNetworkLedger() override
void resetDeadlockDetector()
Reset the deadlock detection timer.
bool operator!=(ServerFeeSummary const &b) const
std::array< SubMapType, SubTypes::sLastEntry > mStreamMaps
TransactionStatus(std::shared_ptr< Transaction > t, bool a, bool l, FailHard f)
void setStandAlone() override
A pool of threads to perform work.
std::recursive_mutex mSubLock
std::optional< TimeKeeper::time_point > expires() const
Return the time when the validator list will expire.
bool operator==(ServerFeeSummary const &b) const
STAmount multiply(STAmount const &amount, Rate const &rate)
BookListeners::pointer getBookListeners(Book const &)
std::uint32_t forwardTxIndex_
std::uint32_t sequence
The sequence number of this manifest.
virtual Resource::Manager & getResourceManager()=0
std::size_t getFetchPackCacheSize() const
Json::Value getJson(LedgerFill const &fill)
Return a new Json::Value representing the ledger with given options.
const SF_UINT64 sfBaseFee
beast::insight::Gauge tracking_transitions
bool haveValidated()
Whether we have ever fully validated a ledger.
std::chrono::seconds getValidatedLedgerAge()
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
std::shared_ptr< Ledger const > getClosedLedger()
beast::insight::Gauge connected_transitions
boost::asio::steady_timer clusterTimer_
virtual Json::Value countersJson() const =0
Render performance counters in Json.
std::vector< TransactionStatus > mTransactions
void reportConsensusStateChange(ConsensusPhase phase)
T emplace_back(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
bool transResultInfo(TER code, std::string &token, std::string &text)
bool unsubServer(std::uint64_t uListener) override
std::chrono::milliseconds prevRoundTime() const
Get duration of the previous round.
void processTransaction(std::shared_ptr< Transaction > &transaction, bool bUnlimited, RPC::SubmitSync sync, bool bLocal, FailHard failType) override
Process a transaction.
std::shared_ptr< STTx const > sterilize(STTx const &stx)
Sterilize a transaction.
std::unordered_set< uint256, beast::uhash<> > features
Stats(Handler const &handler, beast::insight::Collector::ptr const &collector)
bool unsubBookChanges(std::uint64_t uListener) override
virtual NodeStore::Database & getNodeStore()=0
virtual beast::Journal journal(std::string const &name)=0
virtual ManifestCache & validatorManifests()=0
virtual ServerHandler & getServerHandler()=0
std::size_t getLocalTxCount() override
std::uint64_t initialSyncUs_
std::size_t size() const noexcept
std::uint32_t getLoadFactor() const
Json::Value getLedgerFetchInfo() override
const SF_UINT16 sfLedgerEntryType
@ Valid
Signature and local checks are good / passed.
bool unsubBook(std::uint64_t uListener, Book const &) override
void canonicalize(std::shared_ptr< Transaction > *pTransaction)
std::uint32_t acceptLedger(std::optional< std::chrono::milliseconds > consensusDelay) override
Accepts the current transaction tree, return the new ledger's sequence.
SubInfoMapType mSubAccount
std::string SERVER_DOMAIN
void pubValidatedTransaction(std::shared_ptr< ReadView const > const &ledger, AcceptedLedgerTx const &transaction, bool last)
TxMeta const & getMeta() const
void clearNeedNetworkLedger() override
void rngfill(void *buffer, std::size_t bytes, Generator &g)
Lightweight wrapper to tag static string.
const uint256 featureNegativeUNL
@ ltACCOUNT_ROOT
A ledger object which describes an account.
bool checkLastClosedLedger(const Overlay::PeerSequence &, uint256 &networkClosed)
std::string strOperatingMode(OperatingMode const mode, bool const admin) const override
void getBookPage(std::shared_ptr< ReadView const > &lpLedger, Book const &, AccountID const &uTakerID, const bool bProof, unsigned int iLimit, Json::Value const &jvMarker, Json::Value &jvResult) override
void insertDeliveredAmount(Json::Value &meta, ReadView const &, std::shared_ptr< STTx const > const &serializedTx, TxMeta const &)
Add a delivered_amount field to the meta input/output parameter.
void pubPeerStatus(std::function< Json::Value(void)> const &) override
std::condition_variable mCond
void getCountsJson(Json::Value &obj)
LedgerIndex getCurrentLedgerIndex()
bool subLedger(InfoSub::ref ispListener, Json::Value &jvResult) override
beast::insight::Gauge full_transitions
int RELAY_UNTRUSTED_VALIDATIONS
static const std::array< char const *, 5 > stateNames
error_code_i subAccountHistory(InfoSub::ref ispListener, AccountID const &account) override
subscribe an account's new transactions and retrieve the account's historical transactions
std::size_t prevProposers() const
Get the number of proposing peers that participated in the previous round.
virtual Overlay & overlay()=0
std::atomic< OperatingMode > mMode
std::shared_ptr< Ledger const > getValidatedLedger()
bool unsubManifests(std::uint64_t uListener) override
std::optional< T > get(std::string const &name) const
Rules makeRulesGivenLedger(DigestAwareReadView const &ledger, Rules const ¤t)
std::atomic< bool > amendmentBlocked_
void submitTransaction(std::shared_ptr< STTx const > const &) override
OperatingMode
Specifies the mode under which the server believes it's operating.
virtual std::optional< std::uint32_t > networkID() const =0
Returns the ID of the network this server is configured for, if any.
virtual void clearFailures()=0
Json::Value transJson(const STTx &transaction, TER result, bool validated, std::shared_ptr< ReadView const > const &ledger)
void join(char const *name, std::chrono::milliseconds wait, beast::Journal j)
Returns once all counted in-flight closures are destroyed.
ConsensusPhase mLastConsensusPhase
void updateLocalTx(ReadView const &view) override
void pubConsensus(ConsensusPhase phase)
std::string to_string(Manifest const &m)
Format the specified manifest to a string for debugging purposes.
void for_each(std::function< void(ClusterNode const &)> func) const
Invokes the callback once for every cluster node.
bool subRTTransactions(InfoSub::ref ispListener) override
NetClock::time_point getReportTime() const
beast::insight::Gauge disconnected_transitions
static const auto genesisAccountId
const SF_ACCOUNT sfAccount
void pubProposedTransaction(std::shared_ptr< ReadView const > const &ledger, std::shared_ptr< STTx const > const &transaction, TER result) override
@ ltRIPPLE_STATE
A ledger object which describes a bidirectional trust line.
std::string strHex(FwdIt begin, FwdIt end)
Json::Value getServerInfo(bool human, bool admin, bool counters) override
virtual Json::Value currentJson() const =0
Render currently executing jobs and RPC calls and durations in Json.
LedgerMaster & m_ledgerMaster
bool subServer(InfoSub::ref ispListener, Json::Value &jvResult, bool admin) override
auto getCurrentNodeIDs() -> hash_set< NodeID >
Get the set of node ids associated with current validations.
std::shared_ptr< SubAccountHistoryIndex > index_
std::optional< LedgerSpecifier > ledger
boost::asio::steady_timer accountHistoryTxTimer_
@ SigBad
Signature is bad. Didn't do local checks.
bool validating() const
Whether we are validating consensus ledgers.
std::unique_ptr< LocalTxs > make_LocalTxs()
Metrics getMetrics(OpenView const &view) const
Returns fee metrics in reference fee level units.
void setup(Setup const &setup, beast::Journal journal)
CounterData getCounterData() const
std::unique_ptr< LoadEvent > makeLoadEvent(JobType t, std::string const &name)
Return a scoped LoadEvent.
T set_intersection(T... args)
beast::insight::Gauge full_duration
virtual perf::PerfLog & getPerfLog()=0
send_if_pred< Predicate > send_if(std::shared_ptr< Message > const &m, Predicate const &f)
Helper function to aid in type deduction.
virtual std::uint64_t getPeerDisconnect() const =0
CanonicalTXSet OrderedTxs
bool subBook(InfoSub::ref ispListener, Book const &) override
bool subConsensus(InfoSub::ref ispListener) override
Json::Value getConsensusInfo() override
beast::insight::Gauge connected_duration
std::size_t count() const
Return the number of configured validator list sites.
ClosureCounter< void, boost::system::error_code const & > waitHandlerCounter_
bool cdirFirst(ReadView const &view, uint256 const &root, std::shared_ptr< SLE const > &page, unsigned int &index, uint256 &entry)
Returns the first entry in the directory, advancing the index.
std::atomic< bool > stopHistorical_
SubAccountHistoryMapType mSubAccountHistory
void mode(OperatingMode om)
Record state transition.
std::optional< AccountID > accountFromStringStrict(std::string const &account)
Get an AccountID from an account ID or public key.
static const std::array< Json::StaticString const, 5 > states_
static std::string getWordFromBlob(void const *blob, size_t bytes)
Chooses a single dictionary word from the data.
void unsubAccountInternal(std::uint64_t seq, hash_set< AccountID > const &vnaAccountIDs, bool rt) override
const SF_UINT32 sfSigningTime
std::shared_ptr< STTx const > popAcctTransaction(std::shared_ptr< STTx const > const &tx)
Get the next transaction held for a particular account if any.
void unsubAccountHistory(InfoSub::ref ispListener, AccountID const &account, bool historyOnly) override
unsubscribe an account's transactions
State accounting records two attributes for each possible server state: 1) Amount of time spent in ea...
A reference to a handler for performing polled collection.
std::uint64_t getQuality(uint256 const &uBase)
virtual std::uint64_t getPeerDisconnectCharges() const =0
virtual HashRouter & getHashRouter()=0
bool modify(modify_type const &f)
Modify the open ledger.
STAmount const & getFieldAmount(SField const &field) const
bool unsubPeerStatus(std::uint64_t uListener) override
bool transactionBatch(bool drain) override
Apply transactions in batches.
bool setFlags(uint256 const &key, int flags)
Set the flags on a hash.
void handleNewValidation(Application &app, std::shared_ptr< STValidation > const &val, std::string const &source)
Handle a new validation.
const AccountID accountId_
bool isTemMalformed(TER x)
static std::uint32_t trunc32(std::uint64_t v)
std::unique_ptr< FeeVote > make_FeeVote(FeeSetup const &setup, beast::Journal journal)
Create an instance of the FeeVote logic.
Json::Value jsonClipped() const
OperatingMode getOperatingMode() const override
PublicKey const & identity() const
std::optional< TxQ::Metrics > em
std::size_t quorum() const
Get quorum value for current trusted key set.
bool exists(std::string const &name) const
Returns true if a section with the given name exists.
const SF_VECTOR256 sfAmendments
InfoSub::pointer findRpcSub(std::string const &strUrl) override
void set(value_type value) const
Set the value on the gauge.
std::uint32_t loadBaseServer
Section & section(std::string const &name)
Returns the section with the given name.
void clearLedgerFetch() override
std::uint32_t getLoadFee() const
std::optional< Substitute< Closure > > wrap(Closure &&closure)
Wrap the passed closure with a reference counter.
Json::Value rate(Account const &account, double multiplier)
Set a transfer rate.
virtual TransactionMaster & getMasterTransaction()=0
Number root(Number f, unsigned d)
bool beginConsensus(uint256 const &networkClosed) override
void setAmendmentBlocked() override
@ FULL
we have the ledger and can even validate