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/Feature.h>
44 #include <ripple/protocol/HashPrefix.h>
45 #include <ripple/protocol/Indexes.h>
46 #include <ripple/protocol/PublicKey.h>
47 #include <ripple/protocol/SecretKey.h>
48 #include <ripple/protocol/UintTypes.h>
49 #include <ripple/protocol/digest.h>
50 #include <ripple/protocol/jss.h>
51 #include <boost/optional.hpp>
97 return std::make_unique<sles_iter_impl>(*
this);
101 equal(base_type
const& impl)
const override
104 return iter_ == p->iter_;
117 auto const item = *
iter_;
119 return std::make_shared<SLE const>(sit, item.key());
146 return std::make_unique<txs_iter_impl>(*
this);
150 equal(base_type
const& impl)
const override
152 if (
auto const p =
dynamic_cast<txs_iter_impl const*
>(&impl))
153 return iter_ == p->iter_;
166 auto const item = *
iter_;
196 sle->setFieldAmount(
sfBalance, info_.drops);
200 if (!amendments.empty())
203 sle->setFieldV256(
sfAmendments, STVector256{amendments});
208 setImmutable(config);
225 , rules_(config.features)
234 JLOG(j.
warn()) <<
"Don't have transaction root for ledger" <<
info_.
seq;
241 JLOG(j.
warn()) <<
"Don't have state data root for ledger" <<
info_.
seq;
263 prevLedger.stateMap_->family()))
264 , stateMap_(prevLedger.stateMap_->snapShot(true))
265 , fees_(prevLedger.fees_)
266 , rules_(prevLedger.rules_)
314 info_.seq = ledgerSeq;
315 info_.closeTime = closeTime;
343 bool correctCloseTime,
368 return std::make_shared<STTx const>(sit);
379 result.
first = std::make_shared<STTx const>(s);
397 boost::optional<uint256>
403 if (last && item->key() >= last)
411 if (k.
key == beast::zero)
419 auto sle = std::make_shared<SLE>(
420 SerialIter{item->data(), item->size()}, item->key());
431 return std::make_unique<sles_iter_impl>(
stateMap_->begin());
437 return std::make_unique<sles_iter_impl>(
stateMap_->end());
444 return std::make_unique<sles_iter_impl>(stateMap_->upper_bound(key));
450 return std::make_unique<txs_iter_impl>(!
open(),
txMap_->begin());
456 return std::make_unique<txs_iter_impl>(!
open(),
txMap_->end());
462 return txMap_->hasItem(key);
468 auto const& item = txMap_->peekItem(key);
474 return {std::move(result.first), std::move(result.second)};
485 if (!stateMap_->peekItem(key,
digest))
487 return digest.as_uint256();
496 LogicError(
"Ledger::rawErase: key not found");
506 std::make_shared<SHAMapItem const>(sle->key(), std::move(ss))))
507 LogicError(
"Ledger::rawInsert: key already exists");
517 std::make_shared<SHAMapItem const>(sle->key(), std::move(ss))))
518 LogicError(
"Ledger::rawReplace: key not found");
530 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
531 s.
addVL(txn->peekData());
532 s.
addVL(metaData->peekData());
533 if (!
txMap().addGiveItem(
535 std::make_shared<SHAMapItem const>(key, std::move(s))))
599 auto sle = std::make_shared<SLE>(
600 SerialIter{value->data(), value->size()}, value->key());
614 for (
auto const& n : nUnlData)
632 boost::optional<PublicKey>
647 boost::optional<PublicKey>
672 if (!hasToDisable && !hasToReEnable)
679 for (
auto v : oldNUnl)
681 if (hasToReEnable && v.isFieldPresent(
sfPublicKey) &&
697 if (!newNUnl.
empty())
730 if (!missingNodes1.
empty())
732 if (
auto stream = j.
info())
734 stream << missingNodes1.
size() <<
" missing account node(s)";
735 stream <<
"First: " << missingNodes1[0].what();
747 txMap_->walkMap(missingNodes2, 32);
750 if (!missingNodes2.
empty())
752 if (
auto stream = j.
info())
754 stream << missingNodes2.
size() <<
" missing transaction node(s)";
755 stream <<
"First: " << missingNodes2[0].what();
758 return missingNodes1.
empty() && missingNodes2.
empty();
776 JLOG(ledgerJ.
fatal()) <<
"ledger is not sensible" << j;
794 if ((prevIndex & 0xff) == 0)
803 sle = std::make_shared<SLE>(k);
808 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(
sfHashes));
812 assert(hashes.
size() <= 256);
829 sle = std::make_shared<SLE>(k);
834 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(
sfHashes));
837 assert(hashes.
size() <= 256);
838 if (hashes.
size() == 256)
872 auto j = app.
journal(
"Ledger");
877 JLOG(j.debug()) <<
"Save aborted";
882 JLOG(j.trace()) <<
"saveValidatedLedger " << (
current ?
"" :
"fromAcquire ")
884 static boost::format deleteLedger(
885 "DELETE FROM Ledgers WHERE LedgerSeq = %u;");
886 static boost::format deleteTrans1(
887 "DELETE FROM Transactions WHERE LedgerSeq = %u;");
888 static boost::format deleteTrans2(
889 "DELETE FROM AccountTransactions WHERE LedgerSeq = %u;");
890 static boost::format deleteAcctTrans(
891 "DELETE FROM AccountTransactions WHERE TransID = '%s';");
895 JLOG(j.fatal()) <<
"AH is zero: " <<
getJson(*ledger);
903 JLOG(j.fatal()) <<
"saveAcceptedLedger: seq=" << seq
925 aLedger = std::make_shared<AcceptedLedger>(
933 JLOG(j.warn()) <<
"An accepted ledger was missing nodes";
943 *db << boost::str(deleteLedger % seq);
949 soci::transaction tr(*db);
951 *db << boost::str(deleteTrans1 % seq);
952 *db << boost::str(deleteTrans2 % seq);
956 for (
auto const& [_, acceptedLedgerTx] : aLedger->getMap())
967 auto const& accts = acceptedLedgerTx->getAffected();
972 "INSERT INTO AccountTransactions "
973 "(TransID, Account, LedgerSeq, TxnSeq) VALUES ");
981 for (
auto const& account : accts)
1001 JLOG(j.trace()) <<
"ActTx: " << sql;
1006 JLOG(j.warn()) <<
"Transaction in ledger " << seq
1007 <<
" affects no accounts";
1014 acceptedLedgerTx->getTxn()->getMetaSQL(
1015 seq, acceptedLedgerTx->getEscMeta()) +
1026 R
"sql(INSERT OR REPLACE INTO Ledgers
1027 (LedgerHash,LedgerSeq,PrevHash,TotalCoins,ClosingTime,PrevClosingTime,
1028 CloseTimeRes,CloseFlags,AccountSetHash,TransSetHash)
1030 (:ledgerHash,:ledgerSeq,:prevHash,:totalCoins,:closingTime,:prevClosingTime,
1031 :closeTimeRes,:closeFlags,:accountSetHash,:transSetHash);)sql");
1035 soci::transaction tr(*db);
1040 auto const closeTime =
1042 auto const parentCloseTime =
1044 auto const closeTimeResolution =
1050 *db << addLedger, soci::use(hash), soci::use(seq),
1051 soci::use(parentHash), soci::use(drops), soci::use(closeTime),
1052 soci::use(parentCloseTime), soci::use(closeTimeResolution),
1053 soci::use(closeFlags), soci::use(accountHash), soci::use(txHash);
1078 JLOG(stream) <<
"Double pend save for " << ledger->
info().
seq;
1093 JLOG(stream) <<
"Pend save with seq in pending saves "
1100 char const*
const jobName{
1101 isCurrent ?
"Ledger::pendSave" :
"Ledger::pendOldSave"};
1104 if (!isSynchronous &&
1107 saveValidatedLedger(app, ledger, isCurrent);
1149 boost::optional<std::string> sLedgerHash, sPrevHash, sAccountHash,
1151 boost::optional<std::uint64_t> totDrops, closingTime, prevClosingTime,
1152 closeResolution, closeFlags, ledgerSeq64;
1156 "LedgerHash, PrevHash, AccountSetHash, TransSetHash, "
1158 "ClosingTime, PrevClosingTime, CloseTimeRes, CloseFlags,"
1159 "LedgerSeq from Ledgers " +
1162 *db << sql, soci::into(sLedgerHash), soci::into(sPrevHash),
1163 soci::into(sAccountHash), soci::into(sTransHash), soci::into(totDrops),
1164 soci::into(closingTime), soci::into(prevClosingTime),
1165 soci::into(closeResolution), soci::into(closeFlags),
1166 soci::into(ledgerSeq64);
1168 if (!db->got_data())
1171 JLOG(stream) <<
"Ledger not found: " << sqlSuffix;
1176 ledgerSeq = rangeCheckedCast<std::uint32_t>(ledgerSeq64.value_or(0));
1178 uint256 prevHash{}, accountHash{}, transHash{};
1180 (void)ledgerHash.
parseHex(*sLedgerHash);
1182 (void)prevHash.parseHex(*sPrevHash);
1184 (void)accountHash.parseHex(*sAccountHash);
1186 (void)transHash.parseHex(*sTransHash);
1195 info.
drops = totDrops.value_or(0);
1196 info.
closeTime = time_point{duration{closingTime.value_or(0)}};
1197 info.
parentCloseTime = time_point{duration{prevClosingTime.value_or(0)}};
1200 info.
seq = ledgerSeq;
1203 auto ledger = std::make_shared<Ledger>(
1220 Config
const& config,
1239 s <<
"WHERE LedgerSeq = " << ledgerIndex;
1240 std::tie(ledger, std::ignore, std::ignore) =
1254 s <<
"WHERE LedgerHash = '" << ledgerHash <<
"'";
1255 std::tie(ledger, std::ignore, std::ignore) =
1261 assert(!ledger || ledger->
info().
hash == ledgerHash);
1272 "SELECT LedgerHash FROM Ledgers INDEXED BY SeqLedger WHERE LedgerSeq='";
1278 auto db = app.getLedgerDB().checkoutDb();
1280 boost::optional<std::string> lh;
1281 *db << sql, soci::into(lh);
1283 if (!db->got_data() || !lh)
1291 (void)ret.parseHex(hash);
1302 auto db = app.getLedgerDB().checkoutDb();
1304 boost::optional<std::string> lhO, phO;
1306 *db <<
"SELECT LedgerHash,PrevHash FROM Ledgers "
1307 "INDEXED BY SeqLedger Where LedgerSeq = :ls;",
1308 soci::into(lhO), soci::into(phO), soci::use(ledgerIndex);
1312 auto stream = app.journal(
"Ledger").trace();
1313 JLOG(stream) <<
"Don't have ledger " << ledgerIndex;
1317 return ledgerHash.parseHex(*lhO) && parentHash.parseHex(*phO);
1326 "SELECT LedgerSeq,LedgerHash,PrevHash FROM Ledgers WHERE LedgerSeq >= ";
1328 sql.
append(
" AND LedgerSeq <= ");
1332 auto db = app.getLedgerDB().checkoutDb();
1336 boost::optional<std::string> ph;
1337 soci::statement st =
1338 (db->prepare << sql, soci::into(ls), soci::into(lh), soci::into(ph));
1344 ret[rangeCheckedCast<std::uint32_t>(ls)];
1345 (void)hashes.
first.parseHex(lh);
1347 (void)hashes.
second.parseHex(*ph);
1352 auto stream = app.journal(
"Ledger").warn();
1353 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 Family & getNodeFamily()=0
bool addSLE(SLE const &sle)
bool isFlagLedger(LedgerIndex seq)
Returns true if the given ledgerIndex is a flag ledgerIndex.
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_
std::enable_if_t< std::is_same< T, char >::value||std::is_same< T, unsigned char >::value, Slice > makeSlice(std::array< T, N > const &a)
const SF_UINT32 sfReserveBase
A pair of SHAMap key and LedgerEntryType.
virtual TaggedCache< uint256, AcceptedLedger > & getAcceptedLedgerCache()=0
bool isVotingLedger() const
Returns true if the ledger directly precedes a flag ledger.
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.
boost::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
std::unique_ptr< sles_type::iter_base > slesEnd() const override
const SF_UINT32 sfFirstLedgerSequence
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 SF_UINT32 sfSequence
sles_type::value_type dereference() const override
Keylet const & skip() noexcept
The index of the "short" skip list.
constexpr std::uint32_t FLAG_LEDGER_INTERVAL
Serializer getSerializer() const
bool exists(Keylet const &k) const override
Determine if a state item exists.
bool equal(base_type const &impl) const override
void push_back(STObject const &object)
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.
virtual void store(NodeObjectType type, Blob &&data, uint256 const &hash, std::uint32_t ledgerSeq)=0
Store the object.
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
void setFieldVL(SField const &field, Blob const &)
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.
void updateNegativeUNL()
update the Negative UNL ledger component.
virtual void missingNode(std::uint32_t refNum)=0
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.
LedgerInfo const & info() const override
Returns information about the ledger.
T time_since_epoch(T... args)
boost::optional< PublicKey > validatorToReEnable() const
get the to be re-enabled validator's master public key if any
bool txExists(uint256 const &key) const override
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()
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.
const SF_UINT32 sfReserveIncrement
virtual Config & config()=0
boost::optional< PublicKey > validatorToDisable() const
get the to be disabled validator's master public key if any
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 isFlagLedger() const
Returns true if the ledger is a flag ledger.
bool equal(base_type const &impl) const override
sles_iter_impl & operator=(sles_iter_impl const &)=delete
virtual JobQueue & getJobQueue()=0
const SF_VL sfValidatorToDisable
XRPAmount FEE_ACCOUNT_RESERVE
void rawInsert(std::shared_ptr< SLE > const &sle) override
Unconditionally insert a state item.
bool assertSensible(beast::Journal ledgerJ) const
@ 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.
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
const SF_UINT64 sfBaseFee
bool getCloseAgree(LedgerInfo const &info)
const SF_VECTOR256 sfHashes
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
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
static uint256 calculateLedgerHash(LedgerInfo const &info)
bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
bool setup(Config const &config)
void emplace_back(Args &&... args)
LedgerIndex seq() const
Returns the sequence number of the base ledger.
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_
const SField sfDisabledValidator
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
const SF_AMOUNT sfBalance
const SF_UINT32 sfReferenceFeeUnits
int addVL(Blob const &vector)
hash_set< PublicKey > negativeUNL() const
get Negative UNL validators' master public keys
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.
const SF_ACCOUNT sfAccount
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
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_UINT32 sfLastLedgerSequence
constexpr auto ledgerDefaultTimeResolution
Initial resolution of ledger close time.
Keylet const & negativeUNL() noexcept
The (fixed) index of the object containing the ledger negativeUNL.
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
void setFieldU32(SField const &field, std::uint32_t)
std::unique_ptr< base_type > copy() const override
const SField sfDisabledValidators
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)
const SF_VECTOR256 sfAmendments
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.
const SF_VL sfValidatorToReEnable
std::string toBase58(AccountID const &) const
Return ripple::toBase58 for the AccountID.
NetClock::time_point parentCloseTime
virtual TransactionMaster & getMasterTransaction()=0