xrpld
Loading...
Searching...
No Matches
Simulate.cpp
1#include <xrpld/app/ledger/LedgerMaster.h>
2#include <xrpld/app/ledger/OpenLedger.h>
3#include <xrpld/app/misc/Transaction.h>
4#include <xrpld/app/misc/TxQ.h>
5#include <xrpld/rpc/Context.h>
6#include <xrpld/rpc/DeliveredAmount.h>
7#include <xrpld/rpc/detail/SyntheticFields.h>
8#include <xrpld/rpc/detail/TransactionSign.h>
9
10#include <xrpl/basics/Log.h>
11#include <xrpl/basics/Number.h>
12#include <xrpl/basics/Slice.h>
13#include <xrpl/basics/StringUtilities.h>
14#include <xrpl/basics/strHex.h>
15#include <xrpl/core/NetworkIDService.h>
16#include <xrpl/core/ServiceRegistry.h>
17#include <xrpl/json/json_value.h>
18#include <xrpl/ledger/ApplyView.h>
19#include <xrpl/ledger/OpenView.h>
20#include <xrpl/protocol/AccountID.h>
21#include <xrpl/protocol/ErrorCodes.h>
22#include <xrpl/protocol/Indexes.h>
23#include <xrpl/protocol/RPCErr.h>
24#include <xrpl/protocol/SField.h>
25#include <xrpl/protocol/STParsedJSON.h>
26#include <xrpl/protocol/Serializer.h>
27#include <xrpl/protocol/TER.h>
28#include <xrpl/protocol/TxFlags.h>
29#include <xrpl/protocol/TxFormats.h>
30#include <xrpl/protocol/jss.h>
31#include <xrpl/resource/Fees.h>
32
33#include <cstdint>
34#include <exception>
35#include <expected>
36#include <functional>
37#include <memory>
38#include <optional>
39#include <stdexcept>
40#include <string>
41#include <utility>
42
43namespace xrpl {
44
45static std::expected<std::uint32_t, json::Value>
47{
48 // autofill Sequence
49 bool const hasTicketSeq = txJson.isMember(sfTicketSequence.jsonName);
50 auto const& accountStr = txJson[jss::Account];
51 if (!accountStr.isString())
52 {
53 // sanity check, should fail earlier
54 // LCOV_EXCL_START
55 return std::unexpected(rpc::invalidFieldError("tx.Account"));
56 // LCOV_EXCL_STOP
57 }
58 auto const srcAddressID = parseBase58<AccountID>(accountStr.asString());
59 if (!srcAddressID.has_value())
60 {
61 return std::unexpected(
63 }
64 SLE::const_pointer const sle =
65 context.app.getOpenLedger().current()->read(keylet::account(*srcAddressID));
66 if (!hasTicketSeq && !sle)
67 {
68 JLOG(context.app.getJournal("Simulate").debug())
69 << "Failed to find source account "
70 << "in current ledger: " << toBase58(*srcAddressID);
71
73 }
74
75 return hasTicketSeq ? 0 : context.app.getTxQ().nextQueuableSeq(sle).value();
76}
77
79autofillSignature(json::Value& sigObject, std::string const& fieldPrefix = "tx")
80{
81 if (!sigObject.isMember(jss::SigningPubKey))
82 {
83 // autofill SigningPubKey
84 sigObject[jss::SigningPubKey] = "";
85 }
86
87 if (sigObject.isMember(jss::Signers))
88 {
89 if (!sigObject[jss::Signers].isArray())
90 return rpc::invalidFieldError(fieldPrefix + ".Signers");
91 // check multisigned signers
92 for (unsigned index = 0; index < sigObject[jss::Signers].size(); index++)
93 {
94 auto& signer = sigObject[jss::Signers][index];
95 if (!signer.isObject() || !signer.isMember(jss::Signer) ||
96 !signer[jss::Signer].isObject())
97 {
99 fieldPrefix + ".Signers[" + std::to_string(index) + "]");
100 }
101
102 if (!signer[jss::Signer].isMember(jss::SigningPubKey))
103 {
104 // autofill SigningPubKey
105 signer[jss::Signer][jss::SigningPubKey] = "";
106 }
107
108 if (!signer[jss::Signer].isMember(jss::TxnSignature))
109 {
110 // autofill TxnSignature
111 signer[jss::Signer][jss::TxnSignature] = "";
112 }
113 else if (signer[jss::Signer][jss::TxnSignature] != "")
114 {
115 // Transaction must not be signed
116 return rpcError(RpcTxSigned);
117 }
118 }
119 }
120
121 if (!sigObject.isMember(jss::TxnSignature))
122 {
123 // autofill TxnSignature
124 sigObject[jss::TxnSignature] = "";
125 }
126 else if (sigObject[jss::TxnSignature] != "")
127 {
128 // Transaction must not be signed
129 return rpcError(RpcTxSigned);
130 }
131 return std::nullopt;
132}
133
136{
137 if (auto error = autofillSignature(txJson))
138 return error;
139
140 if (txJson.isMember(sfSponsorSignature.jsonName))
141 {
142 auto& sponsorSignature = txJson[sfSponsorSignature.jsonName];
143 if (!sponsorSignature.isObject())
144 return rpc::objectFieldError(sfSponsorSignature.jsonName);
145
146 if (auto const error = autofillSignature(sponsorSignature, "tx.SponsorSignature"))
147 return error;
148 }
149
150 if (!txJson.isMember(jss::Sequence))
151 {
152 auto const seq = getAutofillSequence(txJson, context);
153 if (!seq)
154 return seq.error();
155 txJson[sfSequence.jsonName] = *seq;
156 }
157
158 if (!txJson.isMember(jss::NetworkID))
159 {
160 auto const networkId = context.app.getNetworkIDService().getNetworkID();
161 if (networkId > 1024)
162 txJson[jss::NetworkID] = to_string(networkId);
163 }
164
165 if (!txJson.isMember(jss::Fee))
166 {
167 // Autofill Fee after normalizing nested signer fields so the fee
168 // estimator sees the full transaction shape.
169 auto feeOrError = rpc::getCurrentNetworkFee(
170 context.role,
171 context.app.config(),
172 context.app.getFeeTrack(),
173 context.app.getTxQ(),
174 context.app,
175 txJson);
176 if (feeOrError.isMember(jss::error))
177 return feeOrError;
178 txJson[jss::Fee] = feeOrError;
179 }
180
181 return std::nullopt;
182}
183
184static json::Value
186{
187 json::Value txJson;
188
189 if (params.isMember(jss::tx_blob))
190 {
191 if (params.isMember(jss::tx_json))
192 {
193 return rpc::makeParamError("Can only include one of `tx_blob` and `tx_json`.");
194 }
195
196 auto const txBlob = params[jss::tx_blob];
197 if (!txBlob.isString())
198 {
199 return rpc::invalidFieldError(jss::tx_blob);
200 }
201
202 auto unHexed = strUnHex(txBlob.asString());
203 if (!unHexed || unHexed->empty())
204 return rpc::invalidFieldError(jss::tx_blob);
205
206 try
207 {
208 SerialIter sitTrans(makeSlice(*unHexed));
210 }
211 catch (std::runtime_error const&)
212 {
213 return rpc::invalidFieldError(jss::tx_blob);
214 }
215 }
216 else if (params.isMember(jss::tx_json))
217 {
218 txJson = params[jss::tx_json];
219 if (!txJson.isObject())
220 {
221 return rpc::objectFieldError(jss::tx_json);
222 }
223 }
224 else
225 {
226 return rpc::makeParamError("Neither `tx_blob` nor `tx_json` included.");
227 }
228
229 // basic sanity checks for transaction shape
230 if (!txJson.isMember(jss::TransactionType))
231 {
232 return rpc::missingFieldError("tx.TransactionType");
233 }
234
235 if (!txJson.isMember(jss::Account))
236 {
237 return rpc::missingFieldError("tx.Account");
238 }
239
240 return txJson;
241}
242
243static json::Value
245{
246 json::Value jvResult;
247 // Process the transaction
248 OpenView view = *context.app.getOpenLedger().current();
249 auto const result = context.app.getTxQ().apply(
250 context.app, view, transaction->getSTransaction(), TapDryRun, context.j);
251
252 jvResult[jss::applied] = result.applied;
253 jvResult[jss::ledger_index] = view.seq();
254
255 bool const isBinaryOutput = context.params.get(jss::binary, false).asBool();
256
257 // Convert the TER to human-readable values
258 std::string token;
259 std::string message;
260 if (transResultInfo(result.ter, token, message))
261 {
262 // Engine result
263 jvResult[jss::engine_result] = token;
264 jvResult[jss::engine_result_code] = result.ter;
265 jvResult[jss::engine_result_message] = message;
266 }
267 else
268 {
269 // shouldn't be hit
270 // LCOV_EXCL_START
271 jvResult[jss::engine_result] = "unknown";
272 jvResult[jss::engine_result_code] = result.ter;
273 jvResult[jss::engine_result_message] = "unknown";
274 // LCOV_EXCL_STOP
275 }
276
277 if (token == "tesSUCCESS")
278 {
279 jvResult[jss::engine_result_message] = "The simulated transaction would have been applied.";
280 }
281
282 if (result.metadata)
283 {
284 if (isBinaryOutput)
285 {
286 auto const metaBlob = result.metadata->getAsObject().getSerializer().getData();
287 jvResult[jss::meta_blob] = strHex(makeSlice(metaBlob));
288 }
289 else
290 {
291 jvResult[jss::meta] = result.metadata->getJson(JsonOptions::Values::None);
293 jvResult[jss::meta], view, transaction->getSTransaction(), *result.metadata);
294 }
295 }
296
297 if (isBinaryOutput)
298 {
299 auto const txBlob = transaction->getSTransaction()->getSerializer().getData();
300 jvResult[jss::tx_blob] = strHex(makeSlice(txBlob));
301 }
302 else
303 {
304 jvResult[jss::tx_json] = transaction->getJson(JsonOptions::Values::None);
305 }
306
307 return jvResult;
308}
309
310// {
311// tx_blob: <string> XOR tx_json: <object>,
312// binary: <bool>
313// }
316{
318
319 json::Value txJson; // the tx as a JSON
320
321 // check validity of `binary` param
322 if (context.params.isMember(jss::binary) && !context.params[jss::binary].isBool())
323 {
324 return rpc::invalidFieldError(jss::binary);
325 }
326
327 for (auto const field : {jss::secret, jss::seed, jss::seed_hex, jss::passphrase})
328 {
329 if (context.params.isMember(field))
330 {
331 return rpc::invalidFieldError(field);
332 }
333 }
334
335 // get JSON equivalent of transaction
336 txJson = getTxJsonFromParams(context.params);
337 if (txJson.isMember(jss::error))
338 return txJson;
339
340 // autofill fields if they're not included (e.g. `Fee`, `Sequence`)
341 if (auto error = autofillTx(txJson, context))
342 return *error;
343
344 STParsedJSONObject parsed(std::string(jss::tx_json), txJson);
345 if (!parsed.object.has_value())
346 return parsed.error;
347
349 try
350 {
351 stTx = std::make_shared<STTx>(std::move(parsed.object.value()));
352 }
353 catch (std::exception& e)
354 {
356 jvResult[jss::error] = "invalidTransaction";
357 jvResult[jss::error_exception] = e.what();
358 return jvResult;
359 }
360
361 if (stTx->getTxnType() == ttBATCH)
362 {
364 }
365
366 // Reject transactions with the tfInnerBatchTxn flag.
367 if (stTx->isFlag(tfInnerBatchTxn))
368 {
369 return rpc::makeError(
370 RpcInvalidParams, "tfInnerBatchTxn flag is not allowed on top-level transactions.");
371 }
372
373 std::string reason;
374 auto transaction = std::make_shared<Transaction>(stTx, reason, context.app);
375 // Actually run the transaction through the transaction processor
376 try
377 {
378 return simulateTxn(context, transaction);
379 }
380 // LCOV_EXCL_START this is just in case, so xrpld doesn't crash
381 catch (std::exception const& e)
382 {
384 jvResult[jss::error] = "internalSimulate";
385 jvResult[jss::error_exception] = e.what();
386 return jvResult;
387 }
388 // LCOV_EXCL_STOP
389}
390
391} // namespace xrpl
Stream debug() const
Definition Journal.h:344
Represents a JSON value.
Definition json_value.h:117
bool isObject() const
bool asBool() const
Value get(UInt index, Value const &defaultValue) const
If the array contains at least index+1 elements, returns the element value, otherwise returns default...
bool isBool() const
UInt size() const
Number of values in array or object.
bool isMember(char const *key) const
Return true if the object has a member named key.
virtual Config & config()=0
virtual std::uint32_t getNetworkID() const noexcept=0
Get the configured network ID.
std::shared_ptr< OpenView const > current() const
Returns a view to the current open ledger.
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
LedgerIndex seq() const
Returns the sequence number of the base ledger.
Definition ReadView.h:115
std::shared_ptr< STLedgerEntry const > const_pointer
json::Value getJson(JsonOptions=JsonOptions::Values::None) const override
Definition STObject.cpp:845
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.
constexpr std::uint32_t value() const
Definition SeqProxy.h:80
virtual TxQ & getTxQ()=0
virtual beast::Journal getJournal(std::string const &name)=0
virtual OpenLedger & getOpenLedger()=0
virtual NetworkIDService & getNetworkIDService()=0
virtual LoadFeeTrack & getFeeTrack()=0
SeqProxy nextQueuableSeq(SLE::ConstRef sleAccount) const
Return the next sequence that would go in the TxQ for an account.
Definition TxQ.cpp:1619
ApplyResult apply(Application &app, OpenView &view, std::shared_ptr< STTx const > const &tx, ApplyFlags flags, beast::Journal j)
Add a new transaction to the open ledger, hold it in the queue, or reject it.
Definition TxQ.cpp:761
T make_shared(T... args)
@ Object
object value (collection of name/value pairs).
Definition json_value.h:29
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:220
Charge const kFeeMediumBurdenRpc
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)
void insertAllSyntheticInJson(json::Value &metadata, ReadView const &ledger, std::shared_ptr< STTx const > const &transaction, TxMeta const &transactionMeta)
Adds all synthetic fields to transaction metadata JSON.
std::string invalidFieldMessage(std::string const &name)
Definition ErrorCodes.h:273
json::Value makeParamError(std::string const &message)
Returns a new json object that indicates invalid parameters.
Definition ErrorCodes.h:231
json::Value invalidFieldError(std::string const &name)
Definition ErrorCodes.h:285
json::Value missingFieldError(std::string const &name)
Definition ErrorCodes.h:243
json::Value makeError(ErrorCodeI code)
Returns a new json object that reflects the error code.
json::Value objectFieldError(std::string const &name)
Definition ErrorCodes.h:261
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr FlagValue tfInnerBatchTxn
Definition TxFlags.h:44
@ RpcSrcActMalformed
Definition ErrorCodes.h:103
@ RpcNotImpl
Definition ErrorCodes.h:114
@ RpcInvalidParams
Definition ErrorCodes.h:67
@ RpcTxSigned
Definition ErrorCodes.h:138
@ RpcSrcActNotFound
Definition ErrorCodes.h:105
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::string strHex(FwdIt begin, FwdIt end)
Definition strHex.h:13
SField const sfGeneric
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
static json::Value simulateTxn(rpc::JsonContext &context, std::shared_ptr< Transaction > transaction)
Definition Simulate.cpp:244
bool transResultInfo(TER code, std::string &token, std::string &text)
Definition TER.cpp:242
json::Value doSimulate(rpc::JsonContext &)
Definition Simulate.cpp:315
static json::Value getTxJsonFromParams(json::Value const &params)
Definition Simulate.cpp:185
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:657
Slice makeSlice(std::array< T, N > const &a)
Definition Slice.h:228
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
std::optional< Blob > strUnHex(std::size_t strSize, Iterator begin, Iterator end)
@ TapDryRun
Definition ApplyView.h:46
static std::optional< json::Value > autofillTx(json::Value &txJson, rpc::JsonContext &context)
Definition Simulate.cpp:135
static std::optional< json::Value > autofillSignature(json::Value &sigObject, std::string const &fieldPrefix="tx")
Definition Simulate.cpp:79
static std::expected< std::uint32_t, json::Value > getAutofillSequence(json::Value const &txJson, rpc::JsonContext &context)
Definition Simulate.cpp:46
T ref(T... args)
resource::Charge & loadType
Definition Context.h:30
beast::Journal const j
Definition Context.h:28
Application & app
Definition Context.h:29
json::Value params
Definition Context.h:51
T to_string(T... args)
T unexpected(T... args)
T what(T... args)