-
Notifications
You must be signed in to change notification settings - Fork 973
/
LedgerManagerImpl.cpp
1766 lines (1586 loc) · 60.1 KB
/
LedgerManagerImpl.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "ledger/LedgerManagerImpl.h"
#include "bucket/BucketList.h"
#include "bucket/BucketManager.h"
#include "catchup/AssumeStateWork.h"
#include "crypto/Hex.h"
#include "crypto/KeyUtils.h"
#include "crypto/SHA.h"
#include "crypto/SecretKey.h"
#include "database/Database.h"
#include "herder/Herder.h"
#include "herder/HerderPersistence.h"
#include "herder/HerderUtils.h"
#include "herder/LedgerCloseData.h"
#include "herder/TxSetFrame.h"
#include "herder/Upgrades.h"
#include "history/HistoryManager.h"
#include "ledger/FlushAndRotateMetaDebugWork.h"
#include "ledger/LedgerHeaderUtils.h"
#include "ledger/LedgerRange.h"
#include "ledger/LedgerTxn.h"
#include "ledger/LedgerTxnEntry.h"
#include "ledger/LedgerTxnHeader.h"
#include "main/Application.h"
#include "main/Config.h"
#include "main/ErrorMessages.h"
#include "overlay/OverlayManager.h"
#include "transactions/OperationFrame.h"
#include "transactions/TransactionFrameBase.h"
#include "transactions/TransactionMetaFrame.h"
#include "transactions/TransactionSQL.h"
#include "transactions/TransactionUtils.h"
#include "util/DebugMetaUtils.h"
#include "util/Fs.h"
#include "util/GlobalChecks.h"
#include "util/LogSlowExecution.h"
#include "util/Logging.h"
#include "util/ProtocolVersion.h"
#include "util/XDRCereal.h"
#include "util/XDROperators.h"
#include "util/XDRStream.h"
#include "work/WorkScheduler.h"
#include <fmt/format.h>
#include "xdr/Stellar-ledger.h"
#include "xdr/Stellar-transaction.h"
#include "xdrpp/printer.h"
#include "xdrpp/types.h"
#include "medida/buckets.h"
#include "medida/counter.h"
#include "medida/meter.h"
#include "medida/metrics_registry.h"
#include "medida/timer.h"
#include <Tracy.hpp>
#include <chrono>
#include <numeric>
#include <regex>
#include <sstream>
#include <stdexcept>
#include <thread>
/*
The ledger module:
1) gets the externalized tx set
2) applies this set to the last closed ledger
3) sends the changed entries to the BucketList
4) saves the changed entries to SQL
5) saves the ledger hash and header to SQL
6) sends the new ledger hash and the tx set to the history
7) sends the new ledger hash and header to the Herder
catching up to network:
1) Wait for SCP to tell us what the network is on now
2) Pull history log or static deltas from history archive
3) Replay or force-apply deltas, depending on catchup mode
*/
using namespace std;
namespace stellar
{
const uint32_t LedgerManager::GENESIS_LEDGER_SEQ = 1;
const uint32_t LedgerManager::GENESIS_LEDGER_VERSION = 0;
const uint32_t LedgerManager::GENESIS_LEDGER_BASE_FEE = 100;
const uint32_t LedgerManager::GENESIS_LEDGER_BASE_RESERVE = 100000000;
const uint32_t LedgerManager::GENESIS_LEDGER_MAX_TX_SIZE = 100;
const int64_t LedgerManager::GENESIS_LEDGER_TOTAL_COINS = 1000000000000000000;
void
SorobanLedgerMetrics::accumulateLedgerCpuInsn(uint64_t cpuInsn)
{
mLedgerCpuInsn += cpuInsn;
}
void
SorobanLedgerMetrics::accumulateLedgerReadEntry(uint64_t readEntry)
{
mLedgerReadEntry += readEntry;
}
void
SorobanLedgerMetrics::accumulateLedgerReadByte(uint64_t readByte)
{
mLedgerReadByte += readByte;
}
void
SorobanLedgerMetrics::accumulateLedgerWriteEntry(uint64_t writeEntry)
{
mLedgerWriteEntry += writeEntry;
}
void
SorobanLedgerMetrics::accumulateLedgerWriteByte(uint64_t writeByte)
{
mLedgerWriteByte += writeByte;
}
void
SorobanLedgerMetrics::publishAndResetMetrics()
{
mMetrics.NewHistogram({"soroban", "ledger", "cpu-insn"})
.Update(mLedgerCpuInsn);
mMetrics.NewHistogram({"soroban", "ledger", "read-entry"})
.Update(mLedgerReadEntry);
mMetrics.NewHistogram({"soroban", "ledger", "read-ledger-byte"})
.Update(mLedgerReadByte);
mMetrics.NewHistogram({"soroban", "ledger", "write-entry"})
.Update(mLedgerWriteEntry);
mMetrics.NewHistogram({"soroban", "ledger", "write-ledger-byte"})
.Update(mLedgerWriteByte);
mLedgerCpuInsn = 0;
mLedgerReadEntry = 0;
mLedgerReadByte = 0;
mLedgerWriteEntry = 0;
mLedgerWriteByte = 0;
}
medida::MetricsRegistry&
SorobanLedgerMetrics::registry() const
{
return mMetrics;
}
std::unique_ptr<LedgerManager>
LedgerManager::create(Application& app)
{
return std::make_unique<LedgerManagerImpl>(app);
}
std::string
LedgerManager::ledgerAbbrev(LedgerHeader const& header)
{
return ledgerAbbrev(header, xdrSha256(header));
}
std::string
LedgerManager::ledgerAbbrev(uint32_t seq, uint256 const& hash)
{
std::ostringstream oss;
oss << "[seq=" << seq << ", hash=" << hexAbbrev(hash) << "]";
return oss.str();
}
std::string
LedgerManager::ledgerAbbrev(LedgerHeader const& header, uint256 const& hash)
{
return ledgerAbbrev(header.ledgerSeq, hash);
}
std::string
LedgerManager::ledgerAbbrev(LedgerHeaderHistoryEntry const& he)
{
return ledgerAbbrev(he.header, he.hash);
}
LedgerManagerImpl::LedgerManagerImpl(Application& app)
: mApp(app)
, mSorobanLedgerMetrics(app.getMetrics())
, mTransactionApply(
app.getMetrics().NewTimer({"ledger", "transaction", "apply"}))
, mTransactionCount(
app.getMetrics().NewHistogram({"ledger", "transaction", "count"}))
, mOperationCount(
app.getMetrics().NewHistogram({"ledger", "operation", "count"}))
, mPrefetchHitRate(
app.getMetrics().NewHistogram({"ledger", "prefetch", "hit-rate"}))
, mLedgerClose(app.getMetrics().NewTimer({"ledger", "ledger", "close"}))
, mLedgerAgeClosed(app.getMetrics().NewBuckets(
{"ledger", "age", "closed"}, {5000.0, 7000.0, 10000.0, 20000.0}))
, mLedgerAge(
app.getMetrics().NewCounter({"ledger", "age", "current-seconds"}))
, mTransactionApplySucceeded(
app.getMetrics().NewCounter({"ledger", "apply", "success"}))
, mTransactionApplyFailed(
app.getMetrics().NewCounter({"ledger", "apply", "failure"}))
, mMetaStreamBytes(
app.getMetrics().NewMeter({"ledger", "metastream", "bytes"}, "byte"))
, mMetaStreamWriteTime(
app.getMetrics().NewTimer({"ledger", "metastream", "write"}))
, mLastClose(mApp.getClock().now())
, mCatchupDuration(
app.getMetrics().NewTimer({"ledger", "catchup", "duration"}))
, mState(LM_BOOTING_STATE)
{
setupLedgerCloseMetaStream();
}
void
LedgerManagerImpl::moveToSynced()
{
setState(LM_SYNCED_STATE);
}
void
LedgerManagerImpl::setState(State s)
{
if (s != getState())
{
std::string oldState = getStateHuman();
mState = s;
mApp.syncOwnMetrics();
CLOG_INFO(Ledger, "Changing state {} -> {}", oldState, getStateHuman());
if (mState != LM_CATCHING_UP_STATE)
{
mApp.getCatchupManager().logAndUpdateCatchupStatus(true);
}
if (mState == LM_CATCHING_UP_STATE && !mStartCatchup)
{
mStartCatchup = std::make_unique<VirtualClock::time_point>(
mApp.getClock().now());
}
else if (mState == LM_SYNCED_STATE && mStartCatchup)
{
std::chrono::nanoseconds duration =
mApp.getClock().now() - *mStartCatchup;
mCatchupDuration.Update(duration);
CLOG_DEBUG(Perf, "Caught up to the network in {} seconds",
std::chrono::duration<double>(duration).count());
}
}
}
LedgerManager::State
LedgerManagerImpl::getState() const
{
return mState;
}
std::string
LedgerManagerImpl::getStateHuman() const
{
static std::array<const char*, LM_NUM_STATE> stateStrings = std::array{
"LM_BOOTING_STATE", "LM_SYNCED_STATE", "LM_CATCHING_UP_STATE"};
return std::string(stateStrings[getState()]);
}
LedgerHeader
LedgerManager::genesisLedger()
{
LedgerHeader result;
// all fields are initialized by default to 0
// set the ones that are not 0
result.ledgerVersion = GENESIS_LEDGER_VERSION;
result.baseFee = GENESIS_LEDGER_BASE_FEE;
result.baseReserve = GENESIS_LEDGER_BASE_RESERVE;
result.maxTxSetSize = GENESIS_LEDGER_MAX_TX_SIZE;
result.totalCoins = GENESIS_LEDGER_TOTAL_COINS;
result.ledgerSeq = GENESIS_LEDGER_SEQ;
return result;
}
void
LedgerManagerImpl::startNewLedger(LedgerHeader const& genesisLedger)
{
auto ledgerTime = mLedgerClose.TimeScope();
SecretKey skey = SecretKey::fromSeed(mApp.getNetworkID());
LedgerTxn ltx(mApp.getLedgerTxnRoot(), false);
auto const& cfg = mApp.getConfig();
ltx.loadHeader().current() = genesisLedger;
if (cfg.USE_CONFIG_FOR_GENESIS)
{
SorobanNetworkConfig::initializeGenesisLedgerForTesting(
cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION, ltx, mApp);
}
LedgerEntry rootEntry;
rootEntry.lastModifiedLedgerSeq = 1;
rootEntry.data.type(ACCOUNT);
auto& rootAccount = rootEntry.data.account();
rootAccount.accountID = skey.getPublicKey();
rootAccount.thresholds[0] = 1;
rootAccount.balance = genesisLedger.totalCoins;
ltx.create(rootEntry);
CLOG_INFO(Ledger, "Established genesis ledger, closing");
CLOG_INFO(Ledger, "Root account: {}", skey.getStrKeyPublic());
CLOG_INFO(Ledger, "Root account seed: {}", skey.getStrKeySeed().value);
ledgerClosed(ltx, /*ledgerCloseMeta*/ nullptr, /*initialLedgerVers*/ 0);
ltx.commit();
}
void
LedgerManagerImpl::startNewLedger()
{
auto ledger = genesisLedger();
auto const& cfg = mApp.getConfig();
if (cfg.USE_CONFIG_FOR_GENESIS)
{
ledger.ledgerVersion = cfg.TESTING_UPGRADE_LEDGER_PROTOCOL_VERSION;
ledger.baseFee = cfg.TESTING_UPGRADE_DESIRED_FEE;
ledger.baseReserve = cfg.TESTING_UPGRADE_RESERVE;
ledger.maxTxSetSize = cfg.TESTING_UPGRADE_MAX_TX_SET_SIZE;
}
startNewLedger(ledger);
}
static void
setLedgerTxnHeader(LedgerHeader const& lh, Application& app)
{
LedgerTxn ltx(app.getLedgerTxnRoot());
ltx.loadHeader().current() = lh;
ltx.commit();
}
void
LedgerManagerImpl::loadLastKnownLedger(bool restoreBucketlist,
bool isLedgerStateReady)
{
ZoneScoped;
// Step 1. Load LCL state from the DB and extract latest ledger hash
string lastLedger =
mApp.getPersistentState().getState(PersistentState::kLastClosedLedger);
if (lastLedger.empty())
{
throw std::runtime_error(
"No reference in DB to any last closed ledger");
}
CLOG_INFO(Ledger, "Last closed ledger (LCL) hash is {}", lastLedger);
Hash lastLedgerHash = hexToBin256(lastLedger);
// Step 2. Restore LedgerHeader from DB based on the ledger hash derived
// earlier, or verify we're at genesis if in no-history mode
std::optional<LedgerHeader> latestLedgerHeader;
if (mApp.getConfig().MODE_STORES_HISTORY_LEDGERHEADERS)
{
if (mRebuildInMemoryState)
{
LedgerHeader lh;
CLOG_INFO(Ledger,
"Setting empty ledger while core rebuilds state: {}",
ledgerAbbrev(lh));
setLedgerTxnHeader(lh, mApp);
latestLedgerHeader = lh;
}
else
{
auto currentLedger =
LedgerHeaderUtils::loadByHash(getDatabase(), lastLedgerHash);
if (!currentLedger)
{
throw std::runtime_error("Could not load ledger from database");
}
HistoryArchiveState has = getLastClosedLedgerHAS();
if (currentLedger->ledgerSeq != has.currentLedger)
{
throw std::runtime_error("Invalid database state: last known "
"ledger does not agree with HAS");
}
CLOG_INFO(Ledger, "Loaded LCL header from database: {}",
ledgerAbbrev(*currentLedger));
setLedgerTxnHeader(*currentLedger, mApp);
latestLedgerHeader = *currentLedger;
}
}
else
{
// In no-history mode, this method should only be called when
// the LCL is genesis.
releaseAssertOrThrow(mLastClosedLedger.hash == lastLedgerHash);
releaseAssertOrThrow(mLastClosedLedger.header.ledgerSeq ==
GENESIS_LEDGER_SEQ);
CLOG_INFO(Ledger, "LCL is genesis: {}",
ledgerAbbrev(mLastClosedLedger));
latestLedgerHeader = mLastClosedLedger.header;
}
releaseAssert(latestLedgerHeader.has_value());
// Step 3. Restore BucketList if we're doing a full core startup
// (startServices=true), OR when using BucketListDB
if (restoreBucketlist || mApp.getConfig().isUsingBucketListDB())
{
HistoryArchiveState has = getLastClosedLedgerHAS();
auto missing = mApp.getBucketManager().checkForMissingBucketsFiles(has);
auto pubmissing = mApp.getHistoryManager()
.getMissingBucketsReferencedByPublishQueue();
missing.insert(missing.end(), pubmissing.begin(), pubmissing.end());
if (!missing.empty())
{
CLOG_ERROR(Ledger,
"{} buckets are missing from bucket directory '{}'",
missing.size(), mApp.getBucketManager().getBucketDir());
throw std::runtime_error("Bucket directory is corrupt");
}
if (mApp.getConfig().MODE_ENABLES_BUCKETLIST)
{
// Only restart merges in full startup mode. Many modes in core
// (standalone offline commands, in-memory setup) do not need to
// spin up expensive merge processes.
auto assumeStateWork =
mApp.getWorkScheduler().executeWork<AssumeStateWork>(
has, latestLedgerHeader->ledgerVersion, restoreBucketlist);
if (assumeStateWork->getState() == BasicWork::State::WORK_SUCCESS)
{
CLOG_INFO(Ledger, "Assumed bucket-state for LCL: {}",
ledgerAbbrev(*latestLedgerHeader));
}
else
{
// Work should only fail during graceful shutdown
releaseAssertOrThrow(mApp.isStopping());
}
}
}
// Step 4. Restore LedgerManager's internal state
advanceLedgerPointers(*latestLedgerHeader);
if (protocolVersionStartsFrom(latestLedgerHeader->ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
if (isLedgerStateReady)
{
// Step 5. If ledger state is ready and core is in v20, load network
// configs right away
LedgerTxn ltx(mApp.getLedgerTxnRoot());
updateNetworkConfig(ltx);
}
else
{
// In some modes, e.g. in-memory, core's state is rebuilt
// asynchronously via catchup. In this case, we're not able to load
// the network config at this time, and instead must let catchup do
// it when ready.
CLOG_INFO(Ledger,
"Ledger state is being rebuilt, network config will "
"be loaded once the rebuild is done");
}
}
}
bool
LedgerManagerImpl::rebuildingInMemoryState()
{
return mRebuildInMemoryState;
}
void
LedgerManagerImpl::setupInMemoryStateRebuild()
{
if (!mRebuildInMemoryState)
{
LedgerHeader lh;
HistoryArchiveState has;
auto& ps = mApp.getPersistentState();
ps.setState(PersistentState::kLastClosedLedger,
binToHex(xdrSha256(lh)));
ps.setState(PersistentState::kHistoryArchiveState, has.toString());
ps.setState(PersistentState::kLastSCPData, "");
ps.setState(PersistentState::kLastSCPDataXDR, "");
ps.setState(PersistentState::kLedgerUpgrades, "");
mRebuildInMemoryState = true;
}
}
Database&
LedgerManagerImpl::getDatabase()
{
return mApp.getDatabase();
}
uint32_t
LedgerManagerImpl::getLastMaxTxSetSize() const
{
return mLastClosedLedger.header.maxTxSetSize;
}
uint32_t
LedgerManagerImpl::getLastMaxTxSetSizeOps() const
{
auto n = mLastClosedLedger.header.maxTxSetSize;
return protocolVersionStartsFrom(mLastClosedLedger.header.ledgerVersion,
ProtocolVersion::V_11)
? n
: (n * MAX_OPS_PER_TX);
}
Resource
LedgerManagerImpl::maxLedgerResources(bool isSoroban)
{
ZoneScoped;
if (isSoroban)
{
auto conf = getSorobanNetworkConfig();
std::vector<int64_t> limits = {conf.ledgerMaxTxCount(),
conf.ledgerMaxInstructions(),
conf.ledgerMaxTransactionSizesBytes(),
conf.ledgerMaxReadBytes(),
conf.ledgerMaxWriteBytes(),
conf.ledgerMaxReadLedgerEntries(),
conf.ledgerMaxWriteLedgerEntries()};
return Resource(limits);
}
else
{
uint32_t maxOpsLedger = getLastMaxTxSetSizeOps();
return Resource(maxOpsLedger);
}
}
Resource
LedgerManagerImpl::maxSorobanTransactionResources()
{
ZoneScoped;
auto const& conf = mApp.getLedgerManager().getSorobanNetworkConfig();
int64_t const opCount = 1;
std::vector<int64_t> limits = {opCount,
conf.txMaxInstructions(),
conf.txMaxSizeBytes(),
conf.txMaxReadBytes(),
conf.txMaxWriteBytes(),
conf.txMaxReadLedgerEntries(),
conf.txMaxWriteLedgerEntries()};
return Resource(limits);
}
int64_t
LedgerManagerImpl::getLastMinBalance(uint32_t ownerCount) const
{
auto const& lh = mLastClosedLedger.header;
if (protocolVersionIsBefore(lh.ledgerVersion, ProtocolVersion::V_9))
return (2 + ownerCount) * lh.baseReserve;
else
return (2LL + ownerCount) * int64_t(lh.baseReserve);
}
uint32_t
LedgerManagerImpl::getLastReserve() const
{
return mLastClosedLedger.header.baseReserve;
}
uint32_t
LedgerManagerImpl::getLastTxFee() const
{
return mLastClosedLedger.header.baseFee;
}
LedgerHeaderHistoryEntry const&
LedgerManagerImpl::getLastClosedLedgerHeader() const
{
return mLastClosedLedger;
}
HistoryArchiveState
LedgerManagerImpl::getLastClosedLedgerHAS()
{
ZoneScoped;
string hasString = mApp.getPersistentState().getState(
PersistentState::kHistoryArchiveState);
HistoryArchiveState has;
has.fromString(hasString);
return has;
}
uint32_t
LedgerManagerImpl::getLastClosedLedgerNum() const
{
return mLastClosedLedger.header.ledgerSeq;
}
SorobanNetworkConfig&
LedgerManagerImpl::getSorobanNetworkConfigInternal()
{
releaseAssert(mSorobanNetworkConfig);
return *mSorobanNetworkConfig;
}
SorobanNetworkConfig const&
LedgerManagerImpl::getSorobanNetworkConfig()
{
return getSorobanNetworkConfigInternal();
}
bool
LedgerManagerImpl::hasSorobanNetworkConfig() const
{
return mSorobanNetworkConfig.has_value();
}
#ifdef BUILD_TESTS
SorobanNetworkConfig&
LedgerManagerImpl::getMutableSorobanNetworkConfig()
{
return getSorobanNetworkConfigInternal();
}
#endif
SorobanLedgerMetrics&
LedgerManagerImpl::getSorobanMetrics()
{
return mSorobanLedgerMetrics;
}
void
LedgerManagerImpl::publishSorobanMetrics()
{
releaseAssert(mSorobanNetworkConfig);
medida::MetricsRegistry& registry = mSorobanLedgerMetrics.registry();
// first publish the network config limits
auto contractMaxSizeBytes = mSorobanNetworkConfig->maxContractSizeBytes();
auto ledgerMaxInstructions = mSorobanNetworkConfig->ledgerMaxInstructions();
auto txMaxInstructions = mSorobanNetworkConfig->txMaxInstructions();
auto txMemoryLimit = mSorobanNetworkConfig->txMemoryLimit();
auto ledgerMaxReadLedgerEntries =
mSorobanNetworkConfig->ledgerMaxReadLedgerEntries();
auto ledgerMaxReadBytes = mSorobanNetworkConfig->ledgerMaxReadBytes();
auto ledgerMaxWriteLedgerEntries =
mSorobanNetworkConfig->ledgerMaxWriteLedgerEntries();
auto ledgerMaxWriteBytes = mSorobanNetworkConfig->ledgerMaxWriteBytes();
auto txMaxReadLedgerEntries =
mSorobanNetworkConfig->txMaxReadLedgerEntries();
auto txMaxReadBytes = mSorobanNetworkConfig->txMaxReadBytes();
auto txMaxWriteLedgerEntries =
mSorobanNetworkConfig->txMaxWriteLedgerEntries();
auto txMaxWriteBytes = mSorobanNetworkConfig->txMaxWriteBytes();
auto bucketListTargetSizeBytes =
mSorobanNetworkConfig->bucketListTargetSizeBytes();
auto txMaxContractEventsSizeBytes =
mSorobanNetworkConfig->txMaxContractEventsSizeBytes();
auto contractDataKeySizeBytes =
mSorobanNetworkConfig->maxContractDataKeySizeBytes();
auto contractDataEntrySizeBytes =
mSorobanNetworkConfig->maxContractDataEntrySizeBytes();
registry.NewCounter({"soroban", "config", "contract-max-rw-key-byte"})
.set_count(contractDataKeySizeBytes);
registry.NewCounter({"soroban", "config", "contract-max-rw-data-byte"})
.set_count(contractDataEntrySizeBytes);
registry.NewCounter({"soroban", "config", "contract-max-rw-code-byte"})
.set_count(contractMaxSizeBytes);
registry.NewCounter({"soroban", "config", "tx-max-cpu-insn"})
.set_count(txMaxInstructions);
registry.NewCounter({"soroban", "config", "tx-max-mem-byte"})
.set_count(txMemoryLimit);
registry.NewCounter({"soroban", "config", "tx-max-read-entry"})
.set_count(txMaxReadLedgerEntries);
registry.NewCounter({"soroban", "config", "tx-max-read-ledger-byte"})
.set_count(txMaxReadBytes);
registry.NewCounter({"soroban", "config", "tx-max-write-entry"})
.set_count(txMaxWriteLedgerEntries);
registry.NewCounter({"soroban", "config", "tx-max-write-ledger-byte"})
.set_count(txMaxWriteBytes);
registry.NewCounter({"soroban", "config", "tx-max-emit-event-byte"})
.set_count(txMaxContractEventsSizeBytes);
registry.NewCounter({"soroban", "config", "ledger-max-cpu-insn"})
.set_count(ledgerMaxInstructions);
registry.NewCounter({"soroban", "config", "ledger-max-read-entry"})
.set_count(ledgerMaxReadLedgerEntries);
registry.NewCounter({"soroban", "config", "ledger-max-read-ledger-byte"})
.set_count(ledgerMaxReadBytes);
registry.NewCounter({"soroban", "config", "ledger-max-write-entry"})
.set_count(ledgerMaxWriteLedgerEntries);
registry.NewCounter({"soroban", "config", "ledger-max-write-ledger-byte"})
.set_count(ledgerMaxWriteBytes);
registry.NewCounter({"soroban", "config", "bucket-list-target-size-byte"})
.set_count(bucketListTargetSizeBytes);
// then publish the actual ledger usage
mSorobanLedgerMetrics.publishAndResetMetrics();
}
// called by txherder
void
LedgerManagerImpl::valueExternalized(LedgerCloseData const& ledgerData)
{
ZoneScoped;
// Capture LCL before we do any processing (which may trigger ledger close)
auto lcl = getLastClosedLedgerNum();
CLOG_INFO(Ledger,
"Got consensus: [seq={}, prev={}, txs={}, ops={}, sv: {}]",
ledgerData.getLedgerSeq(),
hexAbbrev(ledgerData.getTxSet()->previousLedgerHash()),
ledgerData.getTxSet()->sizeTxTotal(),
ledgerData.getTxSet()->sizeOpTotalForLogging(),
stellarValueToString(mApp.getConfig(), ledgerData.getValue()));
auto st = getState();
if (st != LedgerManager::LM_BOOTING_STATE &&
st != LedgerManager::LM_CATCHING_UP_STATE &&
st != LedgerManager::LM_SYNCED_STATE)
{
releaseAssert(false);
}
closeLedgerIf(ledgerData);
auto& cm = mApp.getCatchupManager();
cm.processLedger(ledgerData);
// We set the state to synced
// if we have closed the latest ledger we have heard of.
bool appliedLatest = false;
if (cm.getLargestLedgerSeqHeard() == getLastClosedLedgerNum())
{
setState(LM_SYNCED_STATE);
appliedLatest = true;
}
// New ledger(s) got closed, notify Herder
if (getLastClosedLedgerNum() > lcl)
{
CLOG_DEBUG(Ledger,
"LedgerManager::valueExternalized LCL advanced {} -> {}",
lcl, getLastClosedLedgerNum());
mApp.getHerder().lastClosedLedgerIncreased(appliedLatest);
}
FrameMark;
}
void
LedgerManagerImpl::closeLedgerIf(LedgerCloseData const& ledgerData)
{
ZoneScoped;
if (mLastClosedLedger.header.ledgerSeq + 1 == ledgerData.getLedgerSeq())
{
auto& cm = mApp.getCatchupManager();
// if catchup work is running, we don't want ledger manager to close
// this ledger and potentially cause issues.
if (cm.isCatchupInitialized() && !cm.catchupWorkIsDone())
{
CLOG_INFO(
Ledger,
"Can't close ledger: {} in LM because catchup is running",
ledgerAbbrev(mLastClosedLedger));
return;
}
closeLedger(ledgerData);
CLOG_INFO(Ledger, "Closed ledger: {}", ledgerAbbrev(mLastClosedLedger));
}
else if (ledgerData.getLedgerSeq() <= mLastClosedLedger.header.ledgerSeq)
{
CLOG_INFO(
Ledger,
"Skipping close ledger: local state is {}, more recent than {}",
mLastClosedLedger.header.ledgerSeq, ledgerData.getLedgerSeq());
}
else
{
if (mState != LM_CATCHING_UP_STATE)
{
// Out of sync, buffer what we just heard and start catchup.
CLOG_INFO(
Ledger, "Lost sync, local LCL is {}, network closed ledger {}",
mLastClosedLedger.header.ledgerSeq, ledgerData.getLedgerSeq());
}
setState(LM_CATCHING_UP_STATE);
}
}
void
LedgerManagerImpl::startCatchup(
CatchupConfiguration configuration, std::shared_ptr<HistoryArchive> archive,
std::set<std::shared_ptr<Bucket>> bucketsToRetain)
{
ZoneScoped;
setState(LM_CATCHING_UP_STATE);
mApp.getCatchupManager().startCatchup(configuration, archive,
bucketsToRetain);
}
uint64_t
LedgerManagerImpl::secondsSinceLastLedgerClose() const
{
uint64_t ct = getLastClosedLedgerHeader().header.scpValue.closeTime;
if (ct == 0)
{
return 0;
}
uint64_t now = mApp.timeNow();
return (now > ct) ? (now - ct) : 0;
}
void
LedgerManagerImpl::syncMetrics()
{
mLedgerAge.set_count(secondsSinceLastLedgerClose());
mApp.syncOwnMetrics();
}
void
LedgerManagerImpl::emitNextMeta()
{
ZoneScoped;
releaseAssert(mNextMetaToEmit);
releaseAssert(mMetaStream || mMetaDebugStream);
auto timer = LogSlowExecution("MetaStream write",
LogSlowExecution::Mode::AUTOMATIC_RAII,
"took", std::chrono::milliseconds(100));
auto streamWrite = mMetaStreamWriteTime.TimeScope();
if (mMetaStream)
{
size_t written = 0;
mMetaStream->writeOne(mNextMetaToEmit->getXDR(), nullptr, &written);
mMetaStream->flush();
mMetaStreamBytes.Mark(written);
}
if (mMetaDebugStream)
{
mMetaDebugStream->writeOne(mNextMetaToEmit->getXDR());
// Flush debug meta in case there's a crash later in commit (in which
// case we'd lose the data in internal buffers). This way we preserve
// the meta for problematic ledgers that is vital for diagnostics.
mMetaDebugStream->flush();
}
mNextMetaToEmit.reset();
}
/*
This is the main method that closes the current ledger based on
the close context that was computed by SCP or by the historical module
during replays.
*/
void
LedgerManagerImpl::closeLedger(LedgerCloseData const& ledgerData)
{
ZoneScoped;
auto ledgerTime = mLedgerClose.TimeScope();
LogSlowExecution closeLedgerTime{"closeLedger",
LogSlowExecution::Mode::MANUAL, "",
std::chrono::milliseconds::max()};
LedgerTxn ltx(mApp.getLedgerTxnRoot());
auto header = ltx.loadHeader();
auto initialLedgerVers = header.current().ledgerVersion;
++header.current().ledgerSeq;
header.current().previousLedgerHash = mLastClosedLedger.hash;
CLOG_DEBUG(Ledger, "starting closeLedger() on ledgerSeq={}",
header.current().ledgerSeq);
ZoneValue(static_cast<int64_t>(header.current().ledgerSeq));
auto now = mApp.getClock().now();
mLedgerAgeClosed.Update(now - mLastClose);
mLastClose = now;
mLedgerAge.set_count(0);
TxSetXDRFrameConstPtr txSet = ledgerData.getTxSet();
// If we do not support ledger version, we can't apply that ledger, fail!
if (header.current().ledgerVersion >
mApp.getConfig().LEDGER_PROTOCOL_VERSION)
{
CLOG_ERROR(Ledger, "Unknown ledger version: {}",
header.current().ledgerVersion);
CLOG_ERROR(Ledger, "{}", UPGRADE_STELLAR_CORE);
throw std::runtime_error(fmt::format(
FMT_STRING("cannot apply ledger with not supported version: {:d}"),
header.current().ledgerVersion));
}
if (txSet->previousLedgerHash() != getLastClosedLedgerHeader().hash)
{
CLOG_ERROR(Ledger, "TxSet mismatch: LCD wants {}, LCL is {}",
ledgerAbbrev(ledgerData.getLedgerSeq() - 1,
txSet->previousLedgerHash()),
ledgerAbbrev(getLastClosedLedgerHeader()));
CLOG_ERROR(Ledger, "{}",
xdr_to_string(getLastClosedLedgerHeader(), "Full LCL"));
CLOG_ERROR(Ledger, "{}", POSSIBLY_CORRUPTED_LOCAL_DATA);
throw std::runtime_error("txset mismatch");
}
if (txSet->getContentsHash() != ledgerData.getValue().txSetHash)
{
CLOG_ERROR(
Ledger,
"Corrupt transaction set: TxSet hash is {}, SCP value reports {}",
binToHex(txSet->getContentsHash()),
binToHex(ledgerData.getValue().txSetHash));
CLOG_ERROR(Ledger, "{}", POSSIBLY_CORRUPTED_QUORUM_SET);
throw std::runtime_error("corrupt transaction set");
}
auto const& sv = ledgerData.getValue();
header.current().scpValue = sv;
maybeResetLedgerCloseMetaDebugStream(header.current().ledgerSeq);
auto applicableTxSet = txSet->prepareForApply(mApp);
if (applicableTxSet == nullptr)
{
CLOG_ERROR(
Ledger,
"Corrupt transaction set: TxSet cannot be prepared for apply",
binToHex(txSet->getContentsHash()),
binToHex(ledgerData.getValue().txSetHash));
CLOG_ERROR(Ledger, "{}", POSSIBLY_CORRUPTED_QUORUM_SET);
throw std::runtime_error("transaction set cannot be processed");
}
// In addition to the _canonical_ LedgerResultSet hashed into the
// LedgerHeader, we optionally collect an even-more-fine-grained record of
// the ledger entries modified by each tx during tx processing in a
// LedgerCloseMeta, for streaming to attached clients (typically: horizon).
std::unique_ptr<LedgerCloseMetaFrame> ledgerCloseMeta;
if (mMetaStream || mMetaDebugStream)
{
if (mNextMetaToEmit)
{
releaseAssert(mNextMetaToEmit->ledgerHeader().hash ==
getLastClosedLedgerHeader().hash);
emitNextMeta();
}
releaseAssert(!mNextMetaToEmit);
// Write to a local variable rather than a member variable first: this
// enables us to discard incomplete meta and retry, should anything in
// this method throw.
ledgerCloseMeta = std::make_unique<LedgerCloseMetaFrame>(
header.current().ledgerVersion);
ledgerCloseMeta->reserveTxProcessing(applicableTxSet->sizeTxTotal());
ledgerCloseMeta->populateTxSet(*txSet);
}
// 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
std::vector<TransactionFrameBasePtr> const txs =
applicableTxSet->getTxsInApplyOrder();
// first, prefetch source accounts for txset, then charge fees
prefetchTxSourceIds(txs);
processFeesSeqNums(txs, ltx, *applicableTxSet, ledgerCloseMeta);
TransactionResultSet txResultSet;
txResultSet.results.reserve(txs.size());
applyTransactions(*applicableTxSet, txs, ltx, txResultSet, ledgerCloseMeta);
if (mApp.getConfig().MODE_STORES_HISTORY_MISC)
{
storeTxSet(mApp.getDatabase(), ltx.loadHeader().current().ledgerSeq,
*txSet);
}
ltx.loadHeader().current().txSetResultHash = xdrSha256(txResultSet);
// apply any upgrades that were decided during consensus
// this must be done after applying transactions as the txset
// was validated before upgrades
for (size_t i = 0; i < sv.upgrades.size(); i++)
{
LedgerUpgrade lupgrade;
auto valid = Upgrades::isValidForApply(sv.upgrades[i], lupgrade, mApp,
ltx, ltx.loadHeader().current());
switch (valid)
{
case Upgrades::UpgradeValidity::VALID:
break;
case Upgrades::UpgradeValidity::XDR_INVALID:
{
CLOG_ERROR(Ledger, "Unknown upgrade at index {}", i);
continue;