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/MPTokenIssuanceID.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/NFTSyntheticSerializer.h>
24#include <xrpl/protocol/RPCErr.h>
25#include <xrpl/protocol/SField.h>
26#include <xrpl/protocol/STParsedJSON.h>
27#include <xrpl/protocol/Serializer.h>
28#include <xrpl/protocol/TER.h>
29#include <xrpl/protocol/TxFlags.h>
30#include <xrpl/protocol/TxFormats.h>
31#include <xrpl/protocol/jss.h>
32#include <xrpl/resource/Fees.h>
33
34#include <cstdint>
35#include <exception>
36#include <expected>
37#include <functional>
38#include <memory>
39#include <optional>
40#include <stdexcept>
41#include <string>
42#include <utility>
43
44namespace xrpl {
45
46static std::expected<std::uint32_t, json::Value>
48{
49 // autofill Sequence
50 bool const hasTicketSeq = txJson.isMember(sfTicketSequence.jsonName);
51 auto const& accountStr = txJson[jss::Account];
52 if (!accountStr.isString())
53 {
54 // sanity check, should fail earlier
55 // LCOV_EXCL_START
56 return std::unexpected(rpc::invalidFieldError("tx.Account"));
57 // LCOV_EXCL_STOP
58 }
59 auto const srcAddressID = parseBase58<AccountID>(accountStr.asString());
60 if (!srcAddressID.has_value())
61 {
62 return std::unexpected(
64 }
65 SLE::const_pointer const sle =
66 context.app.getOpenLedger().current()->read(keylet::account(*srcAddressID));
67 if (!hasTicketSeq && !sle)
68 {
69 JLOG(context.app.getJournal("Simulate").debug())
70 << "Failed to find source account "
71 << "in current ledger: " << toBase58(*srcAddressID);
72
74 }
75
76 return hasTicketSeq ? 0 : context.app.getTxQ().nextQueuableSeq(sle).value();
77}
78
80autofillSignature(json::Value& sigObject, std::string const& fieldPrefix = "tx")
81{
82 if (!sigObject.isMember(jss::SigningPubKey))
83 {
84 // autofill SigningPubKey
85 sigObject[jss::SigningPubKey] = "";
86 }
87
88 if (sigObject.isMember(jss::Signers))
89 {
90 if (!sigObject[jss::Signers].isArray())
91 return rpc::invalidFieldError(fieldPrefix + ".Signers");
92 // check multisigned signers
93 for (unsigned index = 0; index < sigObject[jss::Signers].size(); index++)
94 {
95 auto& signer = sigObject[jss::Signers][index];
96 if (!signer.isObject() || !signer.isMember(jss::Signer) ||
97 !signer[jss::Signer].isObject())
98 {
100 fieldPrefix + ".Signers[" + std::to_string(index) + "]");
101 }
102
103 if (!signer[jss::Signer].isMember(jss::SigningPubKey))
104 {
105 // autofill SigningPubKey
106 signer[jss::Signer][jss::SigningPubKey] = "";
107 }
108
109 if (!signer[jss::Signer].isMember(jss::TxnSignature))
110 {
111 // autofill TxnSignature
112 signer[jss::Signer][jss::TxnSignature] = "";
113 }
114 else if (signer[jss::Signer][jss::TxnSignature] != "")
115 {
116 // Transaction must not be signed
117 return rpcError(RpcTxSigned);
118 }
119 }
120 }
121
122 if (!sigObject.isMember(jss::TxnSignature))
123 {
124 // autofill TxnSignature
125 sigObject[jss::TxnSignature] = "";
126 }
127 else if (sigObject[jss::TxnSignature] != "")
128 {
129 // Transaction must not be signed
130 return rpcError(RpcTxSigned);
131 }
132 return std::nullopt;
133}
134
137{
138 if (auto error = autofillSignature(txJson))
139 return error;
140
141 if (txJson.isMember(sfSponsorSignature.jsonName))
142 {
143 auto& sponsorSignature = txJson[sfSponsorSignature.jsonName];
144 if (!sponsorSignature.isObject())
145 return rpc::objectFieldError(sfSponsorSignature.jsonName);
146
147 if (auto const error = autofillSignature(sponsorSignature, "tx.SponsorSignature"))
148 return error;
149 }
150
151 if (!txJson.isMember(jss::Sequence))
152 {
153 auto const seq = getAutofillSequence(txJson, context);
154 if (!seq)
155 return seq.error();
156 txJson[sfSequence.jsonName] = *seq;
157 }
158
159 if (!txJson.isMember(jss::NetworkID))
160 {
161 auto const networkId = context.app.getNetworkIDService().getNetworkID();
162 if (networkId > 1024)
163 txJson[jss::NetworkID] = to_string(networkId);
164 }
165
166 if (!txJson.isMember(jss::Fee))
167 {
168 // Autofill Fee after normalizing nested signer fields so the fee
169 // estimator sees the full transaction shape.
170 auto feeOrError = rpc::getCurrentNetworkFee(
171 context.role,
172 context.app.config(),
173 context.app.getFeeTrack(),
174 context.app.getTxQ(),
175 context.app,
176 txJson);
177 if (feeOrError.isMember(jss::error))
178 return feeOrError;
179 txJson[jss::Fee] = feeOrError;
180 }
181
182 return std::nullopt;
183}
184
185static json::Value
187{
188 json::Value txJson;
189
190 if (params.isMember(jss::tx_blob))
191 {
192 if (params.isMember(jss::tx_json))
193 {
194 return rpc::makeParamError("Can only include one of `tx_blob` and `tx_json`.");
195 }
196
197 auto const txBlob = params[jss::tx_blob];
198 if (!txBlob.isString())
199 {
200 return rpc::invalidFieldError(jss::tx_blob);
201 }
202
203 auto unHexed = strUnHex(txBlob.asString());
204 if (!unHexed || unHexed->empty())
205 return rpc::invalidFieldError(jss::tx_blob);
206
207 try
208 {
209 SerialIter sitTrans(makeSlice(*unHexed));
211 }
212 catch (std::runtime_error const&)
213 {
214 return rpc::invalidFieldError(jss::tx_blob);
215 }
216 }
217 else if (params.isMember(jss::tx_json))
218 {
219 txJson = params[jss::tx_json];
220 if (!txJson.isObject())
221 {
222 return rpc::objectFieldError(jss::tx_json);
223 }
224 }
225 else
226 {
227 return rpc::makeParamError("Neither `tx_blob` nor `tx_json` included.");
228 }
229
230 // basic sanity checks for transaction shape
231 if (!txJson.isMember(jss::TransactionType))
232 {
233 return rpc::missingFieldError("tx.TransactionType");
234 }
235
236 if (!txJson.isMember(jss::Account))
237 {
238 return rpc::missingFieldError("tx.Account");
239 }
240
241 return txJson;
242}
243
244static json::Value
246{
247 json::Value jvResult;
248 // Process the transaction
249 OpenView view = *context.app.getOpenLedger().current();
250 auto const result = context.app.getTxQ().apply(
251 context.app, view, transaction->getSTransaction(), TapDryRun, context.j);
252
253 jvResult[jss::applied] = result.applied;
254 jvResult[jss::ledger_index] = view.seq();
255
256 bool const isBinaryOutput = context.params.get(jss::binary, false).asBool();
257
258 // Convert the TER to human-readable values
259 std::string token;
260 std::string message;
261 if (transResultInfo(result.ter, token, message))
262 {
263 // Engine result
264 jvResult[jss::engine_result] = token;
265 jvResult[jss::engine_result_code] = result.ter;
266 jvResult[jss::engine_result_message] = message;
267 }
268 else
269 {
270 // shouldn't be hit
271 // LCOV_EXCL_START
272 jvResult[jss::engine_result] = "unknown";
273 jvResult[jss::engine_result_code] = result.ter;
274 jvResult[jss::engine_result_message] = "unknown";
275 // LCOV_EXCL_STOP
276 }
277
278 if (token == "tesSUCCESS")
279 {
280 jvResult[jss::engine_result_message] = "The simulated transaction would have been applied.";
281 }
282
283 if (result.metadata)
284 {
285 if (isBinaryOutput)
286 {
287 auto const metaBlob = result.metadata->getAsObject().getSerializer().getData();
288 jvResult[jss::meta_blob] = strHex(makeSlice(metaBlob));
289 }
290 else
291 {
292 jvResult[jss::meta] = result.metadata->getJson(JsonOptions::Values::None);
294 jvResult[jss::meta], view, transaction->getSTransaction(), *result.metadata);
296 jvResult, transaction->getSTransaction(), *result.metadata);
298 jvResult[jss::meta], transaction->getSTransaction(), *result.metadata);
299 }
300 }
301
302 if (isBinaryOutput)
303 {
304 auto const txBlob = transaction->getSTransaction()->getSerializer().getData();
305 jvResult[jss::tx_blob] = strHex(makeSlice(txBlob));
306 }
307 else
308 {
309 jvResult[jss::tx_json] = transaction->getJson(JsonOptions::Values::None);
310 }
311
312 return jvResult;
313}
314
315// {
316// tx_blob: <string> XOR tx_json: <object>,
317// binary: <bool>
318// }
321{
323
324 json::Value txJson; // the tx as a JSON
325
326 // check validity of `binary` param
327 if (context.params.isMember(jss::binary) && !context.params[jss::binary].isBool())
328 {
329 return rpc::invalidFieldError(jss::binary);
330 }
331
332 for (auto const field : {jss::secret, jss::seed, jss::seed_hex, jss::passphrase})
333 {
334 if (context.params.isMember(field))
335 {
336 return rpc::invalidFieldError(field);
337 }
338 }
339
340 // get JSON equivalent of transaction
341 txJson = getTxJsonFromParams(context.params);
342 if (txJson.isMember(jss::error))
343 return txJson;
344
345 // autofill fields if they're not included (e.g. `Fee`, `Sequence`)
346 if (auto error = autofillTx(txJson, context))
347 return *error;
348
349 STParsedJSONObject parsed(std::string(jss::tx_json), txJson);
350 if (!parsed.object.has_value())
351 return parsed.error;
352
354 try
355 {
356 stTx = std::make_shared<STTx>(std::move(parsed.object.value()));
357 }
358 catch (std::exception& e)
359 {
361 jvResult[jss::error] = "invalidTransaction";
362 jvResult[jss::error_exception] = e.what();
363 return jvResult;
364 }
365
366 if (stTx->getTxnType() == ttBATCH)
367 {
369 }
370
371 // Reject transactions with the tfInnerBatchTxn flag.
372 if (stTx->isFlag(tfInnerBatchTxn))
373 {
374 return rpc::makeError(
375 RpcInvalidParams, "tfInnerBatchTxn flag is not allowed on top-level transactions.");
376 }
377
378 std::string reason;
379 auto transaction = std::make_shared<Transaction>(stTx, reason, context.app);
380 // Actually run the transaction through the transaction processor
381 try
382 {
383 return simulateTxn(context, transaction);
384 }
385 // LCOV_EXCL_START this is just in case, so xrpld doesn't crash
386 catch (std::exception const& e)
387 {
389 jvResult[jss::error] = "internalSimulate";
390 jvResult[jss::error_exception] = e.what();
391 return jvResult;
392 }
393 // LCOV_EXCL_STOP
394}
395
396} // 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::const_ref sleAccount) const
Return the next sequence that would go in the TxQ for an account.
Definition TxQ.cpp:1590
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:739
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:198
Charge const kFeeMediumBurdenRpc
void insertMPTokenIssuanceID(json::Value &response, std::shared_ptr< STTx const > const &transaction, TxMeta const &transactionMeta)
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 insertDeliveredAmount(json::Value &meta, ReadView const &, std::shared_ptr< STTx const > const &serializedTx, TxMeta const &)
Add a delivered_amount field to the meta input/output parameter.
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
void insertNFTSyntheticInJson(json::Value &, std::shared_ptr< STTx const > const &, TxMeta const &)
Adds common synthetic fields to transaction-related JSON responses.
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:245
bool transResultInfo(TER code, std::string &token, std::string &text)
Definition TER.cpp:236
json::Value doSimulate(rpc::JsonContext &)
Definition Simulate.cpp:320
static json::Value getTxJsonFromParams(json::Value const &params)
Definition Simulate.cpp:186
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:651
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:136
static std::optional< json::Value > autofillSignature(json::Value &sigObject, std::string const &fieldPrefix="tx")
Definition Simulate.cpp:80
static std::expected< std::uint32_t, json::Value > getAutofillSequence(json::Value const &txJson, rpc::JsonContext &context)
Definition Simulate.cpp:47
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)