-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathApplicationUtils.cpp
More file actions
1206 lines (1089 loc) · 36 KB
/
ApplicationUtils.cpp
File metadata and controls
1206 lines (1089 loc) · 36 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 "main/ApplicationUtils.h"
#include "bucket/BucketManager.h"
#include "bucket/LiveBucketList.h"
#include "catchup/ApplyBucketsWork.h"
#include "catchup/CatchupConfiguration.h"
#include "crypto/Hex.h"
#include "database/Database.h"
#include "herder/Herder.h"
#include "herder/HerderUtils.h"
#include "herder/QuorumIntersectionChecker.h"
#include "history/HistoryArchive.h"
#include "history/HistoryArchiveManager.h"
#include "history/HistoryArchiveReportWork.h"
#include "historywork/GetHistoryArchiveStateWork.h"
#include "invariant/BucketListIsConsistentWithDatabase.h"
#include "ledger/LedgerHeaderUtils.h"
#include "ledger/LedgerManager.h"
#include "ledger/LedgerManagerImpl.h"
#include "ledger/LedgerTypeUtils.h"
#include "main/ErrorMessages.h"
#include "main/PersistentState.h"
#include "main/StellarCoreVersion.h"
#include "overlay/OverlayManager.h"
#include "scp/LocalNode.h"
#include "util/GlobalChecks.h"
#include "util/Logging.h"
#include "util/XDRCereal.h"
#include "util/types.h"
#include "util/xdrquery/XDRQuery.h"
#include "work/WorkScheduler.h"
#include "xdr/Stellar-ledger-entries.h"
#include <filesystem>
#include <lib/http/HttpClient.h>
#include <locale>
#include <map>
#include <optional>
#include <regex>
namespace stellar
{
namespace
{
void
writeLedgerAggregationTable(
std::ofstream& ofs,
std::optional<xdrquery::XDRFieldExtractor> const& groupByExtractor,
std::map<std::vector<xdrquery::ResultType>, xdrquery::XDRAccumulator> const&
accumulators)
{
std::vector<std::string> keyFields;
if (groupByExtractor)
{
keyFields = groupByExtractor->getColumnNames();
for (auto const& keyField : keyFields)
{
ofs << keyField << ",";
}
}
if (!accumulators.empty())
{
auto const& [_, accumulator] = *accumulators.begin();
for (auto const& acc : accumulator.getAccumulators())
{
ofs << acc->getName() << ",";
}
}
ofs << std::endl;
for (auto const& [key, accumulator] : accumulators)
{
if (!key.empty())
{
for (size_t i = 0; i < key.size(); ++i)
{
if (key[i])
{
ofs << xdrquery::resultToString(*key[i]);
}
ofs << ",";
}
}
for (auto const& acc : accumulator.getAccumulators())
{
ofs << std::visit([](auto&& v) { return fmt::to_string(v); },
acc->getValue())
<< ",";
}
ofs << std::endl;
}
}
} // namespace
Application::pointer
setupApp(Config& cfg, VirtualClock& clock)
{
LOG_INFO(DEFAULT_LOG, "Starting stellar-core {}", STELLAR_CORE_VERSION);
Application::pointer app;
app = Application::create(clock, cfg, false);
if (!app->getHistoryArchiveManager().checkSensibleConfig())
{
return nullptr;
}
return app;
}
int
runApp(Application::pointer app)
{
// start() is idempotent, so it's safe to call even if app was already
// started
app->start();
// Perform additional startup procedures (must be done after the app is
// setup) and run the app
try
{
if (!app->getConfig().MODE_AUTO_STARTS_OVERLAY)
{
app->getOverlayManager().start();
}
app->applyCfgCommands();
}
catch (std::exception const& e)
{
LOG_FATAL(DEFAULT_LOG, "Got an exception: {}", e.what());
LOG_FATAL(DEFAULT_LOG, "{}", REPORT_INTERNAL_BUG);
return 1;
}
auto& io = app->getClock().getIOContext();
asio::io_context::work mainWork(io);
while (!io.stopped())
{
app->getClock().crank();
}
return 0;
}
bool
applyBucketsForLCL(Application& app)
{
HistoryArchiveState has;
has.fromString(app.getPersistentState().getState(
PersistentState::kHistoryArchiveState, app.getDatabase().getSession()));
auto maxProtocolVersion = app.getConfig().LEDGER_PROTOCOL_VERSION;
std::string headerEncoded = app.getPersistentState().getState(
PersistentState::kLastClosedLedgerHeader,
app.getDatabase().getSession());
if (!headerEncoded.empty())
{
LedgerHeader currentLedger =
LedgerHeaderUtils::decodeFromData(headerEncoded);
maxProtocolVersion = currentLedger.ledgerVersion;
}
std::map<std::string, std::shared_ptr<LiveBucket>> buckets;
auto work = app.getWorkScheduler().scheduleWork<ApplyBucketsWork>(
buckets, has, maxProtocolVersion);
while (app.getClock().crank(true) && !work->isDone())
;
return work->getState() == BasicWork::State::WORK_SUCCESS;
}
void
httpCommand(std::string const& command, unsigned short port)
{
std::string ret;
std::ostringstream path;
path << "/";
bool gotCommand = false;
for (auto const& c : command)
{
if (gotCommand)
{
if (isAsciiAlphaNumeric(c))
{
path << c;
}
else
{
path << '%' << std::hex << std::setw(2) << std::setfill('0')
<< (unsigned int)c;
}
}
else
{
path << c;
if (c == '?')
{
gotCommand = true;
}
}
}
int code = http_request("127.0.0.1", path.str(), port, ret);
if (code == 200)
{
std::cout << ret << std::endl;
}
else
{
LOG_INFO(DEFAULT_LOG, "http failed({}) port: {} command: {}", code,
port, command);
}
}
void
setAuthenticatedLedgerHashPair(Application::pointer app,
LedgerNumHashPair& authPair,
uint32_t startLedger, std::string startHash)
{
auto const& lm = app->getLedgerManager();
auto tryCheckpoint = [&](uint32_t seq, Hash h) {
if (HistoryManager::isLastLedgerInCheckpoint(seq, app->getConfig()))
{
LOG_INFO(DEFAULT_LOG,
"Found authenticated checkpoint hash {} for ledger {}",
hexAbbrev(h), seq);
authPair.first = seq;
authPair.second = std::make_optional<Hash>(h);
return true;
}
else if (authPair.first != seq)
{
authPair.first = seq;
LOG_INFO(DEFAULT_LOG,
"Ledger {} is not a checkpoint boundary, waiting.", seq);
}
return false;
};
if (startLedger != 0 && !startHash.empty())
{
Hash h = hexToBin256(startHash);
if (tryCheckpoint(startLedger, h))
{
return;
}
}
if (lm.isSynced())
{
auto const& lhe = lm.getLastClosedLedgerHeader();
tryCheckpoint(lhe.header.ledgerSeq, lhe.hash);
}
else
{
auto lcd = app->getLedgerApplyManager().maybeGetLargestBufferedLedger();
if (lcd)
{
uint32_t seq = lcd->getLedgerSeq() - 1;
Hash hash = lcd->getTxSet()->previousLedgerHash();
tryCheckpoint(seq, hash);
}
}
}
int
selfCheck(Config cfg)
{
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
// We run self-checks from a "loaded but dormant" state where the
// application is not started, but the LM has loaded the LCL.
app->getLedgerManager().partiallyLoadLastKnownLedgerForUtils();
// First we schedule the cheap, asynchronous "online" checks that get run by
// the HTTP "self-check" endpoint, and crank until they're done.
LOG_INFO(DEFAULT_LOG, "Self-check phase 1: fast online checks");
auto seq1 = app->scheduleSelfCheck(false);
while (clock.crank(true) && !seq1->isDone())
;
// Then we scan all the buckets to check they have expected hashes.
LOG_INFO(DEFAULT_LOG, "Self-check phase 2: bucket hash verification");
auto seq2 = app->getBucketManager().scheduleVerifyReferencedBucketsWork(
*app, app->getLedgerManager().getLastClosedLedgerHAS());
while (clock.crank(true) && !seq2->isDone())
;
// Then we load the entire BL ledger state into memory and check it against
// the database. This part is synchronous and should _not_ be run "online",
// it's too expensive; it also can't easily be turned _into_ something you
// can run online, because it would need to snapshot the database for the
// duration of the run and, for example, sqlite doesn't support lockless
// snapshotting / MVCC.
//
// What we do instead is register a background thread listening for
// control-C so at least the user can interrupt this if they get impatient.
asio::signal_set stopSignals(app->getWorkerIOContext(), SIGINT);
#ifdef SIGQUIT
stopSignals.add(SIGQUIT);
#endif
#ifdef SIGTERM
stopSignals.add(SIGTERM);
#endif
stopSignals.async_wait([](asio::error_code const& ec, int sig) {
if (!ec)
{
LOG_INFO(DEFAULT_LOG, "got signal {}, exiting self-check", sig);
exit(1);
}
});
LOG_INFO(DEFAULT_LOG, "Self-check phase 3: ledger consistency checks");
BucketListIsConsistentWithDatabase blc(*app);
bool blcOk = true;
try
{
blc.checkEntireBucketlist();
}
catch (std::runtime_error& e)
{
LOG_ERROR(DEFAULT_LOG, "Error during bucket-list consistency check: {}",
e.what());
blcOk = false;
}
LOG_INFO(DEFAULT_LOG, "Self-check phase 4: crypto benchmarking");
size_t signPerSec = 0, verifyPerSec = 0;
SecretKey::benchmarkOpsPerSecond(signPerSec, verifyPerSec, 10000);
LOG_INFO(DEFAULT_LOG, "Benchmarked {} signatures / sec", signPerSec);
LOG_INFO(DEFAULT_LOG, "Benchmarked {} verifications / sec", verifyPerSec);
if (seq1->getState() == BasicWork::State::WORK_SUCCESS &&
seq2->getState() == BasicWork::State::WORK_SUCCESS && blcOk)
{
LOG_INFO(DEFAULT_LOG, "Self-check succeeded");
return 0;
}
else
{
LOG_ERROR(DEFAULT_LOG, "Self-check failed");
return 1;
}
}
int
mergeBucketList(Config cfg, std::string const& outputDir)
{
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
auto& lm = app->getLedgerManager();
auto& bm = app->getBucketManager();
lm.partiallyLoadLastKnownLedgerForUtils();
HistoryArchiveState has = lm.getLastClosedLedgerHAS();
auto bucket = bm.mergeBuckets(app->getClock().getIOContext(), has);
using std::filesystem::path;
path bpath(bucket->getFilename());
path outpath(outputDir);
outpath /= bpath.filename();
if (fs::durableRename(bpath.string(), outpath.string(), outputDir))
{
LOG_INFO(DEFAULT_LOG, "Wrote merged bucket {}", outpath);
return 0;
}
else
{
LOG_ERROR(DEFAULT_LOG, "Writing bucket failed");
return 1;
}
}
// Per-LedgerKey metrics used for dumping archival state
struct StateArchivalMetric
{
// True if the newest version of the entry is a DEADENTRY
bool isDead{};
// Number of bytes that the newest version of the entry occupies in the
// BucketList
uint64_t newestBytes{};
// Number of bytes that all outdated versions of the entry occupy in the
// BucketList
uint64_t outdatedBytes{};
};
static void
processArchivalMetrics(
std::shared_ptr<LiveBucket const> const b,
UnorderedMap<LedgerKey, StateArchivalMetric>& ledgerEntries,
UnorderedMap<LedgerKey, std::pair<StateArchivalMetric, uint32_t>>& ttls)
{
for (LiveBucketInputIterator in(b); in; ++in)
{
auto const& be = *in;
bool isDead = be.type() == DEADENTRY;
LedgerKey k = isDead ? be.deadEntry() : LedgerEntryKey(be.liveEntry());
bool isTTL = k.type() == TTL;
if (!isTemporaryEntry(k) && !isTTL)
{
continue;
}
if (isTTL)
{
auto iter = ttls.find(k);
if (iter == ttls.end())
{
StateArchivalMetric metric;
metric.isDead = isDead;
metric.newestBytes = xdr::xdr_size(be);
if (isDead)
{
ttls.emplace(k, std::make_pair(metric, 0));
}
else
{
ttls.emplace(
k, std::make_pair(
metric,
be.liveEntry().data.ttl().liveUntilLedgerSeq));
}
}
else
{
iter->second.first.outdatedBytes += xdr::xdr_size(be);
}
}
else
{
auto iter = ledgerEntries.find(k);
if (iter == ledgerEntries.end())
{
StateArchivalMetric metric;
metric.isDead = isDead;
metric.newestBytes = xdr::xdr_size(be);
ledgerEntries.emplace(k, metric);
}
else
{
iter->second.outdatedBytes += xdr::xdr_size(be);
}
}
}
}
void
getHotArchiveListBalanceForAsset(Application& app,
HistoryArchiveState const& has,
Asset const& asset,
AssetContractInfo const& assetContractInfo,
int64_t& runningBalance)
{
std::map<LedgerKey, LedgerEntry> archived =
app.getBucketManager().loadCompleteHotArchiveState(has);
for (auto const& [_, entry] : archived)
{
auto balance = getAssetBalance(entry, asset, assetContractInfo);
if (balance.overflowed)
{
throw std::runtime_error("Total asset balance overflowed int64_t");
}
if (balance.assetMatched &&
(!balance.balance || !addBalance(runningBalance, *balance.balance)))
{
throw std::runtime_error("Total asset balance overflowed int64_t");
}
}
}
void
getLiveBucketListBalanceForAsset(Application& app,
HistoryArchiveState const& has,
Asset const& asset,
AssetContractInfo const& assetContractInfo,
int64_t& runningBalance)
{
std::vector<Hash> liveHashes;
std::unordered_set<LedgerKey> seenKeys;
for (uint32_t i = 0; i < LiveBucketList::kNumLevels; ++i)
{
HistoryStateBucket<LiveBucket> const& hsb = has.currentBuckets.at(i);
liveHashes.emplace_back(hexToBin256(hsb.curr));
liveHashes.emplace_back(hexToBin256(hsb.snap));
}
auto& bm = app.getBucketManager();
for (auto const& hash : liveHashes)
{
if (isZero(hash))
{
continue;
}
auto b = bm.getBucketByHash<LiveBucket>(hash);
if (!b)
{
throw std::runtime_error(std::string("missing bucket: ") +
binToHex(hash));
}
for (LiveBucketInputIterator in(b); in; ++in)
{
auto const& be = *in;
if (be.type() != LIVEENTRY && be.type() != INITENTRY)
{
if (be.type() == DEADENTRY &&
canHoldAsset(be.deadEntry().type(), asset))
{
seenKeys.emplace(be.deadEntry());
}
continue;
}
LedgerKey k = LedgerEntryKey(be.liveEntry());
if (!canHoldAsset(be.liveEntry().data.type(), asset) ||
seenKeys.count(k) != 0)
{
continue;
}
auto balance =
getAssetBalance(be.liveEntry(), asset, assetContractInfo);
if (balance.overflowed)
{
throw std::runtime_error(
"Total asset balance overflowed int64_t");
}
if (!balance.assetMatched)
{
continue;
}
if (!balance.balance ||
!addBalance(runningBalance, *balance.balance))
{
throw std::runtime_error(
"Total asset balance overflowed int64_t");
}
seenKeys.emplace(k);
}
}
}
int
calculateAssetSupply(Config cfg, Asset const& asset)
{
ZoneScoped;
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
auto& lm = app->getLedgerManager();
lm.partiallyLoadLastKnownLedgerForUtils();
HistoryArchiveState has = lm.getLastClosedLedgerHAS();
auto assetContractInfo = getAssetContractInfo(asset, app->getNetworkID());
int64_t sumBalance = 0;
// For native asset, include the fee pool
if (asset.type() == ASSET_TYPE_NATIVE)
{
auto feePool = lm.getLastClosedLedgerHeader().header.feePool;
sumBalance = feePool;
CLOG_INFO(Bucket, "Fee pool balance: {}", feePool);
}
getLiveBucketListBalanceForAsset(*app, has, asset, assetContractInfo,
sumBalance);
getHotArchiveListBalanceForAsset(*app, has, asset, assetContractInfo,
sumBalance);
CLOG_INFO(
Bucket,
"Total asset supply in Hot/Live buckets (and feePool for XLM): {}",
sumBalance);
// For native asset, validate against totalCoins
if (asset.type() == ASSET_TYPE_NATIVE)
{
auto totalCoins = lm.getLastClosedLedgerHeader().header.totalCoins;
CLOG_INFO(Bucket, "Total Coins in ledgerHeader: {}", totalCoins);
if (sumBalance != totalCoins)
{
CLOG_WARNING(Bucket,
"Total XLM mismatch! totalCoins-bucketBalance: {}",
totalCoins - sumBalance);
return 1;
}
else
{
CLOG_INFO(Bucket, "Total XLM matches");
}
}
return 0;
}
int
dumpStateArchivalStatistics(Config cfg)
{
ZoneScoped;
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
app->getLedgerManager().partiallyLoadLastKnownLedgerForUtils();
auto& lm = app->getLedgerManager();
auto& bm = app->getBucketManager();
HistoryArchiveState has = lm.getLastClosedLedgerHAS();
std::vector<Hash> hashes;
for (uint32_t i = 0; i < LiveBucketList::kNumLevels; ++i)
{
HistoryStateBucket<LiveBucket> const& hsb = has.currentBuckets.at(i);
hashes.emplace_back(hexToBin256(hsb.curr));
hashes.emplace_back(hexToBin256(hsb.snap));
}
UnorderedMap<LedgerKey, StateArchivalMetric> ledgerEntries;
// key -> (metric, liveUntilLedger)
UnorderedMap<LedgerKey, std::pair<StateArchivalMetric, uint32_t>> ttls;
float blSize = 0;
for (auto const& hash : hashes)
{
if (isZero(hash))
{
continue;
}
auto b = bm.getBucketByHash<LiveBucket>(hash);
if (!b)
{
throw std::runtime_error(std::string("missing bucket: ") +
binToHex(hash));
}
processArchivalMetrics(b, ledgerEntries, ttls);
blSize += b->getSize();
}
// *BytesNewest == bytes consumed only by newest version of BucketEntry
// *BytesOutdated == bytes consumed only by outdated version of BucketEntry
// live -> liveUntilLedger >= ledgerSeq
// expired -> liveUntilLedger < ledgerSeq, but not yet evicted
uint64_t liveBytesNewest{};
uint64_t liveBytesOutdated{};
uint64_t expiredBytesNewest{};
uint64_t expiredBytesOutdated{};
uint64_t evictedBytes{}; // All evicted bytes considered "outdated"
for (auto const& [k, leMetric] : ledgerEntries)
{
auto ttlIter = ttls.find(getTTLKey(k));
releaseAssertOrThrow(ttlIter != ttls.end());
auto const& [ttlMetric, liveUntilLedger] = ttlIter->second;
auto newestBytes = ttlMetric.newestBytes + leMetric.newestBytes;
auto outdatedBytes = ttlMetric.outdatedBytes + leMetric.outdatedBytes;
if (ttlMetric.isDead)
{
releaseAssertOrThrow(leMetric.isDead);
// All bytes considered outdated for evicted entries
evictedBytes += newestBytes + outdatedBytes;
}
else
{
releaseAssertOrThrow(!leMetric.isDead);
// If entry is live
if (liveUntilLedger >=
app->getLedgerManager().getLastClosedLedgerNum())
{
liveBytesNewest += newestBytes;
liveBytesOutdated += outdatedBytes;
}
else
{
expiredBytesNewest += newestBytes;
expiredBytesOutdated += outdatedBytes;
}
}
}
CLOG_INFO(Bucket, "Live BucketList total bytes: {}", blSize);
CLOG_INFO(Bucket,
"Live Temporary Entries: Newest bytes {} ({}%), Outdated bytes "
"{} ({}%)",
liveBytesNewest, (liveBytesNewest / blSize) * 100,
liveBytesOutdated, (liveBytesOutdated / blSize) * 100);
CLOG_INFO(Bucket,
"Expired but not evicted Temporary: Newest bytes {} ({}%), "
"Outdated bytes {} ({}%)",
expiredBytesNewest, (expiredBytesNewest / blSize) * 100,
expiredBytesOutdated, (expiredBytesOutdated / blSize) * 100);
CLOG_INFO(Bucket, "Evicted Temporary Entries: Outdated bytes {} ({}%)",
evictedBytes, (evictedBytes / blSize) * 100);
return 0;
}
int
dumpLedger(Config cfg, std::string const& outputFile,
std::optional<std::string> filterQuery,
std::optional<uint32_t> lastModifiedLedgerCount,
std::optional<uint64_t> limit, std::optional<std::string> groupBy,
std::optional<std::string> aggregate, bool dumpHotArchive,
bool includeAllStates)
{
if (groupBy && !aggregate)
{
LOG_FATAL(DEFAULT_LOG, "--group-by without --agg is not allowed.");
}
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
auto& lm = app->getLedgerManager();
lm.partiallyLoadLastKnownLedgerForUtils();
auto liveSnapshot =
app->getAppConnector().copySearchableLiveBucketListSnapshot();
auto ttlGetter = [&liveSnapshot, includeAllStates,
dumpHotArchive](LedgerKey const& key) -> uint32_t {
if (includeAllStates || dumpHotArchive)
{
throw std::runtime_error(
"TTL is undefined when `--include-all-states` or "
"`--hot-archive` flag is set.");
}
auto entry = liveSnapshot->load(key);
if (!entry)
{
throw std::runtime_error("No TTL entry found for key: " +
xdrToCerealString(key, "key"));
}
return entry->data.ttl().liveUntilLedgerSeq;
};
HistoryArchiveState has = lm.getLastClosedLedgerHAS();
std::optional<uint32_t> minLedger;
if (lastModifiedLedgerCount)
{
uint32_t lclNum = lm.getLastClosedLedgerNum();
if (lclNum >= *lastModifiedLedgerCount)
{
minLedger = lclNum - *lastModifiedLedgerCount;
}
else
{
minLedger = 0;
}
}
std::optional<xdrquery::XDRMatcher> matcher;
if (filterQuery)
{
matcher.emplace(*filterQuery, ttlGetter);
}
std::optional<xdrquery::XDRFieldExtractor> groupByExtractor;
if (groupBy)
{
groupByExtractor.emplace(*groupBy, ttlGetter);
}
std::map<std::vector<xdrquery::ResultType>, xdrquery::XDRAccumulator>
accumulators;
std::ofstream ofs(outputFile);
auto& bm = app->getBucketManager();
uint64_t entryCount = 0;
try
{
bm.visitLedgerEntries(
!dumpHotArchive, has, minLedger,
[&](LedgerEntry const& entry) {
return !matcher || matcher->matchXDR(entry);
},
[&](LedgerEntry const& entry) {
if (aggregate)
{
std::vector<xdrquery::ResultType> key;
if (groupByExtractor)
{
key = groupByExtractor->extractFields(entry);
}
auto it = accumulators.find(key);
if (it == accumulators.end())
{
it = accumulators
.emplace(key, xdrquery::XDRAccumulator(
*aggregate, ttlGetter))
.first;
}
it->second.addEntry(entry);
}
else
{
// When only live state is included, we can also output
// TTL for the Soroban entries.
bool addTTL = !includeAllStates && !dumpHotArchive &&
isSorobanEntry(entry.data);
if (!addTTL)
{
ofs << xdrToCerealString(entry, "entry") << std::endl;
}
else
{
uint32_t liveUntilLedger = ttlGetter(getTTLKey(entry));
std::string s = xdrToCerealString(entry, "entry");
s.erase(s.size() - 3, 2); // remove '\n}'
ofs << s << ",\n \"liveUntilLedgerSeq\": "
<< liveUntilLedger << "\n}\n";
}
}
++entryCount;
return !limit || entryCount < *limit;
},
includeAllStates);
}
catch (xdrquery::XDRQueryError& e)
{
LOG_ERROR(DEFAULT_LOG, "Filter query error: {}", e.what());
}
if (aggregate)
{
writeLedgerAggregationTable(ofs, groupByExtractor, accumulators);
}
LOG_INFO(DEFAULT_LOG, "Finished running query, processed {} entries.",
entryCount);
return 0;
}
void
dumpWasmBlob(Config cfg, std::string const& hash, std::string const& dir)
{
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
auto& lm = app->getLedgerManager();
lm.partiallyLoadLastKnownLedgerForUtils();
auto writeBlob = [&](ContractCodeEntry const& entry) {
std::string filename;
if (dir.empty())
{
filename = fmt::format("{}.wasm", binToHex(entry.hash));
}
else
{
filename = fmt::format("{}/{}.wasm", dir, binToHex(entry.hash));
}
std::ofstream ofs(filename, std::ios::binary);
ofs.write(reinterpret_cast<char const*>(entry.code.data()),
entry.code.size());
LOG_INFO(DEFAULT_LOG, "Wrote {} bytes to {}", entry.code.size(),
filename);
};
auto snap = app->getBucketManager()
.getBucketSnapshotManager()
.copySearchableLiveBucketListSnapshot();
if (hash == "ALL")
{
snap->scanForEntriesOfType(
CONTRACT_CODE, [&](BucketEntry const& entry) {
if (entry.type() == INITENTRY || entry.type() == LIVEENTRY)
{
auto const& codeEntry =
entry.liveEntry().data.contractCode();
writeBlob(codeEntry);
}
return Loop::INCOMPLETE;
});
}
else
{
LedgerKey key;
key.type(LedgerEntryType::CONTRACT_CODE);
key.contractCode().hash = hexToBin256(hash);
auto entry = snap->load(key);
if (entry && entry->data.type() == LedgerEntryType::CONTRACT_CODE)
{
auto const& codeEntry = entry->data.contractCode();
writeBlob(codeEntry);
}
else
{
LOG_ERROR(DEFAULT_LOG, "No CONTRACT_CODE entry found with hash {}",
hash);
}
}
}
void
setForceSCPFlag()
{
LOG_WARNING(DEFAULT_LOG, "* ");
LOG_WARNING(DEFAULT_LOG,
"* Nothing to do: `force scp` command has been deprecated");
LOG_WARNING(DEFAULT_LOG,
"* Refer to `--wait-for-consensus` run option instead");
LOG_WARNING(DEFAULT_LOG, "* ");
}
void
initializeDatabase(Config cfg)
{
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg);
LOG_INFO(DEFAULT_LOG, "*");
LOG_INFO(DEFAULT_LOG,
"* The next launch will catchup from the network afresh.");
LOG_INFO(DEFAULT_LOG, "*");
}
void
showOfflineInfo(Config cfg, bool verbose)
{
// needs real time to display proper stats
VirtualClock clock(VirtualClock::REAL_TIME);
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
app->reportInfo(verbose);
}
bool
checkQuorumIntersectionFromJson(std::filesystem::path const& jsonPath,
std::optional<Config> const& cfg)
{
std::atomic<bool> interrupt(false);
auto qicPtr = QuorumIntersectionChecker::create(
parseQuorumMapFromJson(jsonPath.string()), cfg, interrupt, false);
return qicPtr->networkEnjoysQuorumIntersection();
}
#ifdef BUILD_TESTS
void
loadXdr(Config cfg, std::string const& bucketFile)
{
VirtualClock clock;
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
uint256 zero;
LiveBucket bucket(bucketFile, zero, nullptr);
bucket.apply(*app);
}
int
rebuildLedgerFromBuckets(Config cfg)
{
VirtualClock clock(VirtualClock::REAL_TIME);
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false, true);
app->gracefulStop();
while (clock.crank(true))
;
return 1;
}
#endif
int
reportLastHistoryCheckpoint(Config cfg, std::string const& outputFile)
{
VirtualClock clock(VirtualClock::REAL_TIME);
cfg.setNoListen();
Application::pointer app = Application::create(clock, cfg, false);
auto& wm = app->getWorkScheduler();
auto getHistoryArchiveStateWork =
wm.executeWork<GetHistoryArchiveStateWork>();
auto ok = getHistoryArchiveStateWork->getState() ==
BasicWork::State::WORK_SUCCESS;
if (ok)
{
auto state = getHistoryArchiveStateWork->getHistoryArchiveState();
std::string filename = outputFile.empty() ? "-" : outputFile;
if (filename == "-")
{