-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathTxSetFrame.cpp
More file actions
2364 lines (2206 loc) · 74 KB
/
TxSetFrame.cpp
File metadata and controls
2364 lines (2206 loc) · 74 KB
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 "TxSetFrame.h"
#include "TxSetUtils.h"
#include "crypto/Hex.h"
#include "crypto/Random.h"
#include "crypto/SHA.h"
#include "database/Database.h"
#include "herder/ParallelTxSetBuilder.h"
#include "herder/SurgePricingUtils.h"
#include "ledger/LedgerManager.h"
#include "main/Application.h"
#include "main/Config.h"
#include "overlay/Peer.h"
#include "transactions/MutableTransactionResult.h"
#include "transactions/TransactionUtils.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/ProtocolVersion.h"
#include "util/XDRCereal.h"
#include "util/XDROperators.h"
#include "xdrpp/marshal.h"
#include <Tracy.hpp>
#include <algorithm>
#include <list>
#include <numeric>
#include <variant>
namespace stellar
{
namespace
{
std::string
getTxSetPhaseName(TxSetPhase phase)
{
switch (phase)
{
case TxSetPhase::CLASSIC:
return "classic";
case TxSetPhase::SOROBAN:
return "soroban";
default:
throw std::runtime_error("Unknown phase");
}
}
bool
validateSequentialPhaseXDRStructure(TransactionPhase const& phase)
{
bool componentsNormalized =
std::is_sorted(phase.v0Components().begin(), phase.v0Components().end(),
[](auto const& c1, auto const& c2) {
if (!c1.txsMaybeDiscountedFee().baseFee ||
!c2.txsMaybeDiscountedFee().baseFee)
{
return !c1.txsMaybeDiscountedFee().baseFee &&
c2.txsMaybeDiscountedFee().baseFee;
}
return *c1.txsMaybeDiscountedFee().baseFee <
*c2.txsMaybeDiscountedFee().baseFee;
});
if (!componentsNormalized)
{
CLOG_DEBUG(Herder, "Got bad txSet: incorrect component order");
return false;
}
bool componentBaseFeesUnique =
std::adjacent_find(phase.v0Components().begin(),
phase.v0Components().end(),
[](auto const& c1, auto const& c2) {
if (!c1.txsMaybeDiscountedFee().baseFee ||
!c2.txsMaybeDiscountedFee().baseFee)
{
return !c1.txsMaybeDiscountedFee().baseFee &&
!c2.txsMaybeDiscountedFee().baseFee;
}
return *c1.txsMaybeDiscountedFee().baseFee ==
*c2.txsMaybeDiscountedFee().baseFee;
}) == phase.v0Components().end();
if (!componentBaseFeesUnique)
{
CLOG_DEBUG(Herder, "Got bad txSet: duplicate component base fees");
return false;
}
for (auto const& component : phase.v0Components())
{
if (component.txsMaybeDiscountedFee().txs.empty())
{
CLOG_DEBUG(Herder, "Got bad txSet: empty component");
return false;
}
}
return true;
}
bool
validateParallelComponent(ParallelTxsComponent const& component)
{
for (auto const& stage : component.executionStages)
{
if (stage.empty())
{
CLOG_DEBUG(Herder, "Got bad txSet: empty stage");
return false;
}
for (auto const& cluster : stage)
{
if (cluster.empty())
{
CLOG_DEBUG(Herder, "Got bad txSet: empty cluster");
return false;
}
}
}
return true;
}
bool
validateTxSetXDRStructure(GeneralizedTransactionSet const& txSet)
{
int const MAX_PHASE = 1;
if (txSet.v() != 1)
{
CLOG_DEBUG(Herder, "Got bad txSet: unsupported version {}", txSet.v());
return false;
}
auto phaseCount = static_cast<size_t>(TxSetPhase::PHASE_COUNT);
auto const& txSetV1 = txSet.v1TxSet();
// There was no protocol with 1 phase, so checking for 2 phases only
if (txSetV1.phases.size() != phaseCount)
{
CLOG_DEBUG(Herder,
"Got bad txSet: exactly 2 phases are expected, got {}",
txSetV1.phases.size());
return false;
}
for (size_t phaseId = 0; phaseId < phaseCount; ++phaseId)
{
auto const& phase = txSetV1.phases[phaseId];
if (phase.v() > MAX_PHASE)
{
CLOG_DEBUG(Herder, "Got bad txSet: unsupported phase version {}",
phase.v());
return false;
}
if (phase.v() == 1)
{
if (phaseId != static_cast<size_t>(TxSetPhase::SOROBAN))
{
CLOG_DEBUG(Herder,
"Got bad txSet: non-Soroban parallel phase {}",
phase.v());
return false;
}
if (!validateParallelComponent(phase.parallelTxsComponent()))
{
return false;
}
}
else
{
if (!validateSequentialPhaseXDRStructure(phase))
{
return false;
}
}
}
return true;
}
// We want to XOR the tx hash with the set hash.
// This way people can't predict the order that txs will be applied in
struct ApplyTxSorter
{
Hash mSetHash;
ApplyTxSorter(Hash h) : mSetHash{std::move(h)}
{
}
bool
operator()(TransactionFrameBasePtr const& tx1,
TransactionFrameBasePtr const& tx2) const
{
// need to use the hash of whole tx here since multiple txs could
// have the same Contents
return lessThanXored(tx1->getFullHash(), tx2->getFullHash(), mSetHash);
}
};
Hash
computeNonGeneralizedTxSetContentsHash(TransactionSet const& xdrTxSet)
{
ZoneScoped;
SHA256 hasher;
hasher.add(xdrTxSet.previousLedgerHash);
for (auto const& tx : xdrTxSet.txs)
{
hasher.add(xdr::xdr_to_opaque(tx));
}
return hasher.finish();
}
// Note: Soroban txs also use this functionality for simplicity, as it's a
// no-op (all Soroban txs have 1 op max)
int64_t
computePerOpFee(TransactionFrameBase const& tx, uint32_t ledgerVersion)
{
auto rounding =
protocolVersionStartsFrom(ledgerVersion, SOROBAN_PROTOCOL_VERSION)
? Rounding::ROUND_DOWN
: Rounding::ROUND_UP;
auto txOps = tx.getNumOperations();
return bigDivideOrThrow(tx.getInclusionFee(), 1,
static_cast<int64_t>(txOps), rounding);
}
void
transactionsToTransactionSetXDR(TxFrameList const& txs,
Hash const& previousLedgerHash,
TransactionSet& txSet)
{
ZoneScoped;
txSet.txs.resize(xdr::size32(txs.size()));
auto sortedTxs = TxSetUtils::sortTxsInHashOrder(txs);
for (unsigned int n = 0; n < sortedTxs.size(); n++)
{
txSet.txs[n] = sortedTxs[n]->getEnvelope();
}
txSet.previousLedgerHash = previousLedgerHash;
}
void
sequentialPhaseToXdr(TxFrameList const& txs,
InclusionFeeMap const& inclusionFeeMap,
TransactionPhase& xdrPhase)
{
xdrPhase.v(0);
std::map<std::optional<int64_t>, size_t> feeTxCount;
for (auto const& [_, fee] : inclusionFeeMap)
{
++feeTxCount[fee];
}
auto& components = xdrPhase.v0Components();
// Reserve a component per unique base fee in order to have the correct
// pointers in componentPerBid map.
components.reserve(feeTxCount.size());
std::map<std::optional<int64_t>, xdr::xvector<TransactionEnvelope>*>
componentPerBid;
for (auto const& [fee, txCount] : feeTxCount)
{
components.emplace_back(TXSET_COMP_TXS_MAYBE_DISCOUNTED_FEE);
auto& discountedFeeComponent =
components.back().txsMaybeDiscountedFee();
if (fee)
{
discountedFeeComponent.baseFee.activate() = *fee;
}
componentPerBid[fee] = &discountedFeeComponent.txs;
componentPerBid[fee]->reserve(txCount);
}
auto sortedTxs = TxSetUtils::sortTxsInHashOrder(txs);
for (auto const& tx : sortedTxs)
{
componentPerBid[inclusionFeeMap.find(tx)->second]->push_back(
tx->getEnvelope());
}
}
void
parallelPhaseToXdr(TxStageFrameList const& txs,
InclusionFeeMap const& inclusionFeeMap,
TransactionPhase& xdrPhase)
{
xdrPhase.v(1);
std::optional<int64_t> baseFee;
if (!inclusionFeeMap.empty())
{
baseFee = inclusionFeeMap.begin()->second;
}
// We currently don't support multi-component parallel perPhaseTxs, so make
// sure all txs have the same base fee.
for (auto const& [_, fee] : inclusionFeeMap)
{
releaseAssert(fee == baseFee);
}
auto& component = xdrPhase.parallelTxsComponent();
if (baseFee)
{
component.baseFee.activate() = *baseFee;
}
component.executionStages.reserve(txs.size());
auto sortedTxs = TxSetUtils::sortParallelTxsInHashOrder(txs);
for (auto const& stage : sortedTxs)
{
auto& xdrStage = component.executionStages.emplace_back();
xdrStage.reserve(stage.size());
for (auto const& cluster : stage)
{
auto& xdrCluster = xdrStage.emplace_back();
xdrCluster.reserve(cluster.size());
for (auto const& tx : cluster)
{
xdrCluster.push_back(tx->getEnvelope());
}
}
}
}
void
transactionsToGeneralizedTransactionSetXDR(
std::vector<TxSetPhaseFrame> const& phases, Hash const& previousLedgerHash,
GeneralizedTransactionSet& generalizedTxSet)
{
ZoneScoped;
generalizedTxSet.v(1);
generalizedTxSet.v1TxSet().previousLedgerHash = previousLedgerHash;
generalizedTxSet.v1TxSet().phases.resize(phases.size());
for (int i = 0; i < phases.size(); ++i)
{
auto const& txPhase = phases[i];
txPhase.toXDR(generalizedTxSet.v1TxSet().phases[i]);
}
}
TxFrameList
sortedForApplySequential(TxFrameList const& txs, Hash const& txSetHash)
{
TxFrameList retList;
retList.reserve(txs.size());
auto txQueues = TxSetUtils::buildAccountTxQueues(txs);
// build txBatches
// txBatches i-th element contains each i-th transaction for
// accounts with a transaction in the transaction set
std::vector<std::vector<TransactionFrameBasePtr>> txBatches;
while (!txQueues.empty())
{
txBatches.emplace_back();
auto& curBatch = txBatches.back();
// go over all users that still have transactions
for (auto it = txQueues.begin(); it != txQueues.end();)
{
auto& txQueue = *it;
curBatch.emplace_back(txQueue->getTopTx());
txQueue->popTopTx();
if (txQueue->empty())
{
// done with that user
it = txQueues.erase(it);
}
else
{
++it;
}
}
}
for (auto& batch : txBatches)
{
// randomize each batch using the hash of the transaction set
// as a way to randomize even more
ApplyTxSorter s(txSetHash);
std::sort(batch.begin(), batch.end(), s);
for (auto const& tx : batch)
{
retList.push_back(tx);
}
}
return retList;
}
TxStageFrameList
sortedForApplyParallel(TxStageFrameList const& stages, Hash const& txSetHash)
{
ZoneScoped;
TxStageFrameList sortedStages = stages;
ApplyTxSorter sorter(txSetHash);
for (auto& stage : sortedStages)
{
for (auto& cluster : stage)
{
std::sort(cluster.begin(), cluster.end(), sorter);
}
// There is no need to shuffle clusters in the stage, as they are
// independent, so the apply order doesn't matter even if the clusters
// are being applied sequentially.
}
std::sort(sortedStages.begin(), sortedStages.end(),
[&sorter](auto const& a, auto const& b) {
releaseAssert(!a.empty() && !b.empty());
releaseAssert(!a.front().empty() && !b.front().empty());
return sorter(a.front().front(), b.front().front());
});
return sortedStages;
}
bool
addWireTxsToList(Hash const& networkID,
xdr::xvector<TransactionEnvelope> const& xdrTxs,
TxFrameList& txList)
{
auto prevSize = txList.size();
txList.reserve(prevSize + xdrTxs.size());
for (auto const& env : xdrTxs)
{
auto tx = TransactionFrameBase::makeTransactionFromWire(networkID, env);
if (!tx->XDRProvidesValidFee())
{
return false;
}
txList.push_back(tx);
}
if (!std::is_sorted(txList.begin() + prevSize, txList.end(),
&TxSetUtils::hashTxSorter))
{
return false;
}
return true;
}
std::vector<int64_t>
computeLaneBaseFee(TxSetPhase phase, LedgerHeader const& ledgerHeader,
SurgePricingLaneConfig const& surgePricingConfig,
std::vector<int64_t> const& lowestLaneFee,
std::vector<bool> const& hadTxNotFittingLane)
{
std::vector<int64_t> laneBaseFee(lowestLaneFee.size(),
ledgerHeader.baseFee);
auto minBaseFee =
*std::min_element(lowestLaneFee.begin(), lowestLaneFee.end());
for (size_t lane = 0; lane < laneBaseFee.size(); ++lane)
{
// If generic lane is full, then any transaction had to compete with not
// included transactions and independently of the lane they need to have
// at least the minimum fee in the tx set applied.
if (hadTxNotFittingLane[SurgePricingPriorityQueue::GENERIC_LANE])
{
laneBaseFee[lane] = minBaseFee;
}
// If limited lane is full, then the transactions in this lane also had
// to compete with each other and have a base fee associated with this
// lane only.
if (lane != SurgePricingPriorityQueue::GENERIC_LANE &&
hadTxNotFittingLane[lane])
{
laneBaseFee[lane] = lowestLaneFee[lane];
}
if (laneBaseFee[lane] > ledgerHeader.baseFee)
{
CLOG_WARNING(
Herder,
"{} phase: surge pricing for '{}' lane is in effect with base "
"fee={}, baseFee={}",
getTxSetPhaseName(phase),
lane == SurgePricingPriorityQueue::GENERIC_LANE ? "generic"
: "DEX",
laneBaseFee[lane], ledgerHeader.baseFee);
}
}
return laneBaseFee;
}
std::shared_ptr<SurgePricingLaneConfig>
createSurgePricingLangeConfig(TxSetPhase phase, Application& app)
{
ZoneScoped;
releaseAssert(threadIsMain());
releaseAssert(!app.getLedgerManager().isApplying());
auto const& lclHeader =
app.getLedgerManager().getLastClosedLedgerHeader().header;
std::vector<bool> hadTxNotFittingLane;
std::shared_ptr<SurgePricingLaneConfig> surgePricingLaneConfig;
if (phase == TxSetPhase::CLASSIC)
{
auto maxOps = Resource(
{static_cast<uint32_t>(
app.getLedgerManager().getLastMaxTxSetSizeOps()),
static_cast<uint32_t>(app.getConfig().getClassicByteAllowance())});
std::optional<Resource> dexOpsLimit;
if (app.getConfig().MAX_DEX_TX_OPERATIONS_IN_TX_SET)
{
// DEX operations limit implies that DEX transactions should
// compete with each other in in a separate fee lane, which
// is only possible with generalized tx set.
dexOpsLimit =
Resource({*app.getConfig().MAX_DEX_TX_OPERATIONS_IN_TX_SET,
MAX_CLASSIC_BYTE_ALLOWANCE});
}
surgePricingLaneConfig =
std::make_shared<DexLimitingLaneConfig>(maxOps, dexOpsLimit);
}
else
{
releaseAssert(phase == TxSetPhase::SOROBAN);
auto limits = app.getLedgerManager().maxLedgerResources(
/* isSoroban */ true);
// When building Soroban tx sets with parallel execution support,
// instructions are accounted for by the build logic, not by the surge
// pricing config, so we need to relax the instruction limit in surge
// pricing logic.
if (protocolVersionStartsFrom(lclHeader.ledgerVersion,
PARALLEL_SOROBAN_PHASE_PROTOCOL_VERSION))
{
limits.setVal(Resource::Type::INSTRUCTIONS,
std::numeric_limits<int64_t>::max());
}
auto byteLimit = std::min(
static_cast<int64_t>(app.getConfig().getSorobanByteAllowance()),
limits.getVal(Resource::Type::TX_BYTE_SIZE));
limits.setVal(Resource::Type::TX_BYTE_SIZE, byteLimit);
surgePricingLaneConfig =
std::make_shared<SorobanGenericLaneConfig>(limits);
}
return surgePricingLaneConfig;
}
TxFrameList
buildSurgePricedSequentialPhase(
TxFrameList const& txs,
std::shared_ptr<SurgePricingLaneConfig> surgePricingLaneConfig,
std::vector<bool>& hadTxNotFittingLane, uint32_t ledgerVersion)
{
ZoneScoped;
return SurgePricingPriorityQueue::getMostTopTxsWithinLimits(
txs, surgePricingLaneConfig, hadTxNotFittingLane, ledgerVersion);
}
std::pair<std::variant<TxFrameList, TxStageFrameList>,
std::shared_ptr<InclusionFeeMap>>
applySurgePricing(TxSetPhase phase, TxFrameList const& txs, Application& app
#ifdef BUILD_TESTS
,
bool enforceTxsApplyOrder,
txtest::ParallelSorobanOrder const& parallelSorobanOrder
#endif
)
{
ZoneScoped;
auto surgePricingLaneConfig = createSurgePricingLangeConfig(phase, app);
std::vector<bool> hadTxNotFittingLane;
uint32_t ledgerVersion =
app.getLedgerManager().getLastClosedLedgerHeader().header.ledgerVersion;
bool isParallelSoroban =
phase == TxSetPhase::SOROBAN &&
protocolVersionStartsFrom(ledgerVersion,
PARALLEL_SOROBAN_PHASE_PROTOCOL_VERSION);
std::variant<TxFrameList, TxStageFrameList> includedTxs;
if (isParallelSoroban)
{
#ifdef BUILD_TESTS
if (enforceTxsApplyOrder)
{
TxStageFrameList frameList;
if (!txs.empty())
{
for (auto const& stageIndexes : parallelSorobanOrder)
{
TxStageFrame stage;
for (auto const& threadIndexes : stageIndexes)
{
TxFrameList threadTxs;
for (auto const& txIndex : threadIndexes)
{
threadTxs.push_back(txs.at(txIndex));
}
stage.emplace_back(std::move(threadTxs));
}
frameList.emplace_back(std::move(stage));
}
// If the order is empty, we default to a single
// thread with all transactions in it.
if (parallelSorobanOrder.empty())
{
frameList = {{txs}};
}
}
includedTxs = frameList;
// soroban only has one fee lane
hadTxNotFittingLane.emplace_back(false);
}
else
{
#endif
includedTxs = buildSurgePricedParallelSorobanPhase(
txs, app.getConfig(),
app.getLedgerManager().getLastClosedSorobanNetworkConfig(),
surgePricingLaneConfig, hadTxNotFittingLane, ledgerVersion);
#ifdef BUILD_TESTS
}
#endif
}
else
{
includedTxs = buildSurgePricedSequentialPhase(
txs, surgePricingLaneConfig, hadTxNotFittingLane, ledgerVersion);
}
auto visitIncludedTxs =
[&includedTxs](
std::function<void(TransactionFrameBaseConstPtr const&)> visitor) {
std::visit(
[&visitor](auto const& txs) {
using T = std::decay_t<decltype(txs)>;
if constexpr (std::is_same_v<T, TxFrameList>)
{
for (auto const& tx : txs)
{
visitor(tx);
}
}
else if constexpr (std::is_same_v<T, TxStageFrameList>)
{
for (auto const& stage : txs)
{
for (auto const& thread : stage)
{
for (auto const& tx : thread)
{
visitor(tx);
}
}
}
}
else
{
// This can't be just `false` as if an assertion is not
// dependent on template argument, it will be
// unconditionally triggered.
static_assert(!std::is_same_v<T, T>,
"Non-exhaustive visitor");
}
},
includedTxs);
};
std::vector<int64_t> lowestLaneFee;
auto const& lclHeader =
app.getLedgerManager().getLastClosedLedgerHeader().header;
size_t laneCount = surgePricingLaneConfig->getLaneLimits().size();
lowestLaneFee.resize(laneCount, std::numeric_limits<int64_t>::max());
visitIncludedTxs(
[&lowestLaneFee, &surgePricingLaneConfig, &lclHeader](auto const& tx) {
size_t lane = surgePricingLaneConfig->getLane(*tx);
auto perOpFee = computePerOpFee(*tx, lclHeader.ledgerVersion);
lowestLaneFee[lane] = std::min(lowestLaneFee[lane], perOpFee);
});
auto laneBaseFee =
computeLaneBaseFee(phase, lclHeader, *surgePricingLaneConfig,
lowestLaneFee, hadTxNotFittingLane);
auto inclusionFeeMapPtr = std::make_shared<InclusionFeeMap>();
auto& inclusionFeeMap = *inclusionFeeMapPtr;
visitIncludedTxs([&inclusionFeeMap, &laneBaseFee,
&surgePricingLaneConfig](auto const& tx) {
inclusionFeeMap[tx] = laneBaseFee[surgePricingLaneConfig->getLane(*tx)];
});
return std::make_pair(includedTxs, inclusionFeeMapPtr);
}
size_t
countOps(TxFrameList const& txs)
{
return std::accumulate(txs.begin(), txs.end(), size_t(0),
[&](size_t a, TransactionFrameBasePtr const& tx) {
return a + tx->getNumOperations();
});
}
int64_t
computeBaseFeeForLegacyTxSet(LedgerHeader const& lclHeader,
TxFrameList const& txs)
{
ZoneScoped;
auto ledgerVersion = lclHeader.ledgerVersion;
int64_t lowestBaseFee = std::numeric_limits<int64_t>::max();
for (auto const& tx : txs)
{
int64_t txBaseFee = computePerOpFee(*tx, ledgerVersion);
lowestBaseFee = std::min(lowestBaseFee, txBaseFee);
}
int64_t baseFee = lclHeader.baseFee;
if (protocolVersionStartsFrom(ledgerVersion, ProtocolVersion::V_11))
{
size_t surgeOpsCutoff = 0;
if (lclHeader.maxTxSetSize >= MAX_OPS_PER_TX)
{
surgeOpsCutoff = lclHeader.maxTxSetSize - MAX_OPS_PER_TX;
}
if (countOps(txs) > surgeOpsCutoff)
{
baseFee = lowestBaseFee;
}
}
return baseFee;
}
bool
checkFeeMap(InclusionFeeMap const& feeMap, LedgerHeader const& lclHeader)
{
for (auto const& [tx, fee] : feeMap)
{
if (!fee)
{
continue;
}
if (*fee < lclHeader.baseFee)
{
CLOG_DEBUG(Herder,
"Got bad txSet: {} has too low component "
"base fee {}",
hexAbbrev(lclHeader.previousLedgerHash), *fee);
return false;
}
if (tx->getInclusionFee() < getMinInclusionFee(*tx, lclHeader, fee))
{
CLOG_DEBUG(Herder,
"Got bad txSet: {} has tx with fee bid ({}) lower "
"than base fee ({})",
hexAbbrev(lclHeader.previousLedgerHash),
tx->getInclusionFee(),
getMinInclusionFee(*tx, lclHeader, fee));
return false;
}
}
return true;
}
} // namespace
TxSetXDRFrame::TxSetXDRFrame(TransactionSet const& xdrTxSet)
: mXDRTxSet(xdrTxSet)
, mEncodedSize(xdr::xdr_argpack_size(xdrTxSet))
, mHash(computeNonGeneralizedTxSetContentsHash(xdrTxSet))
{
}
TxSetXDRFrame::TxSetXDRFrame(GeneralizedTransactionSet const& xdrTxSet)
: mXDRTxSet(xdrTxSet)
, mEncodedSize(xdr::xdr_argpack_size(xdrTxSet))
, mHash(xdrSha256(xdrTxSet))
{
}
TxSetXDRFrameConstPtr
TxSetXDRFrame::makeFromWire(TransactionSet const& xdrTxSet)
{
ZoneScoped;
std::shared_ptr<TxSetXDRFrame> txSet(new TxSetXDRFrame(xdrTxSet));
return txSet;
}
TxSetXDRFrameConstPtr
TxSetXDRFrame::makeFromWire(GeneralizedTransactionSet const& xdrTxSet)
{
ZoneScoped;
std::shared_ptr<TxSetXDRFrame> txSet(new TxSetXDRFrame(xdrTxSet));
return txSet;
}
TxSetXDRFrameConstPtr
TxSetXDRFrame::makeFromStoredTxSet(StoredTransactionSet const& storedSet)
{
if (storedSet.v() == 0)
{
return TxSetXDRFrame::makeFromWire(storedSet.txSet());
}
return TxSetXDRFrame::makeFromWire(storedSet.generalizedTxSet());
}
std::pair<TxSetXDRFrameConstPtr, ApplicableTxSetFrameConstPtr>
makeTxSetFromTransactions(
PerPhaseTransactionList const& txPhases, Application& app,
uint64_t lowerBoundCloseTimeOffset, uint64_t upperBoundCloseTimeOffset
#ifdef BUILD_TESTS
,
bool skipValidation,
txtest::ParallelSorobanOrder const& parallelSorobanOrder
#endif
)
{
PerPhaseTransactionList invalidTxs;
invalidTxs.resize(txPhases.size());
return makeTxSetFromTransactions(txPhases, app, lowerBoundCloseTimeOffset,
upperBoundCloseTimeOffset, invalidTxs
#ifdef BUILD_TESTS
,
skipValidation, parallelSorobanOrder
#endif
);
}
std::pair<TxSetXDRFrameConstPtr, ApplicableTxSetFrameConstPtr>
makeTxSetFromTransactions(
PerPhaseTransactionList const& txPhases, Application& app,
uint64_t lowerBoundCloseTimeOffset, uint64_t upperBoundCloseTimeOffset,
PerPhaseTransactionList& invalidTxs
#ifdef BUILD_TESTS
,
bool skipValidation,
txtest::ParallelSorobanOrder const& parallelSorobanOrder
#endif
)
{
releaseAssert(threadIsMain());
releaseAssert(!app.getLedgerManager().isApplying());
releaseAssert(txPhases.size() == invalidTxs.size());
releaseAssert(txPhases.size() <=
static_cast<size_t>(TxSetPhase::PHASE_COUNT));
std::vector<TxSetPhaseFrame> validatedPhases;
for (size_t i = 0; i < txPhases.size(); ++i)
{
auto const& phaseTxs = txPhases[i];
bool expectSoroban = static_cast<TxSetPhase>(i) == TxSetPhase::SOROBAN;
if (!std::all_of(phaseTxs.begin(), phaseTxs.end(), [&](auto const& tx) {
return tx->isSoroban() == expectSoroban;
}))
{
throw std::runtime_error("TxSetFrame::makeFromTransactions: phases "
"contain txs of wrong type");
}
auto& invalid = invalidTxs[i];
TxFrameList validatedTxs;
#ifdef BUILD_TESTS
if (skipValidation)
{
validatedTxs = phaseTxs;
}
else
{
#endif
validatedTxs = TxSetUtils::trimInvalid(
phaseTxs, app, lowerBoundCloseTimeOffset,
upperBoundCloseTimeOffset, invalid);
#ifdef BUILD_TESTS
}
#endif
auto phaseType = static_cast<TxSetPhase>(i);
auto [includedTxs, inclusionFeeMapBinding] =
applySurgePricing(phaseType, validatedTxs, app
#ifdef BUILD_TESTS
,
skipValidation, parallelSorobanOrder
#endif
);
auto inclusionFeeMap = inclusionFeeMapBinding;
std::visit(
[&validatedPhases, phaseType, inclusionFeeMap](auto&& txs) {
using T = std::decay_t<decltype(txs)>;
if constexpr (std::is_same_v<T, TxFrameList>)
{
validatedPhases.emplace_back(
TxSetPhaseFrame(phaseType, txs, inclusionFeeMap));
}
else if constexpr (std::is_same_v<T, TxStageFrameList>)
{
validatedPhases.emplace_back(TxSetPhaseFrame(
phaseType, std::move(txs), inclusionFeeMap));
}
else
{
// This can't be just `false` as if an assertion is not
// dependent on template argument, it will be
// unconditionally triggered.
static_assert(!std::is_same_v<T, T>,
"Non-exhaustive visitor");
}
},
includedTxs);
}
auto const& lclHeader = app.getLedgerManager().getLastClosedLedgerHeader();
// Preliminary applicable frame - we don't know the contents hash yet, but
// we also don't return this.
std::unique_ptr<ApplicableTxSetFrame> preliminaryApplicableTxSet(
new ApplicableTxSetFrame(app, lclHeader, validatedPhases,
std::nullopt));
// Do the roundtrip through XDR to ensure we never build an incorrect tx set
// for nomination.
auto outputTxSet = preliminaryApplicableTxSet->toWireTxSetFrame();
#ifdef BUILD_TESTS
if (skipValidation)
{
// Fill in the contents hash if we're skipping the normal roundtrip
// and validation flow.
preliminaryApplicableTxSet->mContentsHash =
outputTxSet->getContentsHash();
return std::make_pair(outputTxSet,
std::move(preliminaryApplicableTxSet));
}
#endif
ApplicableTxSetFrameConstPtr outputApplicableTxSet =
outputTxSet->prepareForApply(app, lclHeader.header);
if (!outputApplicableTxSet)
{
throw std::runtime_error(
"Couldn't prepare created tx set frame for apply");
}
// Make sure no transactions were lost during the roundtrip and the output
// tx set is valid.
bool valid = preliminaryApplicableTxSet->numPhases() ==
outputApplicableTxSet->numPhases();
if (valid)
{
for (size_t i = 0; i < preliminaryApplicableTxSet->numPhases(); ++i)
{
valid = valid && preliminaryApplicableTxSet->sizeTx(
static_cast<TxSetPhase>(i)) ==
outputApplicableTxSet->sizeTx(
static_cast<TxSetPhase>(i));
}
}
// We already trimmed invalid transactions in an earlier call to
// `trimInvalid`, so skip transaction validation here
valid = valid && outputApplicableTxSet->checkValidInternal(
app, lowerBoundCloseTimeOffset,
upperBoundCloseTimeOffset, true);
if (!valid)
{
throw std::runtime_error("Created invalid tx set frame");
}
return std::make_pair(outputTxSet, std::move(outputApplicableTxSet));
}
TxSetXDRFrameConstPtr
TxSetXDRFrame::makeEmpty(LedgerHeaderHistoryEntry const& lclHeader)
{
if (protocolVersionStartsFrom(lclHeader.header.ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
bool isParallelSoroban = false;
isParallelSoroban =
protocolVersionStartsFrom(lclHeader.header.ledgerVersion,
PARALLEL_SOROBAN_PHASE_PROTOCOL_VERSION);
std::vector<TxSetPhaseFrame> emptyPhases = {
TxSetPhaseFrame::makeEmpty(TxSetPhase::CLASSIC, false),
TxSetPhaseFrame::makeEmpty(TxSetPhase::SOROBAN, isParallelSoroban)};
GeneralizedTransactionSet txSet;
transactionsToGeneralizedTransactionSetXDR(emptyPhases, lclHeader.hash,
txSet);
return TxSetXDRFrame::makeFromWire(txSet);
}
TransactionSet txSet;
transactionsToTransactionSetXDR({}, lclHeader.hash, txSet);
return TxSetXDRFrame::makeFromWire(txSet);
}
TxSetXDRFrameConstPtr
TxSetXDRFrame::makeFromHistoryTransactions(Hash const& previousLedgerHash,
TxFrameList const& txs)
{
TransactionSet txSet;
transactionsToTransactionSetXDR(txs, previousLedgerHash, txSet);
return TxSetXDRFrame::makeFromWire(txSet);
}
#ifdef BUILD_TESTS
std::pair<TxSetXDRFrameConstPtr, ApplicableTxSetFrameConstPtr>
makeTxSetFromTransactions(
TxFrameList txs, Application& app, uint64_t lowerBoundCloseTimeOffset,
uint64_t upperBoundCloseTimeOffset, bool enforceTxsApplyOrder,
txtest::ParallelSorobanOrder const& parallelSorobanOrder)
{
TxFrameList invalid;
return makeTxSetFromTransactions(
txs, app, lowerBoundCloseTimeOffset, upperBoundCloseTimeOffset, invalid,
enforceTxsApplyOrder, parallelSorobanOrder);
}