1#include <xrpld/app/ledger/InboundLedgers.h>
2#include <xrpld/app/ledger/Ledger.h>
3#include <xrpld/app/ledger/LedgerToJson.h>
4#include <xrpld/app/ledger/PendingSaves.h>
5#include <xrpld/app/main/Application.h>
6#include <xrpld/app/misc/HashRouter.h>
7#include <xrpld/app/rdb/backend/SQLiteDatabase.h>
8#include <xrpld/consensus/LedgerTiming.h>
9#include <xrpld/core/Config.h>
10#include <xrpld/core/SociDB.h>
12#include <xrpl/basics/Log.h>
13#include <xrpl/basics/contract.h>
14#include <xrpl/beast/utility/instrumentation.h>
15#include <xrpl/core/JobQueue.h>
16#include <xrpl/json/to_string.h>
17#include <xrpl/nodestore/Database.h>
18#include <xrpl/nodestore/detail/DatabaseNodeImp.h>
19#include <xrpl/protocol/Feature.h>
20#include <xrpl/protocol/HashPrefix.h>
21#include <xrpl/protocol/Indexes.h>
22#include <xrpl/protocol/PublicKey.h>
23#include <xrpl/protocol/SecretKey.h>
24#include <xrpl/protocol/digest.h>
25#include <xrpl/protocol/jss.h>
76 equal(base_type
const& impl)
const override
79 return iter_ == p->iter_;
124 equal(base_type
const& impl)
const override
126 if (
auto const p =
dynamic_cast<txs_iter_impl const*
>(&impl))
127 return iter_ == p->iter_;
140 auto const& item = *
iter_;
157 , rules_{config.features}
158 , j_(
beast::Journal(
beast::Journal::getNullSink()))
169 sle->setFieldU32(sfSequence, 1);
170 sle->setAccountID(sfAccount,
id);
175 if (!amendments.empty())
178 sle->setFieldV256(sfAmendments,
STVector256{amendments});
185 if (
std::find(amendments.begin(), amendments.end(), featureXRPFees) !=
196 sle->at(sfBaseFee) = *f;
199 sle->at(sfReserveBase) = *f;
202 sle->at(sfReserveIncrement) = *f;
222 , rules_(config.features)
232 JLOG(j.
warn()) <<
"Don't have transaction root for ledger"
240 JLOG(j.
warn()) <<
"Don't have state data root for ledger"
263 , stateMap_(prevLedger.stateMap_, true)
264 , fees_(prevLedger.fees_)
265 , rules_(prevLedger.rules_)
266 , j_(
beast::Journal(
beast::Journal::getNullSink()))
295 , rules_{config.features}
297 , j_(
beast::Journal(
beast::Journal::getNullSink()))
310 , rules_{config.features}
311 , j_(
beast::Journal(
beast::Journal::getNullSink()))
344 bool correctCloseTime)
347 XRPL_ASSERT(!
open(),
"xrpl::Ledger::setAccepted : valid ledger state");
410 if (last && item->key() >= last)
418 if (k.
key == beast::zero)
421 UNREACHABLE(
"xrpl::Ledger::read : zero key");
476 auto const& item = txMap_.peekItem(key);
482 return {std::move(result.first), std::move(result.second)};
493 if (!stateMap_.peekItem(key,
digest))
504 LogicError(
"Ledger::rawErase: key not found");
511 LogicError(
"Ledger::rawErase: key not found");
522 LogicError(
"Ledger::rawInsert: key already exists");
533 LogicError(
"Ledger::rawReplace: key not found");
543 metaData,
"xrpl::Ledger::rawTxInsert : non-null metadata input");
546 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
547 s.
addVL(txn->peekData());
548 s.
addVL(metaData->peekData());
562 "xrpl::Ledger::rawTxInsertWithHash : non-null metadata input");
565 Serializer s(txn->getDataLength() + metaData->getDataLength() + 16);
566 s.
addVL(txn->peekData());
567 s.
addVL(metaData->peekData());
591 JLOG(
j_.
error()) <<
"Exception in " << __func__ <<
": " << ex.
what();
599 bool oldFees =
false;
600 bool newFees =
false;
602 auto const baseFee = sle->at(~sfBaseFee);
603 auto const reserveBase = sle->at(~sfReserveBase);
604 auto const reserveIncrement = sle->at(~sfReserveIncrement);
609 if (reserveIncrement)
611 oldFees = baseFee || reserveBase || reserveIncrement;
614 auto const baseFeeXRP = sle->at(~sfBaseFeeDrops);
615 auto const reserveBaseXRP = sle->at(~sfReserveBaseDrops);
616 auto const reserveIncrementXRP =
617 sle->at(~sfReserveIncrementDrops);
618 auto assign = [&ret](
632 newFees = baseFeeXRP || reserveBaseXRP || reserveIncrementXRP;
634 if (oldFees && newFees)
648 JLOG(
j_.
error()) <<
"Exception in " << __func__ <<
": " << ex.
what();
660 "xrpl::Ledger::defaultFees : zero fees");
686 sle && sle->isFieldPresent(sfDisabledValidators))
688 auto const& nUnlData = sle->getFieldArray(sfDisabledValidators);
689 for (
auto const& n : nUnlData)
691 if (n.isFieldPresent(sfPublicKey))
693 auto d = n.getFieldVL(sfPublicKey);
711 sle && sle->isFieldPresent(sfValidatorToDisable))
713 auto d = sle->getFieldVL(sfValidatorToDisable);
726 sle && sle->isFieldPresent(sfValidatorToReEnable))
728 auto d = sle->getFieldVL(sfValidatorToReEnable);
744 bool const hasToDisable = sle->isFieldPresent(sfValidatorToDisable);
745 bool const hasToReEnable = sle->isFieldPresent(sfValidatorToReEnable);
747 if (!hasToDisable && !hasToReEnable)
751 if (sle->isFieldPresent(sfDisabledValidators))
753 auto const& oldNUnl = sle->getFieldArray(sfDisabledValidators);
754 for (
auto v : oldNUnl)
756 if (hasToReEnable && v.isFieldPresent(sfPublicKey) &&
757 v.getFieldVL(sfPublicKey) ==
758 sle->getFieldVL(sfValidatorToReEnable))
768 sfPublicKey, sle->getFieldVL(sfValidatorToDisable));
772 if (!newNUnl.
empty())
774 sle->setFieldArray(sfDisabledValidators, newNUnl);
776 sle->makeFieldAbsent(sfValidatorToReEnable);
778 sle->makeFieldAbsent(sfValidatorToDisable);
808 if (!missingNodes1.
empty())
810 if (
auto stream = j.
info())
812 stream << missingNodes1.
size() <<
" missing account node(s)";
813 stream <<
"First: " << missingNodes1[0].what();
828 if (!missingNodes2.
empty())
830 if (
auto stream = j.
info())
832 stream << missingNodes2.
size() <<
" missing transaction node(s)";
833 stream <<
"First: " << missingNodes2[0].what();
836 return missingNodes1.
empty() && missingNodes2.
empty();
855 JLOG(ledgerJ.
fatal()) <<
"ledger is not sensible" << j;
857 UNREACHABLE(
"xrpl::Ledger::assertSensible : ledger is not sensible");
874 if ((prevIndex & 0xff) == 0)
888 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(sfHashes));
893 hashes.
size() <= 256,
894 "xrpl::Ledger::updateSkipList : first maximum hashes size");
897 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
916 hashes =
static_cast<decltype(hashes)
>(sle->getFieldV256(sfHashes));
920 hashes.
size() <= 256,
921 "xrpl::Ledger::updateSkipList : second maximum hashes size");
922 if (hashes.
size() == 256)
926 sle->setFieldU32(sfLastLedgerSequence, prevIndex);
956 auto j = app.
journal(
"Ledger");
957 auto seq = ledger->header().seq;
961 JLOG(j.debug()) <<
"Save aborted";
967 Throw<std::runtime_error>(
"Failed to get relational database");
969 auto const res = db->saveValidatedLedger(ledger,
current);
992 JLOG(stream) <<
"Double pend save for " << ledger->header().seq;
1003 ledger->isImmutable(),
"xrpl::pendSaveValidated : immutable ledger");
1008 JLOG(stream) <<
"Pend save with seq in pending saves "
1009 << ledger->header().seq;
1015 if (!isSynchronous &&
1083 "xrpl::finishLoadByIndexOrHash : valid ledger fees");
1084 ledger->setImmutable();
1086 JLOG(j.
trace()) <<
"Loaded ledger: " <<
to_string(ledger->header().hash);
1123 !ledger || ledger->header().hash == ledgerHash,
1124 "xrpl::loadByHash : ledger hash match if loaded");
A generic endpoint for log messages.
Stream trace() const
Severity stream access functions.
virtual HashRouter & getHashRouter()=0
virtual Config & config()=0
virtual PendingSaves & pendingSaves()=0
virtual beast::Journal journal(std::string const &name)=0
virtual Family & getNodeFamily()=0
virtual JobQueue & getJobQueue()=0
virtual RelationalDatabase & getRelationalDatabase()=0
static constexpr std::uint32_t FEE_UNITS_DEPRECATED
virtual void missingNodeAcquireByHash(uint256 const &refHash, std::uint32_t refNum)=0
Acquire ledger that has a missing node by ledger hash.
bool setFlags(uint256 const &key, HashRouterFlags flags)
Set the flags on a hash.
bool addJob(JobType type, std::string const &name, JobHandler &&jobHandler)
Adds a job to the JobQueue.
sles_iter_impl(sles_iter_impl const &)=default
void increment() override
SHAMap::const_iterator iter_
bool equal(base_type const &impl) const override
std::unique_ptr< base_type > copy() const override
sles_iter_impl & operator=(sles_iter_impl const &)=delete
sles_type::value_type dereference() const override
sles_iter_impl(SHAMap::const_iterator iter)
bool equal(base_type const &impl) const override
SHAMap::const_iterator iter_
txs_iter_impl(txs_iter_impl const &)=default
std::unique_ptr< base_type > copy() const override
txs_iter_impl(bool metadata, SHAMap::const_iterator iter)
void increment() override
txs_type::value_type dereference() const override
txs_iter_impl & operator=(txs_iter_impl const &)=delete
bool txExists(uint256 const &key) const override
std::unique_ptr< txs_type::iter_base > txsEnd() const override
bool isFlagLedger() const
Returns true if the ledger is a flag ledger.
std::optional< digest_type > digest(key_type const &key) const override
Return the digest associated with the key.
void rawTxInsert(uint256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData) override
std::optional< PublicKey > validatorToDisable() const
get the to be disabled validator's master public key if any
uint256 rawTxInsertWithHash(uint256 const &key, std::shared_ptr< Serializer const > const &txn, std::shared_ptr< Serializer const > const &metaData)
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
void updateNegativeUNL()
update the Negative UNL ledger component.
bool assertSensible(beast::Journal ledgerJ) const
bool isVotingLedger() const
Returns true if the ledger directly precedes a flag ledger.
std::unique_ptr< sles_type::iter_base > slesBegin() const override
hash_set< PublicKey > negativeUNL() const
get Negative UNL validators' master public keys
void rawInsert(std::shared_ptr< SLE > const &sle) override
Unconditionally insert a state item.
void rawReplace(std::shared_ptr< SLE > const &sle) override
Unconditionally replace a state item.
void setImmutable(bool rehash=true)
void defaultFees(Config const &config)
bool open() const override
Returns true if this reflects an open ledger.
void rawErase(std::shared_ptr< SLE > const &sle) override
Delete an existing state item.
LedgerHeader const & header() const override
Returns information about the ledger.
void setAccepted(NetClock::time_point closeTime, NetClock::duration closeResolution, bool correctCloseTime)
Ledger(Ledger const &)=delete
std::shared_ptr< SLE > peek(Keylet const &k) const
bool addSLE(SLE const &sle)
std::unique_ptr< txs_type::iter_base > txsBegin() const override
std::unique_ptr< sles_type::iter_base > slesEnd() const override
std::optional< uint256 > succ(uint256 const &key, std::optional< uint256 > const &last=std::nullopt) const override
bool walkLedger(beast::Journal j, bool parallel=false) const
std::unique_ptr< sles_type::iter_base > slesUpperBound(uint256 const &key) const override
std::optional< PublicKey > validatorToReEnable() const
get the to be re-enabled validator's master public key if any
tx_type txRead(key_type const &key) const override
Read a transaction from the tx map.
bool exists(Keylet const &k) const override
Determine if a state item exists.
void finishWork(LedgerIndex seq)
Finish working on a ledger.
bool shouldWork(LedgerIndex seq, bool isSynchronous)
Check if a ledger should be dispatched.
bool startWork(LedgerIndex seq)
Start working on a ledger.
bool pending(LedgerIndex seq)
Return true if a ledger is in the progress of being saved.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
virtual std::optional< LedgerHeader > getNewestLedgerInfo()=0
getNewestLedgerInfo Returns the info of the newest saved ledger.
virtual std::optional< LedgerHeader > getLedgerInfoByHash(uint256 const &ledgerHash)=0
getLedgerInfoByHash Returns the info of the ledger with given hash.
virtual std::optional< LedgerHeader > getLedgerInfoByIndex(LedgerIndex ledgerSeq)=0
getLedgerInfoByIndex Returns a ledger by its sequence.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
uint256 const & as_uint256() const
bool addItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
const_iterator upper_bound(uint256 const &id) const
Find the first item after the given item.
const_iterator end() const
const_iterator begin() const
boost::intrusive_ptr< SHAMapItem const > const & peekItem(uint256 const &id) const
int flushDirty(NodeObjectType t)
Flush modified nodes to the nodestore and convert them to shared.
bool walkMapParallel(std::vector< SHAMapMissingNode > &missingNodes, int maxMissing) const
void walkMap(std::vector< SHAMapMissingNode > &missingNodes, int maxMissing) const
bool hasItem(uint256 const &id) const
Does the tree have an item with the given ID?
int unshare()
Convert any modified nodes to shared.
bool updateGiveItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
bool addGiveItem(SHAMapNodeType type, boost::intrusive_ptr< SHAMapItem const > item)
bool fetchRoot(SHAMapHash const &hash, SHAMapSyncFilter *filter)
SHAMapHash getHash() const
bool delItem(uint256 const &id)
void push_back(STObject const &object)
uint256 const & key() const
Returns the 'key' (or 'index') of this item.
void setFieldVL(SField const &field, Blob const &)
void setFieldU32(SField const &field, std::uint32_t)
Serializer getSerializer() const
static STObject makeInnerObject(SField const &name)
Slice getSlice(std::size_t bytes)
int addVL(Blob const &vector)
Slice slice() const noexcept
constexpr value_type drops() const
Returns the number of drops.
std::optional< Dest > dropsAs() const
T emplace_back(T... args)
Keylet const & skip() noexcept
The index of the "short" skip list.
Keylet const & negativeUNL() noexcept
The (fixed) index of the object containing the ledger negativeUNL.
Keylet const & amendments() noexcept
The index of the amendment table.
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet const & fees() noexcept
The (fixed) index of the object containing the ledger fees.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
static constexpr std::uint32_t XRP_LEDGER_EARLIEST_FEES
The XRP Ledger mainnet's earliest ledger with a FeeSettings object.
std::shared_ptr< Ledger > loadByHash(uint256 const &ledgerHash, Application &app, bool acquire)
std::shared_ptr< Ledger > loadLedgerHelper(LedgerHeader const &info, Application &app, bool acquire)
bool isCurrent(ValidationParms const &p, NetClock::time_point now, NetClock::time_point signTime, NetClock::time_point seenTime)
Whether a validation is still current.
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
static void finishLoadByIndexOrHash(std::shared_ptr< Ledger > const &ledger, Config const &config, beast::Journal j)
bool isFlagLedger(LedgerIndex seq)
Returns true if the given ledgerIndex is a flag ledgerIndex.
static Hasher::result_type digest(void const *data, std::size_t size) noexcept
boost::intrusive_ptr< SHAMapItem > make_shamapitem(uint256 const &tag, Slice data)
Json::Value getJson(LedgerFill const &fill)
Return a new Json::Value representing the ledger with given options.
sha512_half_hasher::result_type sha512Half(Args const &... args)
Returns the SHA512-Half of a series of objects.
std::string to_string(base_uint< Bits, Tag > const &a)
Rules makeRulesGivenLedger(DigestAwareReadView const &ledger, Rules const ¤t)
std::pair< std::shared_ptr< STTx const >, std::shared_ptr< STObject const > > deserializeTxPlusMeta(SHAMapItem const &item)
Deserialize a SHAMapItem containing STTx + STObject metadata.
std::tuple< std::shared_ptr< Ledger >, std::uint32_t, uint256 > getLatestLedger(Application &app)
std::shared_ptr< STTx const > deserializeTx(SHAMapItem const &item)
Deserialize a SHAMapItem containing a single STTx.
create_genesis_t const create_genesis
static bool saveValidatedLedger(Application &app, std::shared_ptr< Ledger const > const &ledger, bool current)
auto constexpr ledgerDefaultTimeResolution
Initial resolution of ledger close time.
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
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.
std::pair< PublicKey, SecretKey > generateKeyPair(KeyType type, Seed const &seed)
Generate a key pair deterministically.
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.
bool getCloseAgree(LedgerHeader const &info)
uint256 calculateLedgerHash(LedgerHeader const &info)
@ current
This was a new validation and was added.
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
std::shared_ptr< Ledger > loadByIndex(std::uint32_t ledgerIndex, Application &app, bool acquire)
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.
@ open
We haven't closed our ledger yet, but others might have.
static std::uint32_t const sLCF_NoConsensusTime
AccountID calcAccountID(PublicKey const &pk)
auto constexpr ledgerGenesisTimeResolution
Close time resolution in genesis ledger.
@ txNode
transaction plus metadata
@ ledgerMaster
ledger master data for signing
constexpr XRPAmount INITIAL_XRP
Configure the native currency.
void Rethrow()
Rethrow the exception currently being handled.
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)
std::uint32_t constexpr FLAG_LEDGER_INTERVAL
XRPAmount reference_fee
The cost of a reference transaction in drops.
XRPAmount account_reserve
The account reserve requirement in drops.
XRPAmount owner_reserve
The per-owned item reserve requirement in drops.
A pair of SHAMap key and LedgerEntryType.
bool check(STLedgerEntry const &) const
Returns true if the SLE matches the type.
T time_since_epoch(T... args)