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,
769 template <
class Handler>
771 Handler
const& handler,
773 :
hook(collector->make_hook(handler))
776 "Disconnected_duration"))
779 "Connected_duration"))
781 collector->make_gauge(
"State_Accounting",
"Syncing_duration"))
784 "Tracking_duration"))
786 collector->make_gauge(
"State_Accounting",
"Full_duration"))
789 "Disconnected_transitions"))
792 "Connected_transitions"))
795 "Syncing_transitions"))
798 "Tracking_transitions"))
800 collector->make_gauge(
"State_Accounting",
"Full_transitions"))
829 {
"disconnected",
"connected",
"syncing",
"tracking",
"full"}};
891 static std::string const hostname = boost::asio::ip::host_name();
898 static std::string const shroudedHostId = [
this]() {
904 return shroudedHostId;
919 boost::asio::steady_timer& timer,
926 [
this, onExpire, onError](boost::system::error_code
const& e) {
927 if ((e.value() == boost::system::errc::success) &&
928 (!m_job_queue.isStopped()))
933 if (e.value() != boost::system::errc::success &&
934 e.value() != boost::asio::error::operation_aborted)
937 JLOG(m_journal.error())
938 <<
"Timer got error '" << e.message()
939 <<
"'. Restarting timer.";
944 timer.expires_from_now(expiry_time);
945 timer.async_wait(std::move(*optionalCountedHandler));
981 using namespace std::chrono_literals;
997 JLOG(
m_journal.
debug()) <<
"Scheduling AccountHistory job for account "
999 using namespace std::chrono_literals;
1010 using namespace std::chrono_literals;
1015 auto constexpr batchInterval = 100ms;
1029 jtBATCH,
"transactionBatch", [
this]() {
1030 transactionBatch(false);
1062 <<
"Node count (" << numPeers <<
") has fallen "
1078 <<
"Node count (" << numPeers <<
") is sufficient.";
1107 using namespace std::chrono_literals;
1124 protocol::TMCluster cluster;
1126 protocol::TMClusterNode& n = *cluster.add_clusternodes();
1131 n.set_nodename(node.
name());
1135 for (
auto& item : gossip.
items)
1137 protocol::TMLoadSource& node = *cluster.add_loadsources();
1139 node.set_cost(item.balance);
1142 std::make_shared<Message>(cluster, protocol::mtCLUSTER),
1162 return "validating";
1181 auto const txid = trans->getTransactionID();
1184 if ((flags & SF_BAD) != 0)
1186 JLOG(
m_journal.
warn()) <<
"Submitted transaction cached bad";
1201 <<
"Submitted transaction invalid: " << reason;
1208 <<
"Exception checking transaction " << txid <<
": " << ex.
what();
1215 auto tx = std::make_shared<Transaction>(trans, reason,
app_);
1235 if ((newFlags & SF_BAD) != 0)
1238 JLOG(
m_journal.
warn()) << transaction->getID() <<
": cached bad!\n";
1239 transaction->setStatus(
INVALID);
1250 *transaction->getSTransaction(),
1258 JLOG(
m_journal.
trace()) <<
"Transaction has bad signature: " << reason;
1259 transaction->setStatus(
INVALID);
1269 if (!transaction->getApplying())
1271 transaction->setApplying();
1287 }
while (transaction->getApplying());
1296 transaction = std::make_shared<Transaction>(*transaction);
1302 lock, [&transaction] {
return !transaction->getApplying(); });
1340 bool changed =
false;
1358 app_, view, e.transaction->getSTransaction(), flags, j);
1359 e.result = result.first;
1360 e.applied = result.second;
1361 changed = changed || result.second;
1371 validatedLedgerIndex = l->info().seq;
1376 e.transaction->clearSubmitResult();
1381 newOL, e.transaction->getSTransaction(), e.result);
1382 e.transaction->setApplied();
1385 e.transaction->setResult(e.result);
1398 <<
"TransactionResult: " << token <<
": " << human;
1403 bool addLocal = e.local;
1408 <<
"Transaction is now included in open ledger";
1409 e.transaction->setStatus(
INCLUDED);
1411 auto const& txCur = e.transaction->getSTransaction();
1417 auto t = std::make_shared<Transaction>(trans, reason,
app_);
1426 e.transaction->setStatus(
OBSOLETE);
1431 <<
"Transaction is likely to claim a"
1432 <<
" fee, but is queued until fee drops";
1434 e.transaction->setStatus(
HELD);
1439 e.transaction->setQueued();
1440 e.transaction->setKept();
1448 <<
"Transaction should be held: " << e.result;
1449 e.transaction->setStatus(
HELD);
1451 e.transaction->setKept();
1457 <<
"Status other than success " << e.result;
1458 e.transaction->setStatus(
INVALID);
1461 auto const enforceFailHard =
1464 if (addLocal && !enforceFailHard)
1468 e.transaction->getSTransaction());
1469 e.transaction->setKept();
1483 protocol::TMTransaction tx;
1486 e.transaction->getSTransaction()->add(s);
1487 tx.set_rawtransaction(s.
data(), s.
size());
1488 tx.set_status(protocol::tsCURRENT);
1489 tx.set_receivetimestamp(
1494 e.transaction->setBroadcast();
1498 if (validatedLedgerIndex)
1500 auto [fee, accountSeq, availableSeq] =
1502 *newOL, e.transaction->getSTransaction());
1503 e.transaction->setCurrentLedgerState(
1504 *validatedLedgerIndex, fee, accountSeq, availableSeq);
1512 e.transaction->clearApplying();
1514 if (!submit_held.
empty())
1519 for (
auto& e : submit_held)
1546 for (
auto const& uDirEntry : sleNode->getFieldV256(
sfIndexes))
1551 switch (sleCur->getType())
1554 if (!jvObjects.
isMember(jss::offers))
1555 jvObjects[jss::offers] =
1558 jvObjects[jss::offers].
append(
1563 if (!jvObjects.
isMember(jss::ripple_lines))
1565 jvObjects[jss::ripple_lines] =
1569 jvObjects[jss::ripple_lines].
append(
1664 JLOG(
m_journal.
trace()) <<
"NetworkOPsImp::checkLastClosedLedger";
1671 uint256 closedLedger = ourClosed->info().hash;
1672 uint256 prevClosedLedger = ourClosed->info().parentHash;
1681 <<
"ValidationTrie " <<
Json::Compact(validations.getJsonTrie());
1685 peerCounts[closedLedger] = 0;
1687 peerCounts[closedLedger]++;
1689 for (
auto& peer : peerList)
1691 uint256 peerLedger = peer->getClosedLedgerHash();
1694 ++peerCounts[peerLedger];
1697 for (
auto const& it : peerCounts)
1698 JLOG(
m_journal.
debug()) <<
"L: " << it.first <<
" n=" << it.second;
1700 uint256 preferredLCL = validations.getPreferredLCL(
1705 bool switchLedgers = preferredLCL != closedLedger;
1707 closedLedger = preferredLCL;
1709 if (switchLedgers && (closedLedger == prevClosedLedger))
1712 JLOG(
m_journal.
info()) <<
"We won't switch to our own previous ledger";
1713 networkClosed = ourClosed->info().hash;
1714 switchLedgers =
false;
1718 networkClosed = closedLedger;
1737 networkClosed = ourClosed->info().hash;
1741 JLOG(
m_journal.
warn()) <<
"We are not running on the consensus ledger";
1767 <<
"JUMP last closed ledger to " << newLCL->info().hash;
1803 protocol::TMStatusChange s;
1804 s.set_newevent(protocol::neSWITCHED_LEDGER);
1805 s.set_ledgerseq(newLCL->info().seq);
1807 s.set_ledgerhashprevious(
1808 newLCL->info().parentHash.begin(), newLCL->info().parentHash.size());
1809 s.set_ledgerhash(newLCL->info().hash.begin(), newLCL->info().hash.size());
1812 send_always(std::make_shared<Message>(s, protocol::mtSTATUS_CHANGE)));
1822 JLOG(
m_journal.
info()) <<
"Consensus time for #" << closingInfo.seq
1823 <<
" with LCL " << closingInfo.parentHash;
1832 JLOG(
m_journal.
warn()) <<
"Don't have LCL, going to tracking";
1839 assert(prevLedger->info().hash == closingInfo.parentHash);
1841 closingInfo.parentHash ==
1848 closingInfo.parentCloseTime,
1853 if (!changes.
added.empty() || !changes.
removed.empty())
1888 protocol::TMHaveTransactionSet msg;
1889 msg.set_hash(map->getHash().as_uint256().begin(), 256 / 8);
1890 msg.set_status(protocol::tsHAVE);
1892 send_always(std::make_shared<Message>(msg, protocol::mtHAVE_SET)));
1906 if (it && (it->getClosedLedgerHash() == deadLedger))
1917 if (networkClosed.
isZero())
1946 2 *
current->info().closeTimeResolution))
1974 jvObj[jss::type] =
"manifestReceived";
1977 jvObj[jss::signing_key] =
1981 jvObj[jss::signature] =
strHex(*sig);
1984 jvObj[jss::domain] = mo.
domain;
1990 if (
auto p = i->second.lock())
1992 p->send(jvObj,
true);
2008 , loadBaseServer{loadFeeTrack.getLoadBase()}
2010 , em{std::move(escalationMetrics)}
2020 em.has_value() != b.
em.has_value())
2026 em->minProcessingFeeLevel != b.
em->minProcessingFeeLevel ||
2027 em->openLedgerFeeLevel != b.
em->openLedgerFeeLevel ||
2028 em->referenceFeeLevel != b.
em->referenceFeeLevel);
2061 jvObj[jss::type] =
"serverStatus";
2063 jvObj[jss::load_base] = f.loadBaseServer;
2064 jvObj[jss::load_factor_server] = f.loadFactorServer;
2065 jvObj[jss::base_fee] = f.baseFee.jsonClipped();
2070 safe_cast<std::uint64_t>(f.loadFactorServer),
2072 f.em->openLedgerFeeLevel,
2074 f.em->referenceFeeLevel)
2077 jvObj[jss::load_factor] =
trunc32(loadFactor);
2078 jvObj[jss::load_factor_fee_escalation] =
2079 f.em->openLedgerFeeLevel.jsonClipped();
2080 jvObj[jss::load_factor_fee_queue] =
2081 f.em->minProcessingFeeLevel.jsonClipped();
2082 jvObj[jss::load_factor_fee_reference] =
2083 f.em->referenceFeeLevel.jsonClipped();
2086 jvObj[jss::load_factor] = f.loadFactorServer;
2100 p->send(jvObj,
true);
2117 if (!streamMap.empty())
2120 jvObj[jss::type] =
"consensusPhase";
2121 jvObj[jss::consensus] =
to_string(phase);
2123 for (
auto i = streamMap.begin(); i != streamMap.end();)
2125 if (
auto p = i->second.lock())
2127 p->send(jvObj,
true);
2132 i = streamMap.erase(i);
2148 auto const signerPublic = val->getSignerPublic();
2150 jvObj[jss::type] =
"validationReceived";
2151 jvObj[jss::validation_public_key] =
2153 jvObj[jss::ledger_hash] =
to_string(val->getLedgerHash());
2154 jvObj[jss::signature] =
strHex(val->getSignature());
2155 jvObj[jss::full] = val->isFull();
2156 jvObj[jss::flags] = val->getFlags();
2158 jvObj[jss::data] =
strHex(val->getSerializer().slice());
2163 if (
auto cookie = (*val)[~
sfCookie])
2167 jvObj[jss::validated_hash] =
strHex(*hash);
2169 auto const masterKey =
2172 if (masterKey != signerPublic)
2176 jvObj[jss::ledger_index] =
to_string(*seq);
2181 for (
auto const& amendment : val->getFieldV256(
sfAmendments))
2186 jvObj[jss::close_time] = *closeTime;
2188 if (
auto const loadFee = (*val)[~
sfLoadFee])
2189 jvObj[jss::load_fee] = *loadFee;
2191 if (
auto const baseFee = val->at(~
sfBaseFee))
2192 jvObj[jss::base_fee] =
static_cast<double>(*baseFee);
2195 jvObj[jss::reserve_base] = *reserveBase;
2198 jvObj[jss::reserve_inc] = *reserveInc;
2203 baseFeeXRP && baseFeeXRP->native())
2204 jvObj[jss::base_fee] = baseFeeXRP->xrp().jsonClipped();
2207 reserveBaseXRP && reserveBaseXRP->native())
2208 jvObj[jss::reserve_base] = reserveBaseXRP->xrp().jsonClipped();
2211 reserveIncXRP && reserveIncXRP->native())
2212 jvObj[jss::reserve_inc] = reserveIncXRP->xrp().jsonClipped();
2217 if (
auto p = i->second.lock())
2219 p->send(jvObj,
true);
2239 jvObj[jss::type] =
"peerStatusChange";
2248 p->send(jvObj,
true);
2262 using namespace std::chrono_literals;
2294 <<
"recvValidation " << val->getLedgerHash() <<
" from " << source;
2324 "This server is amendment blocked, and must be updated to be "
2325 "able to stay in sync with the network.";
2332 "This server has an expired validator list. validators.txt "
2333 "may be incorrectly configured or some [validator_list_sites] "
2334 "may be unreachable.";
2341 "One or more unsupported amendments have reached majority. "
2342 "Upgrade to the latest version before they are activated "
2343 "to avoid being amendment blocked.";
2344 if (
auto const expected =
2348 d[jss::expected_date] = expected->time_since_epoch().count();
2349 d[jss::expected_date_UTC] =
to_string(*expected);
2353 if (warnings.size())
2354 info[jss::warnings] = std::move(warnings);
2369 info[jss::time] =
to_string(std::chrono::floor<std::chrono::microseconds>(
2373 info[jss::network_ledger] =
"waiting";
2375 info[jss::validation_quorum] =
2383 info[jss::node_size] =
"tiny";
2386 info[jss::node_size] =
"small";
2389 info[jss::node_size] =
"medium";
2392 info[jss::node_size] =
"large";
2395 info[jss::node_size] =
"huge";
2404 info[jss::validator_list_expires] =
2405 safe_cast<Json::UInt>(when->time_since_epoch().count());
2407 info[jss::validator_list_expires] = 0;
2417 if (*when == TimeKeeper::time_point::max())
2419 x[jss::expiration] =
"never";
2420 x[jss::status] =
"active";
2427 x[jss::status] =
"active";
2429 x[jss::status] =
"expired";
2434 x[jss::status] =
"unknown";
2435 x[jss::expiration] =
"unknown";
2439 info[jss::io_latency_ms] =
2446 info[jss::pubkey_validator] =
toBase58(
2451 info[jss::pubkey_validator] =
"none";
2464 info[jss::counters][jss::nodestore] = nodestore;
2468 info[jss::pubkey_node] =
2474 info[jss::amendment_blocked] =
true;
2489 lastClose[jss::converge_time_s] =
2494 lastClose[jss::converge_time] =
2498 info[jss::last_close] = lastClose;
2508 info[jss::network_id] =
static_cast<Json::UInt>(*netid);
2510 auto const escalationMetrics =
2518 auto const loadFactorFeeEscalation =
2520 escalationMetrics.openLedgerFeeLevel,
2522 escalationMetrics.referenceFeeLevel)
2526 safe_cast<std::uint64_t>(loadFactorServer),
2527 loadFactorFeeEscalation);
2531 info[jss::load_base] = loadBaseServer;
2532 info[jss::load_factor] =
trunc32(loadFactor);
2533 info[jss::load_factor_server] = loadFactorServer;
2540 info[jss::load_factor_fee_escalation] =
2541 escalationMetrics.openLedgerFeeLevel.jsonClipped();
2542 info[jss::load_factor_fee_queue] =
2543 escalationMetrics.minProcessingFeeLevel.jsonClipped();
2544 info[jss::load_factor_fee_reference] =
2545 escalationMetrics.referenceFeeLevel.jsonClipped();
2549 info[jss::load_factor] =
2550 static_cast<double>(loadFactor) / loadBaseServer;
2552 if (loadFactorServer != loadFactor)
2553 info[jss::load_factor_server] =
2554 static_cast<double>(loadFactorServer) / loadBaseServer;
2559 if (fee != loadBaseServer)
2560 info[jss::load_factor_local] =
2561 static_cast<double>(fee) / loadBaseServer;
2563 if (fee != loadBaseServer)
2564 info[jss::load_factor_net] =
2565 static_cast<double>(fee) / loadBaseServer;
2567 if (fee != loadBaseServer)
2568 info[jss::load_factor_cluster] =
2569 static_cast<double>(fee) / loadBaseServer;
2571 if (escalationMetrics.openLedgerFeeLevel !=
2572 escalationMetrics.referenceFeeLevel &&
2573 (admin || loadFactorFeeEscalation != loadFactor))
2574 info[jss::load_factor_fee_escalation] =
2575 escalationMetrics.openLedgerFeeLevel.decimalFromReference(
2576 escalationMetrics.referenceFeeLevel);
2577 if (escalationMetrics.minProcessingFeeLevel !=
2578 escalationMetrics.referenceFeeLevel)
2579 info[jss::load_factor_fee_queue] =
2580 escalationMetrics.minProcessingFeeLevel
2581 .decimalFromReference(
2582 escalationMetrics.referenceFeeLevel);
2596 XRPAmount const baseFee = lpClosed->fees().base;
2598 l[jss::seq] =
Json::UInt(lpClosed->info().seq);
2599 l[jss::hash] =
to_string(lpClosed->info().hash);
2604 l[jss::reserve_base] =
2605 lpClosed->fees().accountReserve(0).jsonClipped();
2606 l[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped();
2608 lpClosed->info().closeTime.time_since_epoch().count());
2613 l[jss::reserve_base_xrp] =
2614 lpClosed->fees().accountReserve(0).decimalXRP();
2615 l[jss::reserve_inc_xrp] = lpClosed->fees().increment.decimalXRP();
2618 if (std::abs(nowOffset.count()) >= 60)
2619 l[jss::system_time_offset] = nowOffset.count();
2622 if (std::abs(closeOffset.count()) >= 60)
2623 l[jss::close_time_offset] = closeOffset.count();
2625 #if RIPPLED_REPORTING
2635 Json::UInt(age < highAgeThreshold ? age.count() : 0);
2639 auto lCloseTime = lpClosed->info().closeTime;
2641 if (lCloseTime <= closeTime)
2643 using namespace std::chrono_literals;
2644 auto age = closeTime - lCloseTime;
2646 Json::UInt(age < highAgeThreshold ? age.count() : 0);
2653 info[jss::validated_ledger] = l;
2655 info[jss::closed_ledger] = l;
2659 info[jss::published_ledger] =
"none";
2660 else if (lpPublished->info().seq != lpClosed->info().seq)
2661 info[jss::published_ledger] = lpPublished->info().seq;
2668 info[jss::jq_trans_overflow] =
2670 info[jss::peer_disconnects] =
2672 info[jss::peer_disconnects_resources] =
2682 "http",
"https",
"peer",
"ws",
"ws2",
"wss",
"wss2"};
2690 !(port.admin_nets_v4.empty() && port.admin_nets_v6.empty() &&
2691 port.admin_user.empty() && port.admin_password.empty()))
2705 for (
auto const& p : proto)
2706 jv[jss::protocol].append(p);
2713 auto const optPort = grpcSection.
get(
"port");
2714 if (optPort && grpcSection.get(
"ip"))
2717 jv[jss::port] = *optPort;
2719 jv[jss::protocol].append(
"grpc");
2722 info[jss::ports] = std::move(ports);
2758 p->send(jvObj,
true);
2777 if (jvObj[jss::validated].asBool())
2789 p->send(jvObj,
true);
2810 if (
auto p = i->second.lock())
2812 p->send(jvObj,
true);
2830 if (
auto p = i->second.lock())
2832 p->send(jvObj,
true);
2845 for (
auto& jv : jvObj)
2851 else if (jv.isString())
2875 if (jvObj.
isMember(jss::transaction))
2884 << __func__ <<
" : "
2885 <<
"error parsing json for accounts affected";
2894 for (
auto const& affectedAccount : accounts)
2899 auto it = simiIt->second.begin();
2901 while (it != simiIt->second.end())
2912 it = simiIt->second.erase(it);
2919 <<
" iProposed=" << iProposed;
2921 if (!notify.
empty())
2924 isrListener->send(jvObj,
true);
2938 alpAccepted = std::make_shared<AcceptedLedger>(lpAccepted,
app_);
2940 lpAccepted->info().hash, alpAccepted);
2943 assert(alpAccepted->getLedger().
get() == lpAccepted.
get());
2947 <<
"Publishing ledger " << lpAccepted->info().seq <<
" "
2948 << lpAccepted->info().hash;
2956 jvObj[jss::type] =
"ledgerClosed";
2957 jvObj[jss::ledger_index] = lpAccepted->info().seq;
2958 jvObj[jss::ledger_hash] =
to_string(lpAccepted->info().hash);
2960 lpAccepted->info().closeTime.time_since_epoch().count());
2964 jvObj[jss::fee_base] = lpAccepted->fees().base.jsonClipped();
2965 jvObj[jss::reserve_base] =
2966 lpAccepted->fees().accountReserve(0).jsonClipped();
2967 jvObj[jss::reserve_inc] =
2968 lpAccepted->fees().increment.jsonClipped();
2970 jvObj[jss::txn_count] =
Json::UInt(alpAccepted->size());
2974 jvObj[jss::validated_ledgers] =
2984 p->send(jvObj,
true);
3002 p->send(jvObj,
true);
3011 static bool firstTime =
true;
3018 for (
auto& inner : outer.second)
3020 auto& subInfo = inner.second;
3021 if (subInfo.index_->separationLedgerSeq_ == 0)
3024 alpAccepted->getLedger(), subInfo);
3033 for (
auto const& accTx : *alpAccepted)
3037 lpAccepted, *accTx, accTx == *(--alpAccepted->end()));
3066 "reportConsensusStateChange->pubConsensus",
3085 const STTx& transaction,
3096 jvObj[jss::type] =
"transaction";
3101 jvObj[jss::ledger_index] = ledger->info().seq;
3102 jvObj[jss::ledger_hash] =
to_string(ledger->info().hash);
3103 jvObj[jss::transaction][jss::date] =
3104 ledger->info().closeTime.time_since_epoch().count();
3105 jvObj[jss::validated] =
true;
3111 jvObj[jss::validated] =
false;
3112 jvObj[jss::ledger_current_index] = ledger->info().seq;
3115 jvObj[jss::status] = validated ?
"closed" :
"proposed";
3116 jvObj[jss::engine_result] = sToken;
3117 jvObj[jss::engine_result_code] = result;
3118 jvObj[jss::engine_result_message] = sHuman;
3126 if (account != amount.issue().account)
3134 jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText();
3147 auto const& stTxn = transaction.
getTxn();
3153 auto const& meta = transaction.
getMeta();
3168 p->send(jvObj,
true);
3183 p->send(jvObj,
true);
3208 auto const currLedgerSeq = ledger->seq();
3215 for (
auto const& affectedAccount : transaction.
getAffected())
3220 auto it = simiIt->second.begin();
3222 while (it != simiIt->second.end())
3233 it = simiIt->second.erase(it);
3240 auto it = simiIt->second.begin();
3241 while (it != simiIt->second.end())
3252 it = simiIt->second.erase(it);
3259 auto& subs = histoIt->second;
3260 auto it = subs.begin();
3261 while (it != subs.end())
3264 if (currLedgerSeq <= info.index_->separationLedgerSeq_)
3278 it = subs.erase(it);
3289 <<
"pubAccountTransaction: "
3290 <<
"proposed=" << iProposed <<
", accepted=" << iAccepted;
3292 if (!notify.
empty() || !accountHistoryNotify.
empty())
3294 auto const& stTxn = transaction.
getTxn();
3300 auto const& meta = transaction.
getMeta();
3307 isrListener->send(jvObj,
true);
3310 jvObj[jss::account_history_boundary] =
true;
3312 assert(!jvObj.
isMember(jss::account_history_tx_stream));
3313 for (
auto& info : accountHistoryNotify)
3315 auto& index = info.index_;
3316 if (index->forwardTxIndex_ == 0 && !index->haveHistorical_)
3317 jvObj[jss::account_history_tx_first] =
true;
3318 jvObj[jss::account_history_tx_index] = index->forwardTxIndex_++;
3319 info.sink_->send(jvObj,
true);
3344 for (
auto const& affectedAccount : tx->getMentionedAccounts())
3349 auto it = simiIt->second.begin();
3351 while (it != simiIt->second.end())
3362 it = simiIt->second.erase(it);
3369 JLOG(
m_journal.
trace()) <<
"pubProposedAccountTransaction: " << iProposed;
3371 if (!notify.
empty() || !accountHistoryNotify.
empty())
3376 isrListener->send(jvObj,
true);
3378 assert(!jvObj.
isMember(jss::account_history_tx_stream));
3379 for (
auto& info : accountHistoryNotify)
3381 auto& index = info.index_;
3382 if (index->forwardTxIndex_ == 0 && !index->haveHistorical_)
3383 jvObj[jss::account_history_tx_first] =
true;
3384 jvObj[jss::account_history_tx_index] = index->forwardTxIndex_++;
3385 info.sink_->send(jvObj,
true);
3402 for (
auto const& naAccountID : vnaAccountIDs)
3405 <<
"subAccount: account: " <<
toBase58(naAccountID);
3407 isrListener->insertSubAccountInfo(naAccountID, rt);
3412 for (
auto const& naAccountID : vnaAccountIDs)
3414 auto simIterator = subMap.
find(naAccountID);
3415 if (simIterator == subMap.
end())
3419 usisElement[isrListener->getSeq()] = isrListener;
3421 subMap.
insert(simIterator, make_pair(naAccountID, usisElement));
3426 simIterator->second[isrListener->getSeq()] = isrListener;
3437 for (
auto const& naAccountID : vnaAccountIDs)
3440 isrListener->deleteSubAccountInfo(naAccountID, rt);
3457 for (
auto const& naAccountID : vnaAccountIDs)
3459 auto simIterator = subMap.
find(naAccountID);
3461 if (simIterator != subMap.
end())
3464 simIterator->second.erase(uSeq);
3466 if (simIterator->second.empty())
3469 subMap.
erase(simIterator);
3478 enum DatabaseType { Postgres, Sqlite, None };
3479 static const auto databaseType = [&]() -> DatabaseType {
3480 #ifdef RIPPLED_REPORTING
3487 return DatabaseType::Postgres;
3489 return DatabaseType::None;
3497 return DatabaseType::Sqlite;
3499 return DatabaseType::None;
3506 return DatabaseType::Sqlite;
3508 return DatabaseType::None;
3512 if (databaseType == DatabaseType::None)
3515 <<
"AccountHistory job for account "
3527 "AccountHistoryTxStream",
3528 [
this, dbType = databaseType, subInfo]() {
3529 auto const& accountId = subInfo.
index_->accountId_;
3530 auto& lastLedgerSeq = subInfo.
index_->historyLastLedgerSeq_;
3531 auto& txHistoryIndex = subInfo.
index_->historyTxIndex_;
3534 <<
"AccountHistory job for account " <<
toBase58(accountId)
3535 <<
" started. lastLedgerSeq=" << lastLedgerSeq;
3545 auto stx = tx->getSTransaction();
3546 if (stx->getAccountID(
sfAccount) == accountId &&
3547 stx->getSeqProxy().value() == 1)
3551 for (
auto& node : meta->getNodes())
3558 if (
auto inner =
dynamic_cast<const STObject*
>(
3563 inner->getAccountID(
sfAccount) == accountId)
3575 bool unsubscribe) ->
bool {
3578 sptr->send(jvObj,
true);
3604 auto [txResult, status] = db->getAccountTx(args);
3608 <<
"AccountHistory job for account "
3610 <<
" getAccountTx failed";
3615 std::get_if<RelationalDatabase::AccountTxs>(
3616 &txResult.transactions);
3624 <<
"AccountHistory job for account "
3626 <<
" getAccountTx wrong data";
3634 accountId, minLedger, maxLedger, marker, 0,
true};
3635 return db->newestAccountTxPage(options);
3647 while (lastLedgerSeq >= 2 && !subInfo.
index_->stopHistorical_)
3649 int feeChargeCount = 0;
3658 <<
"AccountHistory job for account "
3659 <<
toBase58(accountId) <<
" no InfoSub. Fee charged "
3660 << feeChargeCount <<
" times.";
3665 auto startLedgerSeq =
3666 (lastLedgerSeq > 1024 + 2 ? lastLedgerSeq - 1024 : 2);
3668 <<
"AccountHistory job for account " <<
toBase58(accountId)
3669 <<
", working on ledger range [" << startLedgerSeq <<
","
3670 << lastLedgerSeq <<
"]";
3672 auto haveRange = [&]() ->
bool {
3675 auto haveSomeValidatedLedgers =
3677 validatedMin, validatedMax);
3679 return haveSomeValidatedLedgers &&
3680 validatedMin <= startLedgerSeq &&
3681 lastLedgerSeq <= validatedMax;
3687 <<
"AccountHistory reschedule job for account "
3688 <<
toBase58(accountId) <<
", incomplete ledger range ["
3689 << startLedgerSeq <<
"," << lastLedgerSeq <<
"]";
3695 while (!subInfo.
index_->stopHistorical_)
3698 getMoreTxns(startLedgerSeq, lastLedgerSeq, marker);
3702 <<
"AccountHistory job for account "
3703 <<
toBase58(accountId) <<
" getMoreTxns failed.";
3708 auto const& txns = dbResult->first;
3709 marker = dbResult->second;
3710 size_t num_txns = txns.size();
3711 for (
size_t i = 0; i < num_txns; ++i)
3713 auto const& [tx, meta] = txns[i];
3718 <<
"AccountHistory job for account "
3719 <<
toBase58(accountId) <<
" empty tx or meta.";
3729 <<
"AccountHistory job for account "
3730 <<
toBase58(accountId) <<
" no ledger.";
3735 tx->getSTransaction();
3739 <<
"AccountHistory job for account "
3741 <<
" getSTransaction failed.";
3746 *stTxn, meta->getResultTER(),
true, curTxLedger);
3748 jvTx[jss::account_history_tx_index] = txHistoryIndex--;
3750 if (i + 1 == num_txns ||
3751 txns[i + 1].first->getLedger() != tx->getLedger())
3752 jvTx[jss::account_history_boundary] =
true;
3755 jvTx[jss::meta], *curTxLedger, stTxn, *meta);
3756 if (isFirstTx(tx, meta))
3758 jvTx[jss::account_history_tx_first] =
true;
3762 <<
"AccountHistory job for account "
3764 <<
" done, found last tx.";
3776 <<
"AccountHistory job for account "
3778 <<
" paging, marker=" << marker->ledgerSeq <<
":"
3787 if (!subInfo.
index_->stopHistorical_)
3789 lastLedgerSeq = startLedgerSeq - 1;
3790 if (lastLedgerSeq <= 1)
3793 <<
"AccountHistory job for account "
3795 <<
" done, reached genesis ledger.";
3808 subInfo.
index_->separationLedgerSeq_ = ledger->seq();
3809 auto const& accountId = subInfo.
index_->accountId_;
3811 if (!ledger->exists(accountKeylet))
3814 <<
"subAccountHistoryStart, no account " <<
toBase58(accountId)
3815 <<
", no need to add AccountHistory job.";
3820 if (
auto const sleAcct = ledger->read(accountKeylet); sleAcct)
3825 <<
"subAccountHistoryStart, genesis account "
3827 <<
" does not have tx, no need to add AccountHistory job.";
3837 subInfo.
index_->historyLastLedgerSeq_ = ledger->seq();
3838 subInfo.
index_->haveHistorical_ =
true;
3841 <<
"subAccountHistoryStart, add AccountHistory job: accountId="
3842 <<
toBase58(accountId) <<
", currentLedgerSeq=" << ledger->seq();
3852 if (!isrListener->insertSubAccountHistory(accountId))
3855 <<
"subAccountHistory, already subscribed to account "
3862 isrListener, std::make_shared<SubAccountHistoryIndex>(accountId)};
3867 inner.
emplace(isrListener->getSeq(), ahi);
3873 simIterator->second.emplace(isrListener->getSeq(), ahi);
3887 <<
"subAccountHistory, no validated ledger yet, delay start";
3900 isrListener->deleteSubAccountHistory(account);
3914 auto& subInfoMap = simIterator->second;
3915 auto subInfoIter = subInfoMap.find(seq);
3916 if (subInfoIter != subInfoMap.end())
3918 subInfoIter->second.index_->stopHistorical_ =
true;
3923 simIterator->second.erase(seq);
3924 if (simIterator->second.empty())
3930 <<
"unsubAccountHistory, account " <<
toBase58(account)
3931 <<
", historyOnly = " << (historyOnly ?
"true" :
"false");
3939 listeners->addSubscriber(isrListener);
3949 listeners->removeSubscriber(uSeq);
3963 Throw<std::runtime_error>(
3964 "Operation only possible in STANDALONE mode.");
3979 jvResult[jss::ledger_index] = lpClosed->info().seq;
3980 jvResult[jss::ledger_hash] =
to_string(lpClosed->info().hash);
3982 lpClosed->info().closeTime.time_since_epoch().count());
3985 jvResult[jss::fee_base] = lpClosed->fees().base.jsonClipped();
3986 jvResult[jss::reserve_base] =
3987 lpClosed->fees().accountReserve(0).jsonClipped();
3988 jvResult[jss::reserve_inc] = lpClosed->fees().increment.jsonClipped();
3993 jvResult[jss::validated_ledgers] =
3999 .emplace(isrListener->getSeq(), isrListener)
4009 .emplace(isrListener->getSeq(), isrListener)
4035 .emplace(isrListener->getSeq(), isrListener)
4063 jvResult[jss::random] =
to_string(uRandom);
4065 jvResult[jss::load_base] = feeTrack.getLoadBase();
4066 jvResult[jss::load_factor] = feeTrack.getLoadFactor();
4067 jvResult[jss::hostid] =
getHostId(admin);
4068 jvResult[jss::pubkey_node] =
4073 .emplace(isrListener->getSeq(), isrListener)
4091 .emplace(isrListener->getSeq(), isrListener)
4109 .emplace(isrListener->getSeq(), isrListener)
4127 .emplace(isrListener->getSeq(), isrListener)
4151 .emplace(isrListener->getSeq(), isrListener)
4169 .emplace(isrListener->getSeq(), isrListener)
4217 if (map.find(pInfo->getSeq()) != map.end())
4224 #ifndef USE_NEW_BOOK_PAGE
4235 unsigned int iLimit,
4245 uint256 uTipIndex = uBookBase;
4249 stream <<
"getBookPage:" << book;
4250 stream <<
"getBookPage: uBookBase=" << uBookBase;
4251 stream <<
"getBookPage: uBookEnd=" << uBookEnd;
4252 stream <<
"getBookPage: uTipIndex=" << uTipIndex;
4261 bool bDirectAdvance =
true;
4265 unsigned int uBookEntry;
4271 while (!bDone && iLimit-- > 0)
4275 bDirectAdvance =
false;
4279 auto const ledgerIndex = view.
succ(uTipIndex, uBookEnd);
4283 sleOfferDir.
reset();
4292 uTipIndex = sleOfferDir->key();
4295 cdirFirst(view, uTipIndex, sleOfferDir, uBookEntry, offerIndex);
4298 <<
"getBookPage: uTipIndex=" << uTipIndex;
4300 <<
"getBookPage: offerIndex=" << offerIndex;
4310 auto const uOfferOwnerID = sleOffer->getAccountID(
sfAccount);
4311 auto const& saTakerGets = sleOffer->getFieldAmount(
sfTakerGets);
4312 auto const& saTakerPays = sleOffer->getFieldAmount(
sfTakerPays);
4314 bool firstOwnerOffer(
true);
4320 saOwnerFunds = saTakerGets;
4322 else if (bGlobalFreeze)
4330 auto umBalanceEntry = umBalance.
find(uOfferOwnerID);
4331 if (umBalanceEntry != umBalance.
end())
4335 saOwnerFunds = umBalanceEntry->second;
4336 firstOwnerOffer =
false;
4350 if (saOwnerFunds < beast::zero)
4354 saOwnerFunds.
clear();
4362 STAmount saOwnerFundsLimit = saOwnerFunds;
4374 saOwnerFundsLimit =
divide(saOwnerFunds, offerRate);
4377 if (saOwnerFundsLimit >= saTakerGets)
4380 saTakerGetsFunded = saTakerGets;
4386 saTakerGetsFunded = saOwnerFundsLimit;
4388 saTakerGetsFunded.
setJson(jvOffer[jss::taker_gets_funded]);
4392 saTakerGetsFunded, saDirRate, saTakerPays.
issue()))
4393 .setJson(jvOffer[jss::taker_pays_funded]);
4399 saOwnerFunds,
multiply(saTakerGetsFunded, offerRate));
4401 umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays;
4405 jvOf[jss::quality] = saDirRate.
getText();
4407 if (firstOwnerOffer)
4408 jvOf[jss::owner_funds] = saOwnerFunds.
getText();
4415 if (!
cdirNext(view, uTipIndex, sleOfferDir, uBookEntry, offerIndex))
4417 bDirectAdvance =
true;
4422 <<
"getBookPage: offerIndex=" << offerIndex;
4442 unsigned int iLimit,
4450 MetaView lesActive(lpLedger,
tapNONE,
true);
4451 OrderBookIterator obIterator(lesActive, book);
4455 const bool bGlobalFreeze = lesActive.isGlobalFrozen(book.
out.
account) ||
4456 lesActive.isGlobalFrozen(book.
in.
account);
4458 while (iLimit-- > 0 && obIterator.nextOffer())
4463 auto const uOfferOwnerID = sleOffer->getAccountID(
sfAccount);
4464 auto const& saTakerGets = sleOffer->getFieldAmount(
sfTakerGets);
4465 auto const& saTakerPays = sleOffer->getFieldAmount(
sfTakerPays);
4466 STAmount saDirRate = obIterator.getCurrentRate();
4472 saOwnerFunds = saTakerGets;
4474 else if (bGlobalFreeze)
4482 auto umBalanceEntry = umBalance.
find(uOfferOwnerID);
4484 if (umBalanceEntry != umBalance.
end())
4488 saOwnerFunds = umBalanceEntry->second;
4494 saOwnerFunds = lesActive.accountHolds(
4500 if (saOwnerFunds.isNegative())
4504 saOwnerFunds.zero();
4511 STAmount saTakerGetsFunded;
4512 STAmount saOwnerFundsLimit = saOwnerFunds;
4524 saOwnerFundsLimit =
divide(saOwnerFunds, offerRate);
4527 if (saOwnerFundsLimit >= saTakerGets)
4530 saTakerGetsFunded = saTakerGets;
4535 saTakerGetsFunded = saOwnerFundsLimit;
4537 saTakerGetsFunded.setJson(jvOffer[jss::taker_gets_funded]);
4543 multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue()))
4544 .setJson(jvOffer[jss::taker_pays_funded]);
4547 STAmount saOwnerPays = (
parityRate == offerRate)
4550 saOwnerFunds,
multiply(saTakerGetsFunded, offerRate));
4552 umBalance[uOfferOwnerID] = saOwnerFunds - saOwnerPays;
4554 if (!saOwnerFunds.isZero() || uOfferOwnerID == uTakerID)
4558 jvOf[jss::quality] = saDirRate.
getText();
4573 auto const current = std::chrono::duration_cast<std::chrono::microseconds>(
4613 ++counters_[
static_cast<std::size_t>(om)].transitions;
4615 counters_[
static_cast<std::size_t>(om)].transitions == 1)
4617 initialSyncUs_ = std::chrono::duration_cast<std::chrono::microseconds>(
4618 now - processStart_)
4622 std::chrono::duration_cast<std::chrono::microseconds>(now - start_);
4631 auto [counters, mode, start, initialSync] = getCounterData();
4632 auto const current = std::chrono::duration_cast<std::chrono::microseconds>(
4642 auto& state = obj[jss::state_accounting][
states_[i]];
4643 state[jss::transitions] =
std::to_string(counters[i].transitions);
4644 state[jss::duration_us] =
std::to_string(counters[i].dur.count());
4648 obj[jss::initial_sync_duration_us] =
std::to_string(initialSync);
4663 boost::asio::io_service& io_svc,
4667 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)
virtual std::chrono::duration< std::int32_t > nowOffset() const =0
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
boost::asio::steady_timer batchApplyTimer_
This timer is for applying transaction batches.
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)
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.
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
virtual time_point closeTime() const =0
Returns the close time, in network time.
@ 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()
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
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::array< SubMapType, SubTypes::sLastEntry+1 > mStreamMaps
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
virtual time_point now() const override=0
Returns the estimate of wall time, in network time.
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
virtual std::chrono::duration< std::int32_t > closeOffset() const =0
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