forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Speedex Changes
3944 lines (3649 loc) · 142 KB
/
Speedex Changes
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
New files:
src/herder/AccountCommutativityRequirements.[h|cpp]
src/herder/TransactionCommutativityRequirements.[h|cpp]
src/herder/TxSetCommutativityRequirements.[h|cpp]
src/transactions/CreateSpeedexIOCOfferOpFrame.[h|cpp]
src/ledger/AssetPair.[h|cpp]
src/ledger/LedgerTxnSpeedexConfigSql.cpp
src/simplex/solver.[h|cpp]
src/speedex/BatchSolution.[h|cpp]
src/speedex/DemandOracle.[h|cpp]
src/speedex/DemandUtils.[h|cpp]
src/speedex/IOCOffer.[h|cpp]
src/speedex/IOCOrderbook.[h|cpp]
src/speedex/IOCOrderbookManager.[h|cpp]
src/speedex/LiquidityPoolFrame.[h|cpp]
src/speedex/LiquidityPoolSetFrame.[h|cpp]
src/speedex/OrderbookClearingTarget.[h|cpp]
src/speedex/SpeedexConfigEntryFrame.[h|cpp]
src/speedex/TatonnementControls.[h|cpp]
src/speedex/TatonnementOracle.[h|cpp]
src/speedex/speedex.[h|cpp]
src/speedex/uint256_t.[h|cpp]
Modifications by Theme:
Transaction Preconditions (Commutativity Requirements):
When building a transaction set, we require not only that accounts have sufficient XLM so as to cover
any fee bids, but also that accounts have sufficient amounts of every asset to cover each of their proposed
operations.
- A payment operation mandates that the sender possesses sufficient assets to send.
- A speedex create IOC offer mandates that the sender possesses sufficient assets to sell.
Since each operation can have a different source account and fees can be paid by accounts other than the source account,
each transation induces a map [Account] -> (map [Asset] -> [Amount (int64_t)]);
That is, for the transaction to be valid, certain accounts must possess certain amounts of certain assets.
AccountCommutativityRequirements stores the map [Asset] -> [Amount] for one account, and TransactionCommutativityRequirements stores
a map [Account] -> [AccountCommutativityRequirements].
TxSetCommutativityRequirements stores an accumulation of the requirements for each account, accumulated over all transactions in a transaction set.
The transaction set validation workflow then becomes:
For each transaction:
1. Check that the transaction is well-formed
a. sequence numbers, etc
b. If transaction is commutative, then only commutative ops are allowed
- At the moment, commutative ops are PaymentOp and CreateSpeedexIOCOfferOp
c. Commutative transactions cannot follow noncommutative transactions within a block
2. Build a set of transaction commutativity requirements
3. Add the requirements to the transaction set
For each account that is the seq-num-source for a transaction in the set:
For each transaction:
If all the accounts relevant (i.e. supplying assets for the transaction) meet their preconditions for the whole set, continue.
Otherwise, remove the transaction and all subsequent txs with the same seq-num source.
A siimlar logic applies to the transaction queue. To add a transaction, we compute the requirements, then check if the relevant accounts
all have sufficient balances to cover the new requirements. Replacing transactions look at the difference between new and old requirements.
Errata:
- Asset requirements for one account cannot exceed int64_t. If one account's requirement for some asset exceeds int64_t,
all of that account's transactions are removed.
- Commutative transactions can be fee-bumped, but can only be replaced by commutative transactions (and vice versa).
- This requirement could be weakened, at the cost of a more complex validation check.
Questions:
- In the tx queue, should commutative txs that follow a noncommutative tx be pushed automatically to the next block, instead of being rejected/banned?
Issuance limited assets:
- Introduce an account flag that limits total issuance of each asset to INT64_MAX
- Prevents overflows in commutative phase
- Implemented via TrustLineWrapper
- Log total asset issuance to an account entry extension.
- TrustLineWrapper::IssuerImpl::getAvailableBalance returns INT64_MAX - issuedAmount
- Issuance-limited assets cannot have the issuer account be deleted.
- Errata:
- I have not implemented a mechanism for turning on this flag in a well-defined way (i.e. for an asset that already has been issued).
- Jon suggested possibly a database schema update could track total asset issuance, which we could then just read when enabling the flag.
- We may also prefer to implement this via issuer trustlines (and a flag on said trustline). Current implementation can lead to large
AccountEntry objects.
Commutativity-Enabled Assets:
- To use an asset in the commutative phase, the asset must be issuance limited.
- The receiver must have a valid trustline with limit INT64_MAX.
Transaction processing:
- Transaction Application is multiphase.
- Commutative transactions
- Speedex
- Noncommutative transactions
- Errata:
- Noncommutative transaction seq numbers cannot precede commutative transaction seq numbers (from one account)
Speedex-Related Addiitons:
- New operation code : Create Speedex IOC Offer
- Implemented in CreateSpeedexIOCOffer.[h|cpp]
- Should be run in commutative phase.
- Applying this operation code creates an IOCOffer (src/speedex/IOCOffer.[h|cpp]).
- An IOCOffer is an offer to sell some amount of one asset A in exchange for some other asset B, with a minimum price requirement.
- These are grouped by trading pair (sell asset, buy asset) within IOCOrderbooks (src/speedex/IOCOrderbook.[h|cpp]).
- Trading pairs are stored within one IOCOrderbookManager (src/speedex/IOCOrderbookManager.[h|cpp])
- A LedgerTxn::Impl object contains one IOCOrderbookManager. Committing a child LedgerTxn object adds the offers in the child's orderbook manager
into the parent's orderbook manager.
- Motivation:
- Price computation and offer clearing require interacting repeatedly with orders in an order where offers are sorted by price.
- It is convenient, therefore, to store offers in this manner.
- An alternative would be to add offers in unsorted order to a LedgerTxn object, and then extract them all and sort them into an IOCOrderbookManager.
- New Ledger Entry type: SpeedexConfig
- Contains a list of assets that are tradeable on Speedex.
- These assets need to be commutative-enabled. But for performance reasons, we may not want to allow trading of every asset at once on speedex.
(speedex's performance would possibly degrade if naively trying to trade 10,000 NFTS, for example).
- LedgerTxn gets a loadSnapshot method and a snapshot cache
- Reads ledger entries as they existed at the last time the LedgerTxnRoot committed.
- Useful for the commutative phase - transactions in the commutative phase may sometimes need to read data as it existed at the start of the commutative phase,
without any potential modifications by other transactions. Currently used only for SpeedexConfig entries.
- Would be required for implementing a commutative LiquidityPoolDeposit operation.
- returns shared_ptr<const LedgerEntry> to ensure callers do not attempt to write to this snapshot.
Solution Computation
- Tatonnement runs for a fixed number of rounds
- speedex/TatonnementOracle.[h|cpp]
- Pass computed prices to a custom linear programming solver
- simplex/solver.[h|cpp]
- The lp solves the problem "given these prices, maximize the amount of trading activity"
- Reduces to a network flow problem. This means the simplex constraint matrix is "totally unimodular"
- in concrete terms, all entries are +/- 1 and there's always an integral optimal solution.
- The solver never has to use floating-point arithmetic.
- Output: For each trading pair (sell, buy):
- an amount y, where y/sell_price is the amount of asset "sell" sold to purchase y/buy_price units of asset "buy"
Offer Clearing
- For each trading pair and trading target y (the solution output):
- Starting from offers with the lowest minimum price and moving to higher minimum prices:
- clearedAmount := 0
- Clear the offer as much as possible. That is:
- Set the clearing amount for this offer to be z := min(x * sell_price, y-clearedAmount)
- The offer sells ceil(z / sell_price) units of asset "sell" and purchases floor(z/buy_price) units of asset "buy"
- clearedAmount <- clearedAmount + z
- Throughout this process, track the amount of each asset bought and sold. Assets sold by offers with exceed assets bought due to rounding error.
- Return excess asset to asset source. Note that asset source always exists for commutative-enabled assets.
Errata:
- runSpeedex (in src/speedex/speedex.[h|cpp]) sequences the solution computation with the offer clearing, and outputs
a set of results.
- We need this separate results output, as we cannot use the existing TransactionResult framework to record the results of a speedex run.
- CreateSpeedexIOCOfferOp can succeed, for example, but at the time when this op succeeds, we do not know whether the created offer will actually trade,
and at what rate.
- This results also records trades that happen with the liquidity pools, which do not appear to have any other good place to go.
- Unfortunately, TransactionResultSet has no extension field.
- As implemented right now, runSpeedex computes a SpeedexResults object, which is then ignored (although useful in testing).
See LedgerManagerImpl::applyTransactions.
- The issuance limited assets is easiest to implement if we load the issuer account behind TrustLineWrapper::IssuerImpl.
- This makes it very easy to accidentally load the same LedgerTxnEntry twice.
- This happens in several operation codes and in OfferExchange.[h|cpp].
- The operation codes could be straightforwardly refactored to avoid the problem, while OfferExchange required passing lambdas
that, when called, load a ledger entry, instead of passing entries directly.
- SpeedexConfig entries have a unique key - so there can only be one at any time. This causes a bunch of weird issues in tests with randomly-generated
ledger entries (specifically the bucket tests). The fix is to restrict when autocheck can generate SpeedexConfig entries.
- SpeedexConfig is implemented here as a static variable behind src/ledger/LedgerTxnSpeedexConfigSql.cpp, not a database schema change.
- There are a number of "magic Tatonnement constants" defined in SpeedexConfigEntryFrame. These are not actually "magic", and can be adjusted
with (in my experience) only marginal changes to Tatonnement's performance (and I chose them without too much detailed thought -- "that looks about right");
They are:
TatonnementControlParams
{
.mTaxRate = 5,
- Not currently used. One option for a stopping criterion for Tatonnement would be to say "Would the market clear if we charged an epsilon fee".
- Note that even with this criterion in Tatonnement, it would not be used in the LP solver (i.e. no fee is actually charged).
- The actual rate is 2^-mTaxRate.
.mSmoothMult = 7,
- Each offer's optimal behavior is a discontinuous function. This parameter defines a continuous approximation.
- Mu := 2^-mSmoothMult (At this setting, Mu is roughly 1%)
- Unapproximated:
- Offer trades iff offer.minPrice < market_price
- Approximated:
- Offer trades if offer.minPrice < market_price * (1-Mu)
- Offer does not trade if offer.minPrice > market_price
- Offer trades fractionally in the interim.
Specifically, a lambda fraction executes for lambda := (market_price - offer.minPrice) / (market_price * Mu)
.mMaxRounds = 1000,
- Maximum number of rounds for Tatonnement
.mStepUp = 45,
- When Tatonnement makes a step, increase the step size by mStepUp / 2^mStepSizeRadix == 1.4
Any value in [1.1, 1.5] seems to work acceptably well.
.mStepDown = 25,
- When Tatonnement finds that its target step size is too large (according to its optimization heuristic),
multiply step size by mStepDown / 2^mStepSizeRadix == 0.8
Any value in [0.7, 0.9] seems to work acceptably well.
.mStepSizeRadix = 5,
.mStepRadix = 65
- Step size is multiplied by 2^-mStepRadix.
Too small (large steps) and Tatonnement will likely oscillate, and too large (small steps) and Tatonnement cannot make any steps.
Likely any value in [50, 90] is ok.
};
Hidden parameter : kMinStepSize = 1 << (mStepSizeRadix + 1). Set to be sufficiently large so that step_size * mStepUp >> mStepRadix > step_size.
If one were to run several copies of Tatonnement in parallel (and take the best result), the only parameters worth varying
are mStepRadix and mSmoothMult.
Additionally, within TatonnementOracle, we have the constants (1, 100). These denote that a Tatonnement step is ok if the
guiding heuristic's value does not increase by more than (1/100)=1%
- This relaxes a typical step-size choice criterion common to the numerical optimization literature (Wolfe conditions).
- Need the relaxation because (1) the choice of objective may not actually be convex, so we do not wish to get stuck and (2) for Tatonnement,
making any step is often better than finding the step of the perfect size.
Prices are initialized at 2^32. This is for numerical stability - if prices are too small, than the smallest price increment (1) induces
a comparatively large change in aggregate demand.
Prices are bounded between 1 and 2^{64 - mSmoothMult}. The 64 limit is because prices are represented as 64-bit integers, and the mSmoothMult
factor is needed to ensure intermediate computations do not overflow (although the analysis that led to this bound is very conservative, and may
be unnecessary). There is a point within the demand calculation where a quantity is left-shifted by mSmoothMult.
It is inconvenient, but not a huge problem, if prices run into the maximum limit.
A possible addition to the Tatonnement loop would be to renormalize prices if one price becomes too large or too small.
However, the sum of the price-weighted demand (sum over all assets) at any price point is 0. As such, the geometric mean of prices is preserved
throughout Tatonnement (up to rounding error), and there is no overall price drift as Tatonnement runs. I did not implement this feature
for this Tatonnement implementation. I did implement this for the SOSP version, and found it to be not particularly helpful (although
it did help with numerical stability in very rare circumstances).
Each step of Tatonnement does, in fact, multiply the step size by 2^{-mStepRadix}. This is primarily for numerical stability. The price
update rule within Tatonnement is as follows:
- price += (((net demand) * price * price * step_size) >> mStepRadix)
- Net demand is an int64
- Price is a uint64 (the starting price is 2^32)
- step_size is a uint64, and adjusted heuristically
(The price update rule is not implemented using that exact formula to prevent overflows).
We need some relatively large mStepRadix to compensate for the fact that price * price >> price.
Other files:
- uint256_t.[h|cpp] implements a few 256-bit integer operations. Used inside Tatonnement.
- LiquidityPoolFrame and LiquidityPoolSetFrame perform trade calculations on liquidity pools.
- LiquidityPoolFrame objects are one-directional. That is, they have a sell asset and a buy asset.
This is for convenience when working within Tatonnement.
- One liquidity pool corresponds to two LiquidityPoolFrame objects.
- LiquidityPoolSetFrame manages the LedgerTxnEntry loading (to avoid double-loading a key).
- TatonnementControls manages utility classes for Tatonnement.
- SpeedexConfigEntryFrame wraps a SpeedexConfig entry with utility methods.
- AssetPair is extracted from LedgerTxn. It was quite useful on its own.
Below is a condensed diff (not including tests or newly created files).
============================================================================================
diff --git a/src/herder/TransactionQueue.cpp b/src/herder/TransactionQueue.cpp
index d617624f..057830af 100644
--- a/src/herder/TransactionQueue.cpp
+++ b/src/herder/TransactionQueue.cpp
@@ -80,6 +81,14 @@ canReplaceByFee(TransactionFrameBasePtr tx, TransactionFrameBasePtr oldTx,
int64_t oldFee = oldTx->getFeeBid();
uint32_t oldNumOps = std::max<uint32_t>(1, oldTx->getNumOperations());
+ // More effective way would be to track for each account where the boundary between
+ // commutative txs and noncommutative txs is, and then check this condition
+ // or that the tx is on the boundary.
+ if (tx -> isCommutativeTransaction() != oldTx -> isCommutativeTransaction()) {
+ minFee = INT64_MAX;
+ return false;
+ }
+
// newFee / newNumOps >= FEE_MULTIPLIER * oldFee / oldNumOps
// is equivalent to
// newFee * oldNumOps >= FEE_MULTIPLIER * oldFee * newNumOps
@@ -159,7 +168,7 @@ TransactionQueue::canAdd(TransactionFrameBasePtr tx,
return TransactionQueue::AddResult::ADD_STATUS_FILTERED;
}
- int64_t netFee = tx->getFeeBid();
+ //int64_t netFee = tx->getFeeBid();
int64_t seqNum = 0;
TransactionFrameBasePtr oldTx;
@@ -181,6 +190,13 @@ TransactionQueue::canAdd(TransactionFrameBasePtr tx,
}
seqNum = transactions.back().mTx->getSeqNum();
+
+ if ((!transactions.back().mTx -> isCommutativeTransaction())
+ && tx -> isCommutativeTransaction())
+ {
+ // Can't follow a noncommutative tx with a commutative tx
+ return TransactionQueue::AddResult::ADD_STATUS_ERROR;
+ }
}
else
{
@@ -208,11 +224,11 @@ TransactionQueue::canAdd(TransactionFrameBasePtr tx,
}
oldTx = oldTxIter->mTx;
- int64_t oldFee = oldTx->getFeeBid();
- if (oldTx->getFeeSourceID() == tx->getFeeSourceID())
- {
- netFee -= oldFee;
- }
+ //int64_t oldFee = oldTx->getFeeBid();
+ //if (oldTx->getFeeSourceID() == tx->getFeeSourceID())
+ // {
+ // netFee -= oldFee;
+ // }
}
seqNum = tx->getSeqNum() - 1;
@@ -243,8 +259,23 @@ TransactionQueue::canAdd(TransactionFrameBasePtr tx,
return TransactionQueue::AddResult::ADD_STATUS_ERROR;
}
+ if (oldTx)
+ {
+ if (!mCommutativityRequirements.tryReplaceTransaction(tx, oldTx, ltx))
+ {
+ tx->getResult().result.code(txINSUFFICIENT_BALANCE);
+ return TransactionQueue::AddResult::ADD_STATUS_ERROR;
+ }
+ } else {
+ if (!mCommutativityRequirements.tryAddTransaction(tx, ltx))
+ {
+ tx->getResult().result.code(txINSUFFICIENT_BALANCE);
+ return TransactionQueue::AddResult::ADD_STATUS_ERROR;
+ }
+ }
+
@@ -269,7 +300,7 @@ TransactionQueue::releaseFeeMaybeEraseAccountState(TransactionFrameBasePtr tx)
iter->second.mTotalFees -= tx->getFeeBid();
if (iter->second.mTransactions.empty())
{
- if (iter->second.mTotalFees == 0)
+ if (mCommutativityRequirements.tryCleanAccountEntry(iter->first))
{
mAccountStates.erase(iter);
}
@@ -372,10 +403,14 @@ TransactionQueue::dropTransactions(AccountStates::iterator stateIter,
// the fee-source for some other transaction or (2) reset the age otherwise.
if (stateIter->second.mTransactions.empty())
{
- if (stateIter->second.mTotalFees == 0)
+ if (mCommutativityRequirements.tryCleanAccountEntry(stateIter->first))
{
mAccountStates.erase(stateIter);
}
+ // if (stateIter->second.mTotalFees == 0)
+ // {
+ // mAccountStates.erase(stateIter);
+ // }
else
{
stateIter->second.mAge = 0;
@@ -604,10 +639,15 @@ TransactionQueue::shift()
mBannedTransactionsCounter.inc(
static_cast<int64_t>(it->second.mTransactions.size()));
it->second.mTransactions.clear();
- if (it->second.mTotalFees == 0)
+
+ if (mCommutativityRequirements.tryCleanAccountEntry(it->first))
{
- it = mAccountStates.erase(it);
+ mAccountStates.erase(it);
}
+ //if (it->second.mTotalFees == 0)
+ //{
+ // it = mAccountStates.erase(it);
+ //}
else
{
it->second.mAge = 0;
diff --git a/src/herder/TransactionQueue.h b/src/herder/TransactionQueue.h
index 0f68751f..b559c4ed 100644
--- a/src/herder/TransactionQueue.h
+++ b/src/herder/TransactionQueue.h
@@ -173,6 +175,7 @@ class TransactionQueue
uint32 const mPendingDepth;
AccountStates mAccountStates;
+ TxSetCommutativityRequirements mCommutativityRequirements;
BannedTransactions mBannedTransactions;
uint32_t mLedgerVersion;
diff --git a/src/herder/TxSetFrame.cpp b/src/herder/TxSetFrame.cpp
index 48791fb6..d50ecf5e 100644
--- a/src/herder/TxSetFrame.cpp
+++ b/src/herder/TxSetFrame.cpp
@@ -105,12 +106,27 @@ SeqSorter(TransactionFrameBasePtr const& tx1,
* transactions for an account are sorted by sequence number (ascending)
* the order between accounts is randomized
*/
-std::vector<TransactionFrameBasePtr>
+std::pair<TxSetFrame::TransactionPtrVec, TxSetFrame::TransactionPtrVec>
TxSetFrame::sortForApply()
{
ZoneScoped;
auto txQueues = buildAccountTxQueues();
+
+ TransactionPtrVec commutativeTxs;
+
+ for (auto& [_, queue] : txQueues) {
+ while (!queue.empty()) {
+ auto front = queue.front();
+ if (front->isCommutativeTransaction()) {
+ commutativeTxs.push_back(front);
+ queue.pop_front();
+ } else {
+ break;
+ }
+ }
+ }
+
// build txBatches
// txBatches i-th element contains each i-th transaction for accounts with a
// transaction in the transaction set
@@ -123,6 +139,10 @@ TxSetFrame::sortForApply()
// go over all users that still have transactions
for (auto it = txQueues.begin(); it != txQueues.end();)
{
+ if (it->second.empty()) {
+ it = txQueues.erase(it);
+ continue;
+ }
auto& h = it->second.front();
curBatch.emplace_back(h);
it->second.pop_front();
@@ -138,8 +158,9 @@ TxSetFrame::sortForApply()
}
}
- vector<TransactionFrameBasePtr> retList;
- retList.reserve(mTransactions.size());
+ TransactionPtrVec retList;
+ retList.reserve(mTransactions.size() - commutativeTxs.size());
+
for (auto& batch : txBatches)
{
// randomize each batch using the hash of the transaction set
@@ -152,7 +173,7 @@ TxSetFrame::sortForApply()
}
}
- return retList;
+ return std::make_pair(commutativeTxs, retList);
}
struct SurgeCompare
@@ -283,14 +304,18 @@ TxSetFrame::checkOrTrim(Application& app,
bool justCheck, uint64_t lowerBoundCloseTimeOffset,
uint64_t upperBoundCloseTimeOffset)
{
ZoneScoped;
LedgerTxn ltx(app.getLedgerTxnRoot());
- UnorderedMap<AccountID, int64_t> accountFeeMap;
+ TxSetCommutativityRequirements reqs;
+
auto accountTxMap = buildAccountTxQueues();
+
for (auto& kv : accountTxMap)
{
int64_t lastSeq = 0;
+ bool foundNoncommutative = false;
auto iter = kv.second.begin();
while (iter != kv.second.end())
{
@@ -298,6 +323,7 @@ TxSetFrame::checkOrTrim(Application& app,
if (!tx->checkValid(ltx, lastSeq, lowerBoundCloseTimeOffset,
upperBoundCloseTimeOffset))
{
+ std::printf("individual tx failed a validity check\n");
if (justCheck)
{
CLOG_DEBUG(
@@ -309,14 +335,47 @@ TxSetFrame::checkOrTrim(Application& app,
tx->getResultCode());
return false;
}
- trimmed.emplace_back(tx);
- removeTx(tx);
- iter = kv.second.erase(iter);
+ while (iter != kv.second.end()) {
+ trimmed.emplace_back(*iter);
+ removeTx(*iter);
+ iter = kv.second.erase(iter);
+ }
+ continue;
}
else
{
+
+ if (tx -> isCommutativeTransaction() && foundNoncommutative)
+ {
+
+ std::printf("wtf\n");
+ if (justCheck)
+ {
+ CLOG_DEBUG(
+ Herder,
+ "Cannot follow noncommutative tx by commutative tx in one block");
+ return false;
+ }
+ while(iter != kv.second.end())
+ {
+ trimmed.emplace_back(*iter);
+ removeTx(*iter);
+ iter = kv.second.erase(iter);
+ }
+ continue;
+ }
+
+ if (!tx -> isCommutativeTransaction()) {
+ std::printf("found noncommutative\n");
+ foundNoncommutative = true;
+ }
+
lastSeq = tx->getSeqNum();
- int64_t& accFee = accountFeeMap[tx->getFeeSourceID()];
+
+ auto res = reqs.validateAndAddTransaction(tx, ltx);
+
+
+ /*int64_t& accFee = accountFeeMap[tx->getFeeSourceID()];
if (INT64_MAX - accFee < tx->getFeeBid())
{
accFee = INT64_MAX;
@@ -324,41 +383,57 @@ TxSetFrame::checkOrTrim(Application& app,
else
{
accFee += tx->getFeeBid();
+ } */
+
+ if (res) {
+ ++iter;
+ } else {
+ std::printf("validateandAddTransaction failed\n");
+ if (justCheck) {
+ CLOG_DEBUG(
+ Herder,
+ "Invalid TxSet: TODO logging");
+ return false;
+ }
+ while (iter != kv.second.end())
+ {
+ trimmed.emplace_back(*iter);
+ removeTx(*iter);
+ iter = kv.second.erase(iter);
+ }
+ continue;
}
- ++iter;
}
}
}
auto header = ltx.loadHeader();
- for (auto& kv : accountTxMap)
+
+ for (auto& [_, accountTxs] : accountTxMap)
{
- auto iter = kv.second.begin();
- while (iter != kv.second.end())
- {
- auto tx = *iter;
- auto feeSource = stellar::loadAccount(ltx, tx->getFeeSourceID());
- auto totFee = accountFeeMap[tx->getFeeSourceID()];
- if (getAvailableBalance(header, feeSource) < totFee)
- {
- if (justCheck)
- {
- CLOG_DEBUG(Herder,
- "Got bad txSet: {} account can't pay fee tx: {}",
- hexAbbrev(mPreviousLedgerHash),
- xdr_to_string(tx->getEnvelope(),
- "TransactionEnvelope"));
- return false;
- }
- while (iter != kv.second.end())
- {
- trimmed.emplace_back(*iter);
- removeTx(*iter);
- ++iter;
+ auto iter = accountTxs.begin();
+ while (iter != accountTxs.end()) {
+
+ auto relevantAccounts = (*iter)->getRelevantAccounts();
+ for (auto acct : relevantAccounts) {
+ //TODO cache results of this check
+ if (!reqs.checkAccountHasSufficientBalance(acct, ltx, header)) {
+ std::printf("insufficient balance?\n");
+ if (justCheck) {
+ CLOG_DEBUG(
+ Herder,
+ "Insufficient balance TODO logging");
+ return false;
+ }
+ while (iter != accountTxs.end()) {
+ trimmed.emplace_back(*iter);
+ removeTx(*iter);
+ iter = accountTxs.erase(iter);
+ }
+ continue;
}
}
- else
- {
+ if (iter != accountTxs.end()) {
++iter;
}
}
diff --git a/src/herder/TxSetFrame.h b/src/herder/TxSetFrame.h
index ede66de2..ee5fcf6a 100644
--- a/src/herder/TxSetFrame.h
+++ b/src/herder/TxSetFrame.h
@@ -35,7 +35,7 @@ class AbstractTxSetFrameForApply
virtual size_t sizeOp() const = 0;
- virtual std::vector<TransactionFrameBasePtr> sortForApply() = 0;
+ virtual std::pair<std::vector<TransactionFrameBasePtr>, std::vector<TransactionFrameBasePtr>> sortForApply() = 0;
virtual void toXDR(TransactionSet& set) = 0;
};
@@ -44,12 +44,13 @@ class TxSetFrame : public AbstractTxSetFrameForApply
std::optional<Hash> mHash;
// mValid caches both the last app LCL that we checked
- // vaidity for, and the result of that validity check.
+ // validity for, and the result of that validity check.
std::optional<std::pair<Hash, bool>> mValid;
Hash mPreviousLedgerHash;
using AccountTransactionQueue = std::deque<TransactionFrameBasePtr>;
+ using TransactionPtrVec = std::vector<TransactionFrameBasePtr>;
bool checkOrTrim(Application& app,
std::vector<TransactionFrameBasePtr>& trimmed,
@@ -79,7 +80,7 @@ class TxSetFrame : public AbstractTxSetFrameForApply
virtual void sortForHash();
- std::vector<TransactionFrameBasePtr> sortForApply() override;
+ std::pair<TransactionPtrVec, TransactionPtrVec> sortForApply() override;
bool checkValid(Application& app, uint64_t lowerBoundCloseTimeOffset,
uint64_t upperBoundCloseTimeOffset);
diff --git a/src/ledger/LedgerManagerImpl.cpp b/src/ledger/LedgerManagerImpl.cpp
index 6b4e43b6..638b0fc0 100644
--- a/src/ledger/LedgerManagerImpl.cpp
+++ b/src/ledger/LedgerManagerImpl.cpp
@@ -637,16 +639,23 @@ LedgerManagerImpl::closeLedger(LedgerCloseData const& ledgerData)
// the transaction set that was agreed upon by consensus
// was sorted by hash; we reorder it so that transactions are
// sorted such that sequence numbers are respected
- vector<TransactionFrameBasePtr> txs = ledgerData.getTxSet()->sortForApply();
+ auto [commutativeTxs, noncommutativeTxs] = ledgerData.getTxSet()->sortForApply();
// first, prefetch source accounts for txset, then charge fees
- prefetchTxSourceIds(txs);
- processFeesSeqNums(txs, ltx, txSet->getBaseFee(header.current()),
+ prefetchTxSourceIds(commutativeTxs);
+ prefetchTxSourceIds(noncommutativeTxs);
+ auto baseFee = txSet -> getBaseFee(header.current());
+ processFeesSeqNums(commutativeTxs, ltx, baseFee,
+ ledgerCloseMeta);
+ //header is no longer valid -- the ltx.commit inside processFeesSeqNums invalidates it.
+
+ processFeesSeqNums(noncommutativeTxs, ltx, baseFee,
ledgerCloseMeta);
TransactionResultSet txResultSet;
- txResultSet.results.reserve(txs.size());
- applyTransactions(txs, ltx, txResultSet, ledgerCloseMeta);
+ auto txs_size = commutativeTxs.size() + noncommutativeTxs.size();
+ txResultSet.results.reserve(txs_size);
+ applyTransactions(commutativeTxs, noncommutativeTxs, ltx, txResultSet, ledgerCloseMeta);
ltx.loadHeader().current().txSetResultHash = xdrSha256(txResultSet);
@@ -765,14 +774,19 @@ LedgerManagerImpl::closeLedger(LedgerCloseData const& ledgerData)
void
LedgerManagerImpl::applyTransactions(
- std::vector<TransactionFrameBasePtr>& txs, AbstractLedgerTxn& ltx,
+ std::vector<TransactionFrameBasePtr>& commutativeTxs,
+ std::vector<TransactionFrameBasePtr>& noncommutativeTxs,
+ AbstractLedgerTxn& ltx,
TransactionResultSet& txResultSet,
std::unique_ptr<LedgerCloseMeta> const& ledgerCloseMeta)
{
@@ -1068,14 +1137,18 @@ LedgerManagerImpl::applyTransactions(
int index = 0;
// Record counts
- auto numTxs = txs.size();
+ auto numTxs = commutativeTxs.size() + noncommutativeTxs.size();
size_t numOps = 0;
if (numTxs > 0)
{
mTransactionCount.Update(static_cast<int64_t>(numTxs));
TracyPlot("ledger.transaction.count", static_cast<int64_t>(numTxs));
numOps =
- std::accumulate(txs.begin(), txs.end(), size_t(0),
+ std::accumulate(noncommutativeTxs.begin(), noncommutativeTxs.end(), size_t(0),
+ [](size_t s, TransactionFrameBasePtr const& v) {
+ return s + v->getNumOperations();
+ })
+ + std::accumulate(commutativeTxs.begin(), commutativeTxs.end(), size_t(0),
[](size_t s, TransactionFrameBasePtr const& v) {
return s + v->getNumOperations();
});
@@ -1085,53 +1158,19 @@ LedgerManagerImpl::applyTransactions(
ltx.loadHeader().current().ledgerSeq, numTxs, numOps);
}
- prefetchTransactionData(txs);
+ prefetchTransactionData(commutativeTxs);
+ for (auto tx : commutativeTxs) {
+ applyTransaction(tx, ltx, txResultSet, ledgerCloseMeta, index);
+ }
+ runSpeedex(ltx);
+
+ prefetchTransactionData(noncommutativeTxs);
+
+ for (auto tx : noncommutativeTxs)
+ {
+ applyTransaction(tx, ltx, txResultSet, ledgerCloseMeta, index);
}
logTxApplyMetrics(ltx, numTxs, numOps);
diff --git a/src/ledger/LedgerManagerImpl.h b/src/ledger/LedgerManagerImpl.h
index 812bd461..6da07a7a 100644
--- a/src/ledger/LedgerManagerImpl.h
+++ b/src/ledger/LedgerManagerImpl.h
@@ -69,7 +69,15 @@ class LedgerManagerImpl : public LedgerManager
std::unique_ptr<LedgerCloseMeta> const& ledgerCloseMeta);
void
- applyTransactions(std::vector<TransactionFrameBasePtr>& txs,
+ applyTransaction(TransactionFrameBasePtr& tx,
+ AbstractLedgerTxn& ltx,
+ TransactionResultSet& txResultSet,
+ std::unique_ptr<LedgerCloseMeta> const& ledgerCloseMeta,
+ int& index);
+
+ void
+ applyTransactions(std::vector<TransactionFrameBasePtr>& commutativeTxs,
+ std::vector<TransactionFrameBasePtr>& noncommutativeTxs,
AbstractLedgerTxn& ltx, TransactionResultSet& txResultSet,
std::unique_ptr<LedgerCloseMeta> const& ledgerCloseMeta);
diff --git a/src/ledger/LedgerTxn.cpp b/src/ledger/LedgerTxn.cpp
index b362afe2..693e7b2a 100644
--- a/src/ledger/LedgerTxn.cpp
+++ b/src/ledger/LedgerTxn.cpp
#ifdef BEST_OFFER_DEBUGGING
void
@@ -468,6 +456,10 @@ LedgerTxn::Impl::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
: nullptr;
updateWorstBestOffer(wboIter.assets(), descPtr);
}
+
+ //gather speedex ioc offers
+
+ mSpeedexIOCOrderbooks.commitChild(mChild -> getSpeedexIOCOffers());
}
catch (std::exception& e)
{
@@ -1434,6 +1426,32 @@ LedgerTxn::Impl::load(LedgerTxn& self, InternalLedgerKey const& key)
return ltxe;
}
+std::shared_ptr<const LedgerEntry>
+LedgerTxn::loadSnapshotEntry(LedgerKey const& key) const {
+ return mImpl -> loadSnapshotEntry(key);
+}
+
+std::shared_ptr<const LedgerEntry>
+LedgerTxn::Impl::loadSnapshotEntry(LedgerKey const& key) const
+{
+ //maintain same access validity invariants on snapshots as on regular entries
+ //Does not check if there is a child -- child snapshots are the same as parent snapshots,
+ //as snapshots are not modified until root ledger commits.
+ throwIfSealed();
+
+ auto snapshotIter = mSnapshots.find(key);
+ if (snapshotIter != mSnapshots.end()) {
+ return (snapshotIter->second);
+ }
+
+ auto parentSnapshot = mParent.loadSnapshotEntry(key);
+ if (parentSnapshot) {
+ mSnapshots.emplace(key, parentSnapshot);
+ }
+ return parentSnapshot;
+
+}
+
std::map<AccountID, std::vector<LedgerTxnEntry>>
LedgerTxn::loadAllOffers()
{
@@ -1617,6 +1635,30 @@ LedgerTxn::Impl::loadOffersByAccountAndAsset(LedgerTxn& self,
}
}
+void
+LedgerTxn::addSpeedexIOCOffer(AssetPair assetPair, const IOCOffer& offer) {
+ getImpl() -> addSpeedexIOCOffer(assetPair, offer);
+}
+
+void
+LedgerTxn::Impl::addSpeedexIOCOffer(AssetPair assetPair, const IOCOffer& offer) {
+ throwIfChild();
+ throwIfSealed();
+ mSpeedexIOCOrderbooks.addOffer(assetPair, offer);
+}
+
+IOCOrderbookManager &
+LedgerTxn::getSpeedexIOCOffers() {
+ return getImpl() -> getSpeedexIOCOffers();
+}
+
+IOCOrderbookManager &
+LedgerTxn::Impl::getSpeedexIOCOffers() {
+ throwIfChild();
+ //TODO some check to see whether parent has any offers that aren't included here?
+ return mSpeedexIOCOrderbooks;
+}
+
std::vector<LedgerTxnEntry>
LedgerTxn::loadPoolShareTrustLinesByAccountAndAsset(AccountID const& account,
Asset const& asset)
@@ -1713,7 +1755,9 @@ LedgerTxn::Impl::rollback()
}
mEntry.clear();
+ mSnapshots.clear();
mMultiOrderBook.clear();
+ mSpeedexIOCOrderbooks.clear();
mActive.clear();
mActiveHeader.reset();
mIsSealed = true;
@@ -1813,6 +1857,12 @@ LedgerTxn::dropLiquidityPools()
throw std::runtime_error("called dropLiquidityPools on non-root LedgerTxn");
}
+void
+LedgerTxn::dropSpeedexConfigs()
+{
+ throw std::runtime_error("called dropSpeedexConfigs on non-root LedgerTxn");
+}
+
double
LedgerTxn::getPrefetchHitRate() const
{
@@ -2253,6 +2303,7 @@ LedgerTxnRoot::Impl::Impl(Database& db, size_t entryCacheSize,
, mDatabase(db)
, mHeader(std::make_unique<LedgerHeader>())
, mEntryCache(entryCacheSize)
+ , mSnapshotCache(entryCacheSize)
, mBulkLoadBatchSize(prefetchBatchSize)
, mChild(nullptr)
#ifdef BEST_OFFER_DEBUGGING
@@ -2314,6 +2365,15 @@ LedgerTxnRoot::Impl::throwIfChild() const
}
}
+void
+LedgerTxnRoot::Impl::clearAllCaches() const
+{
+ mEntryCache.clear();
+ mBestOffers.clear();
+ mSnapshotCache.clear();
+}
+
+
void
LedgerTxnRoot::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
{
@@ -2359,6 +2419,9 @@ BulkLedgerEntryChangeAccumulator::accumulate(EntryIterator const& iter)
case LIQUIDITY_POOL:
accum(iter, mLiquidityPoolToUpsert, mLiquidityPoolToDelete);
break;
+ case SPEEDEX_CONFIG:
+ accum(iter, mSpeedexConfigToUpsert, mSpeedexConfigToDelete);
+ break;
default:
abort();
}
@@ -2441,6 +2504,18 @@ LedgerTxnRoot::Impl::bulkApply(BulkLedgerEntryChangeAccumulator& bleca,
bulkDeleteLiquidityPool(deleteLiquidityPool, cons);
deleteLiquidityPool.clear();
}
+ auto& upsertSpeedexConfig = bleca.getSpeedexConfigToUpsert();
+ if (upsertSpeedexConfig.size() > bufferThreshold)
+ {
+ bulkUpsertSpeedexConfig(upsertSpeedexConfig);
+ upsertSpeedexConfig.clear();
+ }
+ auto& deleteSpeedexConfig = bleca.getSpeedexConfigToDelete();
+ if (deleteSpeedexConfig.size() > bufferThreshold)
+ {
+ bulkDeleteSpeedexConfig(deleteSpeedexConfig, cons);
+ deleteSpeedexConfig.clear();
+ }
}
void
@@ -2490,6 +2567,7 @@ LedgerTxnRoot::Impl::commitChild(EntryIterator iter, LedgerTxnConsistency cons)
// Clearing the cache does not throw
mBestOffers.clear();
mEntryCache.clear();
+ mSnapshotCache.clear();
// std::unique_ptr<...>::reset does not throw
mTransaction.reset();
@@ -2626,6 +2704,12 @@ LedgerTxnRoot::dropLiquidityPools()
mImpl->dropLiquidityPools();
}
+void
+LedgerTxnRoot::dropSpeedexConfigs()
+{
+ mImpl -> dropSpeedexConfigs();
+}
+
uint32_t
LedgerTxnRoot::prefetch(UnorderedSet<LedgerKey> const& keys)
{
@@ -2644,6 +2728,7 @@ LedgerTxnRoot::Impl::prefetch(UnorderedSet<LedgerKey> const& keys)
UnorderedSet<LedgerKey> data;
UnorderedSet<LedgerKey> claimablebalance;
UnorderedSet<LedgerKey> liquiditypool;
+ UnorderedSet<LedgerKey> speedexConfig;
auto cacheResult =
[&](UnorderedMap<LedgerKey, std::shared_ptr<LedgerEntry const>> const&
@@ -2715,6 +2800,14 @@ LedgerTxnRoot::Impl::prefetch(UnorderedSet<LedgerKey> const& keys)
liquiditypool.clear();
}
break;
+ case SPEEDEX_CONFIG:
+ insertIfNotLoaded(speedexConfig, key);
+ if (speedexConfig.size() == mBulkLoadBatchSize)
+ {
+ cacheResult(bulkLoadSpeedexConfig(speedexConfig));
+ speedexConfig.clear();
+ }
+ break;
}
}
@@ -2725,6 +2818,7 @@ LedgerTxnRoot::Impl::prefetch(UnorderedSet<LedgerKey> const& keys)
cacheResult(bulkLoadData(data));
cacheResult(bulkLoadClaimableBalance(claimablebalance));
cacheResult(bulkLoadLiquidityPool(liquiditypool));
+ cacheResult(bulkLoadSpeedexConfig(speedexConfig));
return total;
}
@@ -3217,19 +3311,19 @@ LedgerTxnRoot::Impl::getNewestVersion(InternalLedgerKey const& gkey) const
case LIQUIDITY_POOL:
entry = loadLiquidityPool(key);
break;
+ case SPEEDEX_CONFIG:
+ //Note that the mocking of the config makes it as though
+ // logically, there exists a speedex config at genesis.
+ // This breaks tests that assume keys don't exist until
+ // they're created.
+ entry = loadSpeedexConfig(key);
+ break;
default:
throw std::runtime_error("Unknown key type");