20#include <xrpld/app/ledger/OpenLedger.h>
21#include <xrpld/app/main/Application.h>
22#include <xrpld/app/misc/DeliverMax.h>
23#include <xrpld/app/misc/Transaction.h>
24#include <xrpld/app/misc/TxQ.h>
25#include <xrpld/app/paths/Pathfinder.h>
26#include <xrpld/app/tx/apply.h>
27#include <xrpld/app/tx/applySteps.h>
28#include <xrpld/rpc/detail/LegacyPathFind.h>
29#include <xrpld/rpc/detail/RPCHelpers.h>
30#include <xrpld/rpc/detail/TransactionSign.h>
31#include <xrpl/basics/Log.h>
32#include <xrpl/basics/mulDiv.h>
33#include <xrpl/json/json_writer.h>
34#include <xrpl/protocol/ErrorCodes.h>
35#include <xrpl/protocol/RPCErr.h>
36#include <xrpl/protocol/STParsedJSON.h>
37#include <xrpl/protocol/Sign.h>
38#include <xrpl/protocol/TxFlags.h>
99 LogicError(
"Accessing unknown SigningForParams::getSigner()");
107 LogicError(
"Accessing unknown SigningForParams::getPublicKey()");
139 bool const isMasterKey = publicKeyAcctID == accountID;
151 auto const& sle = *accountState;
160 if ((sle.isFieldPresent(sfRegularKey)) &&
161 (publicKeyAcctID == sle.getAccountID(sfRegularKey)))
178 if (tx_json[jss::TransactionType].asString() != jss::Payment)
182 if (tx_json.
isMember(jss::DeliverMax))
186 if (tx_json[jss::DeliverMax] != tx_json[jss::Amount])
189 "Cannot specify differing 'Amount' and 'DeliverMax'");
192 tx_json[jss::Amount] = tx_json[jss::DeliverMax];
205 if (!tx_json.
isMember(jss::Destination))
208 auto const dstAccountID =
209 parseBase58<AccountID>(tx_json[jss::Destination].asString());
213 if (params.
isMember(jss::build_path) &&
217 "Field 'build_path' not allowed in this context.");
222 "Cannot specify both 'tx_json.Paths' and 'build_path'");
254 std::make_shared<RippleLineCache>(
255 ledger, app.
journal(
"RippleLineCache")),
274 auto j = app.
journal(
"RPCHandler");
275 JLOG(j.debug()) <<
"transactionSign: build_path: "
313 if (!tx_json.
isMember(jss::TransactionType))
319 if (!tx_json.
isMember(jss::Account))
326 auto const srcAddressID =
327 parseBase58<AccountID>(tx_json[jss::Account].asString());
356 ret.
second = *srcAddressID;
389static transactionPreProcessResult
397 auto j = app.
journal(
"RPCHandler");
409 !(params.
isMember(jss::offline) && params[jss::offline].
asBool());
427 return std::move(txJsonResult);
442 JLOG(j.debug()) <<
"transactionSign: Failed to find source account "
443 <<
"in current ledger: " <<
toBase58(srcAddressID);
450 if (!tx_json.
isMember(jss::Sequence))
452 bool const hasTicketSeq =
453 tx_json.
isMember(sfTicketSequence.jsonName);
454 if (!hasTicketSeq && !sle)
457 <<
"transactionSign: Failed to find source account "
458 <<
"in current ledger: " <<
toBase58(srcAddressID);
462 tx_json[jss::Sequence] =
469 if (!tx_json.
isMember(jss::NetworkID))
472 if (networkId > 1024)
473 tx_json[jss::NetworkID] =
to_string(networkId);
507 if (tx_json.
isMember(jss::TxnSignature))
541 if (!parsed.
object.has_value())
544 err[jss::error] = parsed.
error[jss::error];
545 err[jss::error_code] = parsed.
error[jss::error_code];
546 err[jss::error_message] = parsed.
error[jss::error_message];
555 parsed.
object->setFieldVL(
559 stTx = std::make_shared<STTx>(std::move(parsed.
object.value()));
569 "Exception occurred constructing serialized transaction");
605 tpTrans = std::make_shared<Transaction>(stTx, reason, app);
606 if (tpTrans->getStatus() !=
NEW)
609 rpcINTERNAL,
"Unable to construct transaction: " + reason);
621 tpTrans->getSTransaction()->add(s);
626 auto sttxNew = std::make_shared<STTx const>(sit);
630 sttxNew->getTransactionID(),
642 std::make_shared<Transaction>(sttxNew, reason, app);
646 if (!tpTransNew->getSTransaction()->isEquivalent(
647 *tpTrans->getSTransaction()))
651 tpTrans = std::move(tpTransNew);
667 ret.
second = std::move(tpTrans);
679 jvResult[jss::tx_json] =
681 jvResult[jss::hash] =
to_string(tpTrans->getID());
687 jvResult[jss::tx_json],
688 tpTrans->getSTransaction()->getTxnType(),
691 jvResult[jss::tx_blob] =
692 strHex(tpTrans->getSTransaction()->getSerializer().peekData());
701 jvResult[jss::engine_result] = sToken;
702 jvResult[jss::engine_result_code] = tpTrans->getResult();
703 jvResult[jss::engine_result_message] = sHuman;
709 rpcINTERNAL,
"Exception occurred during JSON handling.");
731 tx[jss::Sequence] =
"0";
734 if (!tx.
isMember(jss::SigningPubKey))
736 tx[jss::SigningPubKey] =
"";
739 if (!tx.
isMember(jss::TxnSignature))
741 tx[jss::TxnSignature] =
"";
746 if (!tx[jss::Signers].isArray())
750 for (
auto& signer : tx[jss::Signers])
752 if (!signer.isMember(jss::Signer) ||
753 !signer[jss::Signer].isObject())
755 if (!signer[jss::Signer].isMember(jss::SigningPubKey))
758 signer[jss::Signer][jss::SigningPubKey] =
"";
760 if (!signer[jss::Signer].isMember(jss::TxnSignature))
763 signer[jss::Signer][jss::TxnSignature] =
"";
769 if (!parsed.
object.has_value())
805 auto const baseFee = ledger->fees().base;
811 auto const limit =
mulDiv(feeDefault, mult, div);
813 Throw<std::overflow_error>(
"mulDiv");
818 ss <<
"Fee of " << fee <<
" exceeds the requested tx limit of "
845 if (request.
isMember(jss::fee_mult_max))
847 if (request[jss::fee_mult_max].isInt())
849 mult = request[jss::fee_mult_max].
asInt();
854 jss::fee_mult_max,
"a positive integer"));
861 jss::fee_mult_max,
"a positive integer"));
864 if (request.
isMember(jss::fee_div_max))
866 if (request[jss::fee_div_max].isInt())
868 div = request[jss::fee_div_max].
asInt();
873 jss::fee_div_max,
"a positive integer"));
880 jss::fee_div_max,
"a positive integer"));
886 if (feeOrError.isMember(jss::error))
888 tx[jss::Fee] = std::move(feeOrError);
904 using namespace detail;
906 auto j = app.
journal(
"RPCHandler");
907 JLOG(j.debug()) <<
"transactionSign: " << jvRequest;
910 SigningForParams signForParams;
911 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
912 jvRequest, role, signForParams, validatedLedgerAge, app);
914 if (!preprocResult.second)
915 return preprocResult.first;
920 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
939 using namespace detail;
942 auto j = app.
journal(
"RPCHandler");
943 JLOG(j.debug()) <<
"transactionSubmit: " << jvRequest;
946 SigningForParams signForParams;
947 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
948 jvRequest, role, signForParams, validatedLedgerAge, app);
950 if (!preprocResult.second)
951 return preprocResult.first;
955 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
969 rpcINTERNAL,
"Exception occurred during transaction submission.");
981 if (!jvRequest.
isMember(jss::tx_json))
984 Json::Value const& tx_json(jvRequest[jss::tx_json]);
992 if (!tx_json.
isMember(jss::Sequence))
995 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
998 if (!tx_json[sfSigningPubKey.getJsonName()].
asString().
empty())
1001 "When multi-signing 'tx_json.SigningPubKey' must be empty.");
1012 if (signers.empty())
1020 return (a[sfAccount] < b[sfAccount]);
1028 return (a[sfAccount] == b[sfAccount]);
1031 if (dupIter != signers.end())
1034 err <<
"Duplicate Signers:Signer:Account entries ("
1035 <<
toBase58((*dupIter)[sfAccount]) <<
") are not allowed.";
1040 if (signers.end() !=
1044 [&signingForID](
STObject const& elem) {
1045 return elem[sfAccount] == signingForID;
1049 err <<
"A Signer may not be the transaction's Account ("
1069 auto j = app.
journal(
"RPCHandler");
1070 JLOG(j.debug()) <<
"transactionSignFor: " << jvRequest;
1073 const char accountField[] =
"account";
1075 if (!jvRequest.
isMember(accountField))
1079 auto const signerAccountID =
1080 parseBase58<AccountID>(jvRequest[accountField].asString());
1081 if (!signerAccountID)
1087 if (!jvRequest.
isMember(jss::tx_json))
1098 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
1099 tx_json[sfSigningPubKey.getJsonName()] =
"";
1104 using namespace detail;
1106 Json::Value err = checkMultiSignFields(jvRequest);
1112 SigningForParams signForParams(*signerAccountID);
1114 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
1115 jvRequest, role, signForParams, validatedLedgerAge, app);
1117 if (!preprocResult.second)
1118 return preprocResult.first;
1121 signForParams.validMultiSign(),
1122 "ripple::RPC::transactionSignFor : valid multi-signature");
1128 auto const err = acctMatchesPubKey(
1129 account_state, *signerAccountID, signForParams.getPublicKey());
1136 auto& sttx = preprocResult.second;
1140 signer[sfAccount] = *signerAccountID;
1141 signer.
setFieldVL(sfTxnSignature, signForParams.getSignature());
1143 sfSigningPubKey, signForParams.getPublicKey().slice());
1146 if (!sttx->isFieldPresent(sfSigners))
1147 sttx->setFieldArray(sfSigners, {});
1149 auto& signers = sttx->peekFieldArray(sfSigners);
1150 signers.emplace_back(std::move(signer));
1153 auto err = sortAndValidateSigners(signers, (*sttx)[sfAccount]);
1160 transactionConstructImpl(sttx, ledger->rules(), app);
1180 auto j = app.
journal(
"RPCHandler");
1181 JLOG(j.debug()) <<
"transactionSubmitMultiSigned: " << jvRequest;
1185 using namespace detail;
1187 Json::Value err = checkMultiSignFields(jvRequest);
1194 auto [txJsonResult, srcAddressID] = checkTxJsonFields(
1204 return std::move(txJsonResult);
1213 <<
"transactionSubmitMultiSigned: Failed to find source account "
1214 <<
"in current ledger: " <<
toBase58(srcAddressID);
1232 err = checkPayment(jvRequest, tx_json, srcAddressID, role, app,
false);
1242 if (!parsedTx_json.
object)
1245 jvResult[
"error"] = parsedTx_json.
error[
"error"];
1246 jvResult[
"error_code"] = parsedTx_json.
error[
"error_code"];
1247 jvResult[
"error_message"] = parsedTx_json.
error[
"error_message"];
1253 std::make_shared<STTx>(std::move(parsedTx_json.
object.value()));
1264 "Exception while serializing transaction: " + reason);
1277 if (!stTx->getFieldVL(sfSigningPubKey).empty())
1280 err <<
"Invalid " << sfSigningPubKey.fieldName
1281 <<
" field. Field must be empty when multi-signing.";
1286 if (stTx->isFieldPresent(sfTxnSignature))
1290 auto const fee = stTx->getFieldAmount(sfFee);
1295 err <<
"Invalid " << sfFee.fieldName
1296 <<
" field. Fees must be specified in XRP.";
1302 err <<
"Invalid " << sfFee.fieldName
1303 <<
" field. Fees must be greater than zero.";
1309 if (!stTx->isFieldPresent(sfSigners))
1314 auto& signers = stTx->peekFieldArray(sfSigners);
1316 if (signers.empty())
1321 signers.begin(), signers.end(), [](
STObject const& obj) {
1325 obj.isFieldPresent(sfAccount) &&
1326 obj.isFieldPresent(sfSigningPubKey) &&
1327 obj.isFieldPresent(sfTxnSignature) && obj.getCount() == 3);
1328 }) != signers.end())
1331 "Signers array may only contain Signer entries.");
1335 auto err = sortAndValidateSigners(signers, srcAddressID);
1341 transactionConstructImpl(stTx, ledger->rules(), app);
1355 rpcINTERNAL,
"Exception occurred during transaction submission.");
T adjacent_find(T... args)
Value removeMember(const char *key)
Remove and return the named member.
std::string asString() const
Returns the unquoted string value.
bool isMember(const char *key) const
Return true if the object has a member named key.
virtual Config & config()=0
virtual LoadFeeTrack & getFeeTrack()=0
virtual OpenLedger & openLedger()=0
virtual beast::Journal journal(std::string const &name)=0
virtual bool checkSigs() const =0
virtual HashRouter & getHashRouter()=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.
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.
STPathSet getBestPaths(int maxPaths, STPath &fullLiquidityPath, STPathSet const &extraPaths, AccountID const &srcIssuer, std::function< bool(void)> const &continueCallback={})
Slice slice() const noexcept
AccountID const *const multiSigningAcctID_
std::optional< PublicKey > multiSignPublicKey_
SigningForParams(SigningForParams const &rhs)=delete
bool validMultiSign() const
SigningForParams(AccountID const &multiSigningAcctID)
AccountID const & getSigner() const
bool isMultiSigning() const
void moveMultiSignature(Buffer &&multiSignature)
PublicKey const & getPublicKey() const
Buffer const & getSignature() const
bool isSingleSigning() const
void setPublicKey(PublicKey const &multiSignPublicKey)
Rules controlling protocol behavior.
constexpr bool holds() const noexcept
void setIssuer(AccountID const &uIssuer)
Issue const & issue() const
bool native() const noexcept
static STObject makeInnerObject(SField const &name)
void setFieldVL(SField const &field, Blob const &)
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
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
auto constexpr maxValidatedLedgerAge
static int constexpr defaultAutoFillFeeMultiplier
static int constexpr defaultAutoFillFeeDivisor
static Json::Value checkPayment(Json::Value const ¶ms, Json::Value &tx_json, AccountID const &srcAddressID, Role const role, Application &app, bool doPath)
static error_code_i acctMatchesPubKey(std::shared_ptr< SLE const > accountState, AccountID const &accountID, PublicKey const &publicKey)
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 transactionPreProcessResult transactionPreProcessImpl(Json::Value ¶ms, Role role, SigningForParams &signingArgs, std::chrono::seconds validatedLedgerAge, Application &app)
static std::pair< Json::Value, Transaction::pointer > transactionConstructImpl(std::shared_ptr< STTx const > const &stTx, Rules const &rules, Application &app)
static Json::Value checkMultiSignFields(Json::Value const &jvRequest)
static Json::Value sortAndValidateSigners(STArray &signers, AccountID const &signingForID)
static Json::Value transactionFormatResultImpl(Transaction::pointer tpTrans, unsigned apiVersion)
Json::Value transactionSign(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app)
Returns a Json::objectValue.
unsigned int getAPIVersionNumber(Json::Value const &jv, bool betaEnabled)
Retrieve the api version number from the json value.
bool contains_error(Json::Value const &json)
Returns true if the json contains an rpc error specification.
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.
Json::Value make_error(error_code_i code)
Returns a new json object that reflects the error code.
Json::Value invalid_field_error(std::string const &name)
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.
std::string missing_field_message(std::string const &name)
std::string invalid_field_message(std::string const &name)
std::string expected_field_message(std::string const &name, std::string const &type)
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 transactionSubmit(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app, ProcessTransactionFn const &processTransaction)
Returns a Json::objectValue.
static XRPAmount getTxFee(Application const &app, Config const &config, Json::Value tx)
Json::Value object_field_error(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 transactionSignFor(Json::Value jvRequest, unsigned apiVersion, NetworkOPs::FailHard failType, Role role, std::chrono::seconds validatedLedgerAge, Application &app)
Returns a Json::objectValue.
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 missing_field_error(std::string const &name)
std::optional< std::pair< PublicKey, SecretKey > > keypairForSignature(Json::Value const ¶ms, Json::Value &error, unsigned int apiVersion)
Keylet account(AccountID const &id) noexcept
AccountID root.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
bool verify(PublicKey const &publicKey, Slice const &m, Slice const &sig, bool mustBeFullyCanonical=true) noexcept
Verify a signature on a message.
Serializer buildMultiSigningData(STObject const &obj, AccountID const &signingID)
Return a Serializer suitable for computing a multisigning TxnSignature.
XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Compute only the expected base fee for a transaction.
bool isLegalNet(STAmount const &value)
AccountID calcAccountID(PublicKey const &pk)
Json::Value rpcError(int iError)
bool isUnlimited(Role const &role)
ADMIN and IDENTIFIED roles shall have unlimited resources.
Buffer sign(PublicKey const &pk, SecretKey const &sk, Slice const &message)
Generate a signature for a message.
std::string strHex(FwdIt begin, FwdIt end)
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 amountFromJsonNoThrow(STAmount &result, Json::Value const &jvSource)
void forceValidity(HashRouter &router, uint256 const &txid, Validity validity)
Sets the validity of a given transaction in the cache.
bool passesLocalChecks(STObject const &st, std::string &)
@ 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)
constexpr std::uint32_t tfFullyCanonicalSig
Transaction flags.
XRPAmount scaleFeeLoad(XRPAmount fee, LoadFeeTrack const &feeTrack, Fees const &fees, bool bUnlimited)
XRPAmount toDrops(FeeLevel< T > const &level, XRPAmount baseFee)
std::optional< std::uint64_t > mulDiv(std::uint64_t value, std::uint64_t mul, std::uint64_t div)
Return value*mul/div accurately.
std::pair< Validity, std::string > checkValidity(HashRouter &router, STTx const &tx, Rules const &rules, Config const &config)
Checks transaction signature and local checks.
bool transResultInfo(TER code, std::string &token, std::string &text)
Role
Indicates the level of administrative permission to grant.
void LogicError(std::string const &how) noexcept
Called when faulty logic causes a broken invariant.
XRPAmount reference_fee
The cost of a reference transaction in drops.
transactionPreProcessResult(std::shared_ptr< STTx > &&st)
transactionPreProcessResult & operator=(transactionPreProcessResult const &)=delete
transactionPreProcessResult(transactionPreProcessResult const &)=delete
transactionPreProcessResult(Json::Value &&json)
transactionPreProcessResult()=delete
std::shared_ptr< STTx > const second
transactionPreProcessResult(transactionPreProcessResult &&rhs)=default
transactionPreProcessResult & operator=(transactionPreProcessResult &&)=delete