-
Notifications
You must be signed in to change notification settings - Fork 973
/
TransactionFrame.cpp
1740 lines (1565 loc) · 51.7 KB
/
TransactionFrame.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "util/asio.h"
#include "TransactionFrame.h"
#include "OperationFrame.h"
#include "crypto/Hex.h"
#include "crypto/SHA.h"
#include "crypto/SignerKey.h"
#include "crypto/SignerKeyUtils.h"
#include "database/Database.h"
#include "database/DatabaseUtils.h"
#include "herder/TxSetFrame.h"
#include "invariant/InvariantDoesNotHold.h"
#include "invariant/InvariantManager.h"
#include "ledger/LedgerHeaderUtils.h"
#include "ledger/LedgerTxn.h"
#include "ledger/LedgerTxnEntry.h"
#include "ledger/LedgerTxnHeader.h"
#include "main/Application.h"
#include "transactions/SignatureChecker.h"
#include "transactions/SignatureUtils.h"
#include "transactions/SponsorshipUtils.h"
#include "transactions/TransactionBridge.h"
#include "transactions/TransactionMetaFrame.h"
#include "transactions/TransactionUtils.h"
#include "util/Decoder.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/ProtocolVersion.h"
#include "util/XDROperators.h"
#include "util/XDRStream.h"
#include "xdr/Stellar-ledger.h"
#include "xdrpp/marshal.h"
#include "xdrpp/printer.h"
#include <Tracy.hpp>
#include <string>
#include "medida/meter.h"
#include "medida/metrics_registry.h"
#include <algorithm>
#include <numeric>
namespace stellar
{
using namespace std;
using namespace stellar::txbridge;
TransactionFrame::TransactionFrame(Hash const& networkID,
TransactionEnvelope const& envelope)
: mEnvelope(envelope), mNetworkID(networkID)
{
// Create operation frames with dummy results. Currently the proper results
// are initialized in `TransactionFrame::resetResults` and eventually the
// operation frames should be decoupled from the results completely and
// created just once.
auto& ops = mEnvelope.type() == ENVELOPE_TYPE_TX_V0
? mEnvelope.v0().tx.operations
: mEnvelope.v1().tx.operations;
getResult().result.code(txFAILED);
getResult().result.results().resize(static_cast<uint32_t>(ops.size()));
for (size_t i = 0; i < ops.size(); i++)
{
mOperations.push_back(
makeOperation(ops[i], getResult().result.results()[i], i));
}
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
// Initialize the fee to 0, callers will compute the fee appropriately
mSorobanResourceFee = std::make_optional<FeePair>();
#endif
}
Hash const&
TransactionFrame::getFullHash() const
{
if (isZero(mFullHash))
{
mFullHash = xdrSha256(mEnvelope);
}
return (mFullHash);
}
Hash const&
TransactionFrame::getContentsHash() const
{
#ifdef _DEBUG
// force recompute
Hash oldHash;
std::swap(mContentsHash, oldHash);
#endif
if (isZero(mContentsHash))
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX_V0)
{
mContentsHash = sha256(xdr::xdr_to_opaque(
mNetworkID, ENVELOPE_TYPE_TX, 0, mEnvelope.v0().tx));
}
else
{
mContentsHash = sha256(xdr::xdr_to_opaque(
mNetworkID, ENVELOPE_TYPE_TX, mEnvelope.v1().tx));
}
}
#ifdef _DEBUG
releaseAssert(isZero(oldHash) || (oldHash == mContentsHash));
#endif
return (mContentsHash);
}
void
TransactionFrame::clearCached()
{
Hash zero;
mContentsHash = zero;
mFullHash = zero;
}
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
void
TransactionFrame::pushContractEvents(xdr::xvector<ContractEvent>&& evts)
{
mEvents = evts;
}
void
TransactionFrame::pushDiagnosticEvents(xdr::xvector<DiagnosticEvent>&& evts)
{
mDiagnosticEvents = evts;
}
void
TransactionFrame::setReturnValue(SCVal&& returnValue)
{
mReturnValue = returnValue;
}
#endif
TransactionEnvelope const&
TransactionFrame::getEnvelope() const
{
return mEnvelope;
}
TransactionEnvelope&
TransactionFrame::getEnvelope()
{
return mEnvelope;
}
SequenceNumber
TransactionFrame::getSeqNum() const
{
return mEnvelope.type() == ENVELOPE_TYPE_TX_V0 ? mEnvelope.v0().tx.seqNum
: mEnvelope.v1().tx.seqNum;
}
AccountID
TransactionFrame::getFeeSourceID() const
{
return getSourceID();
}
AccountID
TransactionFrame::getSourceID() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX_V0)
{
AccountID res;
res.ed25519() = mEnvelope.v0().tx.sourceAccountEd25519;
return res;
}
return toAccountID(mEnvelope.v1().tx.sourceAccount);
}
uint32_t
TransactionFrame::getNumOperations() const
{
return mEnvelope.type() == ENVELOPE_TYPE_TX_V0
? static_cast<uint32_t>(mEnvelope.v0().tx.operations.size())
: static_cast<uint32_t>(mEnvelope.v1().tx.operations.size());
}
Resource
TransactionFrame::getResources() const
{
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
if (isSoroban())
{
auto r = sorobanResources();
int64_t txSize = xdr::xdr_size(mEnvelope.v1().tx);
int64_t const opCount = 1;
return Resource({opCount, r.instructions, txSize, r.readBytes,
r.writeBytes,
static_cast<int64_t>(r.footprint.readOnly.size()),
static_cast<int64_t>(r.footprint.readWrite.size())});
}
#endif
return Resource(getNumOperations());
}
std::vector<Operation> const&
TransactionFrame::getRawOperations() const
{
return mEnvelope.type() == ENVELOPE_TYPE_TX_V0
? mEnvelope.v0().tx.operations
: mEnvelope.v1().tx.operations;
}
int64_t
TransactionFrame::getFullFee() const
{
return mEnvelope.type() == ENVELOPE_TYPE_TX_V0 ? mEnvelope.v0().tx.fee
: mEnvelope.v1().tx.fee;
}
int64_t
TransactionFrame::getInclusionFee() const
{
int64_t feeBid = getFullFee();
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
if (!isSoroban())
{
return feeBid;
}
// We rely here on the Soroban fee being computed at
// this point.
releaseAssertOrThrow(mSorobanResourceFee);
if (feeBid < mSorobanResourceFee->non_refundable_fee)
{
return 0;
}
feeBid -= mSorobanResourceFee->non_refundable_fee;
int64_t declaredRefundableFee = sorobanRefundableFee();
if (feeBid < declaredRefundableFee)
{
return 0;
}
return feeBid - declaredRefundableFee;
#else
return feeBid;
#endif
}
int64_t
TransactionFrame::getFee(LedgerHeader const& header,
std::optional<int64_t> baseFee, bool applying) const
{
if (!baseFee)
{
return getFullFee();
}
if (protocolVersionStartsFrom(header.ledgerVersion,
ProtocolVersion::V_11) ||
!applying)
{
int64_t feeBid = getInclusionFee();
int64_t flatFee = getFullFee() - feeBid;
int64_t adjustedFee =
*baseFee * std::max<int64_t>(1, getNumOperations());
if (applying)
{
return flatFee + std::min<int64_t>(getInclusionFee(), adjustedFee);
}
else
{
return flatFee + adjustedFee;
}
}
else
{
return getFullFee();
}
}
void
TransactionFrame::addSignature(SecretKey const& secretKey)
{
auto sig = SignatureUtils::sign(secretKey, getContentsHash());
addSignature(sig);
}
void
TransactionFrame::addSignature(DecoratedSignature const& signature)
{
clearCached();
getSignatures(mEnvelope).push_back(signature);
}
bool
TransactionFrame::checkSignature(SignatureChecker& signatureChecker,
LedgerTxnEntry const& account,
int32_t neededWeight)
{
ZoneScoped;
auto& acc = account.current().data.account();
std::vector<Signer> signers;
if (acc.thresholds[0])
{
auto signerKey = KeyUtils::convertKey<SignerKey>(acc.accountID);
signers.push_back(Signer(signerKey, acc.thresholds[0]));
}
signers.insert(signers.end(), acc.signers.begin(), acc.signers.end());
return signatureChecker.checkSignature(signers, neededWeight);
}
bool
TransactionFrame::checkSignatureNoAccount(SignatureChecker& signatureChecker,
AccountID const& accountID)
{
ZoneScoped;
std::vector<Signer> signers;
auto signerKey = KeyUtils::convertKey<SignerKey>(accountID);
signers.push_back(Signer(signerKey, 1));
return signatureChecker.checkSignature(signers, 0);
}
bool
TransactionFrame::checkExtraSigners(SignatureChecker& signatureChecker)
{
ZoneScoped;
if (extraSignersExist())
{
auto const& extraSigners = mEnvelope.v1().tx.cond.v2().extraSigners;
std::vector<Signer> signers;
std::transform(extraSigners.begin(), extraSigners.end(),
std::back_inserter(signers),
[](SignerKey const& k) { return Signer(k, 1); });
// Sanity check for the int32 cast below
static_assert(decltype(PreconditionsV2::extraSigners)::max_size() <=
INT32_MAX);
// We want to verify that there is a signature for each extraSigner, so
// we assign a weight of 1 to each key, and set the neededWeight to the
// number of extraSigners
return signatureChecker.checkSignature(
signers, static_cast<int32_t>(signers.size()));
}
return true;
}
LedgerTxnEntry
TransactionFrame::loadSourceAccount(AbstractLedgerTxn& ltx,
LedgerTxnHeader const& header)
{
ZoneScoped;
auto res = loadAccount(ltx, header, getSourceID());
if (protocolVersionIsBefore(header.current().ledgerVersion,
ProtocolVersion::V_8))
{
// this is buggy caching that existed in old versions of the protocol
if (res)
{
auto newest = ltx.getNewestVersion(LedgerEntryKey(res.current()));
mCachedAccount = newest;
}
else
{
mCachedAccount.reset();
}
}
return res;
}
LedgerTxnEntry
TransactionFrame::loadAccount(AbstractLedgerTxn& ltx,
LedgerTxnHeader const& header,
AccountID const& accountID)
{
ZoneScoped;
if (protocolVersionIsBefore(header.current().ledgerVersion,
ProtocolVersion::V_8) &&
mCachedAccount &&
mCachedAccount->ledgerEntry().data.account().accountID == accountID)
{
// this is buggy caching that existed in old versions of the protocol
auto res = stellar::loadAccount(ltx, accountID);
if (res)
{
res.currentGeneralized() = *mCachedAccount;
}
else
{
res = ltx.create(*mCachedAccount);
}
auto newest = ltx.getNewestVersion(LedgerEntryKey(res.current()));
mCachedAccount = newest;
return res;
}
else
{
return stellar::loadAccount(ltx, accountID);
}
}
bool
TransactionFrame::hasDexOperations() const
{
for (auto const& op : mOperations)
{
if (op->isDexOperation())
{
return true;
}
}
return false;
}
bool
TransactionFrame::isSoroban() const
{
return !mOperations.empty() && mOperations[0]->isSoroban();
}
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
SorobanResources const&
TransactionFrame::sorobanResources() const
{
releaseAssertOrThrow(isSoroban());
return mEnvelope.v1().tx.ext.sorobanData().resources;
}
#endif
std::shared_ptr<OperationFrame>
TransactionFrame::makeOperation(Operation const& op, OperationResult& res,
size_t index)
{
return OperationFrame::makeHelper(op, res, *this,
static_cast<uint32_t>(index));
}
void
TransactionFrame::resetResults(LedgerHeader const& header,
std::optional<int64_t> baseFee, bool applying)
{
auto& ops = mEnvelope.type() == ENVELOPE_TYPE_TX_V0
? mEnvelope.v0().tx.operations
: mEnvelope.v1().tx.operations;
// pre-allocates the results for all operations
getResult().result.code(txSUCCESS);
getResult().result.results().resize(static_cast<uint32_t>(ops.size()));
mOperations.clear();
// bind operations to the results
for (size_t i = 0; i < ops.size(); i++)
{
mOperations.push_back(
makeOperation(ops[i], getResult().result.results()[i], i));
}
// feeCharged is updated accordingly to represent the cost of the
// transaction regardless of the failure modes.
getResult().feeCharged = getFee(header, baseFee, applying);
}
std::optional<TimeBounds const> const
TransactionFrame::getTimeBounds() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX_V0)
{
return mEnvelope.v0().tx.timeBounds ? std::optional<TimeBounds const>(
*mEnvelope.v0().tx.timeBounds)
: std::optional<TimeBounds const>();
}
else
{
auto const& cond = mEnvelope.v1().tx.cond;
switch (cond.type())
{
case PRECOND_NONE:
{
return std::optional<TimeBounds const>();
}
case PRECOND_TIME:
{
return std::optional<TimeBounds const>(cond.timeBounds());
}
case PRECOND_V2:
{
return cond.v2().timeBounds
? std::optional<TimeBounds const>(*cond.v2().timeBounds)
: std::optional<TimeBounds const>();
}
default:
throw std::runtime_error("unknown condition type");
}
}
}
std::optional<LedgerBounds const> const
TransactionFrame::getLedgerBounds() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX)
{
auto const& cond = mEnvelope.v1().tx.cond;
if (cond.type() == PRECOND_V2 && cond.v2().ledgerBounds)
{
return std::optional<LedgerBounds const>(*cond.v2().ledgerBounds);
}
}
return std::optional<LedgerBounds const>();
}
Duration
TransactionFrame::getMinSeqAge() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX)
{
auto& cond = mEnvelope.v1().tx.cond;
return cond.type() == PRECOND_V2 ? cond.v2().minSeqAge : 0;
}
return 0;
}
uint32
TransactionFrame::getMinSeqLedgerGap() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX)
{
auto& cond = mEnvelope.v1().tx.cond;
return cond.type() == PRECOND_V2 ? cond.v2().minSeqLedgerGap : 0;
}
return 0;
}
std::optional<SequenceNumber const> const
TransactionFrame::getMinSeqNum() const
{
if (mEnvelope.type() == ENVELOPE_TYPE_TX)
{
auto& cond = mEnvelope.v1().tx.cond;
if (cond.type() == PRECOND_V2 && cond.v2().minSeqNum)
{
return std::optional<SequenceNumber const>(*cond.v2().minSeqNum);
}
}
return std::optional<SequenceNumber const>();
}
bool
TransactionFrame::extraSignersExist() const
{
return mEnvelope.type() == ENVELOPE_TYPE_TX &&
mEnvelope.v1().tx.cond.type() == PRECOND_V2 &&
!mEnvelope.v1().tx.cond.v2().extraSigners.empty();
}
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
bool
TransactionFrame::validateSorobanOpsConsistency() const
{
bool hasSorobanOp = mOperations[0]->isSoroban();
for (auto const& op : mOperations)
{
bool isSorobanOp = op->isSoroban();
// Mixing Soroban ops with non-Soroban ops is not allowed.
if (isSorobanOp != hasSorobanOp)
{
return false;
}
}
// Only one operation is allowed per Soroban transaction.
if (hasSorobanOp && mOperations.size() != 1)
{
return false;
}
return true;
}
bool
TransactionFrame::validateSorobanResources(SorobanNetworkConfig const& config,
uint32_t protocolVersion) const
{
auto const& resources = sorobanResources();
auto const& readEntries = resources.footprint.readOnly;
auto const& writeEntries = resources.footprint.readWrite;
if (resources.instructions > config.txMaxInstructions())
{
return false;
}
if (resources.readBytes > config.txMaxReadBytes())
{
return false;
}
if (resources.writeBytes > config.txMaxWriteBytes())
{
return false;
}
if (resources.contractEventsSizeBytes >
config.txMaxContractEventsSizeBytes())
{
return false;
}
if (readEntries.size() + writeEntries.size() >
config.txMaxReadLedgerEntries() ||
writeEntries.size() > config.txMaxWriteLedgerEntries())
{
return false;
}
auto footprintKeyIsValid = [&](LedgerKey const& key) -> bool {
if (isSorobanExtEntry(key))
{
return false;
}
switch (key.type())
{
case ACCOUNT:
case CONTRACT_DATA:
case CONTRACT_CODE:
break;
case TRUSTLINE:
{
auto const& tl = key.trustLine();
if (!isAssetValid(tl.asset, protocolVersion) ||
(tl.asset.type() == ASSET_TYPE_NATIVE) ||
isIssuer(tl.accountID, tl.asset))
{
return false;
}
break;
}
case OFFER:
case DATA:
case CLAIMABLE_BALANCE:
case LIQUIDITY_POOL:
case CONFIG_SETTING:
return false;
default:
throw std::runtime_error("unknown ledger key type");
}
if (xdr::xdr_size(key) > config.maxContractDataKeySizeBytes())
{
return false;
}
return true;
};
for (auto const& lk : readEntries)
{
if (!footprintKeyIsValid(lk))
{
return false;
}
}
for (auto const& lk : writeEntries)
{
if (!footprintKeyIsValid(lk))
{
return false;
}
}
auto txSize = xdr::xdr_size(mEnvelope.v1().tx);
if (txSize > config.txMaxSizeBytes())
{
return false;
}
return true;
}
void
TransactionFrame::refundSorobanFee(AbstractLedgerTxn& ltxOuter)
{
if (mFeeRefund == 0)
{
return;
}
LedgerTxn ltx(ltxOuter);
auto header = ltx.loadHeader();
auto sourceAccount = loadSourceAccount(ltx, header);
if (!sourceAccount)
{
throw std::runtime_error("Unexpected database state");
}
auto& acc = sourceAccount.current().data.account();
stellar::addBalance(acc.balance, mFeeRefund);
header.current().feePool -= mFeeRefund;
ltx.commit();
}
FeePair
TransactionFrame::computeSorobanResourceFee(
uint32_t protocolVersion, SorobanNetworkConfig const& sorobanConfig,
Config const& cfg, bool useConsumedRefundableResources) const
{
CxxTransactionResources cxxResources;
auto const& txResources = sorobanResources();
cxxResources.instructions = txResources.instructions;
cxxResources.read_entries =
static_cast<uint32>(txResources.footprint.readOnly.size() +
txResources.footprint.readWrite.size());
cxxResources.write_entries =
static_cast<uint32>(txResources.footprint.readWrite.size());
cxxResources.read_bytes = txResources.readBytes;
cxxResources.write_bytes = txResources.writeBytes;
cxxResources.transaction_size_bytes =
static_cast<uint32>(xdr::xdr_size(mEnvelope));
cxxResources.contract_events_size_bytes =
txResources.contractEventsSizeBytes;
if (useConsumedRefundableResources)
{
// It is possible that consumed events size is higher than the
// declared size (in such a case the transaction will fail). We
// still don't want to overcharge the fees though.
if (cxxResources.contract_events_size_bytes >
mConsumedContractEventsSizeBytes)
{
cxxResources.contract_events_size_bytes =
mConsumedContractEventsSizeBytes;
}
}
// This may throw, but only in case of the Core version misconfiguration.
return rust_bridge::compute_transaction_resource_fee(
cfg.CURRENT_LEDGER_PROTOCOL_VERSION, protocolVersion, cxxResources,
sorobanConfig.rustBridgeFeeConfiguration());
}
int64
TransactionFrame::sorobanRefundableFee() const
{
if (mEnvelope.type() != ENVELOPE_TYPE_TX || mEnvelope.v1().tx.ext.v() != 1)
{
return 0;
}
return mEnvelope.v1().tx.ext.sorobanData().refundableFee;
}
void
TransactionFrame::maybeComputeSorobanResourceFee(
uint32_t protocolVersion, SorobanNetworkConfig const& sorobanConfig,
Config const& cfg)
{
// NB: We recompute the resource fee on-demand in case if the fees change
// between the ledger where the transaction has been accepted and the ledger
// where it is being applied.
if (!isSoroban())
{
return;
}
// At this point the frame might not have been validated yet, so
// the resources might not be present or Soroban might not be supported
// at all. Hence just set the resource fees to 0 and rely on validation
// checks to not use this.
if (protocolVersionIsBefore(protocolVersion, SOROBAN_PROTOCOL_VERSION) ||
mEnvelope.type() != ENVELOPE_TYPE_TX || mEnvelope.v1().tx.ext.v() != 1)
{
mSorobanResourceFee = std::make_optional<FeePair>();
return;
}
// We always use the declared resource value for the resource fee
// computation. The refunds are performed as a separate operation that
// doesn't involve modifying any transaction fees.
mSorobanResourceFee = std::make_optional<FeePair>(
computeSorobanResourceFee(protocolVersion, sorobanConfig, cfg,
/* useConsumedRefundableResources */ false));
}
bool
TransactionFrame::consumeRefundableSorobanResources(
uint32_t contractEventSizeBytes, int64_t rentFee, uint32_t protocolVersion,
SorobanNetworkConfig const& sorobanConfig, Config const& cfg)
{
mConsumedContractEventsSizeBytes += contractEventSizeBytes;
mConsumedRentFee += rentFee;
mFeeRefund = sorobanRefundableFee();
if (mFeeRefund < mConsumedRentFee)
{
return false;
}
mFeeRefund -= mConsumedRentFee;
FeePair consumedFee =
computeSorobanResourceFee(protocolVersion, sorobanConfig, cfg,
/* useConsumedRefundableResources */ true);
if (mFeeRefund < consumedFee.refundable_fee)
{
return false;
}
mFeeRefund -= consumedFee.refundable_fee;
return true;
}
#endif
bool
TransactionFrame::isTooEarly(LedgerTxnHeader const& header,
uint64_t lowerBoundCloseTimeOffset) const
{
auto const tb = getTimeBounds();
if (tb)
{
uint64 closeTime = header.current().scpValue.closeTime;
if (tb->minTime &&
(tb->minTime > (closeTime + lowerBoundCloseTimeOffset)))
{
return true;
}
}
if (protocolVersionStartsFrom(header.current().ledgerVersion,
ProtocolVersion::V_19))
{
auto const lb = getLedgerBounds();
return lb && lb->minLedger > header.current().ledgerSeq;
}
return false;
}
bool
TransactionFrame::isTooLate(LedgerTxnHeader const& header,
uint64_t upperBoundCloseTimeOffset) const
{
auto const tb = getTimeBounds();
if (tb)
{
// Prior to consensus, we can pass in an upper bound estimate on when we
// expect the ledger to close so we don't accept transactions that will
// expire by the time they are applied
uint64 closeTime = header.current().scpValue.closeTime;
if (tb->maxTime &&
(tb->maxTime < (closeTime + upperBoundCloseTimeOffset)))
{
return true;
}
}
if (protocolVersionStartsFrom(header.current().ledgerVersion,
ProtocolVersion::V_19))
{
auto const lb = getLedgerBounds();
return lb && lb->maxLedger != 0 &&
lb->maxLedger <= header.current().ledgerSeq;
}
return false;
}
bool
TransactionFrame::isTooEarlyForAccount(LedgerTxnHeader const& header,
LedgerTxnEntry const& sourceAccount,
uint64_t lowerBoundCloseTimeOffset) const
{
if (protocolVersionIsBefore(header.current().ledgerVersion,
ProtocolVersion::V_19))
{
return false;
}
auto accountEntry = [&]() -> AccountEntry const& {
return sourceAccount.current().data.account();
};
auto accSeqTime = hasAccountEntryExtV3(accountEntry())
? getAccountEntryExtensionV3(accountEntry()).seqTime
: 0;
auto minSeqAge = getMinSeqAge();
auto lowerBoundCloseTime =
header.current().scpValue.closeTime + lowerBoundCloseTimeOffset;
if (minSeqAge > lowerBoundCloseTime ||
lowerBoundCloseTime - minSeqAge < accSeqTime)
{
return true;
}
auto accSeqLedger =
hasAccountEntryExtV3(accountEntry())
? getAccountEntryExtensionV3(accountEntry()).seqLedger
: 0;
auto minSeqLedgerGap = getMinSeqLedgerGap();
auto ledgerSeq = header.current().ledgerSeq;
if (minSeqLedgerGap > ledgerSeq ||
ledgerSeq - minSeqLedgerGap < accSeqLedger)
{
return true;
}
return false;
}
bool
TransactionFrame::commonValidPreSeqNum(Application& app, AbstractLedgerTxn& ltx,
bool chargeFee,
uint64_t lowerBoundCloseTimeOffset,
uint64_t upperBoundCloseTimeOffset)
{
ZoneScoped;
// this function does validations that are independent of the account state
// (stay true regardless of other side effects)
uint32_t ledgerVersion = ltx.loadHeader().current().ledgerVersion;
if ((protocolVersionIsBefore(ledgerVersion, ProtocolVersion::V_13) &&
(mEnvelope.type() == ENVELOPE_TYPE_TX ||
hasMuxedAccount(mEnvelope))) ||
(protocolVersionStartsFrom(ledgerVersion, ProtocolVersion::V_13) &&
mEnvelope.type() == ENVELOPE_TYPE_TX_V0))
{
getResult().result.code(txNOT_SUPPORTED);
return false;
}
if (protocolVersionIsBefore(ledgerVersion, ProtocolVersion::V_19) &&
mEnvelope.type() == ENVELOPE_TYPE_TX &&
mEnvelope.v1().tx.cond.type() == PRECOND_V2)
{
getResult().result.code(txNOT_SUPPORTED);
return false;
}
if (extraSignersExist())
{
auto const& extraSigners = mEnvelope.v1().tx.cond.v2().extraSigners;
static_assert(decltype(PreconditionsV2::extraSigners)::max_size() == 2);
if (extraSigners.size() == 2 && extraSigners[0] == extraSigners[1])
{
getResult().result.code(txMALFORMED);
return false;
}
for (auto const& signer : extraSigners)
{
if (signer.type() == SIGNER_KEY_TYPE_ED25519_SIGNED_PAYLOAD &&
signer.ed25519SignedPayload().payload.empty())
{
getResult().result.code(txMALFORMED);
return false;
}
}
}
if (getNumOperations() == 0)
{
getResult().result.code(txMISSING_OPERATION);
return false;
}
#ifdef ENABLE_NEXT_PROTOCOL_VERSION_UNSAFE_FOR_PRODUCTION
if (!validateSorobanOpsConsistency())
{
getResult().result.code(txMALFORMED);
return false;
}
if (isSoroban())
{
if (protocolVersionIsBefore(ledgerVersion, SOROBAN_PROTOCOL_VERSION))
{
getResult().result.code(txMALFORMED);
return false;
}
if (mEnvelope.type() != ENVELOPE_TYPE_TX ||
mEnvelope.v1().tx.ext.v() != 1)
{
getResult().result.code(txMALFORMED);
return false;
}
auto const& sorobanConfig =
app.getLedgerManager().getSorobanNetworkConfig(ltx);
if (!validateSorobanResources(sorobanConfig, ledgerVersion))
{
getResult().result.code(txSOROBAN_RESOURCE_LIMIT_EXCEEDED);
return false;
}
auto const& sorobanData = mEnvelope.v1().tx.ext.sorobanData();
// Refundable fee shouldn't exceed tx-specified refundable fee.
// NB: Overall Soroban resource fee is verified as a part of
// the fee bid validation.
if (sorobanData.refundableFee < mSorobanResourceFee->refundable_fee)
{
getResult().result.code(txINSUFFICIENT_FEE);
return false;