forked from stellar/stellar-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLedgerManagerImpl.cpp
1850 lines (1651 loc) · 63.3 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/BucketManager.h"
#include "bucket/HotArchiveBucketList.h"
#include "bucket/LiveBucketList.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/LedgerCloseData.h"
#include "herder/TxSetFrame.h"
#include "herder/Upgrades.h"
#include "history/HistoryManager.h"
#include "ledger/FlushAndRotateMetaDebugWork.h"
#include "ledger/LedgerHeaderUtils.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 "transactions/MutableTransactionResult.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/XDRStream.h"
#include "work/WorkScheduler.h"
#include "xdrpp/printer.h"
#include <fmt/format.h>
#include "xdr/Stellar-ledger-entries.h"
#include "xdr/Stellar-ledger.h"
#include "xdr/Stellar-transaction.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 <optional>
#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;
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::LedgerApplyMetrics::LedgerApplyMetrics(
medida::MetricsRegistry& registry)
: mTransactionApply(registry.NewTimer({"ledger", "transaction", "apply"}))
, mTransactionCount(
registry.NewHistogram({"ledger", "transaction", "count"}))
, mOperationCount(registry.NewHistogram({"ledger", "operation", "count"}))
, mPrefetchHitRate(
registry.NewHistogram({"ledger", "prefetch", "hit-rate"}))
, mLedgerClose(registry.NewTimer({"ledger", "ledger", "close"}))
, mLedgerAgeClosed(registry.NewBuckets({"ledger", "age", "closed"},
{5000.0, 7000.0, 10000.0, 20000.0}))
, mLedgerAge(registry.NewCounter({"ledger", "age", "current-seconds"}))
, mTransactionApplySucceeded(
registry.NewCounter({"ledger", "apply", "success"}))
, mTransactionApplyFailed(
registry.NewCounter({"ledger", "apply", "failure"}))
, mSorobanTransactionApplySucceeded(
registry.NewCounter({"ledger", "apply-soroban", "success"}))
, mSorobanTransactionApplyFailed(
registry.NewCounter({"ledger", "apply-soroban", "failure"}))
, mMetaStreamBytes(
registry.NewMeter({"ledger", "metastream", "bytes"}, "byte"))
, mMetaStreamWriteTime(registry.NewTimer({"ledger", "metastream", "write"}))
{
}
LedgerManagerImpl::LedgerManagerImpl(Application& app)
: mApp(app)
, mLedgerApplyMetrics(app.getMetrics())
, mSorobanMetrics(app.getMetrics())
, 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::beginApply()
{
releaseAssert(threadIsMain());
// Go into "applying" state, this will prevent catchup from starting
mCurrentlyApplyingLedger = true;
// Notify Herder that application started, so it won't fire out of sync
// timer
mApp.getHerder().beginApply();
}
void
LedgerManagerImpl::setState(State s)
{
releaseAssert(threadIsMain());
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.getLedgerApplyManager().logAndUpdateCatchupStatus(true);
}
}
}
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()]);
}
LedgerManagerImpl::LedgerState const&
LedgerManagerImpl::getLCLState() const
{
releaseAssert(threadIsMain());
return mLastClosedLedgerState;
}
LedgerManagerImpl::LedgerState&
LedgerManagerImpl::getLCLState()
{
releaseAssert(threadIsMain());
return mLastClosedLedgerState;
}
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 = mLedgerApplyMetrics.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);
auto output =
sealLedgerTxnAndStoreInBucketsAndDB(ltx, /*ledgerCloseMeta*/ nullptr,
/*initialLedgerVers*/ 0);
advanceLastClosedLedgerState(output);
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)
{
ZoneScoped;
// Step 1. Load LCL state from the DB and extract latest ledger hash
string lastLedger = mApp.getPersistentState().getState(
PersistentState::kLastClosedLedger, mApp.getDatabase().getSession());
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);
HistoryArchiveState has;
has.fromString(mApp.getPersistentState().getState(
PersistentState::kHistoryArchiveState,
mApp.getDatabase().getSession()));
// 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;
auto currentLedger =
LedgerHeaderUtils::loadByHash(getDatabase(), lastLedgerHash);
if (!currentLedger)
{
throw std::runtime_error("Could not load ledger from database");
}
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;
releaseAssert(latestLedgerHeader.has_value());
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 LCL state
auto output =
advanceBucketListSnapshotAndMakeLedgerState(*latestLedgerHeader, has);
advanceLastClosedLedgerState(output);
// Maybe truncate checkpoint files if we're restarting after a crash
// in applyLedger (in which case any modifications to the ledger state have
// been rolled back)
mApp.getHistoryManager().restoreCheckpoint(latestLedgerHeader->ledgerSeq);
if (protocolVersionStartsFrom(latestLedgerHeader->ledgerVersion,
SOROBAN_PROTOCOL_VERSION))
{
// Step 5. If ledger state is ready and core is in v20, load network
// configs right away
LedgerTxn ltx(mApp.getLedgerTxnRoot());
updateSorobanNetworkConfigForApply(ltx);
getLCLState().sorobanConfig = mApplyState.mSorobanNetworkConfig;
}
}
Database&
LedgerManagerImpl::getDatabase()
{
return mApp.getDatabase();
}
uint32_t
LedgerManagerImpl::getLastMaxTxSetSize() const
{
releaseAssert(threadIsMain());
return getLCLState().ledgerHeader.header.maxTxSetSize;
}
uint32_t
LedgerManagerImpl::getLastMaxTxSetSizeOps() const
{
releaseAssert(threadIsMain());
auto n = getLCLState().ledgerHeader.header.maxTxSetSize;
return protocolVersionStartsFrom(
getLCLState().ledgerHeader.header.ledgerVersion,
ProtocolVersion::V_11)
? n
: (n * MAX_OPS_PER_TX);
}
Resource
LedgerManagerImpl::maxLedgerResources(bool isSoroban)
{
ZoneScoped;
if (isSoroban)
{
return getLastClosedSorobanNetworkConfig().maxLedgerResources();
}
else
{
uint32_t maxOpsLedger = getLastMaxTxSetSizeOps();
return Resource(maxOpsLedger);
}
}
Resource
LedgerManagerImpl::maxSorobanTransactionResources()
{
ZoneScoped;
auto const& conf =
mApp.getLedgerManager().getLastClosedSorobanNetworkConfig();
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
{
releaseAssert(threadIsMain());
auto const& lh = getLCLState().ledgerHeader.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
{
releaseAssert(threadIsMain());
return getLCLState().ledgerHeader.header.baseReserve;
}
uint32_t
LedgerManagerImpl::getLastTxFee() const
{
releaseAssert(threadIsMain());
return getLCLState().ledgerHeader.header.baseFee;
}
LedgerHeaderHistoryEntry const&
LedgerManagerImpl::getLastClosedLedgerHeader() const
{
releaseAssert(threadIsMain());
return getLCLState().ledgerHeader;
}
HistoryArchiveState
LedgerManagerImpl::getLastClosedLedgerHAS()
{
releaseAssert(threadIsMain());
return getLCLState().has;
}
uint32_t
LedgerManagerImpl::getLastClosedLedgerNum() const
{
releaseAssert(threadIsMain());
return getLCLState().ledgerHeader.header.ledgerSeq;
}
SorobanNetworkConfig const&
LedgerManagerImpl::getLastClosedSorobanNetworkConfig()
{
releaseAssert(threadIsMain());
releaseAssert(hasLastClosedSorobanNetworkConfig());
return *getLCLState().sorobanConfig;
}
SorobanNetworkConfig const&
LedgerManagerImpl::getSorobanNetworkConfigForApply()
{
releaseAssert(mApplyState.mSorobanNetworkConfig);
return *mApplyState.mSorobanNetworkConfig;
}
bool
LedgerManagerImpl::hasLastClosedSorobanNetworkConfig() const
{
releaseAssert(threadIsMain());
return static_cast<bool>(getLCLState().sorobanConfig);
}
#ifdef BUILD_TESTS
SorobanNetworkConfig&
LedgerManagerImpl::getMutableSorobanNetworkConfigForApply()
{
releaseAssert(threadIsMain());
return *mApplyState.mSorobanNetworkConfig;
}
std::vector<TransactionMetaFrame> const&
LedgerManagerImpl::getLastClosedLedgerTxMeta()
{
return mLastLedgerTxMeta;
}
void
LedgerManagerImpl::storeCurrentLedgerForTest(LedgerHeader const& header)
{
storePersistentStateAndLedgerHeaderInDB(header, true);
}
#endif
SorobanMetrics&
LedgerManagerImpl::getSorobanMetrics()
{
return mSorobanMetrics;
}
void
LedgerManagerImpl::publishSorobanMetrics()
{
auto const& conf = getSorobanNetworkConfigForApply();
// first publish the network config limits
mSorobanMetrics.mConfigContractDataKeySizeBytes.set_count(
conf.maxContractDataKeySizeBytes());
mSorobanMetrics.mConfigMaxContractDataEntrySizeBytes.set_count(
conf.maxContractDataEntrySizeBytes());
mSorobanMetrics.mConfigMaxContractSizeBytes.set_count(
conf.maxContractSizeBytes());
mSorobanMetrics.mConfigTxMaxSizeByte.set_count(conf.txMaxSizeBytes());
mSorobanMetrics.mConfigTxMaxCpuInsn.set_count(conf.txMaxInstructions());
mSorobanMetrics.mConfigTxMemoryLimitBytes.set_count(conf.txMemoryLimit());
mSorobanMetrics.mConfigTxMaxReadLedgerEntries.set_count(
conf.txMaxReadLedgerEntries());
mSorobanMetrics.mConfigTxMaxReadBytes.set_count(conf.txMaxReadBytes());
mSorobanMetrics.mConfigTxMaxWriteLedgerEntries.set_count(
conf.txMaxWriteLedgerEntries());
mSorobanMetrics.mConfigTxMaxWriteBytes.set_count(conf.txMaxWriteBytes());
mSorobanMetrics.mConfigMaxContractEventsSizeBytes.set_count(
conf.txMaxContractEventsSizeBytes());
mSorobanMetrics.mConfigLedgerMaxTxCount.set_count(conf.ledgerMaxTxCount());
mSorobanMetrics.mConfigLedgerMaxInstructions.set_count(
conf.ledgerMaxInstructions());
mSorobanMetrics.mConfigLedgerMaxTxsSizeByte.set_count(
conf.ledgerMaxTransactionSizesBytes());
mSorobanMetrics.mConfigLedgerMaxReadLedgerEntries.set_count(
conf.ledgerMaxReadLedgerEntries());
mSorobanMetrics.mConfigLedgerMaxReadBytes.set_count(
conf.ledgerMaxReadBytes());
mSorobanMetrics.mConfigLedgerMaxWriteEntries.set_count(
conf.ledgerMaxWriteLedgerEntries());
mSorobanMetrics.mConfigLedgerMaxWriteBytes.set_count(
conf.ledgerMaxWriteBytes());
mSorobanMetrics.mConfigBucketListTargetSizeByte.set_count(
conf.bucketListTargetSizeBytes());
mSorobanMetrics.mConfigFeeWrite1KB.set_count(conf.feeWrite1KB());
// then publish the actual ledger usage
mSorobanMetrics.publishAndResetLedgerWideMetrics();
}
// called by txherder
void
LedgerManagerImpl::valueExternalized(LedgerCloseData const& ledgerData,
bool isLatestSlot)
{
ZoneScoped;
releaseAssert(threadIsMain());
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);
}
auto& lam = mApp.getLedgerApplyManager();
auto res = lam.processLedger(ledgerData, isLatestSlot);
// Go into catchup if we have any future ledgers we're unable to apply
// sequentially.
if (res == LedgerApplyManager::ProcessLedgerResult::
WAIT_TO_APPLY_BUFFERED_OR_CATCHUP)
{
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 {}",
getLastClosedLedgerHeader().header.ledgerSeq,
ledgerData.getLedgerSeq());
}
setState(LM_CATCHING_UP_STATE);
}
}
void
LedgerManagerImpl::startCatchup(
CatchupConfiguration configuration, std::shared_ptr<HistoryArchive> archive,
std::set<std::shared_ptr<LiveBucket>> bucketsToRetain)
{
ZoneScoped;
setState(LM_CATCHING_UP_STATE);
mApp.getLedgerApplyManager().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()
{
mLedgerApplyMetrics.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 = mLedgerApplyMetrics.mMetaStreamWriteTime.TimeScope();
if (mMetaStream)
{
size_t written = 0;
mMetaStream->writeOne(mNextMetaToEmit->getXDR(), nullptr, &written);
mMetaStream->flush();
mLedgerApplyMetrics.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();
}
void
maybeSimulateSleep(Config const& cfg, size_t opSize,
LogSlowExecution& closeTime)
{
if (!cfg.OP_APPLY_SLEEP_TIME_WEIGHT_FOR_TESTING.empty())
{
// Sleep for a parameterized amount of time in simulation mode
std::discrete_distribution<uint32> distribution(
cfg.OP_APPLY_SLEEP_TIME_WEIGHT_FOR_TESTING.begin(),
cfg.OP_APPLY_SLEEP_TIME_WEIGHT_FOR_TESTING.end());
std::chrono::microseconds sleepFor{0};
for (size_t i = 0; i < opSize; i++)
{
sleepFor +=
cfg.OP_APPLY_SLEEP_TIME_DURATION_FOR_TESTING[distribution(
gRandomEngine)];
}
std::chrono::microseconds applicationTime =
closeTime.checkElapsedTime();
if (applicationTime < sleepFor)
{
sleepFor -= applicationTime;
CLOG_DEBUG(Perf, "Simulate application: sleep for {} microseconds",
sleepFor.count());
std::this_thread::sleep_for(sleepFor);
}
}
}
asio::io_context&
getMetaIOContext(Application& app)
{
return app.getConfig().parallelLedgerClose()
? app.getLedgerCloseIOContext()
: app.getClock().getIOContext();
}
void
LedgerManagerImpl::ledgerCloseComplete(uint32_t lcl, bool calledViaExternalize,
LedgerCloseData const& ledgerData)
{
// We just finished applying `lcl`, maybe change LM's state
// Also notify Herder so it can trigger next ledger.
releaseAssert(threadIsMain());
uint32_t latestHeardFromNetwork =
mApp.getLedgerApplyManager().getLargestLedgerSeqHeard();
uint32_t latestQueuedToApply =
mApp.getLedgerApplyManager().getMaxQueuedToApply();
if (calledViaExternalize)
{
releaseAssert(lcl <= latestQueuedToApply);
releaseAssert(latestQueuedToApply <= latestHeardFromNetwork);
}
// Without parallel ledger apply, this should always be true
bool doneApplying = lcl == latestQueuedToApply;
releaseAssert(doneApplying || mApp.getConfig().parallelLedgerClose());
if (doneApplying)
{
mCurrentlyApplyingLedger = false;
}
// Continue execution on the main thread
// if we have closed the latest ledger we have heard of, set state to
// "synced"
bool appliedLatest = false;
if (latestHeardFromNetwork == lcl)
{
mApp.getLedgerManager().moveToSynced();
appliedLatest = true;
}
if (calledViaExternalize)
{
// New ledger(s) got closed, notify Herder
mApp.getHerder().lastClosedLedgerIncreased(appliedLatest,
ledgerData.getTxSet());
}
}
// This is the main entrypoint for the apply thread (and/or synchronous
// application happening on the main thread -- it can happen on either).
// It is called from the LedgerApplyManager and will post its results
// back to the main thread when done, if running on the apply thread.
void
LedgerManagerImpl::applyLedger(LedgerCloseData const& ledgerData,
bool calledViaExternalize)
{
if (mApp.isStopping())
{
return;
}
#ifdef BUILD_TESTS
mLastLedgerTxMeta.clear();
#endif
ZoneScoped;
auto ledgerTime = mLedgerApplyMetrics.mLedgerClose.TimeScope();
LogSlowExecution applyLedgerTime{"applyLedger",
LogSlowExecution::Mode::MANUAL, "",
std::chrono::milliseconds::max()};
LedgerTxn ltx(mApp.getLedgerTxnRoot());
auto header = ltx.loadHeader();
// Note: applyLedger should be able to work correctly based on ledger header
// stored in LedgerTxn. The issue is that in tests LedgerTxn is sometimes
// modified manually, which changes ledger header hash compared to the
// cached one and causes tests to fail.
LedgerHeader prevHeader = header.current();
#ifdef BUILD_TESTS
if (threadIsMain())
{
prevHeader = getLastClosedLedgerHeader().header;
}
#endif
auto prevHash = xdrSha256(prevHeader);
auto initialLedgerVers = header.current().ledgerVersion;
++header.current().ledgerSeq;
header.current().previousLedgerHash = prevHash;
CLOG_DEBUG(Ledger, "starting applyLedger() on ledgerSeq={}",
header.current().ledgerSeq);
ZoneValue(static_cast<int64_t>(header.current().ledgerSeq));
auto now = mApp.getClock().now();
mLedgerApplyMetrics.mLedgerAgeClosed.Update(now - mLastClose);
// mLastClose is only accessed by a single thread, so no synchronization
// needed
mLastClose = now;
mLedgerApplyMetrics.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() != prevHash)
{
CLOG_ERROR(Ledger, "TxSet mismatch: LCD wants {}, LCL is {}",
ledgerAbbrev(ledgerData.getLedgerSeq() - 1,
txSet->previousLedgerHash()),
ledgerAbbrev(prevHeader));
CLOG_ERROR(Ledger, "{}", xdrToCerealString(prevHeader, "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, prevHeader);
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 == prevHash);
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);
}
// first, prefetch source accounts for txset, then charge fees
prefetchTxSourceIds(mApp.getLedgerTxnRoot(), *applicableTxSet,
mApp.getConfig());
auto const mutableTxResults =
processFeesSeqNums(*applicableTxSet, ltx, ledgerCloseMeta, ledgerData);
// Subtle: after this call, `header` is invalidated, and is not safe to use
auto txResultSet = applyTransactions(*applicableTxSet, mutableTxResults,
ltx, ledgerCloseMeta);
if (mApp.getConfig().MODE_STORES_HISTORY_MISC)
{
auto ledgerSeq = ltx.loadHeader().current().ledgerSeq;
mApp.getHistoryManager().appendTransactionSet(ledgerSeq, txSet,
txResultSet);
}
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;
LedgerSnapshot ls(ltx);
auto valid =
Upgrades::isValidForApply(sv.upgrades[i], lupgrade, mApp, ls);
switch (valid)
{
case Upgrades::UpgradeValidity::VALID:
break;
case Upgrades::UpgradeValidity::XDR_INVALID:
{
CLOG_ERROR(Ledger, "Unknown upgrade at index {}", i);
continue;
}
case Upgrades::UpgradeValidity::INVALID:
{
CLOG_ERROR(Ledger, "Invalid upgrade at index {}: {}", i,
xdrToCerealString(lupgrade, "LedgerUpgrade"));
continue;
}
}
try
{
LedgerTxn ltxUpgrade(ltx);
Upgrades::applyTo(lupgrade, mApp, ltxUpgrade);
LedgerEntryChanges changes = ltxUpgrade.getChanges();
if (ledgerCloseMeta)
{
auto& up = ledgerCloseMeta->upgradesProcessing();
up.emplace_back();
UpgradeEntryMeta& uem = up.back();
uem.upgrade = lupgrade;
uem.changes = changes;
}
ltxUpgrade.commit();
}
catch (std::runtime_error& e)
{
CLOG_ERROR(Ledger, "Exception during upgrade: {}", e.what());
}
catch (...)
{
CLOG_ERROR(Ledger, "Unknown exception during upgrade");
}
}
auto maybeNewVersion = ltx.loadHeader().current().ledgerVersion;
auto ledgerSeq = ltx.loadHeader().current().ledgerSeq;
if (protocolVersionStartsFrom(maybeNewVersion, SOROBAN_PROTOCOL_VERSION))
{
updateSorobanNetworkConfigForApply(ltx);
}
LedgerState appliedLedgerState = sealLedgerTxnAndStoreInBucketsAndDB(
ltx, ledgerCloseMeta, initialLedgerVers);
if (ledgerData.getExpectedHash() &&
*ledgerData.getExpectedHash() != appliedLedgerState.ledgerHeader.hash)
{
throw std::runtime_error("Local node's ledger corrupted during close");
}
if (mMetaStream || mMetaDebugStream)