1#include <xrpl/basics/contract.h>
2#include <xrpl/core/NetworkIDService.h>
3#include <xrpl/json/to_string.h>
4#include <xrpl/ledger/View.h>
5#include <xrpl/ledger/helpers/AccountRootHelpers.h>
6#include <xrpl/ledger/helpers/CredentialHelpers.h>
7#include <xrpl/ledger/helpers/OfferHelpers.h>
8#include <xrpl/ledger/helpers/RippleStateHelpers.h>
9#include <xrpl/protocol/Feature.h>
10#include <xrpl/protocol/Indexes.h>
11#include <xrpl/protocol/Protocol.h>
12#include <xrpl/protocol/SystemParameters.h>
13#include <xrpl/protocol/TxFlags.h>
14#include <xrpl/protocol/UintTypes.h>
15#include <xrpl/server/LoadFeeTrack.h>
16#include <xrpl/tx/SignerEntries.h>
17#include <xrpl/tx/Transactor.h>
18#include <xrpl/tx/apply.h>
19#include <xrpl/tx/transactors/delegate/DelegateUtils.h>
20#include <xrpl/tx/transactors/nft/NFTokenUtils.h>
30 JLOG(ctx.
j.
warn()) <<
"Pseudo transactions cannot contain the "
31 "tfInnerBatchTxn flag.";
37 uint32_t
const nodeNID = ctx.
registry.get().getNetworkIDService().getNetworkID();
54 if (*txNID != nodeNID)
61 if (txID == beast::zero)
63 JLOG(ctx.
j.
warn()) <<
"applyTransaction: transaction id may not be zero";
70 <<
": invalid flags.";
86 if (
auto const spk = sigObject.
getFieldVL(sfSigningPubKey);
89 JLOG(j.
debug()) <<
"preflightCheckSigningKey: invalid signing key";
101 if (signature && !signature->empty())
114 for (
auto const& signer : sigObject.
getFieldArray(sfSigners))
116 if (signer.isFieldPresent(sfTxnSignature) && !signer[sfTxnSignature].empty())
124 Slice const signingPubKey = sigObject[sfSigningPubKey];
125 if (!signingPubKey.
empty())
143 if (!ctx.
rules.
enabled(featurePermissionDelegationV1_1))
146 if (ctx.
tx[sfDelegate] == ctx.
tx[sfAccount])
150 if (
auto const ret =
preflight0(ctx, flagMask))
154 if (
id == beast::zero)
156 JLOG(ctx.
j.
warn()) <<
"preflight1: bad account id";
162 if (!fee.native() || fee.negative() || !
isLegalAmount(fee.xrp()))
164 JLOG(ctx.
j.
debug()) <<
"preflight1: invalid fee";
186 "Inner batch transaction must have a parent batch ID.");
206 "xrpl::Transactor::preflight2",
207 "InnerBatch flag only set if feature enabled");
217 JLOG(ctx.
j.
debug()) <<
"preflight2: bad signature. " << sigValid.second;
234 , account_(ctx.tx.getAccountID(sfAccount))
243 return !slice->empty() && slice->length() <= maxLength;
261 auto const delegate = tx[~sfDelegate];
266 auto const sle =
view.
read(delegateKey);
289 return baseFee + (signerCount * baseFee);
308 "xrpl::Transactor::calculateOwnerReserveFee : Owner reserve is "
326 if (!ctx.
tx[sfFee].native())
329 auto const feePaid = ctx.
tx[sfFee].xrp();
333 if (feePaid == beast::zero)
336 JLOG(ctx.
j.
trace()) <<
"Batch: Fee must be zero.";
348 if (feePaid < feeDue)
350 JLOG(ctx.
j.
trace()) <<
"Insufficient fee paid: " <<
to_string(feePaid) <<
"/"
356 if (feePaid == beast::zero)
364 auto const balance = (*sle)[sfBalance].xrp();
373 if (balance < feePaid)
375 JLOG(ctx.
j.
trace()) <<
"Insufficient balance:" <<
" balance=" <<
to_string(balance)
378 if ((balance > beast::zero) && !ctx.
view.
open())
393 auto const feePaid =
ctx_.
tx[sfFee].xrp();
402 sle->setFieldAmount(sfBalance, sle->getFieldAmount(sfBalance) - feePaid);
419 JLOG(j.
trace()) <<
"applyTransaction: delay: source account does not exist "
427 if (t_seqProx.
isSeq())
431 JLOG(j.
trace()) <<
"applyTransaction: has both a TicketSequence "
432 "and a non-zero Sequence number";
435 if (t_seqProx != a_seq)
437 if (a_seq < t_seqProx)
439 JLOG(j.
trace()) <<
"applyTransaction: has future sequence number "
440 <<
"a_seq=" << a_seq <<
" t_seq=" << t_seqProx;
444 JLOG(j.
trace()) <<
"applyTransaction: has past sequence number "
445 <<
"a_seq=" << a_seq <<
" t_seq=" << t_seqProx;
458 JLOG(j.
trace()) <<
"applyTransaction: has future ticket id "
459 <<
"a_seq=" << a_seq <<
" t_seq=" << t_seqProx;
466 JLOG(j.
trace()) <<
"applyTransaction: ticket already used or never created "
467 <<
"a_seq=" << a_seq <<
" t_seq=" << t_seqProx;
484 JLOG(ctx.
j.
trace()) <<
"applyTransaction: delay: source account does not exist "
490 (sle->getFieldH256(sfAccountTxnID) != ctx.
tx.
getFieldH256(sfAccountTxnID)))
506 XRPL_ASSERT(sleAccount,
"xrpl::Transactor::consumeSeqProxy : non-null account");
513 sleAccount->setFieldU32(sfSequence, seqProx.
value() + 1);
533 JLOG(j.
fatal()) <<
"Ticket disappeared from ledger.";
542 JLOG(j.
fatal()) <<
"Unable to delete Ticket from owner.";
553 JLOG(j.
fatal()) <<
"Could not find Ticket owner account root.";
558 if (
auto ticketCount = (*sleAccount)[~sfTicketCount])
560 if (*ticketCount == 1)
562 sleAccount->makeFieldAbsent(sfTicketCount);
566 ticketCount = *ticketCount - 1;
572 JLOG(j.
fatal()) <<
"TicketCount field missing from account root.";
589 XRPL_ASSERT(
account_ != beast::zero,
"xrpl::Transactor::preCompute : nonzero account");
604 sle !=
nullptr ||
account_ == beast::zero,
605 "xrpl::Transactor::apply : non-null SLE or zero account");
619 if (sle->isFieldPresent(sfAccountTxnID))
649 auto const pkSigner = sigObject.
getFieldVL(sfSigningPubKey);
654 if (sigObject.
isFieldPresent(sfTxnSignature) || !pkSigner.empty() ||
677 XRPL_ASSERT(!pkSigner.empty(),
"xrpl::Transactor::checkSign : non-empty signer");
681 JLOG(j.
trace()) <<
"checkSign: signing public key type is unknown";
707 for (
auto const& signer : signers)
709 auto const idAccount = signer.getAccountID(sfAccount);
711 Blob const& pkSigner = signer.getFieldVL(sfSigningPubKey);
712 if (pkSigner.
empty())
732 if (idAccount != idSigner)
754 bool const isMasterDisabled = sleAccount->isFlag(lsfDisableMaster);
757 if ((*sleAccount)[~sfRegularKey] == idSigner)
763 if (!isMasterDisabled && idAccount == idSigner)
769 if (isMasterDisabled && idAccount == idSigner)
789 if (!sleAccountSigners)
791 JLOG(j.
trace()) <<
"applyTransaction: Invalid: Not a multi-signing account.";
798 sleAccountSigners->isFieldPresent(sfSignerListID),
799 "xrpl::Transactor::checkMultiSign : has signer list ID");
801 sleAccountSigners->getFieldU32(sfSignerListID) == 0,
802 "xrpl::Transactor::checkMultiSign : signer list ID is 0");
806 return accountSigners.error();
818 auto iter = accountSigners->begin();
819 for (
auto const& txSigner : txSigners)
821 AccountID const txSignerAcctID = txSigner.getAccountID(sfAccount);
824 while (iter->account < txSignerAcctID)
826 if (++iter == accountSigners->end())
828 JLOG(j.
trace()) <<
"applyTransaction: Invalid SigningAccount.Account.";
832 if (iter->account != txSignerAcctID)
835 JLOG(j.
trace()) <<
"applyTransaction: Invalid SigningAccount.Account.";
842 auto const spk = txSigner.getFieldVL(sfSigningPubKey);
848 JLOG(j.
trace()) <<
"checkMultiSign: signing public key type is unknown";
854 "xrpl::Transactor::checkMultiSign : non-empty signer or "
856 AccountID const signingAcctIDFromPubKey =
886 if (signingAcctIDFromPubKey == txSignerAcctID)
892 std::uint32_t const signerAccountFlags = sleTxSignerRoot->getFieldU32(sfFlags);
894 if ((signerAccountFlags & lsfDisableMaster) != 0u)
896 JLOG(j.
trace()) <<
"applyTransaction: Signer:Account lsfDisableMaster.";
905 if (!sleTxSignerRoot)
907 JLOG(j.
trace()) <<
"applyTransaction: Non-phantom signer "
908 "lacks account root.";
912 if (!sleTxSignerRoot->isFieldPresent(sfRegularKey))
914 JLOG(j.
trace()) <<
"applyTransaction: Account lacks RegularKey.";
917 if (signingAcctIDFromPubKey != sleTxSignerRoot->getAccountID(sfRegularKey))
919 JLOG(j.
trace()) <<
"applyTransaction: Account doesn't match RegularKey.";
924 weightSum += iter->weight;
928 if (weightSum < sleAccountSigners->getFieldU32(sfSignerQuorum))
930 JLOG(j.
trace()) <<
"applyTransaction: Signers failed to meet quorum.";
945 for (
auto const& index : offers)
965 for (
auto const& index : offers)
979 for (
auto const& index : creds)
994 JLOG(viewJ.
error()) <<
"removeDeletedTrustLines: deleted trustlines exceed max "
995 << trustLines.
size();
999 for (
auto const& index : trustLines)
1001 if (
auto const sleState = view.
peek({ltRIPPLE_STATE, index});
1004 JLOG(viewJ.
error()) <<
"removeDeletedTrustLines: failed to delete AMM trustline";
1030 auto const balance = payerSle->getFieldAmount(sfBalance).xrp();
1034 balance != beast::zero && (!
view().
open() || balance >= fee),
1035 "xrpl::Transactor::reset : valid balance");
1049 payerSle->setFieldAmount(sfBalance, balance - fee);
1051 XRPL_ASSERT(
isTesSuccess(ter),
"xrpl::Transactor::reset : result is tesSUCCESS");
1056 if (payerSle != txnAcct)
1068 JLOG(
j_.
debug()) <<
"Transaction trapped: " << txHash;
1096 JLOG(
j_.
fatal()) <<
"Transaction serdes mismatch";
1099 UNREACHABLE(
"xrpl::Transactor::operator() : transaction serdes mismatch");
1105 if (
auto const& trap =
ctx_.
registry.get().getTrapTxID();
1117 XRPL_ASSERT(result !=
temUNKNOWN,
"xrpl::Transactor::operator() : result is not temUNKNOWN");
1120 stream <<
"preclaim result: " <<
transToken(result);
1152 bool const doNFTokenOffers = (result ==
tecEXPIRED);
1153 bool const doCredentials = (result ==
tecEXPIRED);
1154 if (doOffers || doLines || doNFTokenOffers || doCredentials)
1161 &expiredNFTokenOffers,
1163 &expiredCredentials](
1172 "xrpl::Transactor::operator()::visit : non-null SLE "
1174 if (doOffers && before &&
after && (before->getType() == ltOFFER) &&
1175 (before->getFieldAmount(sfTakerPays) ==
after->getFieldAmount(sfTakerPays)))
1181 if (doLines && before &&
after && (before->getType() == ltRIPPLE_STATE))
1187 if (doNFTokenOffers && before &&
after &&
1188 (before->getType() == ltNFTOKEN_OFFER))
1191 if (doCredentials && before &&
after && (before->getType() == ltCREDENTIAL))
1199 auto const resetResult =
reset(fee);
1201 result = resetResult.first;
1203 fee = resetResult.second;
1243 auto const resetResult =
reset(fee);
1245 result = resetResult.first;
1247 fee = resetResult.second;
1270 if (fee < beast::zero)
1271 Throw<std::logic_error>(
"fee charged is negative!");
1277 if (!
view().
open() && fee != beast::zero)
1289 JLOG(
j_.
trace()) << (applied ?
"applied " :
"not applied ") <<
transToken(result);
1291 return {result, applied, metadata};
A generic endpoint for log messages.
Stream trace() const
Severity stream access functions.
State information when applying a tx.
std::size_t size()
Get the number of unapplied changes.
void destroyXRP(XRPAmount const &fee)
ApplyFlags const & flags() const
void discard()
Discard changes and start fresh.
std::reference_wrapper< ServiceRegistry > registry
std::optional< TxMeta > apply(TER)
Apply the transaction result to the base.
TER checkInvariants(TER const result, XRPAmount const fee)
Applies all invariant checkers one by one.
void visit(std::function< void(uint256 const &key, bool isDelete, std::shared_ptr< SLE const > const &before, std::shared_ptr< SLE const > const &after)> const &func)
Visit unapplied changes.
Writeable view to a ledger, for applying a transaction.
virtual void update(std::shared_ptr< SLE > const &sle)=0
Indicate changes to a peeked SLE.
bool dirRemove(Keylet const &directory, std::uint64_t page, uint256 const &key, bool keepRoot)
Remove an entry from a directory.
virtual void erase(std::shared_ptr< SLE > const &sle)=0
Remove a peeked SLE.
virtual std::shared_ptr< SLE > peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
RAII class to set and restore the current transaction rules.
RAII class to set and restore the Number switchover.
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
virtual bool exists(Keylet const &k) const =0
Determine if a state item exists.
virtual bool txExists(key_type const &key) const =0
Returns true if a tx exists in the tx map.
virtual bool open() const =0
Returns true if this reflects an open ledger.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
virtual std::string getFullText() const
Blob getFieldVL(SField const &field) const
bool isEquivalent(STBase const &t) const override
std::uint32_t getFieldU32(SField const &field) const
STArray const & getFieldArray(SField const &field) const
void add(Serializer &s) const override
bool isFlag(std::uint32_t) const
bool isFieldPresent(SField const &field) const
uint256 getFieldH256(SField const &field) const
STBase const & peekAtField(SField const &field) const
AccountID getAccountID(SField const &field) const
STAmount const & getFieldAmount(SField const &field) const
std::uint32_t getFlags() const
Json::Value getJson(JsonOptions options) const override
SeqProxy getSeqProxy() const
AccountID getFeePayer() const
uint256 getTransactionID() const
A type that represents either a sequence value or a ticket value.
static constexpr SeqProxy sequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
constexpr bool isTicket() const
constexpr std::uint32_t value() const
constexpr bool isSeq() const
Slice slice() const noexcept
Service registry for dependency injection.
virtual LoadFeeTrack & getFeeTrack()=0
static Expected< std::vector< SignerEntry >, NotTEC > deserialize(STObject const &obj, beast::Journal journal, std::string_view annotation)
An immutable linear range of bytes.
bool empty() const noexcept
Return true if the byte range is empty.
static NotTEC preflight1(PreflightContext const &ctx, std::uint32_t flagMask)
Performs early sanity checks on the account and fee fields.
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
TER consumeSeqProxy(SLE::pointer const &sleAccount)
void trapTransaction(uint256) const
static TER checkFee(PreclaimContext const &ctx, XRPAmount baseFee)
static XRPAmount minimumFee(ServiceRegistry ®istry, XRPAmount baseFee, Fees const &fees, ApplyFlags flags)
Compute the minimum fee required to process a transaction with a given baseFee based on the current s...
static NotTEC checkSign(PreclaimContext const &ctx)
static XRPAmount calculateOwnerReserveFee(ReadView const &view, STTx const &tx)
ApplyResult operator()()
Process the transaction.
static NotTEC checkPermission(ReadView const &view, STTx const &tx)
static NotTEC preflightSigValidated(PreflightContext const &ctx)
static NotTEC checkBatchSign(PreclaimContext const &ctx)
static NotTEC checkSeqProxy(ReadView const &view, STTx const &tx, beast::Journal j)
static NotTEC preflight2(PreflightContext const &ctx)
Checks whether the signature appears valid.
static NotTEC checkSingleSign(ReadView const &view, AccountID const &idSigner, AccountID const &idAccount, std::shared_ptr< SLE const > sleAccount, beast::Journal const j)
Transactor(Transactor const &)=delete
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
static NotTEC checkPriorTxAndLastLedger(PreclaimContext const &ctx)
static NotTEC checkMultiSign(ReadView const &view, ApplyFlags flags, AccountID const &id, STObject const &sigObject, beast::Journal const j)
static bool validDataLength(std::optional< Slice > const &slice, std::size_t maxLength)
virtual void preCompute()
std::pair< TER, XRPAmount > reset(XRPAmount fee)
Reset the context, discarding any changes made and adjust the fee.
static TER ticketDelete(ApplyView &view, AccountID const &account, uint256 const &ticketIndex, beast::Journal j)
TER deleteSLE(ApplyView &view, std::shared_ptr< SLE > const &sleCredential, beast::Journal j)
std::optional< NotTEC > preflightCheckSimulateKeys(ApplyFlags flags, STObject const &sigObject, beast::Journal j)
Checks the special signing key state needed for simulation.
NotTEC preflightCheckSigningKey(STObject const &sigObject, beast::Journal j)
Checks the validity of the transactor signing key.
Keylet signers(AccountID const &account) noexcept
A SignerList.
Keylet nftoffer(AccountID const &owner, std::uint32_t seq)
An offer from an account to buy or sell an NFT.
static ticket_t const ticket
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Keylet offer(AccountID const &id, std::uint32_t seq) noexcept
An offer from an account.
Keylet delegate(AccountID const &account, AccountID const &authorizedAccount) noexcept
A keylet for Delegate object.
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet credential(AccountID const &subject, AccountID const &issuer, Slice const &credType) noexcept
bool deleteTokenOffer(ApplyView &view, std::shared_ptr< SLE > const &offer)
Deletes the given token offer.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
@ telNETWORK_ID_MAKES_TX_NON_CANONICAL
@ terNO_DELEGATE_PERMISSION
static void removeExpiredNFTokenOffers(ApplyView &view, std::vector< uint256 > const &offers, beast::Journal viewJ)
constexpr FlagValue tfInnerBatchTxn
bool isLegalAmount(XRPAmount const &amount)
Returns true if the amount does not exceed the initial XRP in existence.
@ SigBad
Signature is bad. Didn't do local checks.
std::size_t constexpr expiredOfferRemoveLimit
The maximum number of expired offers to delete at once.
std::string to_string(base_uint< Bits, Tag > const &a)
static void removeExpiredCredentials(ApplyView &view, std::vector< uint256 > const &creds, beast::Journal viewJ)
bool isTecClaimHardFail(TER ter, ApplyFlags flags)
Return true if the transaction can claim a fee (tec), and the ApplyFlags do not allow soft failures.
std::pair< Validity, std::string > checkValidity(HashRouter &router, STTx const &tx, Rules const &rules)
Checks transaction signature and local checks.
uint256 getTicketIndex(AccountID const &account, std::uint32_t uSequence)
std::uint16_t constexpr maxDeletableAMMTrustLines
The maximum number of trustlines to delete as part of AMM account deletion cleanup.
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
static void removeUnfundedOffers(ApplyView &view, std::vector< uint256 > const &offers, beast::Journal viewJ)
TER deleteAMMTrustLine(ApplyView &view, std::shared_ptr< SLE > sleState, std::optional< AccountID > const &ammAccountID, beast::Journal j)
Delete trustline to AMM.
std::string transToken(TER code)
std::optional< KeyType > publicKeyType(Slice const &slice)
Returns the type of public key.
bool isPseudoAccount(std::shared_ptr< SLE const > sleAcct, std::set< SField const * > const &pseudoFieldFilter={})
Returns true if and only if sleAcct is a pseudo-account or specific pseudo-accounts in pseudoFieldFil...
std::size_t constexpr oversizeMetaDataCap
The maximum number of metadata entries allowed in one transaction.
void adjustOwnerCount(ApplyView &view, std::shared_ptr< SLE > const &sle, std::int32_t amount, beast::Journal j)
Adjust the owner count up or down.
@ open
We haven't closed our ledger yet, but others might have.
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
NotTEC checkTxPermission(std::shared_ptr< SLE const > const &delegate, STTx const &tx)
Check if the delegate account has permission to execute the transaction.
AccountID calcAccountID(PublicKey const &pk)
static void removeDeletedTrustLines(ApplyView &view, std::vector< uint256 > const &trustLines, beast::Journal viewJ)
TER offerDelete(ApplyView &view, std::shared_ptr< SLE > const &sle, beast::Journal j)
Delete an offer.
XRPAmount scaleFeeLoad(XRPAmount fee, LoadFeeTrack const &feeTrack, Fees const &fees, bool bUnlimited)
bool isTesSuccess(TER x) noexcept
std::size_t constexpr unfundedOfferRemoveLimit
The maximum number of unfunded offers to delete at once.
NotTEC preflight0(PreflightContext const &ctx, std::uint32_t flagMask)
Performs early sanity checks on the txid and flags.
bool isTecClaim(TER x) noexcept
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)
TERSubset< CanCvtToNotTEC > NotTEC
bool isPseudoTx(STObject const &tx)
Check whether a transaction is a pseudo-transaction.
constexpr FlagValue tfUniversalMask
std::string to_short_string(base_uint< Bits, Tag > const &a)
Reflects the fee settings for a particular ledger.
XRPAmount increment
Additional XRP reserve required per owned ledger object.
XRPAmount base
Cost of a reference transaction in drops.
State information when determining if a tx is likely to claim a fee.
std::reference_wrapper< ServiceRegistry > registry
std::optional< uint256 const > const parentBatchId
State information when preflighting a tx.
std::optional< uint256 const > parentBatchId
std::reference_wrapper< ServiceRegistry > registry