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>
84 LogicError(
"Accessing unknown SigningForParams::getSigner()");
92 LogicError(
"Accessing unknown SigningForParams::getPublicKey()");
137 bool const isMasterKey = publicKeyAcctID == accountID;
149 auto const& sle = *accountState;
158 if ((sle.isFieldPresent(sfRegularKey)) &&
159 (publicKeyAcctID == sle.getAccountID(sfRegularKey)))
176 if (tx_json[jss::TransactionType].asString() != jss::Payment)
180 if (tx_json.
isMember(jss::DeliverMax))
184 if (tx_json[jss::DeliverMax] != tx_json[jss::Amount])
187 "Cannot specify differing 'Amount' and 'DeliverMax'");
190 tx_json[jss::Amount] = tx_json[jss::DeliverMax];
203 if (!tx_json.
isMember(jss::Destination))
206 auto const dstAccountID =
207 parseBase58<AccountID>(tx_json[jss::Destination].asString());
211 if (params.
isMember(jss::build_path) &&
215 "Field 'build_path' not allowed in this context.");
220 "Cannot specify both 'tx_json.Paths' and 'build_path'");
223 if (tx_json.
isMember(sfDomainID.jsonName))
226 if (!tx_json[sfDomainID.jsonName].
isString() ||
269 ledger, app.
journal(
"RippleLineCache")),
289 auto j = app.
journal(
"RPCHandler");
290 JLOG(j.debug()) <<
"transactionSign: build_path: "
328 if (!tx_json.
isMember(jss::TransactionType))
334 if (!tx_json.
isMember(jss::Account))
341 auto const srcAddressID =
342 parseBase58<AccountID>(tx_json[jss::Account].asString());
371 ret.
second = *srcAddressID;
404static transactionPreProcessResult
412 auto j = app.
journal(
"RPCHandler");
424 !(params.
isMember(jss::offline) && params[jss::offline].
asBool());
426 auto const signatureTarget =
428 if (params.
isMember(jss::signature_target))
435 auto const signatureTemplate = signatureTarget
441 if (!signatureTemplate)
465 return std::move(txJsonResult);
480 JLOG(j.debug()) <<
"transactionSign: Failed to find source account "
481 <<
"in current ledger: " <<
toBase58(srcAddressID);
488 if (!tx_json.
isMember(jss::Sequence))
490 bool const hasTicketSeq =
491 tx_json.
isMember(sfTicketSequence.jsonName);
492 if (!hasTicketSeq && !sle)
495 <<
"transactionSign: Failed to find source account "
496 <<
"in current ledger: " <<
toBase58(srcAddressID);
500 tx_json[jss::Sequence] =
504 if (!tx_json.
isMember(jss::NetworkID))
507 if (networkId > 1024)
508 tx_json[jss::NetworkID] =
to_string(networkId);
542 if (tx_json.
isMember(jss::TxnSignature))
569 if (tx_json.
isMember(sfDelegate.jsonName))
572 auto const delegateJson = tx_json[sfDelegate.jsonName];
573 auto const ptrDelegatedAddressID = delegateJson.
isString()
574 ? parseBase58<AccountID>(delegateJson.asString())
577 if (!ptrDelegatedAddressID)
584 auto delegatedAddressID = *ptrDelegatedAddressID;
607 if (!parsed.
object.has_value())
610 err[jss::error] = parsed.
error[jss::error];
611 err[jss::error_code] = parsed.
error[jss::error_code];
612 err[jss::error_message] = parsed.
error[jss::error_message];
625 if (!parsed.
object->isFieldPresent(*signatureTarget))
626 parsed.
object->setFieldObject(
628 STObject{*signatureTemplate, *signatureTarget});
629 sigObject = &parsed.
object->peekFieldObject(*signatureTarget);
645 "Exception occurred constructing serialized transaction");
663 stTx->sign(pk, sk, signatureTarget);
682 if (tpTrans->getStatus() !=
NEW)
685 rpcINTERNAL,
"Unable to construct transaction: " + reason);
697 tpTrans->getSTransaction()->add(s);
706 sttxNew->getTransactionID(),
722 if (!tpTransNew->getSTransaction()->isEquivalent(
723 *tpTrans->getSTransaction()))
727 tpTrans = std::move(tpTransNew);
743 ret.
second = std::move(tpTrans);
755 jvResult[jss::tx_json] =
757 jvResult[jss::hash] =
to_string(tpTrans->getID());
763 jvResult[jss::tx_json],
764 tpTrans->getSTransaction()->getTxnType(),
767 jvResult[jss::tx_blob] =
768 strHex(tpTrans->getSTransaction()->getSerializer().peekData());
777 jvResult[jss::engine_result] = sToken;
778 jvResult[jss::engine_result_code] = tpTrans->getResult();
779 jvResult[jss::engine_result_message] = sHuman;
785 rpcINTERNAL,
"Exception occurred during JSON handling.");
807 tx[jss::Sequence] =
"0";
810 if (!tx.
isMember(jss::SigningPubKey))
812 tx[jss::SigningPubKey] =
"";
815 if (!tx.
isMember(jss::TxnSignature))
817 tx[jss::TxnSignature] =
"";
822 if (!tx[jss::Signers].isArray())
829 for (
auto& signer : tx[jss::Signers])
831 if (!signer.isMember(jss::Signer) ||
832 !signer[jss::Signer].isObject())
834 if (!signer[jss::Signer].isMember(jss::SigningPubKey))
837 signer[jss::Signer][jss::SigningPubKey] =
"";
839 if (!signer[jss::Signer].isMember(jss::TxnSignature))
842 signer[jss::Signer][jss::TxnSignature] =
"";
848 if (!parsed.
object.has_value())
888 auto const baseFee = ledger->fees().base;
894 auto const limit =
mulDiv(feeDefault, mult, div);
896 Throw<std::overflow_error>(
"mulDiv");
901 ss <<
"Fee of " << fee <<
" exceeds the requested tx limit of "
928 if (request.
isMember(jss::fee_mult_max))
930 if (request[jss::fee_mult_max].isInt())
932 mult = request[jss::fee_mult_max].
asInt();
937 jss::fee_mult_max,
"a positive integer"));
944 jss::fee_mult_max,
"a positive integer"));
947 if (request.
isMember(jss::fee_div_max))
949 if (request[jss::fee_div_max].isInt())
951 div = request[jss::fee_div_max].
asInt();
956 jss::fee_div_max,
"a positive integer"));
963 jss::fee_div_max,
"a positive integer"));
969 if (feeOrError.isMember(jss::error))
971 tx[jss::Fee] = std::move(feeOrError);
987 using namespace detail;
989 auto j = app.
journal(
"RPCHandler");
990 JLOG(j.debug()) <<
"transactionSign: " << jvRequest;
993 SigningForParams signForParams;
994 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
995 jvRequest, role, signForParams, validatedLedgerAge, app);
997 if (!preprocResult.second)
998 return preprocResult.first;
1003 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
1022 using namespace detail;
1025 auto j = app.
journal(
"RPCHandler");
1026 JLOG(j.debug()) <<
"transactionSubmit: " << jvRequest;
1029 SigningForParams signForParams;
1030 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
1031 jvRequest, role, signForParams, validatedLedgerAge, app);
1033 if (!preprocResult.second)
1034 return preprocResult.first;
1038 transactionConstructImpl(preprocResult.second, ledger->rules(), app);
1052 rpcINTERNAL,
"Exception occurred during transaction submission.");
1064 if (!jvRequest.
isMember(jss::tx_json))
1067 Json::Value const& tx_json(jvRequest[jss::tx_json]);
1075 if (!tx_json.
isMember(jss::Sequence))
1078 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
1081 if (!tx_json[sfSigningPubKey.getJsonName()].
asString().
empty())
1084 "When multi-signing 'tx_json.SigningPubKey' must be empty.");
1095 if (signers.empty())
1103 return (a[sfAccount] < b[sfAccount]);
1111 return (a[sfAccount] == b[sfAccount]);
1114 if (dupIter != signers.end())
1117 err <<
"Duplicate Signers:Signer:Account entries ("
1118 <<
toBase58((*dupIter)[sfAccount]) <<
") are not allowed.";
1123 if (signers.end() !=
1127 [&signingForID](
STObject const& elem) {
1128 return elem[sfAccount] == signingForID;
1132 err <<
"A Signer may not be the transaction's Account ("
1152 auto j = app.
journal(
"RPCHandler");
1153 JLOG(j.debug()) <<
"transactionSignFor: " << jvRequest;
1156 char const accountField[] =
"account";
1158 if (!jvRequest.
isMember(accountField))
1162 auto const signerAccountID =
1163 parseBase58<AccountID>(jvRequest[accountField].asString());
1164 if (!signerAccountID)
1170 if (!jvRequest.
isMember(jss::tx_json))
1181 if (!tx_json.
isMember(sfSigningPubKey.getJsonName()))
1182 tx_json[sfSigningPubKey.getJsonName()] =
"";
1187 using namespace detail;
1189 Json::Value err = checkMultiSignFields(jvRequest);
1195 SigningForParams signForParams(*signerAccountID);
1197 transactionPreProcessResult preprocResult = transactionPreProcessImpl(
1198 jvRequest, role, signForParams, validatedLedgerAge, app);
1200 if (!preprocResult.second)
1201 return preprocResult.first;
1204 signForParams.validMultiSign(),
1205 "ripple::RPC::transactionSignFor : valid multi-signature");
1211 auto const err = acctMatchesPubKey(
1212 account_state, *signerAccountID, signForParams.getPublicKey());
1219 auto& sttx = preprocResult.second;
1223 signer[sfAccount] = *signerAccountID;
1224 signer.
setFieldVL(sfTxnSignature, signForParams.getSignature());
1226 sfSigningPubKey, signForParams.getPublicKey().slice());
1229 auto const target = signForParams.getSignatureTarget();
1238 auto& signers = sigTarget.peekFieldArray(sfSigners);
1239 signers.emplace_back(std::move(signer));
1242 auto err = sortAndValidateSigners(signers, (*sttx)[sfAccount]);
1249 transactionConstructImpl(sttx, ledger->rules(), app);
1261 unsigned apiVersion,
1269 auto j = app.
journal(
"RPCHandler");
1270 JLOG(j.debug()) <<
"transactionSubmitMultiSigned: " << jvRequest;
1274 using namespace detail;
1276 Json::Value err = checkMultiSignFields(jvRequest);
1283 auto [txJsonResult, srcAddressID] = checkTxJsonFields(
1293 return std::move(txJsonResult);
1302 <<
"transactionSubmitMultiSigned: Failed to find source account "
1303 <<
"in current ledger: " <<
toBase58(srcAddressID);
1321 err = checkPayment(jvRequest, tx_json, srcAddressID, role, app,
false);
1331 if (!parsedTx_json.
object)
1334 jvResult[
"error"] = parsedTx_json.
error[
"error"];
1335 jvResult[
"error_code"] = parsedTx_json.
error[
"error_code"];
1336 jvResult[
"error_message"] = parsedTx_json.
error[
"error_message"];
1353 "Exception while serializing transaction: " + reason);
1366 if (!stTx->getFieldVL(sfSigningPubKey).empty())
1369 err <<
"Invalid " << sfSigningPubKey.fieldName
1370 <<
" field. Field must be empty when multi-signing.";
1375 if (stTx->isFieldPresent(sfTxnSignature))
1379 auto const fee = stTx->getFieldAmount(sfFee);
1384 err <<
"Invalid " << sfFee.fieldName
1385 <<
" field. Fees must be specified in XRP.";
1391 err <<
"Invalid " << sfFee.fieldName
1392 <<
" field. Fees must be greater than zero.";
1398 if (!stTx->isFieldPresent(sfSigners))
1403 auto& signers = stTx->peekFieldArray(sfSigners);
1405 if (signers.empty())
1410 signers.begin(), signers.end(), [](
STObject const& obj) {
1414 obj.isFieldPresent(sfAccount) &&
1415 obj.isFieldPresent(sfSigningPubKey) &&
1416 obj.isFieldPresent(sfTxnSignature) && obj.getCount() == 3);
1417 }) != signers.end())
1420 "Signers array may only contain Signer entries.");
1424 auto err = sortAndValidateSigners(signers, srcAddressID);
1430 transactionConstructImpl(stTx, ledger->rules(), app);
1444 rpcINTERNAL,
"Exception occurred during transaction submission.");
1447 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 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
std::optional< std::reference_wrapper< SField const > > const & getSignatureTarget() const
bool validMultiSign() const
SigningForParams(AccountID const &multiSigningAcctID)
AccountID const & getSigner() const
bool isMultiSigning() const
void moveMultiSignature(Buffer &&multiSignature)
std::optional< std::reference_wrapper< SField const > > signatureTarget_
PublicKey const & getPublicKey() const
Buffer const & getSignature() const
void setSignatureTarget(std::optional< std::reference_wrapper< SField const > > const &field)
bool isSingleSigning() const
void setPublicKey(PublicKey const &multiSignPublicKey)
Rules controlling protocol behavior.
static SField const & getField(int fieldCode)
constexpr bool holds() const noexcept
void setIssuer(AccountID const &uIssuer)
Issue const & issue() const
bool native() const noexcept
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)
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
static std::size_t maxMultiSigners(Rules const *rules=0)
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.
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.
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.
unsigned int getAPIVersionNumber(Json::Value const &jv, bool betaEnabled)
Retrieve the api version number from the json value.
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.
@ rpcDELEGATE_ACT_NOT_FOUND
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)
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