20 #include <ripple/app/ledger/AcceptedLedger.h>
21 #include <ripple/app/ledger/InboundLedgers.h>
22 #include <ripple/app/ledger/Ledger.h>
23 #include <ripple/app/ledger/LedgerMaster.h>
24 #include <ripple/app/ledger/LedgerToJson.h>
25 #include <ripple/app/ledger/OrderBookDB.h>
26 #include <ripple/app/ledger/PendingSaves.h>
27 #include <ripple/app/ledger/TransactionMaster.h>
28 #include <ripple/app/main/Application.h>
29 #include <ripple/app/misc/HashRouter.h>
30 #include <ripple/app/misc/LoadFeeTrack.h>
31 #include <ripple/app/misc/NetworkOPs.h>
32 #include <ripple/basics/Log.h>
33 #include <ripple/basics/StringUtilities.h>
34 #include <ripple/basics/contract.h>
35 #include <ripple/beast/core/LexicalCast.h>
36 #include <ripple/consensus/LedgerTiming.h>
37 #include <ripple/core/Config.h>
38 #include <ripple/core/DatabaseCon.h>
39 #include <ripple/core/JobQueue.h>
40 #include <ripple/core/SociDB.h>
41 #include <ripple/json/to_string.h>
42 #include <ripple/nodestore/Database.h>
43 #include <ripple/protocol/HashPrefix.h>
44 #include <ripple/protocol/Indexes.h>
45 #include <ripple/protocol/PublicKey.h>
46 #include <ripple/protocol/SecretKey.h>
47 #include <ripple/protocol/UintTypes.h>
48 #include <ripple/protocol/digest.h>
49 #include <ripple/protocol/jss.h>
50 #include <boost/optional.hpp>
96 return std::make_unique<sles_iter_impl>(*
this);
100 equal(base_type
const& impl)
const override
103 return iter_ == other.iter_;
115 auto const item = *
iter_;
117 return std::make_shared<SLE const>(sit, item.key());
144 return std::make_unique<txs_iter_impl>(*
this);
148 equal(base_type
const& impl)
const override
150 auto const& other =
dynamic_cast<txs_iter_impl const&
>(impl);
151 return iter_ == other.iter_;
163 auto const item = *
iter_;
193 sle->setFieldAmount(
sfBalance, info_.drops);
197 if (!amendments.empty())
200 sle->setFieldV256(
sfAmendments, STVector256{amendments});
205 setImmutable(config);
222 , rules_(config.features)
231 JLOG(j.
warn()) <<
"Don't have TX root for ledger";
238 JLOG(j.
warn()) <<
"Don't have AS root for ledger";
260 prevLedger.stateMap_->family()))
261 , stateMap_(prevLedger.stateMap_->snapShot(true))
262 , fees_(prevLedger.fees_)
263 , rules_(prevLedger.rules_)
311 info_.seq = ledgerSeq;
312 info_.closeTime = closeTime;
340 bool correctCloseTime,
356 return stateMap_->addItem(std::move(item),
false,
false);
365 return std::make_shared<STTx const>(sit);
376 result.
first = std::make_shared<STTx const>(s);
394 boost::optional<uint256>
400 if (last && item->key() >= last)
408 if (k.
key == beast::zero)
416 auto sle = std::make_shared<SLE>(
417 SerialIter{item->data(), item->size()}, item->key());
428 return std::make_unique<sles_iter_impl>(
stateMap_->begin());
434 return std::make_unique<sles_iter_impl>(
stateMap_->end());
441 return std::make_unique<sles_iter_impl>(stateMap_->upper_bound(key));
447 return std::make_unique<txs_iter_impl>(!
open(),
txMap_->begin());
453 return std::make_unique<txs_iter_impl>(!
open(),
txMap_->end());
459 return txMap_->hasItem(key);
465 auto const& item = txMap_->peekItem(key);
471 return {std::move(result.first), std::move(result.second)};
482 if (!stateMap_->peekItem(key,
digest))
484 return digest.as_uint256();
493 LogicError(
"Ledger::rawErase: key not found");
501 auto item = std::make_shared<SHAMapItem const>(sle->key(), std::move(ss));
502 if (!
stateMap_->addGiveItem(std::move(item),
false,
false))
503 LogicError(
"Ledger::rawInsert: key already exists");
511 auto item = std::make_shared<SHAMapItem const>(sle->key(), std::move(ss));
513 if (!
stateMap_->updateGiveItem(std::move(item),
false,
false))
514 LogicError(
"Ledger::rawReplace: key not found");
526 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
527 s.
addVL(txn->peekData());
528 s.
addVL(metaData->peekData());
529 auto item = std::make_shared<SHAMapItem const>(key, std::move(s));
530 if (!
txMap().addGiveItem(std::move(item),
true,
true))
594 auto sle = std::make_shared<SLE>(
595 SerialIter{value->data(), value->size()}, value->key());
619 if (!missingNodes1.
empty())
621 if (
auto stream = j.
info())
623 stream << missingNodes1.
size() <<
" missing account node(s)";
624 stream <<
"First: " << missingNodes1[0].what();
636 txMap_->walkMap(missingNodes2, 32);
639 if (!missingNodes2.
empty())
641 if (
auto stream = j.
info())
643 stream << missingNodes2.
size() <<
" missing transaction node(s)";
644 stream <<
"First: " << missingNodes2[0].what();
647 return missingNodes1.
empty() && missingNodes2.
empty();
665 JLOG(ledgerJ.
fatal()) <<
"ledger is not sane" << j;
683 if ((prevIndex & 0xff) == 0)
692 sle = std::make_shared<SLE>(k);
697 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(
sfHashes));
701 assert(hashes.
size() <= 256);
718 sle = std::make_shared<SLE>(k);
723 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(
sfHashes));
726 assert(hashes.
size() <= 256);
727 if (hashes.
size() == 256)
744 auto j = app.
journal(
"Ledger");
749 JLOG(j.debug()) <<
"Save aborted";
754 JLOG(j.trace()) <<
"saveValidatedLedger " << (
current ?
"" :
"fromAcquire ")
756 static boost::format deleteLedger(
757 "DELETE FROM Ledgers WHERE LedgerSeq = %u;");
758 static boost::format deleteTrans1(
759 "DELETE FROM Transactions WHERE LedgerSeq = %u;");
760 static boost::format deleteTrans2(
761 "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;");
762 static boost::format deleteAcctTrans(
763 "DELETE FROM AccountTransactions WHERE TransID = '%s';");
767 JLOG(j.fatal()) <<
"AH is zero: " <<
getJson(*ledger);
775 JLOG(j.fatal()) <<
"saveAcceptedLedger: seq=" << seq
797 aLedger = std::make_shared<AcceptedLedger>(
805 JLOG(j.warn()) <<
"An accepted ledger was missing nodes";
815 *db << boost::str(deleteLedger % seq);
821 soci::transaction tr(*db);
823 *db << boost::str(deleteTrans1 % seq);
824 *db << boost::str(deleteTrans2 % seq);
828 for (
auto const& [_, acceptedLedgerTx] : aLedger->getMap())
841 auto const& accts = acceptedLedgerTx->getAffected();
846 "INSERT INTO AccountTransactions "
847 "(TransID, Account, LedgerSeq, TxnSeq) VALUES ");
855 for (
auto const& account : accts)
875 JLOG(j.trace()) <<
"ActTx: " << sql;
880 JLOG(j.warn()) <<
"Transaction in ledger " << seq
881 <<
" affects no accounts";
888 acceptedLedgerTx->getTxn()->getMetaSQL(
889 seq, acceptedLedgerTx->getEscMeta()) +
898 R
"sql(INSERT OR REPLACE INTO Ledgers
899 (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime,
900 CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash)
902 (:ledgerHash,:ledgerSeq,:prevHash,:totalCoins,:closingTime,:prevClosingTime,
903 :closeTimeRes,:closeFlags,:accountSetHash,:transSetHash);)sql");
907 soci::transaction tr(*db);
912 auto const closeTime =
914 auto const parentCloseTime =
916 auto const closeTimeResolution =
922 *db << addLedger, soci::use(hash), soci::use(seq),
923 soci::use(parentHash), soci::use(drops), soci::use(closeTime),
924 soci::use(parentCloseTime), soci::use(closeTimeResolution),
925 soci::use(closeFlags), soci::use(accountHash), soci::use(txHash);
950 JLOG(stream) <<
"Double pend save for " << ledger->
info().
seq;
965 JLOG(stream) <<
"Pend save with seq in pending saves "
972 char const*
const jobName{
973 isCurrent ?
"Ledger::pendSave" :
"Ledger::pendOldSave"};
976 if (!isSynchronous &&
979 saveValidatedLedger(app, ledger, isCurrent);
1021 boost::optional<std::string> sLedgerHash, sPrevHash, sAccountHash,
1023 boost::optional<std::uint64_t> totDrops, closingTime, prevClosingTime,
1024 closeResolution, closeFlags, ledgerSeq64;
1028 "LedgerHash, PrevHash, AccountSetHash, TransSetHash, "
1030 "ClosingTime, PrevClosingTime, CloseTimeRes, CloseFlags,"
1031 "LedgerSeq from Ledgers " +
1034 *db << sql, soci::into(sLedgerHash), soci::into(sPrevHash),
1035 soci::into(sAccountHash), soci::into(sTransHash), soci::into(totDrops),
1036 soci::into(closingTime), soci::into(prevClosingTime),
1037 soci::into(closeResolution), soci::into(closeFlags),
1038 soci::into(ledgerSeq64);
1040 if (!db->got_data())
1043 JLOG(stream) <<
"Ledger not found: " << sqlSuffix;
1048 ledgerSeq = rangeCheckedCast<std::uint32_t>(ledgerSeq64.value_or(0));
1050 uint256 prevHash{}, accountHash{}, transHash{};
1054 prevHash.SetHexExact(*sPrevHash);
1056 accountHash.SetHexExact(*sAccountHash);
1058 transHash.SetHexExact(*sTransHash);
1067 info.
drops = totDrops.value_or(0);
1068 info.
closeTime = time_point{duration{closingTime.value_or(0)}};
1069 info.
parentCloseTime = time_point{duration{prevClosingTime.value_or(0)}};
1072 info.
seq = ledgerSeq;
1075 auto ledger = std::make_shared<Ledger>(
1092 Config
const& config,
1111 s <<
"WHERE LedgerSeq = " << ledgerIndex;
1112 std::tie(ledger, std::ignore, std::ignore) =
1126 s <<
"WHERE LedgerHash = '" << ledgerHash <<
"'";
1127 std::tie(ledger, std::ignore, std::ignore) =
1133 assert(!ledger || ledger->
info().
hash == ledgerHash);
1144 "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='";
1145 sql.
append(beast::lexicalCastThrow<std::string>(ledgerIndex));
1150 auto db = app.getLedgerDB().checkoutDb();
1152 boost::optional<std::string> lh;
1153 *db << sql, soci::into(lh);
1155 if (!db->got_data() || !lh)
1163 ret.SetHexExact(hash);
1174 auto db = app.getLedgerDB().checkoutDb();
1176 boost::optional<std::string> lhO, phO;
1178 *db <<
"SELECT LedgerHash,PrevHash FROM Ledgers "
1179 "INDEXED BY SeqLedger Where LedgerSeq = :ls;",
1180 soci::into(lhO), soci::into(phO), soci::use(ledgerIndex);
1184 auto stream = app.journal(
"Ledger").trace();
1185 JLOG(stream) <<
"Don't have ledger " << ledgerIndex;
1189 ledgerHash.SetHexExact(*lhO);
1190 parentHash.SetHexExact(*phO);
1201 "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= ";
1202 sql.
append(beast::lexicalCastThrow<std::string>(minSeq));
1203 sql.
append(
" AND LedgerSeq <= ");
1204 sql.
append(beast::lexicalCastThrow<std::string>(maxSeq));
1207 auto db = app.getLedgerDB().checkoutDb();
1211 boost::optional<std::string> ph;
1212 soci::statement st =
1213 (db->prepare << sql, soci::into(ls), soci::into(lh), soci::into(ph));
1219 ret[rangeCheckedCast<std::uint32_t>(ls)];
1220 hashes.
first.SetHexExact(lh);
1222 hashes.
second.SetHexExact(*ph);
1227 auto stream = app.journal(
"Ledger").warn();
1228 JLOG(stream) <<
"Null prev hash for ledger seq: " << ls;
std::unique_ptr< sles_type::iter_base > slesUpperBound(uint256 const &key) const override
std::tuple< std::shared_ptr< Ledger >, std::uint32_t, uint256 > loadLedgerHelper(std::string const &sqlSuffix, Application &app, bool acquire)
sles_iter_impl(SHAMap::const_iterator iter)
std::unique_ptr< sles_type::iter_base > slesBegin() const override
virtual void missing_node(std::uint32_t refNum)=0
bool addSLE(SLE const &sle)
void rawReplace(std::shared_ptr< SLE > const &sle) override
Unconditionally replace a state item.
@ ledgerMaster
ledger master data for signing
std::shared_ptr< SHAMap > txMap_
A pair of SHAMap key and LedgerEntryType.
virtual TaggedCache< uint256, AcceptedLedger > & getAcceptedLedgerCache()=0
tx_type txRead(key_type const &key) const override
Read a transaction from the tx map.
Keylet const & amendments() noexcept
The index of the amendment table.
SHAMapHash getHash() const
std::shared_ptr< Ledger > loadByIndex(std::uint32_t ledgerIndex, Application &app, bool acquire)
Stream trace() const
Severity stream access functions.
std::unique_ptr< sles_type::iter_base > slesEnd() const override
bool pending(LedgerIndex seq)
Return true if a ledger is in the progress of being saved.
constexpr value_type drops() const
Returns the number of drops.
const SField sfMetadata(access, STI_METADATA, 257, "Metadata")
const SF_U32 sfSequence(access, STI_UINT32, 4, "Sequence")
sles_type::value_type dereference() const override
const SF_Account sfAccount(access, STI_ACCOUNT, 1, "Account")
Keylet const & skip() noexcept
The index of the "short" skip list.
Serializer getSerializer() const
bool exists(Keylet const &k) const override
Determine if a state item exists.
bool equal(base_type const &impl) const override
std::shared_ptr< SLE > peek(Keylet const &k) const
std::chrono::time_point< Clock, Duration > roundCloseTime(std::chrono::time_point< Clock, Duration > closeTime, std::chrono::duration< Rep, Period > closeResolution)
Calculates the close time for a ledger, given a close time resolution.
void addRaw(LedgerInfo const &info, Serializer &s)
txs_iter_impl & operator=(txs_iter_impl const &)=delete
bool walkLedger(beast::Journal j) const
static std::string const & getMetaSQLInsertReplaceHeader()
bool addJob(JobType type, std::string const &name, JobHandler &&jobHandler)
Adds a job to the JobQueue.
std::string to_string(ListDisposition disposition)
void rawTxInsert(uint256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData) override
Add a transaction to the tx map.
bool startWork(LedgerIndex seq)
Start working on a ledger.
txs_iter_impl(bool metadata, SHAMap::const_iterator iter)
void rawErase(std::shared_ptr< SLE > const &sle) override
Delete an existing state item.
const SF_U32 sfReserveBase(access, STI_UINT32, 31, "ReserveBase")
static void finishLoadByIndexOrHash(std::shared_ptr< Ledger > const &ledger, Config const &config, beast::Journal j)
std::shared_ptr< STTx const > deserializeTx(SHAMapItem const &item)
Deserialize a SHAMapItem containing a single STTx.
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
virtual AccountIDCache const & accountIDCache() const =0
void setImmutable(Config const &config)
constexpr XRPAmount INITIAL_XRP
Configure the native currency.
uint256 getHashByIndex(std::uint32_t ledgerIndex, Application &app)
std::shared_ptr< SLE const > value_type
std::unique_ptr< txs_type::iter_base > txsEnd() const override
static Hasher::result_type digest(void const *data, std::size_t size) noexcept
NetClock::time_point closeTime
uint256 const & key() const
Returns the 'key' (or 'index') of this item.
const SF_U32 sfLastLedgerSequence(access, STI_UINT32, 27, "LastLedgerSequence")
LedgerInfo const & info() const override
Returns information about the ledger.
T time_since_epoch(T... args)
virtual void store(NodeObjectType type, Blob &&data, uint256 const &hash, std::uint32_t seq)=0
Store the object.
bool txExists(uint256 const &key) const override
Returns true if a tx exists in the tx map.
bool assertSane(beast::Journal ledgerJ) const
static bool saveValidatedLedger(Application &app, std::shared_ptr< Ledger const > const &ledger, bool current)
std::shared_ptr< Ledger > loadByHash(uint256 const &ledgerHash, Application &app, bool acquire)
LockedSociSession checkoutDb()
virtual Family & family()=0
void setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime, Config const &config)
void failedSave(std::uint32_t seq, uint256 const &hash)
virtual LedgerMaster & getLedgerMaster()=0
Keylet account(AccountID const &id) noexcept
AccountID root.
virtual PendingSaves & pendingSaves()=0
std::pair< std::shared_ptr< STTx const >, std::shared_ptr< STObject const > > deserializeTxPlusMeta(SHAMapItem const &item)
Deserialize a SHAMapItem containing STTx + STObject metadata.
static constexpr FeeUnit32 TRANSACTION_FEE_BASE
std::unique_ptr< base_type > copy() const override
void Rethrow()
Rethrow the exception currently being handled.
virtual Config & config()=0
bool isCurrent(ValidationParms const &p, NetClock::time_point now, NetClock::time_point signTime, NetClock::time_point seenTime)
Whether a validation is still current.
SHAMap::const_iterator iter_
SHAMap const & stateMap() const
XRPAmount FEE_OWNER_RESERVE
AccountID calcAccountID(PublicKey const &pk)
A SHAMap is both a radix tree with a fan-out of 16 and a Merkle tree.
SHAMap::const_iterator iter_
bool equal(base_type const &impl) const override
sles_iter_impl & operator=(sles_iter_impl const &)=delete
virtual JobQueue & getJobQueue()=0
XRPAmount FEE_ACCOUNT_RESERVE
void rawInsert(std::shared_ptr< SLE > const &sle) override
Unconditionally insert a state item.
const SF_U32 sfReferenceFeeUnits(access, STI_UINT32, 30, "ReferenceFeeUnits")
@ current
This was a new validation and was added.
void finishWork(LedgerIndex seq)
Finish working on a ledger.
@ transactionID
transaction plus signature to give transaction ID
A generic endpoint for log messages.
virtual DatabaseCon & getLedgerDB()=0
bool shouldWork(LedgerIndex seq, bool isSynchronous)
Check if a ledger should be dispatched.
bool SetHexExact(const char *psz)
Parse a hex string into a base_uint The string must contain exactly bytes * 2 hex characters and must...
Json::Value getJson(LedgerFill const &fill)
Return a new Json::Value representing the ledger with given options.
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
SHAMap const & txMap() const
bool getCloseAgree(LedgerInfo const &info)
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
const SF_Vec256 sfHashes(access, STI_VECTOR256, 2, "Hashes")
std::unique_ptr< txs_type::iter_base > txsBegin() const override
bool inLedger(uint256 const &hash, std::uint32_t ledger)
T emplace_back(T... args)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
std::unordered_set< uint256, beast::uhash<> > features
virtual NodeStore::Database & getNodeStore()=0
virtual beast::Journal journal(std::string const &name)=0
const SF_Amount sfBalance(access, STI_AMOUNT, 2, "Balance")
static uint256 calculateLedgerHash(LedgerInfo const &info)
bool setup(Config const &config)
const SF_U32 sfReserveIncrement(access, STI_UINT32, 32, "ReserveIncrement")
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
NetClock::duration closeTimeResolution
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
const create_genesis_t create_genesis
std::shared_ptr< SHAMap > stateMap_
bool open() const override
Returns true if this reflects an open ledger.
boost::optional< uint256 > succ(uint256 const &key, boost::optional< uint256 > const &last=boost::none) const override
Return the key of the next state item.
int addVL(Blob const &vector)
Rules controlling protocol behavior.
Keylet const & fees() noexcept
The (fixed) index of the object containing the ledger fees.
bool getHashesByIndex(std::uint32_t ledgerIndex, uint256 &ledgerHash, uint256 &parentHash, Application &app)
bool check(STLedgerEntry const &) const
Returns true if the SLE matches the type.
int add32(std::uint32_t i)
Information about the notional ledger backing the view.
std::chrono::duration< rep, period > duration
uint256 const & as_uint256() const
const SF_Vec256 sfAmendments(access, STI_VECTOR256, 3, "Amendments")
std::chrono::duration< Rep, Period > getNextLedgerTimeResolution(std::chrono::duration< Rep, Period > previousResolution, bool previousAgree, Seq ledgerSeq)
Calculates the close time resolution for the specified ledger.
const SF_U64 sfBaseFee(access, STI_UINT64, 5, "BaseFee")
constexpr auto ledgerDefaultTimeResolution
Initial resolution of ledger close time.
txs_type::value_type dereference() const override
bool pendSaveValidated(Application &app, std::shared_ptr< Ledger const > const &ledger, bool isSynchronous, bool isCurrent)
Save, or arrange to save, a fully-validated ledger Returns false on error.
Ledger(Ledger const &)=delete
boost::optional< digest_type > digest(key_type const &key) const override
Return the digest associated with the key.
void increment() override
std::chrono::time_point< NetClock > time_point
std::unique_ptr< base_type > copy() const override
virtual HashRouter & getHashRouter()=0
void increment() override
bool setFlags(uint256 const &key, int flags)
Set the flags on a hash.
Slice getSlice(std::size_t bytes)
static const std::uint32_t sLCF_NoConsensusTime
virtual DatabaseCon & getTxnDB()=0
void open(soci::session &s, BasicConfig const &config, std::string const &dbName)
Open a soci session.
std::string toBase58(AccountID const &) const
Return ripple::toBase58 for the AccountID.
NetClock::time_point parentCloseTime
virtual TransactionMaster & getMasterTransaction()=0