xrpld
Loading...
Searching...
No Matches
TxTest.cpp
1#include <helpers/TxTest.h>
2
3#include <xrpl/basics/base_uint.h>
4#include <xrpl/basics/chrono.h>
5#include <xrpl/basics/contract.h>
6#include <xrpl/ledger/ApplyView.h>
7#include <xrpl/ledger/CanonicalTXSet.h>
8#include <xrpl/ledger/Ledger.h>
9#include <xrpl/ledger/OpenView.h>
10#include <xrpl/protocol/AccountID.h>
11#include <xrpl/protocol/Feature.h>
12#include <xrpl/protocol/Fees.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/SField.h>
15#include <xrpl/protocol/STLedgerEntry.h>
16#include <xrpl/protocol/STTx.h>
17#include <xrpl/protocol/TER.h>
18#include <xrpl/protocol_autogen/ledger_entries/AccountRoot.h>
19#include <xrpl/protocol_autogen/ledger_entries/RippleState.h>
20#include <xrpl/protocol_autogen/transactions/AccountSet.h>
21#include <xrpl/protocol_autogen/transactions/Payment.h>
22#include <xrpl/tx/apply.h>
23
24#include <helpers/Account.h>
25#include <helpers/IOU.h>
26
27#include <cstdint>
28#include <memory>
29#include <optional>
30#include <stdexcept>
31#include <utility>
32#include <vector>
33
34namespace xrpl::test {
35
36//------------------------------------------------------------------------------
37// Feature helpers
38//------------------------------------------------------------------------------
39
40FeatureBitset
42{
43 static FeatureBitset const kFeatures = [] {
44 auto const& sa = allAmendments();
46 feats.reserve(sa.size());
47 for ([[maybe_unused]] auto const& [name, _] : sa)
48 {
49 if (auto const f = getRegisteredFeature(name); f.has_value())
50 feats.push_back(*f);
51 }
52 return FeatureBitset(feats);
53 }();
54 return kFeatures;
55}
56
57//------------------------------------------------------------------------------
58// TxTest
59//------------------------------------------------------------------------------
60
62{
63 // Convert FeatureBitset to unordered_set for Rules constructor
64 auto const featureBits = features.value_or(allFeatures());
65 foreachFeature(featureBits, [&](UInt256 const& f) { featureSet_.insert(f); });
66
67 // Create rules with the specified features
68 rules_.emplace(featureSet_);
69
70 // Default fees for testing
71 Fees const fees{
72 XRPAmount{10},
73 XRPAmount{10000000},
74 XRPAmount{2000000},
78
79 // Create a genesis ledger as the base
82 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
83 *rules_,
84 fees,
86 registry_.getNodeFamily());
87
88 // Initialize time from the genesis ledger. closedLedger_ is created above
89 // in the body, so this cannot be a member initializer.
90 // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
91 now_ = closedLedger_->header().closeTime;
92
93 // Create an open view on top of the genesis ledger
96}
97
98bool
99TxTest::isEnabled(UInt256 const& feature) const
100{
101 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
102 return rules_->enabled(feature);
103}
104
105Rules const&
107{
108 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
109 return *rules_;
110}
111
112[[nodiscard]] TxResult
114{
115 auto result = apply(registry_, *openLedger_, *stx, TapNone, registry_.getJournal("apply"));
116
117 // Track successfully applied transactions for canonical reordering on close
118 // We make a copy since the TransactionBase doesn't own the STTx
119 if (result.applied)
120 pendingTxs_.push_back(stx);
121
122 return TxResult{
123 .ter = result.ter,
124 .applied = result.applied,
125 .metadata = std::move(result).metadata,
126 .tx = std::move(stx),
127 };
128}
129
130void
131TxTest::createAccount(Account const& account, XRPAmount xrp, uint32_t accountFlags)
132{
133 auto const paymentTer =
135
136 if (paymentTer != tesSUCCESS)
137 {
138 throw std::runtime_error("TxTest::createAccount: failed to create account");
139 }
140
141 close();
142
143 if (accountFlags != 0)
144 {
145 auto const accountSetTer =
146 submit(transactions::AccountSetBuilder{account}.setSetFlag(accountFlags), account).ter;
147 if (accountSetTer != tesSUCCESS)
148 {
149 throw std::runtime_error("TxTest::createAccount: failed to set account flags");
150 }
151 close();
152 }
153}
154
157{
158 auto const sle = getOpenLedger().read(keylet::account(id));
159 if (!sle)
160 Throw<std::runtime_error>("TxTest::getAccountRoot: account not found");
162}
163
166{
167 return *openLedger_;
168}
169
170OpenView const&
172{
173 return *openLedger_;
174}
175
176Ledger const&
178{
179 return *closedLedger_;
180}
181
182void
184{
185 // Build a new closed ledger from the previous closed ledger,
186 // similar to how buildLedgerImpl works:
187 // 1. Create a new Ledger from the previous closed ledger
188 // 2. Re-apply transactions in canonical order
189 // 3. Mark it as accepted/immutable
190
191 auto const& prevLedger = *closedLedger_;
192
193 auto const ledgerCloseTime = now_ + prevLedger.header().closeTimeResolution;
194
195 now_ = ledgerCloseTime;
196
197 auto const newLedger = std::make_shared<Ledger>(prevLedger, ledgerCloseTime);
198
199 CanonicalTXSet txSet(prevLedger.header().hash);
200 for (auto const& tx : pendingTxs_)
201 txSet.insert(tx);
202
203 {
204 OpenView accum(&*newLedger);
205 for (auto const& [key, tx] : txSet)
206 {
207 auto const result =
208 apply(registry_, accum, *tx, TapNone, registry_.getJournal("apply"));
209 if (!result.applied)
210 {
211 throw std::runtime_error("TxTest::close: failed to apply transaction");
212 }
213 }
214 accum.apply(*newLedger);
215 }
216
217 if (!newLedger->setAccepted(ledgerCloseTime, newLedger->header().closeTimeResolution, true))
218 {
219 Throw<std::runtime_error>("TxTest::close: ledger has an invalid map");
220 }
221
222 closedLedger_ = newLedger;
223
224 pendingTxs_.clear();
225
227 // NOLINTNEXTLINE(bugprone-unchecked-optional-access)
229}
230
231void
236
239{
240 return now_;
241}
242
244TxTest::getBalance(AccountID const& account, IOU const& iou) const
245{
246 auto const sle = openLedger_->read(keylet::trustLine(account, iou.issue()));
247 if (!sle)
248 return STAmount{iou.issue(), 0};
249
250 auto const trustLine = ledger_entries::RippleState{sle};
251
252 auto balance = trustLine.getBalance();
253 if (iou.issue().account == account)
254 {
255 throw std::logic_error("TxTest::getBalance: account is issuer");
256 }
257
258 balance.get<Issue>().account = iou.issue().account;
259 if (account > iou.issue().account)
260 balance.negate();
261 return balance;
262}
263
264} // namespace xrpl::test
Holds transactions which were deferred to the next pass of consensus.
void insert(std::shared_ptr< STTx const > txn)
A currency issued by an account.
Definition Issue.h:18
AccountID account
Definition Issue.h:21
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
Definition OpenView.cpp:170
void apply(TxsRawView &to) const
Apply changes.
Definition OpenView.cpp:129
Rules controlling protocol behavior.
Definition Rules.h:40
Ledger Entry: AccountRoot.
Definition AccountRoot.h:28
Ledger Entry: RippleState.
Definition RippleState.h:28
static Account const kMaster
The master account that holds all XRP in genesis.
TxTest(std::optional< FeatureBitset > features=std::nullopt)
Construct a TxTest environment.
Definition TxTest.cpp:61
void createAccount(Account const &account, XRPAmount xrp, uint32_t accountFlags=0)
Create a new account in the ledger.
Definition TxTest.cpp:131
NetClock::time_point getCloseTime() const
Get the current ledger close time.
Definition TxTest.cpp:238
std::shared_ptr< Ledger const > closedLedger_
Definition TxTest.h:359
OpenView & getOpenLedger()
Get the current open ledger view.
Definition TxTest.cpp:165
bool isEnabled(UInt256 const &feature) const
Check if a feature is enabled.
Definition TxTest.cpp:99
NetClock::time_point now_
Current time (can be advanced arbitrarily for testing).
Definition TxTest.h:370
std::unordered_set< UInt256, beast::Uhash<> > featureSet_
Definition TxTest.h:357
TestServiceRegistry registry_
Definition TxTest.h:356
Rules const & getRules() const
Get the current rules.
Definition TxTest.cpp:106
void close()
Close the current ledger.
Definition TxTest.cpp:183
TxResult submit(T &&builder, Account const &signer)
Submit a transaction from a builder.
Definition TxTest.h:226
void advanceTime(NetClock::duration duration)
Advance time without closing the ledger.
Definition TxTest.cpp:232
std::vector< std::shared_ptr< STTx const > > pendingTxs_
Transactions submitted to the open ledger, for canonical reordering on close.
Definition TxTest.h:365
std::optional< Rules > rules_
Definition TxTest.h:358
Ledger const & getClosedLedger() const
Get the closed (base) ledger view.
Definition TxTest.cpp:177
STAmount getBalance(AccountID const &account, IOU const &iou) const
Get the balance of an IOU for an account.
Definition TxTest.cpp:244
std::shared_ptr< OpenView > openLedger_
Definition TxTest.h:360
ledger_entries::AccountRoot getAccountRoot(AccountID const &id) const
Get the account root object from the current open ledger.
Definition TxTest.cpp:156
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
Converts to IOU Issue or STAmount.
AccountSetBuilder & setSetFlag(std::decay_t< typename SF_UINT32::type::value_type > const &value)
Set sfSetFlag (SoeOptional).
T make_shared(T... args)
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
FeatureBitset allFeatures()
Returns all testable amendments.
Definition TxTest.cpp:41
constexpr XRPAmount
Convert XRP to drops (integral types).
Definition TxTest.h:53
constexpr std::uint32_t kDefaultGasLimit
ApplyResult apply(ServiceRegistry &registry, OpenView &view, STTx const &tx, ApplyFlags flags, beast::Journal journal)
Apply a transaction to an OpenView.
Definition apply.cpp:181
CreateGenesisT const kCreateGenesis
std::optional< UInt256 > getRegisteredFeature(std::string const &name)
void foreachFeature(FeatureBitset bs, F &&f)
Definition Feature.h:383
BaseUInt< 256 > UInt256
Definition base_uint.h:581
constexpr std::uint32_t kDefaultGasPrice
constexpr std::uint32_t kDefaultBytecodeSizeLimit
@ TapNone
Definition ApplyView.h:28
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
std::map< std::string, AmendmentSupport > const & allAmendments()
All amendments libxrpl knows about.
constexpr struct xrpl::OpenLedgerT kOpenLedger
@ tesSUCCESS
Definition TER.h:253
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T const_pointer_cast(T... args)
T push_back(T... args)
T reserve(T... args)
Reflects the fee settings for a particular ledger.
Result of a transaction submission in TxTest.
Definition TxTest.h:158
TER ter
The transaction engine result code.
Definition TxTest.h:159
T value_or(T... args)