1#include <xrpld/app/ledger/OpenLedger.h>
2#include <xrpld/app/main/Application.h>
3#include <xrpld/app/misc/DeliverMax.h>
4#include <xrpld/app/misc/Transaction.h>
5#include <xrpld/app/misc/TxQ.h>
6#include <xrpld/app/paths/Pathfinder.h>
7#include <xrpld/app/tx/apply.h>
8#include <xrpld/app/tx/applySteps.h>
9#include <xrpld/rpc/detail/LegacyPathFind.h>
10#include <xrpld/rpc/detail/RPCHelpers.h>
11#include <xrpld/rpc/detail/TransactionSign.h>
13#include <xrpl/basics/Log.h>
14#include <xrpl/basics/mulDiv.h>
15#include <xrpl/json/json_writer.h>
16#include <xrpl/protocol/ErrorCodes.h>
17#include <xrpl/protocol/InnerObjectFormats.h>
18#include <xrpl/protocol/RPCErr.h>
19#include <xrpl/protocol/STParsedJSON.h>
20#include <xrpl/protocol/Sign.h>
21#include <xrpl/protocol/TxFlags.h>
82 LogicError(
"Accessing unknown SigningForParams::getSigner()");
90 LogicError(
"Accessing unknown SigningForParams::getPublicKey()");
131 bool const isMasterKey = publicKeyAcctID == accountID;
143 auto const& sle = *accountState;
152 if ((sle.isFieldPresent(sfRegularKey)) && (publicKeyAcctID == sle.getAccountID(sfRegularKey)))
169 if (tx_json[jss::TransactionType].asString() != jss::Payment)
173 if (tx_json.
isMember(jss::DeliverMax))
177 if (tx_json[jss::DeliverMax] != tx_json[jss::Amount])
181 tx_json[jss::Amount] = tx_json[jss::DeliverMax];
194 if (!tx_json.
isMember(jss::Destination))
197 auto const dstAccountID = parseBase58<AccountID>(tx_json[jss::Destination].asString());
201 if (params.
isMember(jss::build_path) && ((doPath ==
false) || amount.holds<
MPTIssue>()))
208 if (tx_json.
isMember(sfDomainID.jsonName))
237 if (sendMax.
native() && amount.native())
269 auto j = app.
journal(
"RPCHandler");
307 if (!tx_json.
isMember(jss::TransactionType))
313 if (!tx_json.
isMember(jss::Account))
319 auto const srcAddressID = parseBase58<AccountID>(tx_json[jss::Account].asString());
345 ret.
second = *srcAddressID;
376static transactionPreProcessResult
384 auto j = app.
journal(
"RPCHandler");
397 if (params.
isMember(jss::signature_target))
404 auto const signatureTemplate =
408 if (!signatureTemplate)
431 return std::move(txJsonResult);
446 JLOG(j.debug()) <<
"transactionSign: Failed to find source account "
447 <<
"in current ledger: " <<
toBase58(srcAddressID);
454 if (!tx_json.
isMember(jss::Sequence))
456 bool const hasTicketSeq = tx_json.
isMember(sfTicketSequence.jsonName);
457 if (!hasTicketSeq && !sle)
459 JLOG(j.debug()) <<
"transactionSign: Failed to find source account "
460 <<
"in current ledger: " <<
toBase58(srcAddressID);
467 if (!tx_json.
isMember(jss::NetworkID))
470 if (networkId > 1024)
471 tx_json[jss::NetworkID] =
to_string(networkId);
493 if (tx_json.
isMember(jss::TxnSignature))
519 if (tx_json.
isMember(sfDelegate.jsonName))
522 auto const delegateJson = tx_json[sfDelegate.jsonName];
523 auto const ptrDelegatedAddressID =
526 if (!ptrDelegatedAddressID)
531 auto delegatedAddressID = *ptrDelegatedAddressID;
552 if (!parsed.
object.has_value())
555 err[jss::error] = parsed.
error[jss::error];
556 err[jss::error_code] = parsed.
error[jss::error_code];
557 err[jss::error_message] = parsed.
error[jss::error_message];
570 if (!parsed.
object->isFieldPresent(*signatureTarget))
571 parsed.
object->setFieldObject(*signatureTarget,
STObject{*signatureTemplate, *signatureTarget});
572 sigObject = &parsed.
object->peekFieldObject(*signatureTarget);
602 stTx->sign(pk, sk, signatureTarget);
618 if (tpTrans->getStatus() !=
NEW)
632 tpTrans->getSTransaction()->add(s);
651 if (!tpTransNew->getSTransaction()->isEquivalent(*tpTrans->getSTransaction()))
655 tpTrans = std::move(tpTransNew);
670 ret.
second = std::move(tpTrans);
683 jvResult[jss::hash] =
to_string(tpTrans->getID());
690 jvResult[jss::tx_blob] =
strHex(tpTrans->getSTransaction()->getSerializer().peekData());
699 jvResult[jss::engine_result] = sToken;
700 jvResult[jss::engine_result_code] = tpTrans->getResult();
701 jvResult[jss::engine_result_message] = sHuman;
728 tx[jss::Sequence] =
"0";
731 if (!tx.
isMember(jss::SigningPubKey))
733 tx[jss::SigningPubKey] =
"";
736 if (!tx.
isMember(jss::TxnSignature))
738 tx[jss::TxnSignature] =
"";
743 if (!tx[jss::Signers].isArray())
750 for (
auto& signer : tx[jss::Signers])
752 if (!signer.isMember(jss::Signer) || !signer[jss::Signer].isObject())
754 if (!signer[jss::Signer].isMember(jss::SigningPubKey))
757 signer[jss::Signer][jss::SigningPubKey] =
"";
759 if (!signer[jss::Signer].isMember(jss::TxnSignature))
762 signer[jss::Signer][jss::TxnSignature] =
"";
768 if (!parsed.
object.has_value())
807 auto const baseFee = ledger->fees().base;
808 auto escalatedFee =
toDrops(metrics.openLedgerFeeLevel -
FeeLevel64(1), baseFee) + 1;
812 auto const limit =
mulDiv(feeDefault, mult, div);
814 Throw<std::overflow_error>(
"mulDiv");
819 ss <<
"Fee of " << fee <<
" exceeds the requested tx limit of " << *limit;
845 if (request.
isMember(jss::fee_mult_max))
847 if (request[jss::fee_mult_max].isInt())
849 mult = request[jss::fee_mult_max].
asInt();
859 if (request.
isMember(jss::fee_div_max))
861 if (request[jss::fee_div_max].isInt())
863 div = request[jss::fee_div_max].
asInt();
875 if (feeOrError.isMember(jss::error))
877 tx[jss::Fee] = std::move(feeOrError);
893 using namespace detail;
895 auto j = app.
journal(
"RPCHandler");
896 JLOG(j.debug()) <<
"transactionSign: " << jvRequest;
899 SigningForParams signForParams;
900 transactionPreProcessResult preprocResult =
901 transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app);
903 if (!preprocResult.second)
904 return preprocResult.first;
909 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
928 using namespace detail;
931 auto j = app.
journal(
"RPCHandler");
932 JLOG(j.debug()) <<
"transactionSubmit: " << jvRequest;
935 SigningForParams signForParams;
936 transactionPreProcessResult preprocResult =
937 transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app);
939 if (!preprocResult.second)
940 return preprocResult.first;
944 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
969 if (!jvRequest.
isMember(jss::tx_json))
972 Json::Value const& tx_json(jvRequest[jss::tx_json]);
980 if (!tx_json.
isMember(jss::Sequence))
983 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
989 if (!jvRequest.
isMember(jss::signature_target) && !tx_json[sfSigningPubKey.getJsonName()].
asString().
empty())
1001 if (signers.empty())
1006 return (a[sfAccount] < b[sfAccount]);
1011 return (a[sfAccount] == b[sfAccount]);
1014 if (dupIter != signers.end())
1017 err <<
"Duplicate Signers:Signer:Account entries (" <<
toBase58((*dupIter)[sfAccount]) <<
") are not allowed.";
1022 if (signers.end() !=
std::find_if(signers.begin(), signers.end(), [&signingForID](
STObject const& elem) {
1023 return elem[sfAccount] == signingForID;
1027 err <<
"A Signer may not be the transaction's Account (" <<
toBase58(signingForID) <<
").";
1046 auto j = app.
journal(
"RPCHandler");
1047 JLOG(j.debug()) <<
"transactionSignFor: " << jvRequest;
1050 char const accountField[] =
"account";
1052 if (!jvRequest.
isMember(accountField))
1056 auto const signerAccountID = parseBase58<AccountID>(jvRequest[accountField].asString());
1057 if (!signerAccountID)
1062 if (!jvRequest.
isMember(jss::tx_json))
1073 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
1074 tx_json[sfSigningPubKey.getJsonName()] =
"";
1079 using namespace detail;
1081 Json::Value err = checkMultiSignFields(jvRequest);
1087 SigningForParams signForParams(*signerAccountID);
1089 transactionPreProcessResult preprocResult =
1090 transactionPreProcessImpl(jvRequest, role, signForParams, validatedLedgerAge, app);
1092 if (!preprocResult.second)
1093 return preprocResult.first;
1095 XRPL_ASSERT(signForParams.validMultiSign(),
"xrpl::RPC::transactionSignFor : valid multi-signature");
1100 auto const err = acctMatchesPubKey(account_state, *signerAccountID, signForParams.getPublicKey());
1107 auto& sttx = preprocResult.second;
1111 signer[sfAccount] = *signerAccountID;
1112 signer.
setFieldVL(sfTxnSignature, signForParams.getSignature());
1113 signer.
setFieldVL(sfSigningPubKey, signForParams.getPublicKey().slice());
1116 auto const target = signForParams.getSignatureTarget();
1125 auto& signers = sigTarget.peekFieldArray(sfSigners);
1126 signers.emplace_back(std::move(signer));
1129 auto err = sortAndValidateSigners(signers, (*sttx)[sfAccount]);
1147 unsigned apiVersion,
1155 auto j = app.
journal(
"RPCHandler");
1156 JLOG(j.debug()) <<
"transactionSubmitMultiSigned: " << jvRequest;
1160 using namespace detail;
1162 Json::Value err = checkMultiSignFields(jvRequest);
1169 auto [txJsonResult, srcAddressID] = checkTxJsonFields(
1179 return std::move(txJsonResult);
1186 JLOG(j.debug()) <<
"transactionSubmitMultiSigned: Failed to find source account "
1187 <<
"in current ledger: " <<
toBase58(srcAddressID);
1198 err = checkPayment(jvRequest, tx_json, srcAddressID, role, app,
false);
1208 if (!parsedTx_json.
object)
1211 jvResult[
"error"] = parsedTx_json.
error[
"error"];
1212 jvResult[
"error_code"] = parsedTx_json.
error[
"error_code"];
1213 jvResult[
"error_message"] = parsedTx_json.
error[
"error_message"];
1240 if (!stTx->getFieldVL(sfSigningPubKey).empty())
1243 err <<
"Invalid " << sfSigningPubKey.fieldName <<
" field. Field must be empty when multi-signing.";
1248 if (stTx->isFieldPresent(sfTxnSignature))
1252 auto const fee = stTx->getFieldAmount(sfFee);
1257 err <<
"Invalid " << sfFee.fieldName <<
" field. Fees must be specified in XRP.";
1263 err <<
"Invalid " << sfFee.fieldName <<
" field. Fees must be greater than zero.";
1269 if (!stTx->isFieldPresent(sfSigners))
1274 auto& signers = stTx->peekFieldArray(sfSigners);
1276 if (signers.empty())
1284 obj.isFieldPresent(sfAccount) && obj.isFieldPresent(sfSigningPubKey) &&
1285 obj.isFieldPresent(sfTxnSignature) && obj.getCount() == 3);
1286 }) != signers.end())
1292 auto err = sortAndValidateSigners(signers, srcAddressID);
1313 return transactionFormatResultImpl(txn.
second, apiVersion);
T adjacent_find(T... args)
Value removeMember(char const *key)
Remove and return the named member.
std::string asString() const
Returns the unquoted string value.
bool isMember(char const *key) const
Return true if the object has a member named key.
virtual HashRouter & getHashRouter()=0
virtual Config & config()=0
virtual LoadFeeTrack & getFeeTrack()=0
virtual bool checkSigs() const =0
virtual beast::Journal journal(std::string const &name)=0
virtual OpenLedger & openLedger()=0
Like std::vector<char> but better.
std::size_t size() const noexcept
Returns the number of bytes in the buffer.
Manages the current fee schedule.
bool isLoadedCluster() const
std::shared_ptr< OpenView const > current() const
Returns a view to the current open ledger.
Calculates payment paths.
STPathSet getBestPaths(int maxPaths, STPath &fullLiquidityPath, STPathSet const &extraPaths, AccountID const &srcIssuer, std::function< bool(void)> const &continueCallback={})
bool findPaths(int searchLevel, std::function< bool(void)> const &continueCallback={})
void computePathRanks(int maxPaths, std::function< bool(void)> const &continueCallback={})
Compute the rankings of the paths.
Slice slice() const noexcept
void setSignatureTarget(std::optional< std::reference_wrapper< SField const > > const &field)
std::optional< PublicKey > multiSignPublicKey_
bool validMultiSign() const
AccountID const & getSigner() const
bool isSingleSigning() const
std::optional< std::reference_wrapper< SField const > > const & getSignatureTarget() const
void setPublicKey(PublicKey const &multiSignPublicKey)
PublicKey const & getPublicKey() const
bool isMultiSigning() const
Buffer const & getSignature() const
SigningForParams(AccountID const &multiSigningAcctID)
void moveMultiSignature(Buffer &&multiSignature)
std::optional< std::reference_wrapper< SField const > > signatureTarget_
AccountID const *const multiSigningAcctID_
SigningForParams(SigningForParams const &rhs)=delete
Rules controlling protocol behavior.
static SField const & getField(int fieldCode)
Issue const & issue() const
void setIssuer(AccountID const &uIssuer)
bool native() const noexcept
void setFieldVL(SField const &field, Blob const &)
void setFieldArray(SField const &field, STArray const &v)
STObject & peekFieldObject(SField const &field)
bool isFieldPresent(SField const &field) const
static STObject makeInnerObject(SField const &name)
Holds the serialized result of parsing an input JSON object.
std::optional< STObject > object
The STObject if the parse was successful.
Json::Value error
On failure, an appropriate set of error values.
Json::Value getJson(JsonOptions) const override
static constexpr std::size_t maxMultiSigners
constexpr std::uint32_t value() const
Slice slice() const noexcept
An immutable linear range of bytes.
Metrics getMetrics(OpenView const &view) const
Returns fee metrics in reference fee level units.
SeqProxy nextQueuableSeq(std::shared_ptr< SLE const > const &sleAccount) const
Return the next sequence that would go in the TxQ for an account.
Json::Value jsonClipped() const
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
static int constexpr defaultAutoFillFeeMultiplier
auto constexpr maxValidatedLedgerAge
static int constexpr defaultAutoFillFeeDivisor
static transactionPreProcessResult transactionPreProcessImpl(Json::Value ¶ms, Role role, SigningForParams &signingArgs, std::chrono::seconds validatedLedgerAge, Application &app)
static Json::Value checkPayment(Json::Value const ¶ms, Json::Value &tx_json, AccountID const &srcAddressID, Role const role, Application &app, bool doPath)
static Json::Value transactionFormatResultImpl(Transaction::pointer tpTrans, unsigned apiVersion)
static Json::Value checkMultiSignFields(Json::Value const &jvRequest)
static std::pair< Json::Value, AccountID > checkTxJsonFields(Json::Value const &tx_json, Role const role, bool const verify, std::chrono::seconds validatedLedgerAge, Config const &config, LoadFeeTrack const &feeTrack, unsigned apiVersion)
static std::pair< Json::Value, Transaction::pointer > transactionConstructImpl(std::shared_ptr< STTx const > const &stTx, Rules const &rules, Application &app)
static error_code_i acctMatchesPubKey(std::shared_ptr< SLE const > accountState, AccountID const &accountID, PublicKey const &publicKey)
static Json::Value sortAndValidateSigners(STArray &signers, AccountID const &signingForID)
Json::Value invalid_field_error(std::string const &name)
std::string expected_field_message(std::string const &name, std::string const &type)
Json::Value transactionSubmit(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app, ProcessTransactionFn const &processTransaction)
Returns a Json::objectValue.
std::string missing_field_message(std::string const &name)
void insertDeliverMax(Json::Value &tx_json, TxType txnType, unsigned int apiVersion)
Copy Amount field to DeliverMax field in transaction output JSON.
Json::Value transactionSign(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app)
Returns a Json::objectValue.
Json::Value missing_field_error(std::string const &name)
static XRPAmount getTxFee(Application const &app, Config const &config, Json::Value tx)
Json::Value getCurrentNetworkFee(Role const role, Config const &config, LoadFeeTrack const &feeTrack, TxQ const &txQ, Application const &app, Json::Value const &tx, int mult, int div)
Json::Value object_field_error(std::string const &name)
Json::Value checkFee(Json::Value &request, Role const role, bool doAutoFill, Config const &config, LoadFeeTrack const &feeTrack, TxQ const &txQ, Application const &app)
Fill in the fee on behalf of the client.
Json::Value transactionSignFor(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app)
Returns a Json::objectValue.
static constexpr std::integral_constant< unsigned, Version > apiVersion
Json::Value make_param_error(std::string const &message)
Returns a new json object that indicates invalid parameters.
Json::Value transactionSubmitMultiSigned(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app, ProcessTransactionFn const &processTransaction)
Returns a Json::objectValue.
std::string invalid_field_message(std::string const &name)
std::optional< std::pair< PublicKey, SecretKey > > keypairForSignature(Json::Value const ¶ms, Json::Value &error, unsigned int apiVersion)
Generates a keypair for signature from RPC parameters.
unsigned int getAPIVersionNumber(Json::Value const &jv, bool betaEnabled)
Retrieve the api version number from the json value.
Json::Value make_error(error_code_i code)
Returns a new json object that reflects the error code.
bool contains_error(Json::Value const &json)
Returns true if the json contains an rpc error specification.
Keylet account(AccountID const &id) noexcept
AccountID root.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
std::optional< std::uint64_t > mulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div)
Return value*mul/div accurately.
@ Valid
Signature and local checks are good / passed.
@ SigGoodOnly
Signature is good, but local checks fail.
std::string to_string(base_uint< Bits, Tag > const &a)
std::string strHex(FwdIt begin, FwdIt end)
bool verify(PublicKey const &publicKey, Slice const &m, Slice const &sig) noexcept
Verify a signature on a message.
bool isLegalNet(STAmount const &value)
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
XRPAmount toDrops(FeeLevel< T > const &level, XRPAmount baseFee)
bool transResultInfo(TER code, std::string &token, std::string &text)
Role
Indicates the level of administrative permission to grant.
bool amountFromJsonNoThrow(STAmount &result, Json::Value const &jvSource)
bool passesLocalChecks(STObject const &st, std::string &)
AccountID calcAccountID(PublicKey const &pk)
Json::Value rpcError(error_code_i iError)
std::pair< Validity, std::string > checkValidity(HashRouter &router, STTx const &tx, Rules const &rules, Config const &config)
Checks transaction signature and local checks.
XRPAmount scaleFeeLoad(XRPAmount fee, LoadFeeTrack const &feeTrack, Fees const &fees, bool bUnlimited)
Buffer sign(PublicKey const &pk, SecretKey const &sk, Slice const &message)
Generate a signature for a message.
XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Compute only the expected base fee for a transaction.
void forceValidity(HashRouter &router, uint256 const &txid, Validity validity)
Sets the validity of a given transaction in the cache.
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)
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
@ rpcDELEGATE_ACT_NOT_FOUND
Serializer buildMultiSigningData(STObject const &obj, AccountID const &signingID)
Return a Serializer suitable for computing a multisigning TxnSignature.
XRPAmount reference_fee
The cost of a reference transaction in drops.
transactionPreProcessResult & operator=(transactionPreProcessResult &&)=delete
transactionPreProcessResult(std::shared_ptr< STTx > &&st)
transactionPreProcessResult & operator=(transactionPreProcessResult const &)=delete
transactionPreProcessResult(Json::Value &&json)
transactionPreProcessResult(transactionPreProcessResult &&rhs)=default
transactionPreProcessResult()=delete
transactionPreProcessResult(transactionPreProcessResult const &)=delete
std::shared_ptr< STTx > const second