xrpld
Loading...
Searching...
No Matches
proposal.cpp
1#include <test/jtx/proposal.h>
2
3#include <test/jtx/Account.h>
4#include <test/jtx/Env.h>
5#include <test/jtx/JTx.h>
6#include <test/jtx/batch.h>
7#include <test/jtx/multisign.h>
8#include <test/jtx/ticket.h>
9#include <test/jtx/utility.h>
10
11#include <xrpl/basics/base_uint.h>
12#include <xrpl/basics/chrono.h>
13#include <xrpl/basics/contract.h>
14#include <xrpl/json/json_value.h>
15#include <xrpl/ledger/ReadView.h>
16#include <xrpl/ledger/helpers/ProposalHelpers.h>
17#include <xrpl/protocol/AccountID.h>
18#include <xrpl/protocol/Indexes.h>
19#include <xrpl/protocol/SField.h>
20#include <xrpl/protocol/STAmount.h>
21#include <xrpl/protocol/STLedgerEntry.h>
22#include <xrpl/protocol/STObject.h>
23#include <xrpl/protocol/SeqProxy.h>
24#include <xrpl/protocol/TER.h>
25#include <xrpl/protocol/TxFlags.h>
26#include <xrpl/protocol/jss.h>
27
28#include <cstdint>
29#include <map>
30#include <optional>
31#include <set>
32#include <stdexcept>
33#include <string>
34#include <utility>
35#include <vector>
36
38
40create(Account const& proposer, json::Value const& proposedTx, std::uint32_t expiration)
41{
42 json::Value jv;
43 jv[jss::TransactionType] = jss::TransactionProposalCreate;
44 jv[jss::Account] = proposer.human();
45 jv[sfProposedTransaction.jsonName] = proposedTx;
46 jv[sfExpiration.jsonName] = expiration;
47 return jv;
48}
49
51cancel(Account const& account, uint256 const& proposalID)
52{
53 json::Value jv;
54 jv[jss::TransactionType] = jss::TransactionProposalCancel;
55 jv[jss::Account] = account.human();
56 jv[sfProposalID.jsonName] = to_string(proposalID);
57 return jv;
58}
59
61unsignedPayload(Env const& env, json::Value tx, std::uint32_t ticketSeq)
62{
63 // Unsigned canonical form: an empty SigningPubKey and no signature fields
64 // at all. Signatures may only ever arrive through TransactionProposalSign.
65 tx[jss::SigningPubKey] = "";
66
67 // Ticket-based rather than sequence-based. Sequence is a required common
68 // field, so "no Sequence" is expressed as a Sequence of 0.
69 tx[jss::Sequence] = 0;
70 tx[sfTicketSequence.jsonName] = ticketSeq;
71
72 // The target account pays this fee when the completed transaction is
73 // submitted, so it is fixed now. A fee already chosen by the caller stands.
74 fillFee(tx, *env.current());
75
76 return tx;
77}
78
81{
82 return batch::Inner{std::move(tx), seq}.getTxn();
83}
84
87 Env const& env,
88 Account const& target,
89 std::uint32_t ticketSeq,
90 std::uint32_t flags,
91 std::vector<json::Value> const& inners,
93{
94 // Each inner account other than the outer one will contribute one
95 // BatchSigners entry once the signatures are collected, and the outer fee
96 // has to cover them from the start (Batch::calculateBaseFee).
97 std::uint32_t const signers = numSigners ? *numSigners : [&] {
98 std::set<std::string> participants;
99 for (auto const& inner : inners)
100 {
101 if (auto const account = inner[jss::Account].asString(); account != target.human())
102 participants.insert(account);
103 }
104 return static_cast<std::uint32_t>(participants.size());
105 }();
106
108 target,
109 0,
110 batch::calcBatchFee(env, signers, static_cast<std::uint32_t>(inners.size())),
111 flags);
112
113 json::Value& rawTransactions = jv[jss::RawTransactions];
114 for (auto const& inner : inners)
115 rawTransactions[rawTransactions.size()][jss::RawTransaction] = inner;
116
117 return unsignedPayload(env, std::move(jv), ticketSeq);
118}
119
120void
121authorizeProposer(Env& env, Account const& target, Account const& proposer)
122{
123 env(signers(target, 1, {{proposer, 1}}));
124 env.close();
125}
126
128createTicket(Env& env, Account const& account, std::uint32_t count)
129{
130 // The tickets a TicketCreate makes are numbered from the sequence that
131 // follows the one it consumes.
132 std::uint32_t const firstTicketSeq = env.seq(account) + 1;
133 env(ticket::create(account, count));
134 env.close();
135 return firstTicketSeq;
136}
137
140{
141 return (env.now() + delta).time_since_epoch().count();
142}
143
145entry(Env const& env, AccountID const& target, std::uint32_t ticketSeq)
146{
147 return env.le(keylet::txProposal(target, ticketSeq));
148}
149
151entry(Env const& env, Account const& target, std::uint32_t ticketSeq)
152{
153 return entry(env, target.id(), ticketSeq);
154}
155
156namespace {
157
158// The keys an account's owner directory lists, each with the page it sits on.
159// The pages are read directly, so a key with nothing behind it is still seen.
161ownerDirKeys(ReadView const& view, AccountID const& account)
162{
164
165 auto const root = keylet::ownerDir(account);
166 std::uint64_t page = 0;
167 for (auto sle = view.read(root); sle;)
168 {
169 for (auto const& key : sle->getFieldV256(sfIndexes))
170 keys.emplace(key, page);
171
172 page = sle->getFieldU64(sfIndexNext);
173 if (page == 0)
174 break;
175 sle = view.read(keylet::page(root, page));
176 }
177
178 return keys;
179}
180
181// Whether two reads of a ledger entry found it unchanged, or found nothing both
182// times. Entries that are there are compared whole.
183bool
184unchanged(SLE::const_pointer const& before, SLE::const_pointer const& after)
185{
186 if (!before || !after)
187 return !before && !after;
188
189 return before->key() == after->key() &&
190 static_cast<STObject const&>(*before) == static_cast<STObject const&>(*after);
191}
192
193// Whether a TransactionProposal entry may carry the field when it is created.
194// A fresh proposal has gathered no signatures, so it carries nothing else —
195// except a Sponsor, which a reserve-sponsored creation stamps on the entry from
196// the start.
197bool
198isCreationField(SField const& field)
199{
200 return field == sfLedgerEntryType || field == sfFlags || field == sfOwner ||
201 field == sfProposedTransaction || field == sfExpiration || field == sfOwnerNode ||
202 field == sfPreviousTxnID || field == sfPreviousTxnLgrSeq || field == sfSponsor;
203}
204
205} // namespace
206
207void
209{
210 // Only a TransactionProposalCreate carries the fields read below, and a
211 // condition that quietly checks nothing is worse than none at all.
212 if (jt.jv[jss::TransactionType].asString() != jss::TransactionProposalCreate.cStr())
213 Throw<std::logic_error>("proposal::verify::create: not a TransactionProposalCreate");
214
215 // Funclets run before the transaction is applied, so everything read here
216 // is the state the effects are measured against.
217 auto const& proposedTx = jt.jv[sfProposedTransaction.jsonName];
218 auto const parsedTarget = parseBase58<AccountID>(proposedTx[jss::Account].asString());
219
220 // A payload naming no usable target is a malformed case a test is making
221 // on purpose, and has no ledger effect to measure.
222 if (!parsedTarget)
223 return;
224
225 auto const target = *parsedTarget;
226 auto const proposer = env.lookup(jt.jv[jss::Account].asString());
227 auto const ticketSeq = proposedTx[sfTicketSequence.jsonName].asUInt();
228 auto const expiration = jt.jv[sfExpiration.jsonName].asUInt();
229 auto const cost = proposedTx[jss::TransactionType].asString() == jss::Batch.cStr()
232
233 std::optional<Account> reserveSponsor;
234 if (jt.jv.isMember(sfSponsor.jsonName) &&
235 (jt.jv[sfSponsorFlags.jsonName].asUInt() & spfSponsorReserve) != 0)
236 reserveSponsor.emplace(env.lookup(jt.jv[sfSponsor.jsonName].asString()));
237
238 // Every entry the transaction could touch, read whole, so what follows can
239 // say that nothing moved rather than that the fields we named did not.
240 auto const& view = *env.current();
241
242 // A proposer paying with one of its own Tickets consumes it whenever the
243 // transaction is applied: on success, and on a claimed-fee tec.
244 std::optional<std::uint32_t> ownTicketSeq;
245 if (jt.jv.isMember(sfTicketSequence.jsonName))
246 ownTicketSeq = jt.jv[sfTicketSequence.jsonName].asUInt();
247
248 auto const proposalKeylet = keylet::txProposal(target, ticketSeq);
249 auto const ownerCountBefore = env.ownerCount(proposer);
250 auto const sponsoredOwnerCountBefore = env.sponsoredOwnerCount(proposer);
251 auto const sponsoringOwnerCountBefore =
252 reserveSponsor ? std::optional{env.sponsoringOwnerCount(*reserveSponsor)} : std::nullopt;
253 auto const proposalBefore = view.read(proposalKeylet);
254 auto const targetBefore = view.read(keylet::account(target));
255 auto const ticketBefore = view.read(keylet::ticket(target, SeqProxy::rawTicket(ticketSeq)));
256 auto const proposerDirBefore = ownerDirKeys(view, proposer.id());
257 auto const targetDirBefore = ownerDirKeys(view, target);
258
259 jt.require.emplace_back([=](Env& applied) {
260 auto& test = applied.test;
261 auto const& view = *applied.current();
262
263 auto const created = isTesSuccess(applied.ter());
264 bool const ticketConsumed = ownTicketSeq && (created || isTecClaim(applied.ter()));
265 std::uint32_t const ticketReturned = ticketConsumed ? 1 : 0;
266
267 // The proposer owns the proposal even when another account covers its
268 // reserve. A proposed Batch costs more owner-count increments. A
269 // Ticket the proposer paid with gives one back.
270 test.expect(
271 applied.ownerCount(proposer) ==
272 ownerCountBefore + (created ? cost : 0) - ticketReturned,
273 "proposal reserve");
274 test.expect(
275 applied.sponsoredOwnerCount(proposer) ==
276 sponsoredOwnerCountBefore + (created && reserveSponsor ? cost : 0),
277 "proposal sponsored owner count");
278 if (reserveSponsor)
279 {
280 test.expect(
281 applied.sponsoringOwnerCount(*reserveSponsor) ==
282 *sponsoringOwnerCountBefore + (created ? cost : 0),
283 "proposal sponsoring owner count");
284 }
285
286 // The target's ticket is left for the proposed transaction, including
287 // when the target is also the proposer.
288 test.expect(
289 unchanged(
290 ticketBefore, view.read(keylet::ticket(target, SeqProxy::rawTicket(ticketSeq)))),
291 "proposal target ticket");
292
293 // Nothing else of a distinct target's moves: the proposal belongs in
294 // the proposer's account and owner directory.
295 if (target != proposer.id())
296 {
297 test.expect(
298 unchanged(targetBefore, view.read(keylet::account(target))),
299 "proposal target account");
300 test.expect(ownerDirKeys(view, target) == targetDirBefore, "proposal target directory");
301 }
302
303 auto const sleProposal = view.read(proposalKeylet);
304
305 // The Ticket the proposer paid with has left its directory.
306 auto expectedDir = proposerDirBefore;
307 if (ticketConsumed)
308 {
309 expectedDir.erase(
310 keylet::ticket(proposer.id(), SeqProxy::rawTicket(*ownTicketSeq)).key);
311 }
312
313 if (!created)
314 {
315 // A create that did not succeed leaves the proposal as it found
316 // it, down to the last field.
317 test.expect(unchanged(proposalBefore, sleProposal), "proposal unchanged");
318
319 // Nor did the directory gain a listing for an entry that does not
320 // exist.
321 test.expect(
322 ownerDirKeys(view, proposer.id()) == expectedDir, "proposal owner directory");
323 return;
324 }
325
326 // A successful create must have created the entry, not overwritten one
327 // that was already there. The checks below read the entry after the
328 // write, so they pass either way; this is what rules an overwrite out.
329 if (!test.expect(!proposalBefore, "proposal is new") ||
330 !test.expect(sleProposal, "proposal entry"))
331 return;
332
333 // What is on the ledger is what was submitted: a proposal is only worth
334 // collecting signatures against if the transaction it stores is the one
335 // proposed, so the payload is compared whole.
336 test.expect(sleProposal->getAccountID(sfOwner) == proposer.id(), "proposal owner");
337 test.expect(sleProposal->getFieldU32(sfExpiration) == expiration, "proposal expiration");
338 test.expect(
339 reserveSponsor ? sleProposal->isFieldPresent(sfSponsor) &&
340 sleProposal->getAccountID(sfSponsor) == reserveSponsor->id()
341 : !sleProposal->isFieldPresent(sfSponsor),
342 "proposal sponsor");
343
344 auto const& stored = sleProposal->getFieldObject(sfProposedTransaction);
345 test.expect(stored == parse(proposedTx), "proposal payload");
346
347 // Unsigned canonical form, keyed by the target and ticket the payload
348 // names (On-Chain Cosigner spec §6.1).
349 test.expect(
352 "proposal payload unsigned");
353 test.expect(
354 stored.getAccountID(sfAccount) == target &&
355 stored.getFieldU32(sfTicketSequence) == ticketSeq &&
356 stored.getFieldU32(sfSequence) == 0,
357 "proposal payload target");
358
359 // Nothing beyond the fields a fresh proposal is created with. An
360 // STObject carries a placeholder for each optional field its format
361 // allows, so each field is asked whether it is really present.
362 test.expect(sleProposal->getFieldU32(sfFlags) == 0, "proposal flags");
363 for (auto const& field : *sleProposal)
364 {
365 if (field.getSType() != STI_NOTPRESENT)
366 {
367 test.expect(
368 isCreationField(field.getFName()),
369 "proposal field " + field.getFName().getName());
370 }
371 }
372
373 // The proposal is listed in the proposer's directory on the page its
374 // OwnerNode names, and nothing else listed moved.
375 expectedDir.emplace(sleProposal->key(), sleProposal->getFieldU64(sfOwnerNode));
376 test.expect(ownerDirKeys(view, proposer.id()) == expectedDir, "proposal owner directory");
377 });
378}
379
380} // namespace xrpl::test::jtx::proposal
Represents a JSON value.
Definition json_value.h:121
UInt size() const
Number of values in array or object.
UInt asUInt() const
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.
std::chrono::duration< rep, period > duration
Definition chrono.h:47
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< STLedgerEntry const > const_pointer
static constexpr SeqProxy rawTicket(std::uint32_t v)
Factory function to return a ticket-based SeqProxy.
Definition SeqProxy.h:74
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
std::string const & human() const
Returns the human readable public key.
AccountID id() const
Returns the Account ID.
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
TER ter() const
Return the TER for the last JTx.
Definition Env.h:844
std::uint32_t sponsoringOwnerCount(Account const &account) const
Return the number of sponsoring objects owned by an account.
Definition Env.cpp:284
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
std::uint32_t ownerCount(Account const &account) const
Return the number of objects owned by an account.
Definition Env.cpp:266
Account const & lookup(AccountID const &id) const
Returns the Account given the AccountID.
Definition Env.cpp:180
std::uint32_t seq(Account const &account) const
Returns the next sequence number on account.
Definition Env.cpp:302
std::uint32_t sponsoredOwnerCount(Account const &account) const
Return the number of sponsored objects owned by an account.
Definition Env.cpp:275
beast::unit_test::Suite & test
Definition Env.h:163
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
NetClock::time_point now()
Returns the current network time.
Definition Env.h:326
Adds an inner Batch transaction to a JTx and autofills it.
Definition batch.h:91
json::Value const & getTxn() const
Definition batch.h:132
void operator()(Env &, JTx &) const
Definition proposal.cpp:208
T emplace_back(T... args)
T emplace(T... args)
T insert(T... args)
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet txProposal(AccountID const &target, std::uint32_t ticketSequence) noexcept
A TransactionProposal.
Definition Indexes.cpp:378
Keylet ticket(AccountID const &id, SeqProxy const &ticketSeq)
A ticket belonging to an account.
Definition Indexes.cpp:344
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Definition Indexes.cpp:421
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
bool hasSignatureField(STObject const &proposedTx)
Whether the proposed transaction carries any signature field.
bool hasEmptySigningPubKey(STObject const &proposedTx)
Whether the proposed transaction's SigningPubKey is present and empty, as unsigned canonical form req...
json::Value outer(jtx::Account const &account, uint32_t seq, STAmount const &fee, std::uint32_t flags)
Build an outer Batch transaction JSON object.
Definition batch.cpp:55
XRPAmount calcBatchFee(jtx::Env const &env, uint32_t const &numSigners, uint32_t const &txns=0)
Calculate the expected outer Batch transaction fee.
Definition batch.cpp:37
Helpers for constructing TransactionProposal test transactions.
Definition proposal.cpp:37
json::Value innerTx(json::Value tx, std::uint32_t seq)
Put a transaction into the form an inner transaction of a proposed Batch takes, as batch::Inner does ...
Definition proposal.cpp:80
std::uint32_t createTicket(Env &env, Account const &account, std::uint32_t count)
Create tickets for a proposal to be built against, and close the ledger.
Definition proposal.cpp:128
json::Value unsignedPayload(Env const &env, json::Value tx, std::uint32_t ticketSeq)
Put a transaction of any type into the form a proposal stores it in: unsigned and ticket-based,...
Definition proposal.cpp:61
constexpr std::uint32_t kBatchProposalOwnerCount
Owner-reserve increments held by a proposal of a Batch transaction.
constexpr std::uint32_t kProposalOwnerCount
Owner-reserve increments held by a proposal of an ordinary transaction.
SLE::const_pointer entry(Env const &env, AccountID const &target, std::uint32_t ticketSeq)
The proposal stored against a target account's ticket.
Definition proposal.cpp:145
json::Value create(Account const &proposer, json::Value const &proposedTx, std::uint32_t expiration)
Build a TransactionProposalCreate carrying an unsigned proposed transaction.
Definition proposal.cpp:40
void authorizeProposer(Env &env, Account const &target, Account const &proposer)
Give proposer a place on target's SignerList, so it may create proposals against target.
Definition proposal.cpp:121
json::Value unsignedBatch(Env const &env, Account const &target, std::uint32_t ticketSeq, std::uint32_t flags, std::vector< json::Value > const &inners, std::optional< std::uint32_t > numSigners)
An unsigned outer Batch payload holding inners.
Definition proposal.cpp:86
std::uint32_t expiration(Env &env, NetClock::duration delta)
An absolute expiration delta past the environment's current time.
Definition proposal.cpp:139
json::Value cancel(Account const &account, uint256 const &proposalID)
Build a TransactionProposalCancel naming the proposal to delete.
Definition proposal.cpp:51
json::Value create(Account const &account, std::uint32_t count)
Create one of more tickets.
Definition ticket.cpp:16
void fillFee(json::Value &jv, ReadView const &view)
Set the fee automatically.
Definition utility.cpp:69
STObject parse(json::Value const &jv)
Convert JSON to STObject.
Definition utility.cpp:33
json::Value signers(Account const &account, std::uint32_t quorum, std::vector< Signer > const &v)
Definition multisign.cpp:31
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
Number root(Number f, unsigned d)
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
bool isTecClaim(TER x) noexcept
Definition TER.h:693
constexpr FlagValue spfSponsorReserve
Definition TxFlags.h:468
UInt256 uint256
Definition base_uint.h:587
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
T size(T... args)
Execution context for applying a JSON transaction.
Definition JTx.h:27
RequiresT require
Definition JTx.h:29
json::Value jv
Definition JTx.h:28