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='";
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 >= ";
585 sql.
append(
" AND LedgerSeq <= ");
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 options.offset % numberOfResults);
769 "AccountTransactions INNER JOIN Transactions "
770 "ON Transactions.TransID = AccountTransactions.TransID "
771 "WHERE Account = '%s' %s %s "
772 "ORDER BY AccountTransactions.LedgerSeq %s, "
773 "AccountTransactions.TxnSeq %s, AccountTransactions.TransID %s "
775 selection %
toBase58(options.account) % maxClause % minClause %
776 (descending ?
"DESC" :
"ASC") % (descending ?
"DESC" :
"ASC") %
777 (descending ?
"DESC" :
"ASC") % options.offset % numberOfResults);
778 JLOG(j.
trace()) <<
"txSQL query: " << sql;
808 soci::session& session,
810 LedgerMaster& ledgerMaster,
811 RelationalDatabase::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 RelationalDatabase::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 RelationalDatabase::AccountTxOptions
const& options,
910 session, app, ledgerMaster, options, limit_used,
false, j);
915 soci::session& session,
923 session, app, ledgerMaster, options, limit_used,
true, j);
951 soci::session& session,
953 RelationalDatabase::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 RelationalDatabase::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 RelationalDatabase::AccountTxOptions
const& options,
1029 return getAccountTxsB(session, app, options, limit_used,
false, j);
1034 soci::session& session,
1040 return getAccountTxsB(session, app, options, limit_used,
true, j);
1066 soci::session& session,
1071 RelationalDatabase::AccountTxPageOptions
const& options,
1078 bool lookingForMarker = options.marker.has_value();
1082 if (options.limit == 0 || options.limit == UINT32_MAX ||
1083 (options.limit > page_length && !options.bAdmin))
1084 numberOfResults = page_length;
1086 numberOfResults = options.limit;
1088 if (numberOfResults < limit_used)
1089 return {options.marker, -1};
1090 numberOfResults -= limit_used;
1100 if (lookingForMarker)
1102 findLedger = options.marker->ledgerSeq;
1103 findSeq = options.marker->txnSeq;
1108 newmarker = options.marker;
1111 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1112 Status,RawTxn,TxnMeta
1113 FROM AccountTransactions INNER JOIN Transactions
1114 ON Transactions.TransID = AccountTransactions.TransID
1115 AND AccountTransactions.Account = '%s' WHERE
1122 const char*
const order =
forward ?
"ASC" :
"DESC";
1124 if (findLedger == 0)
1128 prefix + (R
"(AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u'
1129 ORDER BY AccountTransactions.LedgerSeq %s,
1130 AccountTransactions.TxnSeq %s
1132 toBase58(options.account) % options.minLedger % options.maxLedger %
1133 order % order % queryLimit);
1139 forward ? findLedger + 1 : options.minLedger;
1141 forward ? options.maxLedger : findLedger - 1;
1143 auto b58acct =
toBase58(options.account);
1146 R
"(SELECT AccountTransactions.LedgerSeq,AccountTransactions.TxnSeq,
1147 Status,RawTxn,TxnMeta
1148 FROM AccountTransactions, Transactions WHERE
1149 (AccountTransactions.TransID = Transactions.TransID AND
1150 AccountTransactions.Account = '%s' AND
1151 AccountTransactions.LedgerSeq BETWEEN '%u' AND '%u')
1153 (AccountTransactions.TransID = Transactions.TransID AND
1154 AccountTransactions.Account = '%s' AND
1155 AccountTransactions.LedgerSeq = '%u' AND
1156 AccountTransactions.TxnSeq %s '%u')
1157 ORDER BY AccountTransactions.LedgerSeq %s,
1158 AccountTransactions.TxnSeq %s
1161 b58acct % minLedger % maxLedger % b58acct % findLedger % compare %
1162 findSeq % order % order % queryLimit);
1170 boost::optional<std::uint64_t> ledgerSeq;
1171 boost::optional<std::uint32_t> txnSeq;
1172 boost::optional<std::string>
status;
1173 soci::blob txnData(session);
1174 soci::blob txnMeta(session);
1175 soci::indicator dataPresent, metaPresent;
1177 soci::statement st =
1178 (session.prepare << sql,
1179 soci::into(ledgerSeq),
1182 soci::into(txnData, dataPresent),
1183 soci::into(txnMeta, metaPresent));
1189 if (lookingForMarker)
1191 if (findLedger == ledgerSeq.value_or(0) &&
1192 findSeq == txnSeq.value_or(0))
1194 lookingForMarker =
false;
1199 else if (numberOfResults == 0)
1202 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1207 if (dataPresent == soci::i_ok)
1212 if (metaPresent == soci::i_ok)
1218 if (rawMeta.size() == 0)
1219 onUnsavedLedger(ledgerSeq.value_or(0));
1224 rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or(0)),
1227 std::move(rawMeta));
1241 return {newmarker, total};
1246 soci::session& session,
1267 soci::session& session,
1288 soci::session& session,
1295 "SELECT LedgerSeq,Status,RawTxn,TxnMeta "
1296 "FROM Transactions WHERE TransID='";
1302 boost::optional<std::uint64_t> ledgerSeq;
1303 boost::optional<std::string> status;
1304 Blob rawTxn, rawMeta;
1306 soci::blob sociRawTxnBlob(session), sociRawMetaBlob(session);
1307 soci::indicator txn, meta;
1309 session << sql, soci::into(ledgerSeq), soci::into(status),
1310 soci::into(sociRawTxnBlob, txn), soci::into(sociRawMetaBlob, meta);
1312 auto const got_data = session.got_data();
1314 if ((!got_data || txn != soci::i_ok || meta != soci::i_ok) && !
range)
1320 soci::indicator rti;
1323 <<
"SELECT COUNT(DISTINCT LedgerSeq) FROM Transactions WHERE "
1324 "LedgerSeq BETWEEN "
1325 <<
range->first() <<
" AND " <<
range->last() <<
";",
1326 soci::into(count, rti);
1328 if (!session.got_data() || rti != soci::i_ok)
1331 return count == (
range->last() -
range->first() + 1)
1336 convert(sociRawTxnBlob, rawTxn);
1337 convert(sociRawMetaBlob, rawMeta);
1346 return std::pair{std::move(txn),
nullptr};
1349 rangeCheckedCast<std::uint32_t>(ledgerSeq.value());
1351 auto txMeta = std::make_shared<TxMeta>(
id, inLedger, rawMeta);
1353 return std::pair{std::move(txn), std::move(txMeta)};
1357 JLOG(app.journal(
"Ledger").warn())
1358 <<
"Unable to deserialize transaction from raw SQL value. Error: "
1370 boost::filesystem::space_info
space =
1371 boost::filesystem::space(config.legacy(
"database_path"));
1375 JLOG(j.
fatal()) <<
"Remaining free disk space is less than 512MB";
1379 if (config.useTxTables())
1382 boost::filesystem::path dbPath = dbSetup.dataDir /
TxDBName;
1383 boost::system::error_code ec;
1385 boost::filesystem::file_size(dbPath, ec);
1389 <<
"Error checking transaction db file size: " << ec.message();
1393 static auto const pageSize = [&] {
1395 session <<
"PRAGMA page_size;", soci::into(ps);
1398 static auto const maxPages = [&] {
1400 session <<
"PRAGMA max_page_count;", soci::into(mp);
1404 session <<
"PRAGMA page_count;", soci::into(pageCount);
1407 safe_cast<std::uint64_t>(freePages) * pageSize;
1409 <<
"Transaction DB pathname: " << dbPath.string()
1410 <<
"; file size: " << dbSize.
value_or(-1) <<
" bytes"
1411 <<
"; SQLite page size: " << pageSize <<
" bytes"
1412 <<
"; Free pages: " << freePages <<
"; Free space: " << freeSpace
1414 <<
"Note that this does not take into account available disk "
1420 <<
"Free SQLite space for transaction db is less than "
1421 "512MB. To fix this, rippled must be executed with the "
1422 "vacuum parameter before restarting. "
1423 "Note that this activity can take multiple days, "
1424 "depending on database size.";