Repository navigation
Expand file tree
/
Copy pathplugin.cpp
More file actions
1444 lines (1286 loc) · 69.5 KB
/
Copy pathplugin.cpp
File metadata and controls
1444 lines (1286 loc) · 69.5 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
#include <graphene/chain/database_exceptions.hpp>
#include <graphene/chain/database.hpp>
#include <graphene/plugins/chain/plugin.hpp>
#include <graphene/plugins/p2p/p2p_plugin.hpp>
#include <fc/io/json.hpp>
#include <fc/string.hpp>
#include <boost/signals2/connection.hpp>
#include <fstream>
#include <iostream>
#include <graphene/protocol/protocol.hpp>
#include <graphene/protocol/types.hpp>
#include <future>
#include <atomic>
#include <cerrno>
#include <system_error>
#if defined(__unix__) || defined(__APPLE__)
#include <fcntl.h>
#include <unistd.h>
#endif
namespace graphene {
namespace plugins {
namespace chain {
namespace bfs = boost::filesystem;
using fc::flat_map;
using protocol::block_id_type;
namespace {
// Is the named plugin in the `plugin = ...` list? appbase enables plugins only from
// that option (plus its template autostart list, which vizd does not use for
// snapshot), and its by-name lookup is protected, so read the option it splits.
// The value may repeat and each entry may be space/tab/comma separated.
bool plugin_enabled_in_config(const std::string& name) {
const auto& args = appbase::app().get_args();
if (args.count("plugin") == 0) {
return false;
}
for (const auto& spec : args.at("plugin").as<std::vector<std::string>>()) {
std::string current;
for (const char c : spec) {
if (c == ' ' || c == '\t' || c == ',') {
if (current == name) return true;
current.clear();
} else {
current += c;
}
}
if (current == name) return true;
}
return false;
}
} // namespace
class plugin::plugin_impl {
public:
uint64_t shared_memory_size = 0;
boost::filesystem::path shared_memory_dir;
bool replay = false;
bool replay_if_corrupted = true;
bool force_replay = false;
bool resync = false;
bool readonly = false;
bool check_locks = false;
bool validate_invariants = false;
int64_t validate_invariants_residual = 0;
uint32_t flush_interval = 0;
flat_map<uint32_t, protocol::block_id_type> loaded_checkpoints;
uint32_t allow_future_time = 5;
uint64_t read_wait_micro;
uint32_t max_read_wait_retries;
uint64_t write_wait_micro;
uint32_t max_write_wait_retries;
size_t inc_shared_memory_size;
size_t min_free_shared_memory_size;
bool enable_plugins_on_push_transaction;
uint32_t block_num_check_free_size = 0;
bool skip_virtual_ops = false;
std::string snapshot_path; // --snapshot: load state from snapshot file
bool replay_from_snapshot = false; // --replay-from-snapshot: snapshot + dlt_block_log replay
bool auto_recover_from_snapshot = false; // --auto-recover-from-snapshot: auto-recover on corruption
std::string snapshot_dir; // resolved snapshot directory for auto-discovery
graphene::chain::database db;
bool single_write_thread = false;
bool sync_start_logged = false; // guard to log sync start only once
std::atomic<bool> currently_syncing{false}; // true while processing P2P sync blocks
std::mutex recovery_read_mutex;
std::atomic<bool> recovery_in_progress{false}; // true while auto-recovery is running
bool pending_snapshot_load = false; // set when snapshot args present but callback not yet registered
// --validate-database-invariants: per-block supply re-check (issue #204)
boost::signals2::connection invariant_check_connection;
plugin_impl() {
// get default settings
read_wait_micro = db.read_wait_micro();
max_read_wait_retries = db.max_read_wait_retries();
write_wait_micro = db.write_wait_micro();
max_write_wait_retries = db.max_write_wait_retries();
}
// HELPERS
graphene::chain::database &database() {
return db;
}
boost::asio::io_context& io_service() {
return appbase::app().get_io_service();
}
constexpr const static char *plugin_name = "chain_api";
static const std::string &name() {
static std::string name = plugin_name;
return name;
}
void check_time_in_block(const protocol::signed_block &block);
bool accept_block(const protocol::signed_block &block, bool currently_syncing, uint32_t skip);
void accept_transaction(const protocol::signed_transaction &trx);
void wipe_db(const bfs::path &data_dir, bool wipe_block_log);
void replay_db(const bfs::path &data_dir, bool force_replay);
fc::path find_latest_snapshot();
void arm_invariant_checks();
};
void plugin::plugin_impl::check_time_in_block(const protocol::signed_block &block) {
time_point_sec now = fc::time_point::now();
uint64_t max_accept_time = now.sec_since_epoch();
max_accept_time += allow_future_time;
FC_ASSERT(block.timestamp.sec_since_epoch() <= max_accept_time);
}
bool plugin::plugin_impl::accept_block(const protocol::signed_block &block, bool currently_syncing_flag, uint32_t skip) {
check_time_in_block(block);
skip = db.validate_block(block, skip);
bool block_applied;
if (single_write_thread) {
std::promise<bool> promise;
auto result = promise.get_future();
boost::asio::post(io_service(), [&]{
try {
promise.set_value(db.push_block(block, skip));
} catch(...) {
promise.set_exception(std::current_exception());
}
});
block_applied = result.get(); // if an exception was, it will be thrown
} else {
block_applied = db.push_block(block, skip);
}
// Update syncing state only after push_block, and only if the block
// was actually applied. Previously this was done before push_block,
// which caused "Sync mode ended" to be logged even when the block
// failed to apply (e.g. dead-fork blocks that go to fork_db's
// unlinked index). This created false syncing state transitions
// that confused the witness plugin and caused sync oscillation,
// particularly when the emergency master receives blocks from a
// competing fork that have gap=0 but previous != head_block_id.
if (block_applied) {
currently_syncing.store(currently_syncing_flag, std::memory_order_release);
if (currently_syncing_flag) {
if (!sync_start_logged) {
ilog("\033[92m>>> Syncing Blockchain started from block #${n} (head: ${head})\033[0m",
("n", block.block_num())("head", db.head_block_num()));
sync_start_logged = true;
}
if (block.block_num() % 500 == 0) {
ilog("\033[93mSyncing Blockchain --- Got block: #${n} time: ${t} producer: ${p}\033[0m",
("t", block.timestamp)("n", block.block_num())("p", block.validator));
}
} else {
if (sync_start_logged) {
ilog("\033[92mSync mode ended: received normal block #${n} (head: ${head}), sync_start_logged reset\033[0m",
("n", block.block_num())("head", db.head_block_num()));
}
sync_start_logged = false; // reset guard when not syncing
}
}
return block_applied;
}
// ---------- schema version helpers ----------
static uint32_t read_schema_version(const bfs::path& data_dir) {
auto p = data_dir / "schema_version";
if (!bfs::exists(p)) return 0;
std::ifstream f(p.string());
uint32_t v = 0;
f >> v;
return v;
}
static void write_schema_version(const bfs::path& data_dir) {
const auto target = data_dir / "schema_version";
#if defined(__unix__) || defined(__APPLE__)
const auto temp = data_dir / ("schema_version.tmp." + std::to_string(::getpid()));
const auto fail = [](const char* action) {
throw std::system_error(errno, std::generic_category(), action);
};
int fd = ::open(temp.string().c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) fail("open schema version temporary file");
try {
const std::string value = std::to_string(CHAIN_SCHEMA_VERSION);
if (::write(fd, value.data(), value.size()) != static_cast<ssize_t>(value.size()))
fail("write schema version");
if (::fsync(fd) != 0) fail("sync schema version");
if (::close(fd) != 0) { fd = -1; fail("close schema version"); }
fd = -1;
if (::rename(temp.string().c_str(), target.string().c_str()) != 0)
fail("rename schema version");
int dir_fd = ::open(data_dir.string().c_str(), O_RDONLY | O_DIRECTORY);
if (dir_fd < 0) fail("open schema version directory");
if (::fsync(dir_fd) != 0) {
int saved_errno = errno;
::close(dir_fd);
errno = saved_errno;
fail("sync schema version directory");
}
if (::close(dir_fd) != 0) fail("close schema version directory");
} catch (...) {
if (fd >= 0) ::close(fd);
bfs::remove(temp);
throw;
}
#else
std::ofstream f(target.string(), std::ios::trunc);
f << CHAIN_SCHEMA_VERSION;
f.flush();
if (!f) throw std::runtime_error("Failed to write schema version");
#endif
if (read_schema_version(data_dir) != CHAIN_SCHEMA_VERSION)
throw std::runtime_error("Schema version verification failed");
}
// ---------- /schema version helpers ----------
void plugin::plugin_impl::wipe_db(const bfs::path &data_dir, bool wipe_block_log) {
if (wipe_block_log) {
ilog("Wiping blockchain with block log.");
} else {
ilog("Wiping blockchain.");
}
db.wipe(data_dir, shared_memory_dir, wipe_block_log);
db.open(data_dir, shared_memory_dir, CHAIN_INIT_SUPPLY, shared_memory_size, chainbase::database::read_write/*, validate_invariants*/ );
};
void plugin::plugin_impl::replay_db(const bfs::path &data_dir, bool force_replay) {
if (!force_replay) {
auto head_block_log = db.get_block_log().head();
force_replay |= head_block_log && db.revision() >= head_block_log->block_num();
}
if (force_replay) {
wipe_db(data_dir, false);
}
auto from_block_num = force_replay ? 1 : db.head_block_num() + 1;
ilog("Replaying blockchain from block num ${from}.", ("from", from_block_num));
db.reindex(data_dir, shared_memory_dir, from_block_num, shared_memory_size);
};
fc::path plugin::plugin_impl::find_latest_snapshot() {
if (snapshot_dir.empty()) {
return fc::path();
}
fc::path dir_path(snapshot_dir);
if (!fc::exists(dir_path) || !fc::is_directory(dir_path)) {
return fc::path();
}
fc::path best_path;
uint32_t best_block = 0;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) {
if (boost::filesystem::is_regular_file(itr->status())) {
std::string filename = itr->path().filename().string();
std::string ext = itr->path().extension().string();
if (ext == ".vizjson" || ext == ".json") {
auto pos = filename.find("snapshot-block-");
if (pos != std::string::npos) {
try {
std::string num_str = filename.substr(pos + 15);
auto dot_pos = num_str.find('.');
if (dot_pos != std::string::npos) num_str = num_str.substr(0, dot_pos);
uint32_t block_num = static_cast<uint32_t>(std::stoul(num_str));
if (block_num > best_block) {
best_block = block_num;
best_path = fc::path(itr->path().string());
}
} catch (...) {}
}
}
}
}
return best_path;
}
void plugin::plugin_impl::accept_transaction(const protocol::signed_transaction &trx) {
uint32_t skip = db.validate_transaction(trx, db.skip_apply_transaction);
if (single_write_thread) {
std::promise<bool> promise;
auto wait = promise.get_future();
boost::asio::post(io_service(), [&]{
try {
db.push_transaction(trx, skip);
promise.set_value(true);
} catch(...) {
promise.set_exception(std::current_exception());
}
});
wait.get(); // if an exception was, it will be thrown
} else {
db.push_transaction(trx, skip);
}
}
plugin::plugin() {
}
plugin::~plugin() {
}
graphene::chain::database &plugin::db() {
return my->db;
}
const graphene::chain::database &plugin::db() const {
return my->db;
}
std::string plugin::get_state_dir() const {
return my->shared_memory_dir.string();
}
bool plugin::is_syncing() const {
return my->currently_syncing.load(std::memory_order_acquire);
}
std::unique_lock<std::mutex> plugin::try_lock_recovery() const {
return std::unique_lock<std::mutex>(my->recovery_read_mutex, std::try_to_lock);
}
bool plugin::is_recovering() const {
return my->recovery_in_progress.load(std::memory_order_acquire);
}
void plugin::clear_syncing() {
if (my->currently_syncing.exchange(false, std::memory_order_acq_rel)) {
ilog("Sync complete: cleared currently_syncing flag (validator block production may resume)");
my->sync_start_logged = false;
}
}
void plugin::set_program_options(boost::program_options::options_description &cli,
boost::program_options::options_description &cfg) {
cfg.add_options()
(
"shared-file-dir", boost::program_options::value<boost::filesystem::path>()->default_value("state"),
"the location of the shared memory files (absolute path or relative to application data dir)"
) (
"shared-file-size", boost::program_options::value<std::string>()->default_value("2G"),
"Start size of the shared memory file. Default: 2G"
) (
"inc-shared-file-size", boost::program_options::value<std::string>()->default_value("2G"),
"Increasing size on reaching limit of free space in shared memory file (see min-free-shared-file-size). Default: 2G"
) (
"min-free-shared-file-size", boost::program_options::value<std::string>()->default_value("500M"),
"Minimum free space in shared memory file (see inc-shared-file-size). Default: 500M"
) (
"block-num-check-free-size", boost::program_options::value<uint32_t>()->default_value(1000),
"Check free space in shared memory each N blocks. Default: 1000 (each 3000 seconds)."
) (
"checkpoint", boost::program_options::value<std::vector<std::string>>()->composing(),
"Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints."
) (
"flush-state-interval", boost::program_options::value<uint32_t>(),
"flush shared memory changes to disk every N blocks"
) (
"read-wait-micro", boost::program_options::value<uint64_t>(),
"maximum microseconds for trying to get read lock"
) (
"max-read-wait-retries", boost::program_options::value<uint32_t>(),
"maximum number of retries to get read lock"
) (
"write-wait-micro", boost::program_options::value<uint64_t>(),
"maximum microseconds for trying to get write lock"
) (
"max-write-wait-retries", boost::program_options::value<uint32_t>(),
"maximum number of retries to get write lock"
) (
"single-write-thread", boost::program_options::value<bool>()->default_value(false),
"push blocks and transactions from one thread"
) (
"clear-votes-before-block", boost::program_options::value<uint32_t>()->default_value(0),
"remove votes before defined block, should speedup initial synchronization"
) (
"skip-virtual-ops", boost::program_options::value<bool>()->default_value(false),
"virtual operations will not be passed to the plugins, helps to save some memory"
) (
"enable-plugins-on-push-transaction", boost::program_options::value<bool>()->default_value(false),
"enable calling of plugins for operations on push_transaction"
) (
"dlt-block-log-max-blocks", boost::program_options::value<uint32_t>()->default_value(100000),
"Number of recent blocks to keep in the DLT rolling block_log (0 = disabled)"
);
cli.add_options()
(
"replay-blockchain", boost::program_options::bool_switch()->default_value(false),
"clear chain database and replay all blocks"
) (
"replay-if-corrupted", boost::program_options::bool_switch()->default_value(true),
"replay all blocks if shared memory is corrupted"
) (
"force-replay-blockchain", boost::program_options::bool_switch()->default_value(false),
"force clear chain database and replay all blocks"
) (
"replay-from-snapshot", boost::program_options::bool_switch()->default_value(false),
"recover from corruption: import latest snapshot and replay dlt_block_log"
) (
"auto-recover-from-snapshot", boost::program_options::bool_switch()->default_value(true),
"automatically recover from shared memory corruption by importing latest snapshot and replaying dlt_block_log (enabled by default)"
) (
"resync-blockchain", boost::program_options::bool_switch()->default_value(false),
"clear chain database and block log"
) (
"check-locks", boost::program_options::bool_switch()->default_value(false),
"Check correctness of chainbase locking"
) (
"validate-database-invariants", boost::program_options::bool_switch()->default_value(false),
"Validate all supply invariants check out"
) (
"validate-database-invariants-residual", boost::program_options::value<int64_t>()->default_value(0),
"Expected TOKEN supply residual for --validate-database-invariants: a testnet state "
"carrying frozen pre-fix PM dust uses the same value as snapshot-pm-legacy-residual; "
"0 (default) is strict, satoshi-exact"
);
}
void plugin::plugin_initialize(const boost::program_options::variables_map &options) {
my.reset(new plugin_impl());
auto sfd = options.at("shared-file-dir").as<boost::filesystem::path>();
if (sfd.is_relative()) {
my->shared_memory_dir = appbase::app().data_dir() / sfd;
} else {
my->shared_memory_dir = sfd;
}
if (options.count("read-wait-micro")) {
my->read_wait_micro = options.at("read-wait-micro").as<uint64_t>();
}
if (options.count("max-read-wait-retries")) {
my->max_read_wait_retries = options.at("max-read-wait-retries").as<uint32_t>();
}
if (options.count("write-wait-micro")) {
my->write_wait_micro = options.at("write-wait-micro").as<uint64_t>();
}
if (options.count("max-write-wait-retries")) {
my->max_write_wait_retries = options.at("max-write-wait-retries").as<uint32_t>();
}
my->single_write_thread = options.at("single-write-thread").as<bool>();
my->enable_plugins_on_push_transaction = options.at("enable-plugins-on-push-transaction").as<bool>();
my->shared_memory_size = fc::parse_size(options.at("shared-file-size").as<std::string>());
my->inc_shared_memory_size = fc::parse_size(options.at("inc-shared-file-size").as<std::string>());
my->min_free_shared_memory_size = fc::parse_size(options.at("min-free-shared-file-size").as<std::string>());
my->skip_virtual_ops = options.at("skip-virtual-ops").as<bool>();
if (options.count("block-num-check-free-size")) {
my->block_num_check_free_size = options.at("block-num-check-free-size").as<uint32_t>();
}
my->replay = options.at("replay-blockchain").as<bool>();
my->replay_if_corrupted = options.at("replay-if-corrupted").as<bool>();
my->force_replay = options.at("force-replay-blockchain").as<bool>();
my->resync = options.at("resync-blockchain").as<bool>();
my->replay_from_snapshot = options.at("replay-from-snapshot").as<bool>();
my->auto_recover_from_snapshot = options.at("auto-recover-from-snapshot").as<bool>();
my->check_locks = options.at("check-locks").as<bool>();
my->validate_invariants = options.at("validate-database-invariants").as<bool>();
my->validate_invariants_residual = options.at("validate-database-invariants-residual").as<int64_t>();
if (options.count("flush-state-interval")) {
my->flush_interval = options.at("flush-state-interval").as<uint32_t>();
} else {
my->flush_interval = 10000;
}
if (options.count("checkpoint")) {
auto cps = options.at("checkpoint").as<std::vector<std::string>>();
my->loaded_checkpoints.reserve(cps.size());
for (const auto &cp : cps) {
auto item = fc::json::from_string(cp).as<std::pair<uint32_t, protocol::block_id_type>>();
my->loaded_checkpoints[item.first] = item.second;
}
}
// Check if snapshot plugin has a load path configured
if (options.count("snapshot")) {
my->snapshot_path = options.at("snapshot").as<std::string>();
ilog("Chain plugin: will load state from snapshot: ${p}", ("p", my->snapshot_path));
}
// Auto-discover latest snapshot if --snapshot-auto-latest is set and --snapshot is not
if (my->snapshot_path.empty() && options.count("snapshot-auto-latest") && options.at("snapshot-auto-latest").as<bool>()) {
std::string snap_dir = options.count("snapshot-dir") ? options.at("snapshot-dir").as<std::string>() : "";
// If snapshot-dir is not set, default to <data_dir>/snapshots
if (snap_dir.empty()) {
snap_dir = (appbase::app().data_dir() / "snapshots").string();
}
my->snapshot_dir = snap_dir;
fc::path dir_path(snap_dir);
if (fc::exists(dir_path) && fc::is_directory(dir_path)) {
fc::path best_path;
uint32_t best_block = 0;
boost::filesystem::directory_iterator end_itr;
for (boost::filesystem::directory_iterator itr(dir_path); itr != end_itr; ++itr) {
if (boost::filesystem::is_regular_file(itr->status())) {
std::string filename = itr->path().filename().string();
std::string ext = itr->path().extension().string();
if (ext == ".vizjson" || ext == ".json") {
auto pos = filename.find("snapshot-block-");
if (pos != std::string::npos) {
try {
std::string num_str = filename.substr(pos + 15);
auto dot_pos = num_str.find('.');
if (dot_pos != std::string::npos) num_str = num_str.substr(0, dot_pos);
uint32_t block_num = static_cast<uint32_t>(std::stoul(num_str));
if (block_num > best_block) {
best_block = block_num;
best_path = fc::path(itr->path().string());
}
} catch (...) {}
}
}
}
}
if (!best_path.string().empty()) {
my->snapshot_path = best_path.string();
ilog("Chain plugin: auto-discovered latest snapshot: ${p}", ("p", my->snapshot_path));
} else {
wlog("Chain plugin: --snapshot-auto-latest but no snapshots found in ${d}", ("d", snap_dir));
}
}
}
// DLT rolling block_log config
if (options.count("dlt-block-log-max-blocks")) {
my->db._dlt_block_log_max_blocks = options.at("dlt-block-log-max-blocks").as<uint32_t>();
}
// Ensure snapshot_dir is always resolved for auto-recovery even if --snapshot-auto-latest not set
if (my->snapshot_dir.empty()) {
std::string sd = options.count("snapshot-dir") ? options.at("snapshot-dir").as<std::string>() : "";
if (sd.empty()) {
sd = (appbase::app().data_dir() / "snapshots").string();
}
my->snapshot_dir = sd;
}
}
void plugin::plugin_startup() {
ilog("Starting chain with shared_file_size: ${n} bytes", ("n", my->shared_memory_size));
auto data_dir = appbase::app().data_dir() / "state";
if (my->resync) {
wlog("resync requested: deleting block log and shared memory");
my->db.wipe(data_dir, my->shared_memory_dir, true);
}
// ========== force_resync marker recovery (wedge watchdog self-heal) ==========
// The P2P wedged-behind-network watchdog (dlt_p2p_node) writes this marker
// next to shared_memory.bin and exits when it confirms the node is
// permanently stuck on a divergent fork below LIB (rejection livelock,
// 2026-07-13 rpc.viz.cx incident). Fork-switch can't recover state below
// LIB — only wipe + fresh re-bootstrap can. Honor the marker by wiping
// state so head becomes 0, then come up on empty state. This is the exact
// recovery a manual `docker compose up -d --force-recreate` performs, minus
// the operator.
bool resync_marker_seen = false;
{
auto force_resync_marker = my->shared_memory_dir / "force_resync";
if (boost::filesystem::exists(force_resync_marker)) {
resync_marker_seen = true;
wlog("Detected force_resync marker (P2P wedge watchdog). Wiping state for a clean "
"re-bootstrap (network resync or fresh operator-supplied snapshot).");
std::cerr << " force_resync marker found — wiping state for clean re-bootstrap.\n";
try {
my->db.wipe(data_dir, my->shared_memory_dir, true);
} catch (...) {
wlog("force_resync: db.wipe() threw; removing shared_memory.bin directly.");
auto shm = my->shared_memory_dir / "shared_memory.bin";
if (boost::filesystem::exists(shm)) {
boost::system::error_code _shm_ec;
boost::filesystem::remove(shm, _shm_ec);
}
}
// A wedge is a below-LIB divergence: any snapshot THIS node created
// locally (allow-snapshot-serving) was serialized FROM the corrupt
// state, so re-importing it would just re-wedge — a crash loop.
// db.wipe() clears shared_memory.bin + block_log but NOT the
// snapshots/ dir, so --snapshot / --snapshot-auto-latest could
// rediscover that poisoned local snapshot. For this boot, drop any
// configured/auto local snapshot path and disable local snapshot
// auto-recovery so neither the snapshot-load path nor the
// schema/revision recovery paths silently re-import a node-local
// snapshot. The node then comes up on empty state and resyncs from
// the P2P network; if the deployment refreshes a trusted snapshot
// out of band on the supervised restart, that fresh file is used on
// the NEXT boot (marker already cleared). NB: there is no in-wire
// snapshot-fetch-from-peer — recovery is network resync or an
// operator/entrypoint-supplied snapshot, not a protocol download.
my->snapshot_path.clear();
my->auto_recover_from_snapshot = false;
// Remove the marker only after the wipe so a crash mid-wipe re-triggers
// recovery. Use the non-throwing overload: this runs OUTSIDE the
// surrounding try/catch, and a throw here (file locked, permission)
// would abort plugin_startup — with the crash-safe re-trigger that
// becomes a crash loop.
boost::system::error_code _rm_ec;
boost::filesystem::remove(force_resync_marker, _rm_ec);
if (_rm_ec)
wlog("force_resync: failed to remove marker (${e}); may re-trigger next boot.",
("e", _rm_ec.message()));
ilog("force_resync marker cleared; state wiped. Node will come up on empty state and "
"resync from the network (local snapshot auto-import disabled for this boot).");
}
}
// ========== force_replay marker (admin repair) ==========
// node_admin's Objects tab writes this marker and exits when an operator asks to
// rebuild state while keeping the block log: replay reindexes every block, which is
// far cheaper than a network resync and is enough whenever the block log itself is
// intact. The marker is removed before the work starts; a crash mid-replay leaves an
// empty state plus an intact block log, and the normal "revision != head" replay picks
// it up on the next boot.
{
auto force_replay_marker = my->shared_memory_dir / "force_replay";
if (boost::filesystem::exists(force_replay_marker)) {
boost::system::error_code _fr_ec;
if (resync_marker_seen) {
// Both markers asked for a rebuild. The resync above has already wiped state
// AND the block log; replaying an empty log would fail, so the resync wins
// and the stale request is dropped rather than left to crash the next boot.
boost::filesystem::remove(force_replay_marker, _fr_ec);
wlog("force_replay ignored and removed: force_resync already wiped state and "
"the block log in this same startup.");
} else {
wlog("Detected force_replay marker (admin repair). Wiping state and replaying the block log.");
std::cerr << " force_replay marker found — rebuilding state from the block log.\n";
my->force_replay = true;
my->replay = true;
boost::filesystem::remove(force_replay_marker, _fr_ec);
if (_fr_ec)
wlog("force_replay: failed to remove marker (${e}); may re-trigger next boot.",
("e", _fr_ec.message()));
}
}
}
my->db.set_flush_interval(my->flush_interval);
my->db.add_checkpoints(my->loaded_checkpoints);
my->db.set_require_locking(my->check_locks);
my->db.set_read_wait_micro(my->read_wait_micro);
my->db.set_max_read_wait_retries(my->max_read_wait_retries);
my->db.set_write_wait_micro(my->write_wait_micro);
my->db.set_max_write_wait_retries(my->max_write_wait_retries);
my->db.set_inc_shared_memory_size(my->inc_shared_memory_size);
my->db.set_min_free_shared_memory_size(my->min_free_shared_memory_size);
if(my->skip_virtual_ops) {
my->db.set_skip_virtual_ops();
}
if (my->block_num_check_free_size) {
my->db.set_block_num_check_free_size(my->block_num_check_free_size);
}
my->db.enable_plugins_on_push_transaction(my->enable_plugins_on_push_transaction);
// ========== Snapshot loading path ==========
if (!my->snapshot_path.empty() && !my->replay_from_snapshot) {
// Check if shared_memory already has state from a previous run.
// If so, skip snapshot import and use normal open path.
// This prevents re-importing an old snapshot on container restart
// when --snapshot is still in the command line (e.g. VIZD_EXTRA_OPTS).
auto shm_path = my->shared_memory_dir / "shared_memory.bin";
if (boost::filesystem::exists(shm_path) && boost::filesystem::file_size(shm_path) > 0) {
wlog("Shared memory already exists at ${p}. Skipping snapshot import, using normal startup.",
("p", shm_path.string()));
wlog("To force re-import, delete shared_memory first (--resync-blockchain) or remove the shared_memory file.");
} else if (!boost::filesystem::exists(my->snapshot_path)) {
// Snapshot file not found -- maybe it was already consumed (.used) or path is wrong.
// Fall through to normal startup instead of wiping state and failing.
wlog("Snapshot file not found: ${p}. Skipping snapshot import, using normal startup.",
("p", my->snapshot_path));
} else if (snapshot_load_callback) {
// Callback is already registered (snapshot plugin initialized before us) — proceed now.
do_snapshot_load(data_dir, false);
return;
} else if (!plugin_enabled_in_config("snapshot")) {
// --snapshot was accepted but nothing will ever register the callback,
// so the database would stay unopened for the whole run while P2P is
// already running (measured 01.11.2026: SIGSEGV ~250 ms after the
// banner). Name the misconfiguration instead of dying without a word.
elog("--snapshot ${p} requires the snapshot plugin, which is not enabled. "
"Add 'snapshot' to the 'plugin = ...' list in config.ini.",
("p", my->snapshot_path));
throw std::runtime_error(
"--snapshot requires the snapshot plugin: add 'snapshot' to 'plugin = ...' in config.ini");
} else {
// Snapshot plugin hasn't registered its callback yet — defer until
// snapshot plugin calls trigger_snapshot_load().
ilog("Snapshot path configured (${p}) but snapshot plugin callback not yet registered. "
"Deferring snapshot load until snapshot plugin is ready.", ("p", my->snapshot_path));
my->pending_snapshot_load = true;
return;
}
}
// ========== Replay from snapshot + dlt_block_log path ==========
if (my->replay_from_snapshot) {
if (my->snapshot_path.empty()) {
elog("--replay-from-snapshot requires a snapshot path (--snapshot or --snapshot-auto-latest)");
throw std::runtime_error("--replay-from-snapshot requires --snapshot or --snapshot-auto-latest");
}
if (!boost::filesystem::exists(my->snapshot_path)) {
elog("Snapshot file not found: ${p}", ("p", my->snapshot_path));
throw std::runtime_error("Snapshot file not found for --replay-from-snapshot");
}
if (snapshot_load_callback) {
// Callback is already registered — proceed now.
do_snapshot_load(data_dir, true);
return;
} else if (!plugin_enabled_in_config("snapshot")) {
elog("--replay-from-snapshot requires the snapshot plugin, which is not enabled. "
"Add 'snapshot' to the 'plugin = ...' list in config.ini.");
throw std::runtime_error(
"--replay-from-snapshot requires the snapshot plugin: add 'snapshot' to 'plugin = ...' in config.ini");
} else {
// Snapshot plugin hasn't registered its callback yet — defer.
ilog("Replay-from-snapshot configured but snapshot plugin callback not yet registered. "
"Deferring until snapshot plugin is ready.");
my->pending_snapshot_load = true;
return;
}
}
// ========== Schema version check ==========
// Detect chainbase object layout changes before opening shared memory.
// When fields are added/removed/resized in any chainbase-managed object,
// old shared_memory.bin is binary-incompatible and must be rebuilt.
{
uint32_t stored = read_schema_version(data_dir);
if (stored != CHAIN_SCHEMA_VERSION) {
wlog("Chainbase schema version mismatch: stored=${s}, compiled=${c}. "
"Object layout has changed — proactively wiping shared memory.",
("s", stored)("c", CHAIN_SCHEMA_VERSION));
auto shm = my->shared_memory_dir / "shared_memory.bin";
if (bfs::exists(shm)) {
bfs::remove(shm);
wlog("Shared memory wiped.");
}
// After a wipe, db.open() would call init_genesis() and produce
// head=0 / revision=0 — a consistent state that bypasses the
// revision-mismatch recovery path and sends the node into P2P snapshot
// download instead of using a local snapshot.
// Trigger local snapshot recovery explicitly here.
if (my->auto_recover_from_snapshot && snapshot_load_callback) {
fc::path snap = my->find_latest_snapshot();
if (!snap.string().empty()) {
wlog("Schema wipe: found local snapshot ${p}, importing...", ("p", snap.string()));
my->snapshot_path = snap.string();
do_snapshot_load(data_dir, true);
// Write schema version only after successful recovery.
// If do_snapshot_load throws, version stays at the old value
// so the next restart will retry recovery instead of skipping it.
write_schema_version(data_dir);
return;
} else {
wlog("Schema wipe: no local snapshots in ${d}, falling through to normal open.",
("d", my->snapshot_dir));
}
}
// No local snapshot available — fall through. db.open() will call
// init_genesis() (head=0), and write_schema_version at line 639 runs
// after successful open. The "no state" path handles P2P sync or
// replay-if-corrupted replays from block_log.
}
}
// ========== Normal startup path ==========
try {
ilog("Opening shared memory from ${path}", ("path", my->shared_memory_dir.generic_string()));
my->db.open(data_dir, my->shared_memory_dir, CHAIN_INIT_SUPPLY, my->shared_memory_size, chainbase::database::read_write/*, my->validate_invariants*/ );
ilog("db.open() completed successfully, head_block_num=${h}", ("h", my->db.head_block_num()));
auto head_block_log = my->db.get_block_log().head();
ilog("block_log head=${h}", ("h", head_block_log ? std::to_string(head_block_log->block_num()) : std::string("none")));
my->replay |= head_block_log && my->db.revision() != head_block_log->block_num();
if (my->replay) {
my->replay_db(data_dir, my->force_replay);
}
write_schema_version(data_dir);
} catch (const graphene::chain::database_revision_exception &) {
if (my->auto_recover_from_snapshot && snapshot_load_callback) {
wlog("Shared memory corrupted (revision mismatch). Attempting automatic recovery from snapshot...");
fc::path snap = my->find_latest_snapshot();
if (!snap.string().empty()) {
wlog("Auto-recovery: found snapshot ${p}. Wiping shared memory and importing...", ("p", snap.string()));
my->snapshot_path = snap.string();
do_snapshot_load(data_dir, true);
return;
} else {
wlog("Auto-recovery: no snapshots found in ${d}. Falling back to replay.", ("d", my->snapshot_dir));
}
}
if (my->replay_if_corrupted) {
wlog("Error opening database, attempting to replay blockchain.");
my->force_replay |= my->db.revision() >= my->db.head_block_num();
try {
my->replay_db(data_dir, my->force_replay);
} catch (const graphene::chain::block_log_exception &) {
wlog("Error opening block log. Having to resync from network...");
my->wipe_db(data_dir, true);
}
} else {
wlog("Error opening database, quiting. If should replay, set replay-if-corrupted in config.ini to true.");
appbase::app().quit();
return;
}
} catch (...) {
if (my->auto_recover_from_snapshot && snapshot_load_callback) {
wlog("Shared memory corrupted (open failed). Attempting automatic recovery from snapshot...");
fc::path snap = my->find_latest_snapshot();
if (!snap.string().empty()) {
wlog("Auto-recovery: found snapshot ${p}. Wiping shared memory and importing...", ("p", snap.string()));
my->snapshot_path = snap.string();
do_snapshot_load(data_dir, true);
return;
} else {
wlog("Auto-recovery: no snapshots found in ${d}. Falling back to replay.", ("d", my->snapshot_dir));
}
}
if (my->replay_if_corrupted) {
wlog("Error opening database, attempting to replay blockchain.");
try {
my->replay_db(data_dir, true);
} catch (const graphene::chain::block_log_exception &) {
wlog("Error opening block log. Having to resync from network...");
my->wipe_db(data_dir, true);
}
} else {
wlog("Error opening database, quiting. If should replay, set replay-if-corrupted in config.ini to true.");
appbase::app().quit();
return;
}
}
ilog("Started on blockchain with ${n} blocks", ("n", my->db.head_block_num()));
// If --create-snapshot callback is registered, create snapshot and quit
// BEFORE on_sync() — so P2P/witness never start.
if (snapshot_create_callback) {
snapshot_create_callback();
return;
}
// If state is empty and P2P snapshot sync callback is registered,
// download and load snapshot from trusted peers before on_sync().
if (my->db.head_block_num() == 0 && snapshot_p2p_sync_callback) {
std::cerr << " Node has no state (0 blocks). Requesting snapshot from trusted peers...\n";
ilog("Node has no state. Triggering P2P snapshot sync from trusted peers...");
bool sync_failed = false;
try {
snapshot_p2p_sync_callback();
} catch (const fc::exception& e) {
elog("P2P snapshot sync failed: ${e}", ("e", e.to_detail_string()));
std::cerr << " P2P snapshot sync failed: " << e.what() << "\n";
sync_failed = true;
} catch (const std::exception& e) {
elog("P2P snapshot sync failed: ${e}", ("e", e.what()));
std::cerr << " P2P snapshot sync failed: " << e.what() << "\n";
sync_failed = true;
} catch (...) {
elog("P2P snapshot sync failed: unknown exception");
std::cerr << " P2P snapshot sync failed: unknown exception\n";
sync_failed = true;
}
if (sync_failed || my->db.head_block_num() == 0) {
wlog("P2P snapshot sync did not produce state. Will sync from genesis via P2P.");
std::cerr << " WARNING: P2P snapshot sync did not load state.\n";
std::cerr << " Falling back to P2P genesis sync (this will be very slow for mature chains).\n";
} else {
std::cerr << " P2P snapshot sync complete. Started on blockchain with "
<< my->db.head_block_num() << " blocks\n";
ilog("Started on blockchain with ${n} blocks (from P2P snapshot sync)", ("n", my->db.head_block_num()));
}
} else if (my->db.head_block_num() == 0 && !snapshot_p2p_sync_callback) {
wlog("Node has no state (0 blocks) and no P2P snapshot sync configured.");
wlog("Will sync from genesis via P2P (this will be very slow for mature chains).");
wlog("To bootstrap from a trusted peer, configure 'trusted-snapshot-peer' in config.ini.");
std::cerr << " WARNING: Node has 0 blocks and no snapshot sync configured.\n";
std::cerr << " Will sync from genesis via P2P (very slow for mature chains).\n";
std::cerr << " Add 'trusted-snapshot-peer = <ip>:<port>' to config.ini for fast bootstrap.\n";
}
// --validate-database-invariants: issue #204 — the flag used to be accepted and never
// read anywhere. The arming lives in a helper because this function is NOT the only
// exit path: with --replay-from-snapshot / a snapshot path, plugin_startup returns
// early (see do_snapshot_load below), and testnet-vizd runs exactly that way. Arming
// here alone left the flag a silent no-op on the one deployment we accept it on.
my->arm_invariant_checks();
on_sync();
}
void plugin::plugin_impl::arm_invariant_checks() {
if (!validate_invariants)
return;
if (invariant_check_connection.connected())
return; // recovery re-entry: already armed against the same database
ilog("--validate-database-invariants: checking supply invariants at startup and "
"after every applied block (very slow, development only)");
if (validate_invariants_residual != 0)
wlog("--validate-database-invariants: expecting TOKEN delta=${d} "
"(validate-database-invariants-residual — frozen pre-fix testnet dust); "
"this value must be 0 on mainnet", ("d", validate_invariants_residual));
// Startup: a divergent state is fatal — do not serve it to peers.
db.validate_invariants(validate_invariants_residual);
// Per block: report loudly but keep running. Throwing here would be caught by
// CHAIN_TRY_NOTIFY (applied_block is wrapped in it) and only logged anyway, and a
// rethrow as plugin_exception would surface as a block-processing failure, which
// mislabels a LOCAL state problem as an invalid block.
invariant_check_connection = db.applied_block.connect(
[this](const protocol::signed_block &blk) {
try {
// verbose=false: the per-pool breakdown is startup/manual only, so a
// clean run leaves node.log untouched (a divergence still prints it).
db.validate_invariants(validate_invariants_residual, false);
} catch (const fc::exception &e) {
elog("DATABASE INVARIANT VIOLATED after block ${n}: ${e}", ("n", blk.block_num())
("e", e.to_detail_string()));
elog("--validate-database-invariants: this node's state no longer reconciles. "
"Stop it and restore from a trusted snapshot or peer; do not keep serving.");
}
});
}
void plugin::plugin_shutdown() {
if (my->invariant_check_connection.connected())
my->invariant_check_connection.disconnect();
ilog("closing chain database");
my->db.close();
ilog("database closed successfully");
}
void plugin::do_snapshot_load(const bfs::path& data_dir, bool is_recovery) {