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/RelationalDatabase.h>
27 #include <ripple/app/rdb/backend/detail/Node.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>
50 "Need to modify switch statement if enum is modified");
57 return "Transactions";
59 return "AccountTransactions";
73 auto lgr{std::make_unique<DatabaseCon>(
75 lgr->getSession() << boost::str(
76 boost::format(
"PRAGMA cache_size=-%d;") %
82 auto tx{std::make_unique<DatabaseCon>(
84 tx->getSession() << boost::str(
85 boost::format(
"PRAGMA cache_size=-%d;") %
97 (tx->getSession().prepare
98 << (
"PRAGMA table_info(AccountTransactions);"),
103 soci::into(dflt_value, ind),
111 return {std::move(lgr), std::move(tx),
false};
116 return {std::move(lgr), std::move(tx),
true};
119 return {std::move(lgr), {},
true};
127 boost::optional<LedgerIndex> m;
128 session << query, soci::into(m);
137 boost::optional<LedgerIndex> m;
138 session << query, soci::into(m);
145 session <<
"DELETE FROM " <<
to_string(type)
146 <<
" WHERE LedgerSeq == " << ledgerSeq <<
";";
151 soci::session& session,
155 session <<
"DELETE FROM " <<
to_string(type) <<
" WHERE LedgerSeq < "
163 session <<
"SELECT COUNT(*) AS rows "
175 session <<
"SELECT COUNT(*) AS rows, "
176 "MIN(LedgerSeq) AS first, "
177 "MAX(LedgerSeq) AS last "
194 auto j = app.
journal(
"Ledger");
195 auto seq = ledger->info().seq;
198 JLOG(j.trace()) <<
"saveValidatedLedger " << (
current ?
"" :
"fromAcquire ")
201 if (!ledger->info().accountHash.isNonZero())
203 JLOG(j.fatal()) <<
"AH is zero: " <<
getJson({*ledger, {}});
207 if (ledger->info().accountHash != ledger->stateMap().getHash().as_uint256())
209 JLOG(j.fatal()) <<
"sAL: " << ledger->info().accountHash
210 <<
" != " << ledger->stateMap().getHash();
211 JLOG(j.fatal()) <<
"saveAcceptedLedger: seq=" << seq
216 assert(ledger->info().txHash == ledger->txMap().getHash().as_uint256());
222 addRaw(ledger->info(), s);
233 aLedger = std::make_shared<AcceptedLedger>(ledger, app);
235 ledger->info().hash, aLedger);
240 JLOG(j.warn()) <<
"An accepted ledger was missing nodes";
249 static boost::format deleteLedger(
250 "DELETE FROM Ledgers WHERE LedgerSeq = %u;");
251 static boost::format deleteTrans1(
252 "DELETE FROM Transactions WHERE LedgerSeq = %u;");
253 static boost::format deleteTrans2(
254 "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;");
255 static boost::format deleteAcctTrans(
256 "DELETE FROM AccountTransactions WHERE TransID = '%s';");
260 *db << boost::str(deleteLedger % seq);
267 soci::transaction tr(*db);
269 *db << boost::str(deleteTrans1 % seq);
270 *db << boost::str(deleteTrans2 % seq);
274 for (
auto const& acceptedLedgerTx : *aLedger)
284 auto const& accts = acceptedLedgerTx->getAffected();
289 "INSERT INTO AccountTransactions "
290 "(TransID, Account, LedgerSeq, TxnSeq) VALUES ");
298 for (
auto const& account : accts)
318 JLOG(j.trace()) <<
"ActTx: " << sql;
321 else if (
auto const& sleTxn = acceptedLedgerTx->getTxn();
326 JLOG(j.warn()) <<
"Transaction in ledger " << seq
327 <<
" affects no accounts";
333 acceptedLedgerTx->getTxn()->getMetaSQL(
334 seq, acceptedLedgerTx->getEscMeta()) +
345 R
"sql(INSERT OR REPLACE INTO Ledgers
346 (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime,
347 CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash)
349 (:ledgerHash,:ledgerSeq,:prevHash,:totalCoins,:closingTime,:prevClosingTime,
350 :closeTimeRes,:closeFlags,:accountSetHash,:transSetHash);)sql");
354 soci::transaction tr(*db);
356 auto const hash =
to_string(ledger->info().hash);
357 auto const parentHash =
to_string(ledger->info().parentHash);
358 auto const drops =
to_string(ledger->info().drops);
359 auto const closeTime =
360 ledger->info().closeTime.time_since_epoch().count();
361 auto const parentCloseTime =
362 ledger->info().parentCloseTime.time_since_epoch().count();
363 auto const closeTimeResolution =
364 ledger->info().closeTimeResolution.count();
365 auto const closeFlags = ledger->info().closeFlags;
366 auto const accountHash =
to_string(ledger->info().accountHash);
367 auto const txHash =
to_string(ledger->info().txHash);
369 *db << addLedger, soci::use(hash), soci::use(seq),
370 soci::use(parentHash), soci::use(drops), soci::use(closeTime),
371 soci::use(parentCloseTime), soci::use(closeTimeResolution),
372 soci::use(closeFlags), soci::use(accountHash),
392 soci::session& session,
397 boost::optional<std::string> hash, parentHash, accountHash, txHash;
398 boost::optional<std::uint64_t> seq, drops, closeTime, parentCloseTime,
399 closeTimeResolution, closeFlags;
403 "LedgerHash, PrevHash, AccountSetHash, TransSetHash, "
405 "ClosingTime, PrevClosingTime, CloseTimeRes, CloseFlags,"
406 "LedgerSeq FROM Ledgers " +
409 session << sql, soci::into(hash), soci::into(parentHash),
410 soci::into(accountHash), soci::into(txHash), soci::into(drops),
411 soci::into(closeTime), soci::into(parentCloseTime),
412 soci::into(closeTimeResolution), soci::into(closeFlags),
415 if (!session.got_data())
417 JLOG(j.
debug()) <<
"Ledger not found: " << sqlSuffix;
426 if (hash && !info.hash.parseHex(*hash))
428 JLOG(j.
debug()) <<
"Hash parse error for ledger: " << sqlSuffix;
432 if (parentHash && !info.parentHash.parseHex(*parentHash))
434 JLOG(j.
debug()) <<
"parentHash parse error for ledger: " << sqlSuffix;
438 if (accountHash && !info.accountHash.parseHex(*accountHash))
440 JLOG(j.
debug()) <<
"accountHash parse error for ledger: " << sqlSuffix;
444 if (txHash && !info.txHash.parseHex(*txHash))
446 JLOG(j.
debug()) <<
"txHash parse error for ledger: " << sqlSuffix;
450 info.seq = rangeCheckedCast<std::uint32_t>(seq.value_or(0));
451 info.drops =
drops.value_or(0);
452 info.closeTime = time_point{duration{closeTime.value_or(0)}};
453 info.parentCloseTime = time_point{duration{parentCloseTime.value_or(0)}};
454 info.closeFlags = closeFlags.value_or(0);
455 info.closeTimeResolution = duration{closeTimeResolution.value_or(0)};
462 soci::session& session,
467 s <<
"WHERE LedgerSeq = " << ledgerSeq;
475 s <<
"ORDER BY LedgerSeq DESC LIMIT 1";
481 soci::session& session,
487 " ORDER BY LedgerSeq ASC LIMIT 1";
493 soci::session& session,
499 " ORDER BY LedgerSeq DESC LIMIT 1";
505 soci::session& session,
510 s <<
"WHERE LedgerHash = '" << ledgerHash <<
"'";
520 "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='";
521 sql.
append(beast::lexicalCastThrow<std::string>(ledgerIndex));
527 boost::optional<std::string> lh;
528 session << sql, soci::into(lh);
530 if (!session.got_data() || !lh)
546 soci::session& session,
551 boost::optional<std::string> lhO, phO;
553 session <<
"SELECT LedgerHash,PrevHash FROM Ledgers "
554 "INDEXED BY SeqLedger WHERE LedgerSeq = :ls;",
555 soci::into(lhO), soci::into(phO), soci::use(ledgerIndex);
559 auto stream = j.
trace();
560 JLOG(stream) <<
"Don't have ledger " << ledgerIndex;
564 LedgerHashPair hashes;
565 if (!hashes.ledgerHash.parseHex(*lhO) || !hashes.parentHash.parseHex(*phO))
567 auto stream = j.
trace();
568 JLOG(stream) <<
"Error parse hashes for ledger " << ledgerIndex;
577 soci::session& session,
583 "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= ";
584 sql.
append(beast::lexicalCastThrow<std::string>(minSeq));
585 sql.
append(
" AND LedgerSeq <= ");
586 sql.
append(beast::lexicalCastThrow<std::string>(maxSeq));
592 boost::optional<std::string> ph;
594 (session.prepare << sql,
606 JLOG(j.
warn()) <<
"Error parsed hash for ledger seq: " << ls;
610 JLOG(j.
warn()) <<
"Null prev hash for ledger seq: " << ls;
614 JLOG(j.
warn()) <<
"Error parsed prev hash for ledger seq: " << ls;
622 soci::session& session,
630 "SELECT LedgerSeq, Status, RawTxn "
631 "FROM Transactions ORDER BY LedgerSeq DESC LIMIT %u,%u;") %
632 startIndex % quantity);
639 boost::optional<std::uint64_t> ledgerSeq;
640 boost::optional<std::string> status;
641 soci::blob sociRawTxnBlob(session);
646 (session.prepare << sql,
647 soci::into(ledgerSeq),
649 soci::into(sociRawTxnBlob, rti));
654 if (soci::i_ok == rti)
655 convert(sociRawTxnBlob, rawTxn);
660 ledgerSeq, status, rawTxn, app))
669 session <<
"SELECT COUNT(*) FROM Transactions;", soci::into(total);
702 RelationalDatabase::AccountTxOptions
const& options,
718 else if (options.limit == UINT32_MAX)
720 numberOfResults = binary ? BINARY_PAGE_LENGTH : NONBINARY_PAGE_LENGTH;
722 else if (!options.bUnlimited)
725 binary ? BINARY_PAGE_LENGTH : NONBINARY_PAGE_LENGTH, options.limit);
729 numberOfResults = options.limit;
734 if (numberOfResults <= *limit_used)
737 numberOfResults -= *limit_used;
743 if (options.maxLedger)
745 maxClause = boost::str(
746 boost::format(
"AND AccountTransactions.LedgerSeq <= '%u'") %
750 if (options.minLedger)
752 minClause = boost::str(
753 boost::format(
"AND AccountTransactions.LedgerSeq >= '%u'") %
761 boost::format(
"SELECT %s FROM AccountTransactions "
762 "WHERE Account = '%s' %s %s LIMIT %u, %u;") %
763 selection %
toBase58(options.account) % maxClause % minClause %
764 beast::lexicalCastThrow<std::string>(options.offset) %
765 beast::lexicalCastThrow<std::string>(numberOfResults));
770 "AccountTransactions INNER JOIN Transactions "
771 "ON Transactions.TransID = AccountTransactions.TransID "
772 "WHERE Account = '%s' %s %s "
773 "ORDER BY AccountTransactions.LedgerSeq %s, "
774 "AccountTransactions.TxnSeq %s, AccountTransactions.TransID %s "
776 selection %
toBase58(options.account) % maxClause % minClause %
777 (descending ?
"DESC" :
"ASC") % (descending ?
"DESC" :
"ASC") %
778 (descending ?
"DESC" :
"ASC") %
779 beast::lexicalCastThrow<std::string>(options.offset) %
780 beast::lexicalCastThrow<std::string>(numberOfResults));
781 JLOG(j.
trace()) <<
"txSQL query: " << sql;
811 soci::session& session,
813 LedgerMaster& ledgerMaster,
814 RelationalDatabase::AccountTxOptions
const& options,
823 "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta",
836 boost::optional<std::uint64_t> ledgerSeq;
837 boost::optional<std::string>
status;
838 soci::blob sociTxnBlob(session), sociTxnMetaBlob(session);
839 soci::indicator rti, tmi;
840 Blob rawTxn, txnMeta;
843 (session.prepare << sql,
844 soci::into(ledgerSeq),
846 soci::into(sociTxnBlob, rti),
847 soci::into(sociTxnMetaBlob, tmi));
852 if (soci::i_ok == rti)
857 if (soci::i_ok == tmi)
858 convert(sociTxnMetaBlob, txnMeta);
868 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0));
871 <<
"Recovering ledger " << seq <<
", txn " << txn->getID();
881 std::make_shared<TxMeta>(
882 txn->getID(), txn->getLedger(), txnMeta));
887 if (!total && limit_used)
889 RelationalDatabase::AccountTxOptions opt = options;
892 app,
"COUNT(*)", opt, limit_used, descending,
false,
false, j);
894 session << sql1, soci::into(total);
905 soci::session& session,
907 LedgerMaster& ledgerMaster,
908 RelationalDatabase::AccountTxOptions
const& options,
913 session, app, ledgerMaster, options, limit_used,
false, j);
918 soci::session& session,
926 session, app, ledgerMaster, options, limit_used,
true, j);
954 soci::session& session,
956 RelationalDatabase::AccountTxOptions
const& options,
965 "AccountTransactions.LedgerSeq,Status,RawTxn,TxnMeta",
979 boost::optional<std::uint64_t> ledgerSeq;
980 boost::optional<std::string>
status;
981 soci::blob sociTxnBlob(session), sociTxnMetaBlob(session);
982 soci::indicator rti, tmi;
985 (session.prepare << sql,
986 soci::into(ledgerSeq),
988 soci::into(sociTxnBlob, rti),
989 soci::into(sociTxnMetaBlob, tmi));
995 if (soci::i_ok == rti)
998 if (soci::i_ok == tmi)
999 convert(sociTxnMetaBlob, txnMeta);
1002 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0));
1004 ret.
emplace_back(std::move(rawTxn), std::move(txnMeta), seq);
1008 if (!total && limit_used)
1010 RelationalDatabase::AccountTxOptions opt = options;
1013 app,
"COUNT(*)", opt, limit_used, descending,
true,
false, j);
1015 session << sql1, soci::into(total);
1021 return {ret, total};
1026 soci::session& session,
1028 RelationalDatabase::AccountTxOptions
const& options,
1032 return getAccountTxsB(session, app, options, limit_used,
false, j);
1037 soci::session& session,
1043 return getAccountTxsB(session, app, options, limit_used,
true, j);
1069 soci::session& session,
1074 RelationalDatabase::AccountTxPageOptions
const& options,
1081 bool lookingForMarker = options.marker.has_value();
1085 if (options.limit == 0 || options.limit == UINT32_MAX ||
1086 (options.limit > page_length && !options.bAdmin))
1087 numberOfResults = page_length;
1089 numberOfResults = options.limit;
1091 if (numberOfResults < limit_used)
1092 return {options.marker, -1};
1093 numberOfResults -= limit_used;
1103 if (lookingForMarker)
1105 findLedger = options.marker->ledgerSeq;
1106 findSeq = options.marker->txnSeq;
1111 newmarker = options.marker;
1114 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1115 Status,RawTxn,TxnMeta
1116 FROM AccountTransactions INNER JOIN Transactions
1117 ON Transactions.TransID = AccountTransactions.TransID
1118 AND AccountTransactions.Account = '%s' WHERE
1125 const char*
const order =
forward ?
"ASC" :
"DESC";
1127 if (findLedger == 0)
1131 prefix + (R
"(AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u'
1132 ORDER BY AccountTransactions.LedgerSeq %s,
1133 AccountTransactions.TxnSeq %s
1135 toBase58(options.account) % options.minLedger % options.maxLedger %
1136 order % order % queryLimit);
1142 forward ? findLedger + 1 : options.minLedger;
1144 forward ? options.maxLedger : findLedger - 1;
1146 auto b58acct =
toBase58(options.account);
1149 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1150 Status,RawTxn,TxnMeta
1151 FROM AccountTransactions, Transactions WHERE
1152 (AccountTransactions.TransID = Transactions.TransID AND
1153 AccountTransactions.Account = '%s' AND
1154 AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u')
1156 (AccountTransactions.TransID = Transactions.TransID AND
1157 AccountTransactions.Account = '%s' AND
1158 AccountTransactions.LedgerSeq = '%u' AND
1159 AccountTransactions.TxnSeq %s '%u')
1160 ORDER BY AccountTransactions.LedgerSeq %s,
1161 AccountTransactions.TxnSeq %s
1164 b58acct % minLedger % maxLedger % b58acct % findLedger % compare %
1165 findSeq % order % order % queryLimit);
1173 boost::optional<std::uint64_t> ledgerSeq;
1174 boost::optional<std::uint32_t> txnSeq;
1175 boost::optional<std::string>
status;
1176 soci::blob txnData(session);
1177 soci::blob txnMeta(session);
1178 soci::indicator dataPresent, metaPresent;
1180 soci::statement st =
1181 (session.prepare << sql,
1182 soci::into(ledgerSeq),
1185 soci::into(txnData, dataPresent),
1186 soci::into(txnMeta, metaPresent));
1192 if (lookingForMarker)
1194 if (findLedger == ledgerSeq.value_or(0) &&
1195 findSeq == txnSeq.value_or(0))
1197 lookingForMarker =
false;
1202 else if (numberOfResults == 0)
1205 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1210 if (dataPresent == soci::i_ok)
1215 if (metaPresent == soci::i_ok)
1221 if (rawMeta.size() == 0)
1222 onUnsavedLedger(ledgerSeq.value_or(0));
1227 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1230 std::move(rawMeta));
1244 return {newmarker, total};
1249 soci::session& session,
1270 soci::session& session,
1291 soci::session& session,
1298 "SELECT LedgerSeq,Status,RawTxn,TxnMeta "
1299 "FROM Transactions WHERE TransID='";
1305 boost::optional<std::uint64_t> ledgerSeq;
1306 boost::optional<std::string> status;
1307 Blob rawTxn, rawMeta;
1309 soci::blob sociRawTxnBlob(session), sociRawMetaBlob(session);
1310 soci::indicator txn, meta;
1312 session << sql, soci::into(ledgerSeq), soci::into(status),
1313 soci::into(sociRawTxnBlob, txn), soci::into(sociRawMetaBlob, meta);
1315 auto const got_data = session.got_data();
1317 if ((!got_data || txn != soci::i_ok || meta != soci::i_ok) && !
range)
1323 soci::indicator rti;
1326 <<
"SELECT COUNT(DISTINCT LedgerSeq) FROM Transactions WHERE "
1327 "LedgerSeq BETWEEN "
1328 <<
range->first() <<
" AND " <<
range->last() <<
";",
1329 soci::into(count, rti);
1331 if (!session.got_data() || rti != soci::i_ok)
1334 return count == (
range->last() -
range->first() + 1)
1339 convert(sociRawTxnBlob, rawTxn);
1340 convert(sociRawMetaBlob, rawMeta);
1349 return std::pair{std::move(txn),
nullptr};
1352 rangeCheckedCast<std::uint32_t>(ledgerSeq.value());
1354 auto txMeta = std::make_shared<TxMeta>(
id, inLedger, rawMeta);
1356 return std::pair{std::move(txn), std::move(txMeta)};
1360 JLOG(app.journal(
"Ledger").warn())
1361 <<
"Unable to deserialize transaction from raw SQL value. Error: "
1373 boost::filesystem::space_info
space =
1374 boost::filesystem::space(config.legacy(
"database_path"));
1378 JLOG(j.
fatal()) <<
"Remaining free disk space is less than 512MB";
1382 if (config.useTxTables())
1385 boost::filesystem::path dbPath = dbSetup.dataDir /
TxDBName;
1386 boost::system::error_code ec;
1388 boost::filesystem::file_size(dbPath, ec);
1392 <<
"Error checking transaction db file size: " << ec.message();
1396 static auto const pageSize = [&] {
1398 session <<
"PRAGMA page_size;", soci::into(ps);
1401 static auto const maxPages = [&] {
1403 session <<
"PRAGMA max_page_count;", soci::into(mp);
1407 session <<
"PRAGMA page_count;", soci::into(pageCount);
1410 safe_cast<std::uint64_t>(freePages) * pageSize;
1412 <<
"Transaction DB pathname: " << dbPath.string()
1413 <<
"; file size: " << dbSize.
value_or(-1) <<
" bytes"
1414 <<
"; SQLite page size: " << pageSize <<
" bytes"
1415 <<
"; Free pages: " << freePages <<
"; Free space: " << freeSpace
1417 <<
"Note that this does not take into account available disk "
1423 <<
"Free SQLite space for transaction db is less than "
1424 "512MB. To fix this, rippled must be executed with the "
1425 "vacuum parameter before restarting. "
1426 "Note that this activity can take multiple days, "
1427 "depending on database size.";