20 #include <ripple/app/ledger/AcceptedLedger.h>
21 #include <ripple/app/ledger/LedgerMaster.h>
22 #include <ripple/app/ledger/LedgerToJson.h>
23 #include <ripple/app/ledger/PendingSaves.h>
24 #include <ripple/app/ledger/TransactionMaster.h>
25 #include <ripple/app/misc/Manifest.h>
26 #include <ripple/app/rdb/RelationalDBInterface.h>
27 #include <ripple/app/rdb/RelationalDBInterface_nodes.h>
28 #include <ripple/basics/BasicConfig.h>
29 #include <ripple/basics/StringUtilities.h>
30 #include <ripple/core/DatabaseCon.h>
31 #include <ripple/core/SociDB.h>
32 #include <ripple/json/to_string.h>
33 #include <boost/algorithm/string.hpp>
34 #include <boost/range/adaptor/transformed.hpp>
35 #include <soci/sqlite3/soci-sqlite3.h>
49 "Need to modify switch statement if enum is modified");
55 return "Transactions";
57 return "AccountTransactions";
71 auto lgr{std::make_unique<DatabaseCon>(
73 lgr->getSession() << boost::str(
74 boost::format(
"PRAGMA cache_size=-%d;") %
80 auto tx{std::make_unique<DatabaseCon>(
82 tx->getSession() << boost::str(
83 boost::format(
"PRAGMA cache_size=-%d;") %
95 (tx->getSession().prepare
96 << (
"PRAGMA table_info(AccountTransactions);"),
101 soci::into(dflt_value, ind),
109 return {std::move(lgr), std::move(tx),
false};
114 return {std::move(lgr), std::move(tx),
true};
117 return {std::move(lgr), {},
true};
125 boost::optional<LedgerIndex> m;
126 session << query, soci::into(m);
135 boost::optional<LedgerIndex> m;
136 session << query, soci::into(m);
143 session <<
"DELETE FROM " <<
to_string(type)
144 <<
" WHERE LedgerSeq == " << ledgerSeq <<
";";
149 soci::session& session,
153 session <<
"DELETE FROM " <<
to_string(type) <<
" WHERE LedgerSeq < "
161 session <<
"SELECT COUNT(*) AS rows "
169 RelationalDBInterface::CountMinMax
173 session <<
"SELECT COUNT(*) AS rows, "
174 "MIN(LedgerSeq) AS first, "
175 "MAX(LedgerSeq) AS last "
192 auto j = app.
journal(
"Ledger");
196 JLOG(j.trace()) <<
"saveValidatedLedger " << (
current ?
"" :
"fromAcquire ")
201 JLOG(j.fatal()) <<
"AH is zero: " <<
getJson({*ledger, {}});
209 JLOG(j.fatal()) <<
"saveAcceptedLedger: seq=" << seq
231 aLedger = std::make_shared<AcceptedLedger>(ledger, app);
238 JLOG(j.warn()) <<
"An accepted ledger was missing nodes";
247 static boost::format deleteLedger(
248 "DELETE FROM Ledgers WHERE LedgerSeq = %u;");
249 static boost::format deleteTrans1(
250 "DELETE FROM Transactions WHERE LedgerSeq = %u;");
251 static boost::format deleteTrans2(
252 "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;");
253 static boost::format deleteAcctTrans(
254 "DELETE FROM AccountTransactions WHERE TransID = '%s';");
258 *db << boost::str(deleteLedger % seq);
265 soci::transaction tr(*db);
267 *db << boost::str(deleteTrans1 % seq);
268 *db << boost::str(deleteTrans2 % seq);
272 for (
auto const& acceptedLedgerTx : *aLedger)
282 auto const& accts = acceptedLedgerTx->getAffected();
287 "INSERT INTO AccountTransactions "
288 "(TransID, Account, LedgerSeq, TxnSeq) VALUES ");
296 for (
auto const& account : accts)
316 JLOG(j.trace()) <<
"ActTx: " << sql;
319 else if (
auto const& sleTxn = acceptedLedgerTx->getTxn();
324 JLOG(j.warn()) <<
"Transaction in ledger " << seq
325 <<
" affects no accounts";
331 acceptedLedgerTx->getTxn()->getMetaSQL(
332 seq, acceptedLedgerTx->getEscMeta()) +
343 R
"sql(INSERT OR REPLACE INTO Ledgers
344 (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime,
345 CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash)
347 (:ledgerHash,:ledgerSeq,:prevHash,:totalCoins,:closingTime,:prevClosingTime,
348 :closeTimeRes,:closeFlags,:accountSetHash,:transSetHash);)sql");
352 soci::transaction tr(*db);
357 auto const closeTime =
359 auto const parentCloseTime =
361 auto const closeTimeResolution =
367 *db << addLedger, soci::use(hash), soci::use(seq),
368 soci::use(parentHash), soci::use(drops), soci::use(closeTime),
369 soci::use(parentCloseTime), soci::use(closeTimeResolution),
370 soci::use(closeFlags), soci::use(accountHash),
390 soci::session& session,
395 boost::optional<std::string> hash, parentHash, accountHash, txHash;
396 boost::optional<std::uint64_t> seq, drops, closeTime, parentCloseTime,
397 closeTimeResolution, closeFlags;
401 "LedgerHash, PrevHash, AccountSetHash, TransSetHash, "
403 "ClosingTime, PrevClosingTime, CloseTimeRes, CloseFlags,"
404 "LedgerSeq FROM Ledgers " +
407 session << sql, soci::into(hash), soci::into(parentHash),
408 soci::into(accountHash), soci::into(txHash), soci::into(drops),
409 soci::into(closeTime), soci::into(parentCloseTime),
410 soci::into(closeTimeResolution), soci::into(closeFlags),
413 if (!session.got_data())
415 JLOG(j.
debug()) <<
"Ledger not found: " << sqlSuffix;
424 if (hash && !info.hash.parseHex(*hash))
426 JLOG(j.
debug()) <<
"Hash parse error for ledger: " << sqlSuffix;
430 if (parentHash && !info.parentHash.parseHex(*parentHash))
432 JLOG(j.
debug()) <<
"parentHash parse error for ledger: " << sqlSuffix;
436 if (accountHash && !info.accountHash.parseHex(*accountHash))
438 JLOG(j.
debug()) <<
"accountHash parse error for ledger: " << sqlSuffix;
442 if (txHash && !info.txHash.parseHex(*txHash))
444 JLOG(j.
debug()) <<
"txHash parse error for ledger: " << sqlSuffix;
448 info.seq = rangeCheckedCast<std::uint32_t>(seq.value_or(0));
449 info.drops =
drops.value_or(0);
450 info.closeTime = time_point{duration{closeTime.value_or(0)}};
451 info.parentCloseTime = time_point{duration{parentCloseTime.value_or(0)}};
452 info.closeFlags = closeFlags.value_or(0);
453 info.closeTimeResolution = duration{closeTimeResolution.value_or(0)};
460 soci::session& session,
465 s <<
"WHERE LedgerSeq = " << ledgerSeq;
473 s <<
"ORDER BY LedgerSeq DESC LIMIT 1";
479 soci::session& session,
485 " ORDER BY LedgerSeq ASC LIMIT 1";
491 soci::session& session,
497 " ORDER BY LedgerSeq DESC LIMIT 1";
503 soci::session& session,
508 s <<
"WHERE LedgerHash = '" << ledgerHash <<
"'";
518 "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='";
519 sql.
append(beast::lexicalCastThrow<std::string>(ledgerIndex));
525 boost::optional<std::string> lh;
526 session << sql, soci::into(lh);
528 if (!session.got_data() || !lh)
536 if (!ret.parseHex(hash))
544 soci::session& session,
549 boost::optional<std::string> lhO, phO;
551 session <<
"SELECT LedgerHash,PrevHash FROM Ledgers "
552 "INDEXED BY SeqLedger WHERE LedgerSeq = :ls;",
553 soci::into(lhO), soci::into(phO), soci::use(ledgerIndex);
557 auto stream = j.
trace();
558 JLOG(stream) <<
"Don't have ledger " << ledgerIndex;
562 LedgerHashPair hashes;
563 if (!hashes.ledgerHash.parseHex(*lhO) || !hashes.parentHash.parseHex(*phO))
566 JLOG(stream) <<
"Error parse hashes for ledger " << ledgerIndex;
575 soci::session& session,
581 "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= ";
582 sql.
append(beast::lexicalCastThrow<std::string>(minSeq));
583 sql.
append(
" AND LedgerSeq <= ");
584 sql.
append(beast::lexicalCastThrow<std::string>(maxSeq));
590 boost::optional<std::string> ph;
592 (session.prepare << sql,
601 LedgerHashPair& hashes = res[rangeCheckedCast<LedgerIndex>(ls)];
602 if (!hashes.ledgerHash.parseHex(lh))
604 JLOG(j.
warn()) <<
"Error parsed hash for ledger seq: " << ls;
608 JLOG(j.
warn()) <<
"Null prev hash for ledger seq: " << ls;
610 else if (!hashes.parentHash.parseHex(*ph))
612 JLOG(j.
warn()) <<
"Error parsed prev hash for ledger seq: " << ls;
620 soci::session& session,
628 "SELECT LedgerSeq, Status, RawTxn "
629 "FROM Transactions ORDER BY LedgerSeq DESC LIMIT %u,%u;") %
630 startIndex % quantity);
637 boost::optional<std::uint64_t> ledgerSeq;
638 boost::optional<std::string>
status;
639 soci::blob sociRawTxnBlob(session);
644 (session.prepare << sql,
645 soci::into(ledgerSeq),
647 soci::into(sociRawTxnBlob, rti));
652 if (soci::i_ok == rti)
653 convert(sociRawTxnBlob, rawTxn);
658 ledgerSeq,
status, rawTxn, app))
667 session <<
"SELECT COUNT(*) FROM Transactions;", soci::into(total);
699 RelationalDBInterface::AccountTxOptions
const& options,
715 else if (options.limit == UINT32_MAX)
717 numberOfResults = binary ? BINARY_PAGE_LENGTH : NONBINARY_PAGE_LENGTH;
719 else if (!options.bUnlimited)
722 binary ? BINARY_PAGE_LENGTH : NONBINARY_PAGE_LENGTH, options.limit);
726 numberOfResults = options.limit;
731 if (numberOfResults <= *limit_used)
734 numberOfResults -= *limit_used;
740 if (options.maxLedger)
742 maxClause = boost::str(
743 boost::format(
"AND AccountTransactions.LedgerSeq <= '%u'") %
747 if (options.minLedger)
749 minClause = boost::str(
750 boost::format(
"AND AccountTransactions.LedgerSeq >= '%u'") %
758 boost::format(
"SELECT %s FROM AccountTransactions "
759 "WHERE Account = '%s' %s %s LIMIT %u, %u;") %
760 selection % app.accountIDCache().toBase58(options.account) %
761 maxClause % minClause %
762 beast::lexicalCastThrow<std::string>(options.offset) %
763 beast::lexicalCastThrow<std::string>(numberOfResults));
768 "AccountTransactions INNER JOIN Transactions "
769 "ON Transactions.TransID = AccountTransactions.TransID "
770 "WHERE Account = '%s' %s %s "
771 "ORDER BY AccountTransactions.LedgerSeq %s, "
772 "AccountTransactions.TxnSeq %s, AccountTransactions.TransID %s "
774 selection % app.accountIDCache().toBase58(options.account) %
775 maxClause % minClause % (descending ?
"DESC" :
"ASC") %
776 (descending ?
"DESC" :
"ASC") % (descending ?
"DESC" :
"ASC") %
777 beast::lexicalCastThrow<std::string>(options.offset) %
778 beast::lexicalCastThrow<std::string>(numberOfResults));
779 JLOG(j.
trace()) <<
"txSQL query: " << sql;
808 soci::session& session,
810 LedgerMaster& ledgerMaster,
811 RelationalDBInterface::AccountTxOptions
const& options,
820 "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta",
833 boost::optional<std::uint64_t> ledgerSeq;
834 boost::optional<std::string>
status;
835 soci::blob sociTxnBlob(session), sociTxnMetaBlob(session);
836 soci::indicator rti, tmi;
837 Blob rawTxn, txnMeta;
840 (session.prepare << sql,
841 soci::into(ledgerSeq),
843 soci::into(sociTxnBlob, rti),
844 soci::into(sociTxnMetaBlob, tmi));
849 if (soci::i_ok == rti)
854 if (soci::i_ok == tmi)
855 convert(sociTxnMetaBlob, txnMeta);
865 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0));
868 <<
"Recovering ledger " << seq <<
", txn " << txn->getID();
878 std::make_shared<TxMeta>(
879 txn->getID(), txn->getLedger(), txnMeta));
884 if (!total && limit_used)
886 RelationalDBInterface::AccountTxOptions opt = options;
889 app,
"COUNT(*)", opt, limit_used, descending,
false,
false, j);
891 session << sql1, soci::into(total);
902 soci::session& session,
904 LedgerMaster& ledgerMaster,
905 RelationalDBInterface::AccountTxOptions
const& options,
910 session, app, ledgerMaster, options, limit_used,
false, j);
915 soci::session& session,
917 LedgerMaster& ledgerMaster,
918 RelationalDBInterface::AccountTxOptions
const& options,
923 session, app, ledgerMaster, options, limit_used,
true, j);
951 soci::session& session,
953 RelationalDBInterface::AccountTxOptions
const& options,
962 "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta",
976 boost::optional<std::uint64_t> ledgerSeq;
977 boost::optional<std::string>
status;
978 soci::blob sociTxnBlob(session), sociTxnMetaBlob(session);
979 soci::indicator rti, tmi;
982 (session.prepare << sql,
983 soci::into(ledgerSeq),
985 soci::into(sociTxnBlob, rti),
986 soci::into(sociTxnMetaBlob, tmi));
992 if (soci::i_ok == rti)
995 if (soci::i_ok == tmi)
996 convert(sociTxnMetaBlob, txnMeta);
999 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0));
1001 ret.
emplace_back(std::move(rawTxn), std::move(txnMeta), seq);
1005 if (!total && limit_used)
1007 RelationalDBInterface::AccountTxOptions opt = options;
1010 app,
"COUNT(*)", opt, limit_used, descending,
true,
false, j);
1012 session << sql1, soci::into(total);
1018 return {ret, total};
1023 soci::session& session,
1025 RelationalDBInterface::AccountTxOptions
const& options,
1029 return getAccountTxsB(session, app, options, limit_used,
false, j);
1034 soci::session& session,
1036 RelationalDBInterface::AccountTxOptions
const& options,
1040 return getAccountTxsB(session, app, options, limit_used,
true, j);
1067 soci::session& session,
1068 AccountIDCache
const& idCache,
1073 RelationalDBInterface::AccountTxPageOptions
const& options,
1080 bool lookingForMarker = options.marker.has_value();
1084 if (options.limit == 0 || options.limit == UINT32_MAX ||
1085 (options.limit > page_length && !options.bAdmin))
1086 numberOfResults = page_length;
1088 numberOfResults = options.limit;
1090 if (numberOfResults < limit_used)
1091 return {options.marker, -1};
1092 numberOfResults -= limit_used;
1102 if (lookingForMarker)
1104 findLedger = options.marker->ledgerSeq;
1105 findSeq = options.marker->txnSeq;
1110 newmarker = options.marker;
1113 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1114 Status,RawTxn,TxnMeta
1115 FROM AccountTransactions INNER JOIN Transactions
1116 ON Transactions.TransID = AccountTransactions.TransID
1117 AND AccountTransactions.Account = '%s' WHERE
1124 const char*
const order =
forward ?
"ASC" :
"DESC";
1126 if (findLedger == 0)
1130 prefix + (R
"(AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u'
1131 ORDER BY AccountTransactions.LedgerSeq %s,
1132 AccountTransactions.TxnSeq %s
1134 idCache.toBase58(options.account) % options.minLedger %
1135 options.maxLedger % order % order % queryLimit);
1141 forward ? findLedger + 1 : options.minLedger;
1143 forward ? options.maxLedger : findLedger - 1;
1145 auto b58acct = idCache.toBase58(options.account);
1148 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1149 Status,RawTxn,TxnMeta
1150 FROM AccountTransactions, Transactions WHERE
1151 (AccountTransactions.TransID = Transactions.TransID AND
1152 AccountTransactions.Account = '%s' AND
1153 AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u')
1155 (AccountTransactions.TransID = Transactions.TransID AND
1156 AccountTransactions.Account = '%s' AND
1157 AccountTransactions.LedgerSeq = '%u' AND
1158 AccountTransactions.TxnSeq %s '%u')
1159 ORDER BY AccountTransactions.LedgerSeq %s,
1160 AccountTransactions.TxnSeq %s
1163 b58acct % minLedger % maxLedger % b58acct % findLedger % compare %
1164 findSeq % order % order % queryLimit);
1172 boost::optional<std::uint64_t> ledgerSeq;
1173 boost::optional<std::uint32_t> txnSeq;
1174 boost::optional<std::string>
status;
1175 soci::blob txnData(session);
1176 soci::blob txnMeta(session);
1177 soci::indicator dataPresent, metaPresent;
1179 soci::statement st =
1180 (session.prepare << sql,
1181 soci::into(ledgerSeq),
1184 soci::into(txnData, dataPresent),
1185 soci::into(txnMeta, metaPresent));
1191 if (lookingForMarker)
1193 if (findLedger == ledgerSeq.value_or(0) &&
1194 findSeq == txnSeq.value_or(0))
1196 lookingForMarker =
false;
1201 else if (numberOfResults == 0)
1204 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1209 if (dataPresent == soci::i_ok)
1214 if (metaPresent == soci::i_ok)
1220 if (rawMeta.size() == 0)
1221 onUnsavedLedger(ledgerSeq.value_or(0));
1226 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1229 std::move(rawMeta));
1243 return {newmarker, total};
1248 soci::session& session,
1271 soci::session& session,
1294 soci::session& session,
1301 "SELECT LedgerSeq,Status,RawTxn,TxnMeta "
1302 "FROM Transactions WHERE TransID='";
1308 boost::optional<std::uint64_t> ledgerSeq;
1309 boost::optional<std::string> status;
1310 Blob rawTxn, rawMeta;
1312 soci::blob sociRawTxnBlob(session), sociRawMetaBlob(session);
1313 soci::indicator txn, meta;
1315 session << sql, soci::into(ledgerSeq), soci::into(status),
1316 soci::into(sociRawTxnBlob, txn), soci::into(sociRawMetaBlob, meta);
1318 auto const got_data = session.got_data();
1320 if ((!got_data || txn != soci::i_ok || meta != soci::i_ok) && !
range)
1326 soci::indicator rti;
1329 <<
"SELECT COUNT(DISTINCT LedgerSeq) FROM Transactions WHERE "
1330 "LedgerSeq BETWEEN "
1331 <<
range->first() <<
" AND " <<
range->last() <<
";",
1332 soci::into(count, rti);
1334 if (!session.got_data() || rti != soci::i_ok)
1337 return count == (
range->last() -
range->first() + 1)
1342 convert(sociRawTxnBlob, rawTxn);
1343 convert(sociRawMetaBlob, rawMeta);
1352 return std::pair{std::move(txn),
nullptr};
1355 rangeCheckedCast<std::uint32_t>(ledgerSeq.value());
1357 auto txMeta = std::make_shared<TxMeta>(
id, inLedger, rawMeta);
1359 return std::pair{std::move(txn), std::move(txMeta)};
1363 JLOG(app.journal(
"Ledger").warn())
1364 <<
"Unable to deserialize transaction from raw SQL value. Error: "
1376 boost::filesystem::space_info
space =
1377 boost::filesystem::space(config.legacy(
"database_path"));
1381 JLOG(j.
fatal()) <<
"Remaining free disk space is less than 512MB";
1385 if (config.useTxTables())
1388 boost::filesystem::path dbPath = dbSetup.dataDir /
TxDBName;
1389 boost::system::error_code ec;
1391 boost::filesystem::file_size(dbPath, ec);
1395 <<
"Error checking transaction db file size: " << ec.message();
1399 static auto const pageSize = [&] {
1401 session <<
"PRAGMA page_size;", soci::into(ps);
1404 static auto const maxPages = [&] {
1406 session <<
"PRAGMA max_page_count;", soci::into(mp);
1410 session <<
"PRAGMA page_count;", soci::into(pageCount);
1413 safe_cast<std::uint64_t>(freePages) * pageSize;
1415 <<
"Transaction DB pathname: " << dbPath.string()
1416 <<
"; file size: " << dbSize.
value_or(-1) <<
" bytes"
1417 <<
"; SQLite page size: " << pageSize <<
" bytes"
1418 <<
"; Free pages: " << freePages <<
"; Free space: " << freeSpace
1420 <<
"Note that this does not take into account available disk "
1426 <<
"Free SQLite space for transaction db is less than "
1427 "512MB. To fix this, rippled must be executed with the "
1428 "vacuum parameter before restarting. "
1429 "Note that this activity can take multiple days, "
1430 "depending on database size.";