-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathLedgerTxn.cpp
More file actions
3776 lines (3378 loc) · 108 KB
/
LedgerTxn.cpp
File metadata and controls
3776 lines (3378 loc) · 108 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 2018 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 "ledger/LedgerTxn.h"
#include "bucket/BucketManager.h"
#include "bucket/SearchableBucketList.h"
#include "crypto/KeyUtils.h"
#include "database/Database.h"
#include "ledger/InMemorySorobanState.h"
#include "ledger/LedgerManager.h"
#include "ledger/LedgerRange.h"
#include "ledger/LedgerTxnEntry.h"
#include "ledger/LedgerTxnHeader.h"
#include "ledger/LedgerTxnImpl.h"
#include "ledger/LedgerTypeUtils.h"
#include "main/Application.h"
#include "transactions/TransactionUtils.h"
#include "util/GlobalChecks.h"
#include "util/UnorderedSet.h"
#include "util/types.h"
#include "xdr/Stellar-ledger-entries.h"
#include <Tracy.hpp>
#include <soci.h>
#include <algorithm>
#include <stdexcept>
namespace stellar
{
LedgerEntryPtr
LedgerEntryPtr::Init(std::shared_ptr<InternalLedgerEntry> const& lePtr)
{
return {lePtr, EntryPtrState::INIT};
}
LedgerEntryPtr
LedgerEntryPtr::Live(std::shared_ptr<InternalLedgerEntry> const& lePtr)
{
return {lePtr, EntryPtrState::LIVE};
}
LedgerEntryPtr
LedgerEntryPtr::Delete()
{
return {nullptr, EntryPtrState::DELETED};
}
LedgerEntryPtr::LedgerEntryPtr(
std::shared_ptr<InternalLedgerEntry> const& lePtr, EntryPtrState state)
: mEntryPtr(lePtr), mState(state)
{
if (lePtr)
{
if (isDeleted())
{
throw std::runtime_error("DELETED LedgerEntryPtr is not null");
}
}
else
{
if (isInit() || isLive())
{
throw std::runtime_error("INIT/LIVE LedgerEntryPtr is null");
}
}
}
InternalLedgerEntry&
LedgerEntryPtr::operator*() const
{
if (!mEntryPtr)
{
throw std::runtime_error("cannot dereference null mEntryPtr");
}
return *mEntryPtr;
}
InternalLedgerEntry*
LedgerEntryPtr::operator->() const
{
if (!mEntryPtr)
{
throw std::runtime_error("cannot dereference null mEntryPtr");
}
return mEntryPtr.get();
}
std::shared_ptr<InternalLedgerEntry>
LedgerEntryPtr::get() const
{
return mEntryPtr;
}
void
LedgerEntryPtr::mergeFrom(LedgerEntryPtr const& entryPtr)
{
switch (mState)
{
case EntryPtrState::INIT:
{
if (entryPtr.isDeleted())
{
// This isn't possible because we don't call mergeFrom in this case.
// Instead, the init entry is annihilated by the delete
throw std::runtime_error("cannot delete non-live entry");
}
}
break;
case EntryPtrState::LIVE:
{
// cannot commit an init entry into a live entry (If the parent entry is
// live, the child could not have created the same entry)
if (entryPtr.isInit())
{
throw std::runtime_error(
"cannot commit a child init entry into a parent live entry");
}
// propagate state
mState = entryPtr.getState();
}
break;
case EntryPtrState::DELETED:
{
switch (entryPtr.getState())
{
case EntryPtrState::INIT:
mState = EntryPtrState::LIVE;
break;
case EntryPtrState::LIVE:
throw std::runtime_error("cannot set deleted entry to live");
case EntryPtrState::DELETED:
throw std::runtime_error("cannot delete deleted entry");
}
break;
}
default:
throw std::runtime_error("unknown EntryPtrState");
}
// std::shared_ptr<...>::operator= does not throw
mEntryPtr = entryPtr.get();
}
EntryPtrState
LedgerEntryPtr::getState() const
{
return mState;
}
bool
LedgerEntryPtr::isInit() const
{
return mState == EntryPtrState::INIT;
}
bool
LedgerEntryPtr::isLive() const
{
return mState == EntryPtrState::LIVE;
}
bool
LedgerEntryPtr::isDeleted() const
{
return mState == EntryPtrState::DELETED;
}
std::optional<LedgerEntry>
RestoredEntries::getEntryOpt(LedgerKey const& key) const
{
auto it0 = hotArchive.find(key);
auto it1 = liveBucketList.find(key);
// No key should be in both maps.
releaseAssertOrThrow(it0 == hotArchive.end() ||
it1 == liveBucketList.end());
if (it0 != hotArchive.end())
{
return it0->second;
}
else if (it1 != liveBucketList.end())
{
return it1->second;
}
else
{
return std::nullopt;
}
}
bool
RestoredEntries::entryWasRestored(LedgerKey const& k) const
{
return entryWasRestoredFromMap(k, liveBucketList) ||
entryWasRestoredFromMap(k, hotArchive);
}
bool
RestoredEntries::entryWasRestoredFromMap(
LedgerKey const& k, UnorderedMap<LedgerKey, LedgerEntry> const& map)
{
auto it = map.find(k);
if (it != map.end())
{
if (isSorobanEntry(k))
{
// Check invariant: any soroban entry in either restore map should
// have an accompanying TTL entry.
auto ttlkey = getTTLKey(k);
releaseAssert(map.find(ttlkey) != map.end());
}
return true;
}
return false;
}
void
RestoredEntries::addRestoreToMap(LedgerKey const& key, LedgerEntry const& entry,
LedgerKey const& ttlKey,
LedgerEntry const& ttlEntry,
UnorderedMap<LedgerKey, LedgerEntry>& map)
{
releaseAssert(isSorobanEntry(key));
releaseAssert(ttlKey.type() == TTL);
auto [_i, inserted] = map.emplace(key, entry);
releaseAssert(inserted);
auto [_j, ttlInserted] = map.emplace(ttlKey, ttlEntry);
releaseAssert(ttlInserted);
}
void
RestoredEntries::addHotArchiveRestore(LedgerKey const& key,
LedgerEntry const& entry,
LedgerKey const& ttlKey,
LedgerEntry const& ttlEntry)
{
addRestoreToMap(key, entry, ttlKey, ttlEntry, hotArchive);
}
void
RestoredEntries::addLiveBucketlistRestore(LedgerKey const& key,
LedgerEntry const& entry,
LedgerKey const& ttlKey,
LedgerEntry const& ttlEntry)
{
addRestoreToMap(key, entry, ttlKey, ttlEntry, liveBucketList);
}
void
RestoredEntries::addRestoresFrom(RestoredEntries const& other,
bool allowDuplicates)
{
ZoneScoped;
// This method is called from three different call sites. In 2 of them it is
// correct to assert that each restore is new/disjoint from any existing
// restore:
//
// - In the first call site we're committing per-op restores back to the
// per-thread maps. In this case a restore would only have _happened_
// during the op if the thread had not previously done a restore; if
// there had already been a restore, the previous restore should have
// inhibited the subsequent attempted restore. If it didn't there's a
// bug somewhere!
//
// - In the second call site we're committing per-thread restores back to
// the shared (cross-thread) map. In this case the restore, being a
// write, would have been clustered by all other ops that write to that
// entry -- it'd be a concurrency bug if not! -- so there should not be
// any other restores of the same entry from other threads.
//
// In the third place we're committing from an ltx to its parent, and the
// ltx was actually starting with a copy of the restored-maps from the
// parent, so there are going to be duplicates. We allow duplicates in that
// case.
for (auto kvp : other.hotArchive)
{
auto [_, inserted] = hotArchive.emplace(kvp.first, kvp.second);
releaseAssert(inserted || allowDuplicates);
}
for (auto kvp : other.liveBucketList)
{
auto [_, inserted] = liveBucketList.emplace(kvp.first, kvp.second);
releaseAssert(inserted || allowDuplicates);
}
}
bool
operator==(OfferDescriptor const& lhs, OfferDescriptor const& rhs)
{
return lhs.price == rhs.price && lhs.offerID == rhs.offerID;
}
bool
IsBetterOfferComparator::operator()(OfferDescriptor const& lhs,
OfferDescriptor const& rhs) const
{
return isBetterOffer(lhs, rhs);
}
bool
operator==(AssetPair const& lhs, AssetPair const& rhs)
{
return lhs.buying == rhs.buying && lhs.selling == rhs.selling;
}
size_t
AssetPairHash::operator()(AssetPair const& key) const
{
std::hash<Asset> hashAsset;
return hashAsset(key.buying) ^ (hashAsset(key.selling) << 1);
}
#ifdef BEST_OFFER_DEBUGGING
void
compareOffers(std::shared_ptr<LedgerEntry const> debugBest,
std::shared_ptr<LedgerEntry const> best)
{
if ((bool)debugBest ^ (bool)best)
{
if (best)
{
printErrorAndAbort("best offer not null when it should be");
}
else
{
printErrorAndAbort("best offer null when it should not be");
}
}
if (best && *best != *debugBest)
{
printErrorAndAbort("best offer mismatch");
}
}
#endif
// Implementation of AbstractLedgerTxnParent --------------------------------
AbstractLedgerTxnParent::~AbstractLedgerTxnParent()
{
}
// Implementation of EntryIterator --------------------------------------------
EntryIterator::EntryIterator(std::unique_ptr<AbstractImpl>&& impl)
: mImpl(std::move(impl))
{
}
EntryIterator::EntryIterator(EntryIterator&& other)
: mImpl(std::move(other.mImpl))
{
}
EntryIterator::EntryIterator(EntryIterator const& other)
: mImpl(other.mImpl->clone())
{
}
std::unique_ptr<EntryIterator::AbstractImpl> const&
EntryIterator::getImpl() const
{
if (!mImpl)
{
throw std::runtime_error("Iterator is empty");
}
return mImpl;
}
EntryIterator&
EntryIterator::operator++()
{
getImpl()->advance();
return *this;
}
EntryIterator::
operator bool() const
{
return !getImpl()->atEnd();
}
InternalLedgerEntry const&
EntryIterator::entry() const
{
return getImpl()->entry();
}
LedgerEntryPtr const&
EntryIterator::entryPtr() const
{
return getImpl()->entryPtr();
}
bool
EntryIterator::entryExists() const
{
return getImpl()->entryExists();
}
InternalLedgerKey const&
EntryIterator::key() const
{
return getImpl()->key();
}
// Implementation of AbstractLedgerTxn --------------------------------------
AbstractLedgerTxn::~AbstractLedgerTxn()
{
}
// Implementation of LedgerTxn ----------------------------------------------
LedgerTxn::LedgerTxn(AbstractLedgerTxnParent& parent,
bool shouldUpdateLastModified, TransactionMode mode)
: mImpl(
std::make_unique<Impl>(*this, parent, shouldUpdateLastModified, mode))
{
}
LedgerTxn::LedgerTxn(LedgerTxn& parent, bool shouldUpdateLastModified,
TransactionMode mode)
: LedgerTxn((AbstractLedgerTxnParent&)parent, shouldUpdateLastModified,
mode)
{
}
LedgerTxn::Impl::Impl(LedgerTxn& self, AbstractLedgerTxnParent& parent,
bool shouldUpdateLastModified, TransactionMode mode)
: mParent(parent)
, mChild(nullptr)
, mHeader(std::make_unique<LedgerHeader>(mParent.getHeader()))
, mShouldUpdateLastModified(shouldUpdateLastModified)
, mIsSealed(false)
, mConsistency(LedgerTxnConsistency::EXACT)
, mActiveThreadId(std::this_thread::get_id())
{
for (auto const& [key, entry] : mParent.getRestoredHotArchiveKeys())
{
mRestoredEntries.hotArchive.emplace(key, entry);
}
for (auto const& [key, entry] : mParent.getRestoredLiveBucketListKeys())
{
mRestoredEntries.liveBucketList.emplace(key, entry);
}
mParent.addChild(self, mode);
}
LedgerTxn::~LedgerTxn()
{
if (mImpl)
{
rollback();
}
}
std::unique_ptr<LedgerTxn::Impl> const&
LedgerTxn::getImpl() const
{
if (!mImpl)
{
throw std::runtime_error("LedgerTxn was handled");
}
return mImpl;
}
void
LedgerTxn::addChild(AbstractLedgerTxn& child, TransactionMode mode)
{
getImpl()->addChild(child);
}
void
LedgerTxn::Impl::addChild(AbstractLedgerTxn& child)
{
abortIfWrongThread("addChild");
throwIfSealed();
throwIfChild();
mChild = &child;
try
{
for (auto const& kv : mActive)
{
updateEntryIfRecorded(kv.first, false);
}
}
catch (std::exception& e)
{
printErrorAndAbort("fatal error during add child to LedgerTxn: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error during add child to LedgerTxn");
}
// std::set<...>::clear is noexcept
mActive.clear();
// std::shared_ptr<...>::reset is noexcept
mActiveHeader.reset();
}
void
LedgerTxn::Impl::throwIfChild() const
{
if (mChild)
{
throw std::runtime_error("LedgerTxn has child");
}
}
void
LedgerTxn::Impl::throwIfSealed() const
{
if (mIsSealed)
{
throw std::runtime_error("LedgerTxn is sealed");
}
}
void
LedgerTxn::Impl::abortIfWrongThread(const char* functionName) const
{
if (mActiveThreadId != std::this_thread::get_id())
{
printErrorAndAbort(
"LedgerTxn is accessed from wrong thread in function: ",
functionName);
}
}
void
LedgerTxn::Impl::throwIfNotExactConsistency() const
{
if (mConsistency != LedgerTxnConsistency::EXACT)
{
throw std::runtime_error("LedgerTxn consistency level is not exact");
}
}
void
LedgerTxn::Impl::throwIfErasingConfig(InternalLedgerKey const& key) const
{
abortIfWrongThread("throwIfErasingConfig");
if (key.type() == InternalLedgerEntryType::LEDGER_ENTRY &&
key.ledgerKey().type() == CONFIG_SETTING)
{
throw std::runtime_error("Configuration settings cannot be erased.");
}
}
void
LedgerTxn::commit() noexcept
{
getImpl()->commit();
mImpl.reset();
}
void
LedgerTxn::Impl::commit() noexcept
{
abortIfWrongThread("commit");
maybeUpdateLastModifiedThenInvokeThenSeal([&](EntryMap const& entries) {
// getEntryIterator has the strong exception safety guarantee
// commitChild has the strong exception safety guarantee
mParent.commitChild(getEntryIterator(entries), mRestoredEntries,
mConsistency);
});
}
void
LedgerTxn::commitChild(EntryIterator iter,
RestoredEntries const& restoredEntries,
LedgerTxnConsistency cons) noexcept
{
getImpl()->commitChild(std::move(iter), restoredEntries, cons);
}
static LedgerTxnConsistency
joinConsistencyLevels(LedgerTxnConsistency c1, LedgerTxnConsistency c2)
{
switch (c1)
{
case LedgerTxnConsistency::EXACT:
return c2;
case LedgerTxnConsistency::EXTRA_DELETES:
return LedgerTxnConsistency::EXTRA_DELETES;
default:
abort();
}
}
void
LedgerTxn::Impl::commitChild(EntryIterator iter,
RestoredEntries const& restoredEntries,
LedgerTxnConsistency cons) noexcept
{
abortIfWrongThread("commitChild");
// Assignment of xdrpp objects does not have the strong exception safety
// guarantee, so use std::unique_ptr<...>::swap to achieve it
auto childHeader = std::make_unique<LedgerHeader>(mChild->getHeader());
mConsistency = joinConsistencyLevels(mConsistency, cons);
if (!mActive.empty())
{
printErrorAndAbort(
"Attempting to commit a child while parent has active entries");
}
try
{
for (; (bool)iter; ++iter)
{
updateEntry(iter.key(), /* keyHint */ nullptr, iter.entryPtr(),
/* effectiveActive */ false);
}
// We will show that the following update procedure leaves the self
// worst best offer map in a correct state.
//
// Fix an asset pair P in the child worst best offer map, and let V be
// the value associated with P. By definition, every offer in
// LtEq[Self, P, V] has been recorded in the child.
//
// Note that LtEq[Self, P, V] contains (among other things):
//
// - Every offer in LtEq[Parent, P, V] that was not recorded in self
//
// - Every offer in LtEq[Parent, P, V] that was recorded in self and was
// not erased, not modified to a different asset pair, and not
// modified to be worse than V
//
// and does not contain (among other things):
//
// - Every offer in LtEq[Parent, P, V] that was recorded in self and
// erased, modified to a different asset pair, or modified to be worse
// than V
//
// The union of these three groups is LtEq[Parent, P, V]. Then
// we can say that every offer in LtEq[Parent, P, V] is either
// in LtEq[Self, P, V] or is recorded in self. But because every
// offer in LtEq[Self, P, V] is recorded in child, after the
// commit we know that every offer in LtEq[Parent, P, V] must be
// recorded in self.
//
// In the above lemma, we proved that LtEq[Parent, P, V] must be
// recorded in self after the commit. But it is possible that P was in
// the self worst best offer map before the commit, with associated
// value W. In that case, we also know that every offer in
// NotWorstThan[Parent, P, W] is recorded in self after the commit
// because they were already recorded in self before the commit. It is
// clear from the definition of LtEq that
//
// - LtEq[Parent, P, V] contains LtEq[Parent, P, W] if W <= V, or
//
// - LtEq[Parent, P, W] contains LtEq[Parent, P, V] if V <= W
//
// (it is possible that both statements are true if V = W).
//
// Then we can conclude that if
//
// Z = (W <= V) ? V : W
//
// then every offer in LtEq[Parent, P, Z] is recorded in self after the
// commit.
//
// It follows from these two results that the following update procedure
// is correct for each asset pair P in the child worst best offer map
// with associated value V:
//
// - If P is not in the self worst best offer map, then insert (P, V)
// into the self worst best offer map
//
// - If P is in the self worst best offer map with associated value W,
// then update (P, W) to (P, V) if V > W and do nothing otherwise
//
// Fix an asset pair P that is not in the child worst best offer map. In
// this case, the child provides no new information. If P is in the self
// worst best offer map with associated value W, then we know that every
// offer in LtEq[Self, P, W] was recorded in self prior to the
// commit so they still will be recorded in self after the commit. If P
// is also not in the self worst best offer map, then there is no claim
// about the offers with asset pair P that exist in parent and have been
// recorded in self both before and after the commit. In either case,
// there is no need to update the self worst best offer map.
mChild->forAllWorstBestOffers(
[&](Asset const& buying, Asset const& selling,
std::shared_ptr<OfferDescriptor const>& desc) {
updateWorstBestOffer(AssetPair{buying, selling}, desc);
});
}
catch (std::exception& e)
{
printErrorAndAbort("fatal error during commit to LedgerTxn: ",
e.what());
}
catch (...)
{
printErrorAndAbort("unknown fatal error during commit to LedgerTxn");
}
// The child will have started with a copy of the parents mRestoredEntries,
// so we can see duplicates here, but duplicate restores would've been
// caught during restoration in the restoreFrom* functions.
mRestoredEntries.addRestoresFrom(restoredEntries, /*allowDuplicates=*/true);
// std::unique_ptr<...>::swap does not throw
mHeader.swap(childHeader);
mChild = nullptr;
}
LedgerTxnEntry
LedgerTxn::create(InternalLedgerEntry const& entry)
{
return getImpl()->create(*this, entry);
}
LedgerTxnEntry
LedgerTxn::Impl::create(LedgerTxn& self, InternalLedgerEntry const& entry)
{
abortIfWrongThread("create");
throwIfSealed();
throwIfChild();
auto key = entry.toKey();
if (getNewestVersion(key))
{
throw std::runtime_error("Key already exists");
}
auto current = std::make_shared<InternalLedgerEntry>(entry);
auto impl = LedgerTxnEntry::makeSharedImpl(self, *current);
// Set the key to active before constructing the LedgerTxnEntry, as this
// can throw and the LedgerTxnEntry destructor requires that mActive
// contains key. LedgerTxnEntry constructor does not throw so this is
// still exception safe.
mActive.emplace(key, toEntryImplBase(impl));
LedgerTxnEntry ltxe(impl);
auto it = mEntry.end(); // hint that key is not in mEntry
// If the key currently exists in mEntry as a DELETED entry, the new state
// after this INIT entry is merged with the DELETED will be a LIVE. This is
// because the entry would have been a LIVE before the delete. If it were an
// INIT instead, the key would've been annihilated.
updateEntry(key, &it, LedgerEntryPtr::Init(current),
/* effectiveActive */ true);
return ltxe;
}
void
LedgerTxn::createWithoutLoading(InternalLedgerEntry const& entry)
{
getImpl()->createWithoutLoading(entry);
}
void
LedgerTxn::Impl::createWithoutLoading(InternalLedgerEntry const& entry)
{
abortIfWrongThread("createWithoutLoading");
throwIfSealed();
throwIfChild();
auto key = entry.toKey();
auto iter = mActive.find(key);
if (iter != mActive.end())
{
throw std::runtime_error("Key is already active");
}
// If the key currently exists in mEntry as a DELETED entry, the new state
// after this INIT entry is merged with the DELETED will be a LIVE. This is
// because the entry would have been a LIVE before the delete. If it were an
// INIT instead, the key would've been annihilated.
updateEntry(
key, /* keyHint */ nullptr,
LedgerEntryPtr::Init(std::make_shared<InternalLedgerEntry>(entry)),
/* effectiveActive */ false);
}
void
LedgerTxn::updateWithoutLoading(InternalLedgerEntry const& entry)
{
getImpl()->updateWithoutLoading(entry);
}
void
LedgerTxn::Impl::updateWithoutLoading(InternalLedgerEntry const& entry)
{
abortIfWrongThread("updateWithoutLoading");
throwIfSealed();
throwIfChild();
auto key = entry.toKey();
auto iter = mActive.find(key);
if (iter != mActive.end())
{
throw std::runtime_error("Key is already active");
}
updateEntry(
key, /* keyHint */ nullptr,
LedgerEntryPtr::Live(std::make_shared<InternalLedgerEntry>(entry)),
/* effectiveActive */ false);
}
void
LedgerTxn::deactivate(InternalLedgerKey const& key)
{
getImpl()->deactivate(key);
}
void
LedgerTxn::Impl::deactivate(InternalLedgerKey const& key)
{
auto iter = mActive.find(key);
if (iter == mActive.end())
{
throw std::runtime_error("Key is not active");
}
updateEntryIfRecorded(key, false);
// C++14 requirements for exception safety of containers guarantee that
// erase(iter) does not throw
mActive.erase(iter);
}
void
LedgerTxn::deactivateHeader()
{
getImpl()->deactivateHeader();
}
void
LedgerTxn::Impl::deactivateHeader()
{
if (!mActiveHeader)
{
throw std::runtime_error("LedgerTxnHeader is not active");
}
mActiveHeader.reset();
}
void
LedgerTxn::erase(InternalLedgerKey const& key)
{
getImpl()->erase(key);
}
void
LedgerTxn::Impl::erase(InternalLedgerKey const& key)
{
abortIfWrongThread("erase");
throwIfSealed();
throwIfChild();
auto newest = getNewestVersionEntryMap(key);
if (!newest.first)
{
throw std::runtime_error("Key does not exist");
}
throwIfErasingConfig(key);
auto activeIter = mActive.find(key);
bool isActive = activeIter != mActive.end();
updateEntry(key, &newest.second, LedgerEntryPtr::Delete(), false);
// Note: Cannot throw after this point because the entry will not be
// deactivated in that case
// C++14 requirements for exception safety of containers guarantee that
// erase(iter) does not throw
if (isActive)
{
mActive.erase(activeIter);
}
}
void
LedgerTxn::markRestoredFromHotArchive(LedgerEntry const& ledgerEntry,
LedgerEntry const& ttlEntry)
{
getImpl()->markRestoredFromHotArchive(ledgerEntry, ttlEntry);
}
void
LedgerTxn::Impl::markRestoredFromHotArchive(LedgerEntry const& ledgerEntry,
LedgerEntry const& ttlEntry)
{
abortIfWrongThread("markRestoredFromHotArchive");
throwIfSealed();
throwIfChild();
if (!isPersistentEntry(ledgerEntry.data))
{
throw std::runtime_error("Key type not supported in Hot Archive");
}
// Mark the keys as restored
auto addKey = [this](LedgerEntry const& entry) {
auto [_, inserted] =
mRestoredEntries.hotArchive.emplace(LedgerEntryKey(entry), entry);
if (!inserted)
{
throw std::runtime_error("Key already removed from hot archive");
}
};
addKey(ledgerEntry);
addKey(ttlEntry);
}
LedgerTxnEntry
LedgerTxn::restoreFromLiveBucketList(LedgerEntry const& entry, uint32_t ttl)
{
return getImpl()->restoreFromLiveBucketList(*this, entry, ttl);
}
LedgerTxnEntry
LedgerTxn::Impl::restoreFromLiveBucketList(LedgerTxn& self,
LedgerEntry const& entry,
uint32_t ttl)
{
abortIfWrongThread("restoreFromLiveBucketList");
throwIfSealed();
throwIfChild();
auto key = LedgerEntryKey(entry);
if (!isPersistentEntry(key))
{
throw std::runtime_error("Key type not supported for restoration");
}
auto ttlKey = getTTLKey(key);
// Note: key should have already been loaded via loadWithoutRecord by
// caller, so this read should already be in the cache.
auto ttlLtxe = load(self, ttlKey);
if (!ttlLtxe)
{
throw std::runtime_error("Entry restored from live BucketList but does "
"not exist in the live BucketList.");
}
ttlLtxe.current().data.ttl().liveUntilLedgerSeq = ttl;
// Mark the keys as restored
auto addEntry = [this](LedgerEntry const& entry, LedgerKey const& key) {
auto [_, inserted] =
mRestoredEntries.liveBucketList.emplace(key, entry);
if (!inserted)
{
throw std::runtime_error(
"Key already restored from Live BucketList");
}
};
addEntry(entry, key);
addEntry(ttlLtxe.current(), ttlKey);
return ttlLtxe;
}
void
LedgerTxn::eraseWithoutLoading(InternalLedgerKey const& key)
{
getImpl()->eraseWithoutLoading(key);
}
void
LedgerTxn::Impl::eraseWithoutLoading(InternalLedgerKey const& key)
{
abortIfWrongThread("eraseWithoutLoading");
throwIfSealed();
throwIfChild();
throwIfErasingConfig(key);
auto activeIter = mActive.find(key);
bool isActive = activeIter != mActive.end();
updateEntry(key, /* keyHint */ nullptr, LedgerEntryPtr::Delete(), false);
// Note: Cannot throw after this point because the entry will not be
// deactivated in that case
if (isActive)
{
// C++14 requirements for exception safety of containers guarantee that
// erase(iter) does not throw
mActive.erase(activeIter);
}
mConsistency = LedgerTxnConsistency::EXTRA_DELETES;
}
UnorderedMap<LedgerKey, LedgerEntry>
LedgerTxn::getAllOffers()
{