forked from erigontech/silkworm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
toolbox.cpp
1687 lines (1440 loc) · 69 KB
/
toolbox.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 2022 The Silkworm Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include <bit>
#include <bitset>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <regex>
#include <string>
#include <CLI/CLI.hpp>
#include <boost/bind/bind.hpp>
#include <boost/format.hpp>
#include <magic_enum.hpp>
#include <silkworm/chain/config.hpp>
#include <silkworm/chain/genesis.hpp>
#include <silkworm/common/as_range.hpp>
#include <silkworm/common/assert.hpp>
#include <silkworm/common/directories.hpp>
#include <silkworm/common/endian.hpp>
#include <silkworm/common/log.hpp>
#include <silkworm/concurrency/signal_handler.hpp>
#include <silkworm/db/genesis.hpp>
#include <silkworm/db/prune_mode.hpp>
#include <silkworm/db/stages.hpp>
#include <silkworm/stagedsync/stage_interhashes/trie_cursor.hpp>
#include <silkworm/trie/hash_builder.hpp>
#include <silkworm/trie/nibbles.hpp>
#include <silkworm/trie/prefix_set.hpp>
namespace fs = std::filesystem;
using namespace silkworm;
using namespace boost::placeholders;
class Progress {
public:
explicit Progress(uint32_t width) : bar_width_{width}, percent_step_{100u / width} {};
~Progress() = default;
/// Returns current progress percent
[[nodiscard]] uint32_t percent() const {
if (!max_counter_) {
return 100;
}
if (!current_counter_) {
return 0;
}
return static_cast<uint32_t>(current_counter_ * 100 / max_counter_);
}
void step() { current_counter_++; }
void set_current(size_t count) { current_counter_ = std::max(count, current_counter_); }
[[nodiscard]] size_t get_current() const noexcept { return current_counter_; }
[[nodiscard]] size_t get_increment_count() const noexcept { return bar_width_ ? (max_counter_ / bar_width_) : 0u; }
void reset() {
current_counter_ = 0;
printed_bar_len_ = 0;
}
void set_task_count(size_t iterations) {
reset();
max_counter_ = iterations;
}
/// Prints progress ticks
std::string print_interval(char c = '.') {
uint32_t percentage{std::min(percent(), 100u)};
uint32_t numChars{percentage / percent_step_};
if (!numChars) return "";
uint32_t intChars{numChars - printed_bar_len_};
if (!intChars) return "";
std::string ret(intChars, c);
printed_bar_len_ += intChars;
return ret;
}
[[maybe_unused]] [[nodiscard]] std::string print_progress(char c = '.') const {
uint32_t percentage{percent()};
uint32_t numChars{percentage / percent_step_};
if (!numChars) {
return "";
}
std::string ret(numChars, c);
return ret;
}
private:
uint32_t bar_width_;
uint32_t percent_step_;
size_t max_counter_{0};
size_t current_counter_{0};
uint32_t printed_bar_len_{0};
};
struct dbTableEntry {
MDBX_dbi id{0};
std::string name{};
mdbx::txn::map_stat stat;
mdbx::map_handle::info info;
[[nodiscard]] size_t pages() const noexcept {
return stat.ms_branch_pages + stat.ms_leaf_pages + stat.ms_overflow_pages;
}
[[nodiscard]] size_t size() const noexcept { return pages() * stat.ms_psize; }
};
struct dbTablesInfo {
size_t mapsize{0};
size_t filesize{0};
size_t pageSize{0};
size_t pages{0};
size_t size{0};
std::vector<dbTableEntry> tables{};
};
struct dbFreeEntry {
size_t id{0};
size_t pages{0};
size_t size{0};
};
struct dbFreeInfo {
size_t pages{0};
size_t size{0};
std::vector<dbFreeEntry> entries{};
};
bool user_confirmation() {
static std::regex pattern{"^([yY])?([nN])?$"};
std::smatch matches;
std::string user_input;
std::cout << "Confirm ? [y/N] ";
do {
std::cin >> user_input;
std::cin.clear();
if (std::regex_search(user_input, matches, pattern, std::regex_constants::match_default)) {
break;
}
} while (true);
if (matches[2].length()) {
return false;
}
return true;
}
void do_clear(db::EnvConfig& config, bool dry, bool always_yes, const std::vector<std::string>& table_names,
bool drop) {
config.readonly = false;
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
auto env{db::open_env(config)};
auto txn{env.start_write()};
for (const auto& tablename : table_names) {
if (!db::has_map(txn, tablename.c_str())) {
std::cout << "Table " << tablename << " not found" << std::endl;
continue;
}
mdbx::map_handle table_map{txn.open_map(tablename)};
size_t rcount{txn.get_map_stat(table_map).ms_entries};
if (!rcount && !drop) {
std::cout << " Table " << tablename << " is already empty. Skipping" << std::endl;
continue;
}
std::cout << "\n"
<< (drop ? "Dropping" : "Emptying") << " table " << tablename << " (" << rcount << " records) "
<< std::flush;
if (!always_yes) {
if (!user_confirmation()) {
std::cout << " Skipped." << std::endl;
continue;
}
}
std::cout << (dry ? "Simulating commit ..." : "Committing ...") << std::endl;
if (drop) {
txn.drop_map(table_map);
} else {
txn.clear_map(table_map);
}
if (dry) {
txn.abort();
} else {
txn.commit();
}
txn = env.start_write();
}
}
dbFreeInfo get_freeInfo(::mdbx::txn& txn) {
dbFreeInfo ret{};
::mdbx::map_handle free_map{0};
auto page_size{txn.get_map_stat(free_map).ms_psize};
const auto& collect_func{[&ret, &page_size](const ::mdbx::cursor&, ::mdbx::cursor::move_result& data) -> bool {
size_t txId;
std::memcpy(&txId, data.key.data(), sizeof(size_t));
uint32_t pagesCount;
std::memcpy(&pagesCount, data.value.data(), sizeof(uint32_t));
size_t pagesSize = pagesCount * page_size;
ret.pages += pagesCount;
ret.size += pagesSize;
ret.entries.push_back({txId, pagesCount, pagesSize});
return true;
}};
auto free_crs{txn.open_cursor(free_map)};
(void)db::cursor_for_each(free_crs, collect_func);
return ret;
}
dbTablesInfo get_tablesInfo(::mdbx::txn& txn) {
dbTablesInfo ret{};
dbTableEntry* table;
ret.filesize = txn.env().get_info().mi_geo.current;
// Get info from the free database
::mdbx::map_handle free_map{0};
auto stat = txn.get_map_stat(free_map);
auto info = txn.get_handle_info(free_map);
table = new dbTableEntry{free_map.dbi, "FREE_DBI", stat, info};
ret.pageSize += table->stat.ms_psize;
ret.pages += table->pages();
ret.size += table->size();
ret.tables.push_back(*table);
// Get info from the unnamed database
::mdbx::map_handle main_map{1};
stat = txn.get_map_stat(main_map);
info = txn.get_handle_info(main_map);
table = new dbTableEntry{main_map.dbi, "MAIN_DBI", stat, info};
ret.pageSize += table->stat.ms_psize;
ret.pages += table->pages();
ret.size += table->size();
ret.tables.push_back(*table);
const auto& collect_func{[&ret, &txn](const ::mdbx::cursor&, ::mdbx::cursor::move_result& data) -> bool {
auto named_map{txn.open_map(data.key.as_string())};
auto stat2{txn.get_map_stat(named_map)};
auto info2{txn.get_handle_info(named_map)};
auto* table2 = new dbTableEntry{named_map.dbi, data.key.as_string(), stat2, info2};
ret.pageSize += table2->stat.ms_psize;
ret.pages += table2->pages();
ret.size += table2->size();
ret.tables.push_back(*table2);
return true;
}};
// Get all tables from the unnamed database
auto main_crs{txn.open_cursor(main_map)};
(void)db::cursor_for_each(main_crs, collect_func);
return ret;
}
void do_scan(const db::EnvConfig& config) {
static std::string fmt_hdr{" %3s %-24s %=50s %13s %13s %13s"};
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
auto tablesInfo{get_tablesInfo(txn)};
std::cout << "\n Database tables : " << tablesInfo.tables.size() << "\n"
<< std::endl;
if (!tablesInfo.tables.empty()) {
std::cout << (boost::format(fmt_hdr) % "Dbi" % "Table name" % "Progress" % "Keys" % "Data" % "Total")
<< std::endl;
std::cout << (boost::format(fmt_hdr) % std::string(3, '-') % std::string(24, '-') % std::string(50, '-') %
std::string(13, '-') % std::string(13, '-') % std::string(13, '-'))
<< std::flush;
for (dbTableEntry item : tablesInfo.tables) {
mdbx::map_handle tbl_map;
std::cout << "\n"
<< (boost::format(" %3u %-24s ") % item.id % item.name) << std::flush;
if (item.id < 2) {
tbl_map = mdbx::map_handle(item.id);
} else {
tbl_map = txn.open_map(item.name);
}
size_t key_size{0};
size_t data_size{0};
Progress progress{50};
progress.set_task_count(item.stat.ms_entries);
size_t batch_size{progress.get_increment_count()};
auto tbl_crs{txn.open_cursor(tbl_map)};
auto result = tbl_crs.to_first(/*throw_notfound =*/false);
while (result) {
key_size += result.key.size();
data_size += result.value.size();
if (!--batch_size) {
if (SignalHandler::signalled()) {
break;
}
progress.set_current(progress.get_current() + progress.get_increment_count());
std::cout << progress.print_interval('.') << std::flush;
batch_size = progress.get_increment_count();
}
result = tbl_crs.to_next(/*throw_notfound =*/false);
}
if (!SignalHandler::signalled()) {
progress.set_current(item.stat.ms_entries);
std::cout << progress.print_interval('.') << std::flush;
std::cout << (boost::format(" %13s %13s %13s") % human_size(key_size) % human_size(data_size) %
human_size(key_size + data_size))
<< std::flush;
} else {
break;
}
}
}
std::cout << "\n"
<< (SignalHandler::signalled() ? "Aborted" : "Done") << " !\n " << std::endl;
txn.commit();
env.close(config.shared);
}
void do_stages(db::EnvConfig& config) {
static std::string fmt_hdr{" %-24s %10s "};
static std::string fmt_row{" %-24s %10u %-8s"};
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
if (!db::has_map(txn, db::table::kSyncStageProgress.name)) {
throw std::runtime_error("Either not a Silkworm db or table " +
std::string{db::table::kSyncStageProgress.name} + " not found");
}
auto crs{db::open_cursor(txn, db::table::kSyncStageProgress)};
if (txn.get_map_stat(crs.map()).ms_entries) {
std::cout << "\n"
<< (boost::format(fmt_hdr) % "Stage Name" % "Block") << std::endl;
std::cout << (boost::format(fmt_hdr) % std::string(24, '-') % std::string(10, '-')) << std::endl;
auto result{crs.to_first(/*throw_notfound =*/false)};
while (result) {
size_t height{endian::load_big_u64(static_cast<uint8_t*>(result.value.data()))};
// Handle "prune_" stages
size_t offset{0};
static const char* prune_prefix = "prune_";
if (std::memcmp(result.key.data(), prune_prefix, 6) == 0) {
offset = 6;
}
bool Known{db::stages::is_known_stage(result.key.char_ptr() + offset)};
std::cout << (boost::format(fmt_row) % result.key.as_string() % height %
(Known ? std::string(8, ' ') : "Unknown"))
<< std::endl;
result = crs.to_next(/*throw_notfound =*/false);
}
std::cout << "\n"
<< std::endl;
} else {
std::cout << "\n There are no stages to list\n"
<< std::endl;
}
txn.commit();
env.close(config.shared);
}
void do_migrations(db::EnvConfig& config) {
static std::string fmt_hdr{" %-24s"};
static std::string fmt_row{" %-24s"};
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
if (!db::has_map(txn, db::table::kMigrations.name)) {
throw std::runtime_error("Either not a Silkworm db or table " + std::string{db::table::kMigrations.name} +
" not found");
}
auto crs{db::open_cursor(txn, db::table::kMigrations)};
if (txn.get_map_stat(crs.map()).ms_entries) {
std::cout << "\n"
<< (boost::format(fmt_hdr) % "Migration Name") << std::endl;
std::cout << (boost::format(fmt_hdr) % std::string(24, '-')) << std::endl;
auto result{crs.to_first(/*throw_notfound =*/false)};
while (result) {
std::cout << (boost::format(fmt_row) % result.key.as_string()) << std::endl;
result = crs.to_next(/*throw_notfound =*/false);
}
std::cout << "\n"
<< std::endl;
} else {
std::cout << "\n There are no migrations to list\n"
<< std::endl;
}
txn.commit();
env.close(config.shared);
}
void do_stage_set(db::EnvConfig& config, std::string&& stage_name, uint32_t new_height, bool dry) {
config.readonly = false;
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
auto env{silkworm::db::open_env(config)};
auto txn{env.start_write()};
if (!db::stages::is_known_stage(stage_name.c_str())) {
throw std::runtime_error("Stage name " + stage_name + " is not known");
}
if (!db::has_map(txn, silkworm::db::table::kSyncStageProgress.name)) {
throw std::runtime_error("Either non Silkworm db or table " +
std::string(silkworm::db::table::kSyncStageProgress.name) + " not found");
}
auto old_height{db::stages::read_stage_progress(txn, stage_name.c_str())};
db::stages::write_stage_progress(txn, stage_name.c_str(), new_height);
if (!dry) {
txn.commit();
}
std::cout << "\n Stage " << stage_name << " touched from " << old_height << " to " << new_height << "\n"
<< std::endl;
}
void do_tables(db::EnvConfig& config) {
static std::string fmt_hdr{" %3s %-24s %10s %2s %10s %10s %10s %12s %10s %10s"};
static std::string fmt_row{" %3i %-24s %10u %2u %10u %10u %10u %12s %10s %10s"};
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
auto dbTablesInfo{get_tablesInfo(txn)};
auto dbFreeInfo{get_freeInfo(txn)};
std::cout << "\n Database tables : " << dbTablesInfo.tables.size() << std::endl;
std::cout << " Effective pruning : " << db::read_prune_mode(txn).to_string() << "\n"
<< std::endl;
if (!dbTablesInfo.tables.empty()) {
std::cout << (boost::format(fmt_hdr) % "Dbi" % "Table name" % "Records" % "D" % "Branch" % "Leaf" % "Overflow" %
"Size" % "Key" % "Value")
<< std::endl;
std::cout << (boost::format(fmt_hdr) % std::string(3, '-') % std::string(24, '-') % std::string(10, '-') %
std::string(2, '-') % std::string(10, '-') % std::string(10, '-') % std::string(10, '-') %
std::string(12, '-') % std::string(10, '-') % std::string(10, '-'))
<< std::endl;
for (auto& item : dbTablesInfo.tables) {
auto keyMode = magic_enum::enum_name(item.info.key_mode());
auto valueMode = magic_enum::enum_name(item.info.value_mode());
std::cout << (boost::format(fmt_row) % item.id % item.name % item.stat.ms_entries % item.stat.ms_depth %
item.stat.ms_branch_pages % item.stat.ms_leaf_pages % item.stat.ms_overflow_pages %
human_size(item.size()) % keyMode % valueMode)
<< std::endl;
}
}
std::cout << "\n"
<< " Database file size (A) : " << (boost::format("%13s") % human_size(dbTablesInfo.filesize)) << "\n"
<< " Data pages count : " << (boost::format("%13u") % dbTablesInfo.pages) << "\n"
<< " Data pages size (B) : " << (boost::format("%13s") % human_size(dbTablesInfo.size)) << "\n"
<< " Free pages count : " << (boost::format("%13u") % dbTablesInfo.tables[0].pages()) << "\n"
<< " Free pages size (C) : " << (boost::format("%13s") % human_size(dbFreeInfo.size)) << "\n"
<< " Reclaimable space : "
<< (boost::format("%13s") % human_size(dbTablesInfo.filesize - dbTablesInfo.size + dbFreeInfo.size))
<< " == A - B + C \n"
<< std::endl;
txn.commit();
env.close(config.shared);
}
void do_freelist(db::EnvConfig& config, bool detail) {
static std::string fmt_hdr{"%9s %9s %12s"};
static std::string fmt_row{"%9u %9u %12s"};
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
auto dbFreeInfo{get_freeInfo(txn)};
if (!dbFreeInfo.entries.empty() && detail) {
std::cout << "\n"
<< (boost::format(fmt_hdr) % "TxId" % "Pages" % "Size") << "\n"
<< (boost::format(fmt_hdr) % std::string(9, '-') % std::string(9, '-') % std::string(12, '-'))
<< std::endl;
for (auto& item : dbFreeInfo.entries) {
std::cout << (boost::format(fmt_row) % item.id % item.pages % human_size(item.size)) << std::endl;
}
}
std::cout << "\n Record count : " << boost::format("%13u") % dbFreeInfo.entries.size() << "\n"
<< " Free pages count : " << boost::format("%13u") % dbFreeInfo.pages << "\n"
<< " Free pages size : " << boost::format("%13s") % human_size(dbFreeInfo.size) << "\n"
<< std::endl;
txn.commit();
env.close(config.shared);
}
void do_schema(db::EnvConfig& config) {
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
auto schema_version{db::read_schema_version(txn)};
if (!schema_version.has_value()) {
throw std::runtime_error("Not a Silkworm db or no schema version found");
}
std::cout << "\n"
<< "Database schema version : " << schema_version->to_string() << "\n"
<< std::endl;
txn.commit();
env.close(config.shared);
}
void do_compact(db::EnvConfig& config, const std::string& work_dir, bool replace, bool nobak) {
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
fs::path work_path{work_dir};
if (work_path.has_filename()) {
work_path += fs::path::preferred_separator;
}
std::error_code ec;
fs::create_directories(work_path, ec);
if (ec) {
throw std::runtime_error("Directory " + work_path.string() + " does not exist and could not be created");
}
fs::path target_file_path{work_path / fs::path(db::kDbDataFileName)};
if (fs::exists(target_file_path)) {
throw std::runtime_error("Directory " + work_path.string() + " already contains an " +
std::string(db::kDbDataFileName) + " file");
}
auto env{silkworm::db::open_env(config)};
// Determine file size of origin db
size_t src_filesize{env.get_info().mi_geo.current};
// Ensure target working directory has enough free space
// at least the size of origin db
auto target_space = fs::space(target_file_path.parent_path());
if (target_space.free <= src_filesize) {
throw std::runtime_error("Insufficient disk space on working directory's partition");
}
std::cout << "\n Compacting database from " << config.path << "\n into " << target_file_path
<< "\n Please be patient as there is no progress report ..." << std::endl;
env.copy(/*destination*/ target_file_path.string(), /*compactify*/ true, /*forcedynamic*/ true);
std::cout << "\n Database compaction " << (SignalHandler::signalled() ? "aborted !" : "completed ...") << std::endl;
env.close();
if (!SignalHandler::signalled()) {
// Do we have a valid compacted file on disk ?
// replace source with target
if (!fs::exists(target_file_path)) {
throw std::runtime_error("Can't locate compacted database");
}
// Do we have to replace original file ?
if (replace) {
auto source_file_path{db::get_datafile_path(fs::path(config.path))};
// Create a backup copy before replacing ?
if (!nobak) {
std::cout << " Creating backup copy of origin database ..." << std::endl;
std::string src_file_back{db::kDbDataFileName};
src_file_back.append(".bak");
fs::path src_path_bak{source_file_path.parent_path() / fs::path{src_file_back}};
if (fs::exists(src_path_bak)) {
fs::remove(src_path_bak);
}
fs::rename(source_file_path, src_path_bak);
}
std::cout << " Replacing origin database with compacted ..." << std::endl;
if (fs::exists(source_file_path)) {
fs::remove(source_file_path);
}
fs::rename(target_file_path, source_file_path);
}
}
}
void do_copy(db::EnvConfig& src_config, const std::string& target_dir, bool create, bool noempty,
std::vector<std::string>& names, std::vector<std::string>& xnames) {
if (!src_config.exclusive) {
throw std::runtime_error("Function requires exclusive access to source database");
}
fs::path target_path{target_dir};
if (target_path.has_filename()) {
target_path += fs::path::preferred_separator;
}
if (!fs::exists(target_path) || !fs::is_directory(target_path)) {
if (!create) {
throw std::runtime_error("Directory " + target_path.string() + " does not exist. Try --create");
}
std::error_code ec;
fs::create_directories(target_path, ec);
if (ec) {
throw std::runtime_error("Directory " + target_path.string() + " does not exist and could not be created");
}
}
// Target config
db::EnvConfig tgt_config{target_path.string()};
tgt_config.exclusive = true;
fs::path target_file_path{target_path / fs::path(db::kDbDataFileName)};
if (!fs::exists(target_file_path)) {
tgt_config.create = true;
}
// Source db
auto src_env{silkworm::db::open_env(src_config)};
auto src_txn{src_env.start_read()};
// Target db
auto tgt_env{silkworm::db::open_env(tgt_config)};
auto tgt_txn{tgt_env.start_write()};
// Get free info and tables from both source and target environment
auto src_tableInfo = get_tablesInfo(src_txn);
auto tgt_tableInfo = get_tablesInfo(tgt_txn);
// Check source db has tables to copy besides the two system tables
if (src_tableInfo.tables.size() < 3) {
throw std::runtime_error("Source db has no tables to copy.");
}
size_t bytesWritten{0};
std::cout << boost::format(" %-24s %=50s") % "Table" % "Progress" << std::endl;
std::cout << boost::format(" %-24s %=50s") % std::string(24, '-') % std::string(50, '-') << std::flush;
// Loop source tables
for (auto& src_table : src_tableInfo.tables) {
if (SignalHandler::signalled()) {
break;
}
std::cout << "\n " << boost::format("%-24s ") % src_table.name << std::flush;
// Is this a system table ?
if (src_table.id < 2) {
std::cout << "Skipped (SYSTEM TABLE)" << std::flush;
continue;
}
// Is this table present in the list user has provided ?
if (!names.empty()) {
auto it = as_range::find(names, src_table.name);
if (it == names.end()) {
std::cout << "Skipped (no match --tables)" << std::flush;
continue;
}
}
// Is this table present in the list user has excluded ?
if (!xnames.empty()) {
auto it = as_range::find(xnames, src_table.name);
if (it != xnames.end()) {
std::cout << "Skipped (match --xtables)" << std::flush;
continue;
}
}
// Is table empty ?
if (!src_table.stat.ms_entries && noempty) {
std::cout << "Skipped (--noempty)" << std::flush;
continue;
}
// Is source table already present in target db ?
bool exists_on_target{false};
bool populated_on_target{false};
if (!tgt_tableInfo.tables.empty()) {
auto it = as_range::find_if(
tgt_tableInfo.tables, [&src_table](dbTableEntry& item) -> bool { return item.name == src_table.name; });
if (it != tgt_tableInfo.tables.end()) {
exists_on_target = true;
populated_on_target = (it->stat.ms_entries > 0);
}
}
// Ready to copy
auto src_table_map{src_txn.open_map(src_table.name)};
auto src_table_info{src_txn.get_handle_info(src_table_map)};
// If table does not exist on target create it with same flags as
// origin table. Check the info match otherwise.
mdbx::map_handle tgt_table_map;
if (!exists_on_target) {
tgt_table_map = tgt_txn.create_map(src_table.name, src_table_info.key_mode(), src_table_info.value_mode());
} else {
tgt_table_map = tgt_txn.open_map(src_table.name);
auto tgt_table_info{tgt_txn.get_handle_info(tgt_table_map)};
if (src_table_info.flags != tgt_table_info.flags) {
std::cout << "Skipped (source and target have incompatible flags)" << std::flush;
continue;
}
}
// Loop source and write into target
Progress progress{50};
progress.set_task_count(src_table.stat.ms_entries);
size_t batch_size{progress.get_increment_count()};
bool batch_committed{false};
auto src_table_crs{src_txn.open_cursor(src_table_map)};
auto tgt_table_crs{tgt_txn.open_cursor(tgt_table_map)};
MDBX_put_flags_t put_flags{populated_on_target
? MDBX_put_flags_t::MDBX_UPSERT
: ((src_table_info.flags & MDBX_DUPSORT) ? MDBX_put_flags_t::MDBX_APPENDDUP
: MDBX_put_flags_t::MDBX_APPEND)};
auto data{src_table_crs.to_first(/*throw_notfound =*/false)};
while (data) {
::mdbx::error::success_or_throw(tgt_table_crs.put(data.key, &data.value, put_flags));
bytesWritten += (data.key.length() + data.value.length());
if (bytesWritten >= 2_Gibi) {
tgt_txn.commit();
tgt_txn = tgt_env.start_write();
tgt_table_crs.renew(tgt_txn);
batch_committed = true;
bytesWritten = 0;
}
if (!--batch_size) {
if (SignalHandler::signalled()) {
break;
}
progress.set_current(progress.get_current() + progress.get_increment_count());
std::cout << progress.print_interval(batch_committed ? 'W' : '.') << std::flush;
batch_committed = false;
batch_size = progress.get_increment_count();
}
data = src_table_crs.to_next(/*throw_notfound =*/false);
}
// Close all
if (SignalHandler::signalled()) {
break;
}
tgt_txn.commit();
tgt_txn = tgt_env.start_write();
batch_committed = true;
bytesWritten = 0;
progress.set_current(src_table.stat.ms_entries);
std::cout << progress.print_interval(batch_committed ? 'W' : '.') << std::flush;
}
std::cout << "\n All done!" << std::endl;
}
/**
* \brief Initializes a silkworm db.
*
* Can parse a custom genesis file in json format or import data from known chain configs
*
* \param DataDir data_dir : hold data directory info about db paths
* \param json_file : a string representing the path where to load custom json from
* \param uint32_t chain_id : an identifier for a known chain
* \param bool dry : whether or not commit data or run in simulation
*
*/
void do_init_genesis(DataDirectory& data_dir, const std::string&& json_file, uint32_t chain_id, bool dry) {
// Check datadir does not exist
if (data_dir.exists()) {
throw std::runtime_error("Provided data directory already exist");
}
// Ensure data directory tree is built
data_dir.deploy();
// Retrieve source data either from provided json file
// or from embedded sources
std::string source_data;
if (!json_file.empty()) {
std::ifstream ifs(json_file);
source_data = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
} else if (chain_id != 0) {
source_data = read_genesis_data(chain_id);
} else {
throw std::invalid_argument("Either json file or chain_id must be provided");
}
// Parse Json data
// N.B. = instead of {} initialization due to https://github.com/nlohmann/json/issues/2204
auto genesis_json = nlohmann::json::parse(source_data, nullptr, /* allow_exceptions = */ false);
// Prime database
db::EnvConfig config{data_dir.chaindata().path().string(), /*create*/ true};
auto env{db::open_env(config)};
auto txn{env.start_write()};
db::table::check_or_create_chaindata_tables(txn);
db::initialize_genesis(txn, genesis_json, /*allow_exceptions=*/true);
// Set schema version
silkworm::db::VersionBase v{3, 0, 0};
db::write_schema_version(txn, v);
if (!dry) {
txn.commit();
} else {
txn.abort();
}
env.close();
}
void do_chainconfig(db::EnvConfig& config) {
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
auto chain_config{db::read_chain_config(txn)};
if (!chain_config.has_value()) {
throw std::runtime_error("Not an initialized Silkworm db or unknown/custom chain ");
}
const auto& chain{chain_config.value()};
std::cout << "\n Chain id " << chain.chain_id << "\n Settings (json) : \n"
<< chain.to_json().dump() << "\n"
<< std::endl;
txn.commit();
env.close(config.shared);
}
void do_first_byte_analysis(db::EnvConfig& config) {
static std::string fmt_hdr{" %-24s %=50s "};
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
std::cout << "\n"
<< (boost::format(fmt_hdr) % "Table name" % "%") << "\n"
<< (boost::format(fmt_hdr) % std::string(24, '-') % std::string(50, '-')) << "\n"
<< (boost::format(" %-24s ") % db::table::kCode.name) << std::flush;
std::unordered_map<uint8_t, size_t> histogram;
auto code_cursor{db::open_cursor(txn, db::table::kCode)};
Progress progress{50};
size_t total_entries{txn.get_map_stat(code_cursor.map()).ms_entries};
progress.set_task_count(total_entries);
size_t batch_size{progress.get_increment_count()};
code_cursor.to_first();
db::cursor_for_each(code_cursor,
[&histogram, &batch_size, &progress](const ::mdbx::cursor&, mdbx::cursor::move_result& entry) {
if (entry.value.length() > 0) {
uint8_t first_byte{entry.value.at(0)};
++histogram[first_byte];
}
if (!--batch_size) {
progress.set_current(progress.get_current() + progress.get_increment_count());
std::cout << progress.print_interval('.') << std::flush;
batch_size = progress.get_increment_count();
}
return true;
});
BlockNum last_block{db::stages::read_stage_progress(txn, db::stages::kExecutionKey)};
progress.set_current(total_entries);
std::cout << progress.print_interval('.') << std::endl;
std::cout << "\n Last block : " << last_block << "\n Contracts : " << total_entries << "\n"
<< std::endl;
// Sort histogram by usage (from most used to less used)
std::vector<std::pair<uint8_t, size_t>> histogram_sorted;
std::copy(histogram.begin(), histogram.end(),
std::back_inserter<std::vector<std::pair<uint8_t, size_t>>>(histogram_sorted));
std::sort(histogram_sorted.begin(), histogram_sorted.end(),
[](std::pair<uint8_t, size_t>& a, std::pair<uint8_t, size_t>& b) -> bool {
return a.second == b.second ? a.first < b.first : a.second > b.second;
});
if (!histogram_sorted.empty()) {
std::cout << (boost::format(" %-4s %8s") % "Byte" % "Count") << "\n"
<< (boost::format(" %-4s %8s") % std::string(4, '-') % std::string(8, '-')) << std::endl;
for (const auto& [byte_code, usage_count] : histogram_sorted) {
std::cout << (boost::format(" 0x%02x %8u") % static_cast<int>(byte_code) % usage_count) << std::endl;
}
}
std::cout << "\n"
<< std::endl;
}
void do_extract_headers(db::EnvConfig& config, const std::string& file_name, uint32_t step) {
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
/// We can store all header hashes into a single byte array given all
/// hashes are same in length. By consequence we only need to assert
/// total size of byte array is a multiple of hash length.
/// The process is mostly the same we have in genesistool.cpp
/// Open the output file
std::ofstream out_stream{file_name};
out_stream << "/* Generated by Silkworm toolbox's extract headers */\n"
<< "#include <cstdint>\n"
<< "#include <cstddef>\n"
<< "static const uint64_t preverified_hashes_mainnet_internal[] = {" << std::endl;
BlockNum block_max{silkworm::db::stages::read_stage_progress(txn, db::stages::kHeadersKey)};
BlockNum max_height{0};
auto hashes_table{db::open_cursor(txn, db::table::kCanonicalHashes)};
for (BlockNum block_num = 0; block_num <= block_max; block_num += step) {
auto block_key{db::block_key(block_num)};
auto data{hashes_table.find(db::to_slice(block_key), false)};
if (!data.done) {
break;
}
const uint64_t* chuncks{reinterpret_cast<const uint64_t*>(db::from_slice(data.value).data())};
out_stream << " ";
for (int i = 0; i < 4; ++i) {
std::string hex{to_hex(chuncks[i], true)};
out_stream << hex << ",";
}
out_stream << std::endl;
max_height = block_num;
}
out_stream
<< "};\n"
<< "const uint64_t* preverified_hashes_mainnet_data(){return &preverified_hashes_mainnet_internal[0];}\n"
<< "size_t sizeof_preverified_hashes_mainnet_data(){return sizeof(preverified_hashes_mainnet_internal);}\n"
<< "uint64_t preverified_hashes_mainnet_height(){return " << max_height << "ull;}\n"
<< std::endl;
out_stream.close();
}
void do_trie_account_analysis(db::EnvConfig& config) {
static std::string fmt_hdr{" %-24s %=50s "};
if (!config.exclusive) {
throw std::runtime_error("Function requires exclusive access to database");
}
auto env{silkworm::db::open_env(config)};
auto txn{env.start_read()};
std::cout << "\n"
<< (boost::format(fmt_hdr) % "Table name" % "%") << "\n"
<< (boost::format(fmt_hdr) % std::string(24, '-') % std::string(50, '-')) << "\n"
<< (boost::format(" %-24s ") % db::table::kTrieOfAccounts.name) << std::flush;
std::map<size_t, size_t> histogram;
auto code_cursor{db::open_cursor(txn, db::table::kTrieOfAccounts)};