-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathchain_plugin.cpp
2816 lines (2374 loc) · 134 KB
/
chain_plugin.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
#include <eosio/chain_plugin/chain_plugin.hpp>
#include <eosio/chain_plugin/trx_retry_db.hpp>
#include <eosio/producer_plugin/producer_plugin.hpp>
#include <eosio/chain/fork_database.hpp>
#include <eosio/chain/block_log.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/authorization_manager.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/config.hpp>
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/controller.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/snapshot.hpp>
#include <eosio/chain/deep_mind.hpp>
#include <eosio/chain_plugin/trx_finality_status_processing.hpp>
#include <eosio/chain/permission_link_object.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/eosio_contract.hpp>
#include <eosio/resource_monitor_plugin/resource_monitor_plugin.hpp>
#include <chainbase/environment.hpp>
#include <boost/signals2/connection.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <fc/io/json.hpp>
#include <fc/variant.hpp>
#include <signal.h>
#include <cstdlib>
// reflect chainbase::environment for --print-build-info option
FC_REFLECT_ENUM( chainbase::environment::os_t,
(OS_LINUX)(OS_MACOS)(OS_WINDOWS)(OS_OTHER) )
FC_REFLECT_ENUM( chainbase::environment::arch_t,
(ARCH_X86_64)(ARCH_ARM)(ARCH_RISCV)(ARCH_OTHER) )
FC_REFLECT(chainbase::environment, (debug)(os)(arch)(boost_version)(compiler) )
const fc::string deep_mind_logger_name("deep-mind");
eosio::chain::deep_mind_handler _deep_mind_log;
namespace eosio {
//declare operator<< and validate funciton for read_mode in the same namespace as read_mode itself
namespace chain {
std::ostream& operator<<(std::ostream& osm, eosio::chain::db_read_mode m) {
if ( m == eosio::chain::db_read_mode::SPECULATIVE ) {
osm << "speculative";
} else if ( m == eosio::chain::db_read_mode::HEAD ) {
osm << "head";
} else if ( m == eosio::chain::db_read_mode::READ_ONLY ) { // deprecated
osm << "read-only";
} else if ( m == eosio::chain::db_read_mode::IRREVERSIBLE ) {
osm << "irreversible";
}
return osm;
}
void validate(boost::any& v,
const std::vector<std::string>& values,
eosio::chain::db_read_mode* /* target_type */,
int)
{
using namespace boost::program_options;
// Make sure no previous assignment to 'v' was made.
validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
std::string const& s = validators::get_single_string(values);
if ( s == "speculative" ) {
v = boost::any(eosio::chain::db_read_mode::SPECULATIVE);
} else if ( s == "head" ) {
v = boost::any(eosio::chain::db_read_mode::HEAD);
} else if ( s == "read-only" ) {
v = boost::any(eosio::chain::db_read_mode::READ_ONLY);
} else if ( s == "irreversible" ) {
v = boost::any(eosio::chain::db_read_mode::IRREVERSIBLE);
} else {
throw validation_error(validation_error::invalid_option_value);
}
}
std::ostream& operator<<(std::ostream& osm, eosio::chain::validation_mode m) {
if ( m == eosio::chain::validation_mode::FULL ) {
osm << "full";
} else if ( m == eosio::chain::validation_mode::LIGHT ) {
osm << "light";
}
return osm;
}
void validate(boost::any& v,
const std::vector<std::string>& values,
eosio::chain::validation_mode* /* target_type */,
int)
{
using namespace boost::program_options;
// Make sure no previous assignment to 'v' was made.
validators::check_first_occurrence(v);
// Extract the first string from 'values'. If there is more than
// one string, it's an error, and exception will be thrown.
std::string const& s = validators::get_single_string(values);
if ( s == "full" ) {
v = boost::any(eosio::chain::validation_mode::FULL);
} else if ( s == "light" ) {
v = boost::any(eosio::chain::validation_mode::LIGHT);
} else {
throw validation_error(validation_error::invalid_option_value);
}
}
}
using namespace eosio;
using namespace eosio::chain;
using namespace eosio::chain::config;
using namespace eosio::chain::plugin_interface;
using vm_type = wasm_interface::vm_type;
using fc::flat_map;
using boost::signals2::scoped_connection;
class chain_plugin_impl {
public:
chain_plugin_impl()
:pre_accepted_block_channel(app().get_channel<channels::pre_accepted_block>())
,accepted_block_header_channel(app().get_channel<channels::accepted_block_header>())
,accepted_block_channel(app().get_channel<channels::accepted_block>())
,irreversible_block_channel(app().get_channel<channels::irreversible_block>())
,accepted_transaction_channel(app().get_channel<channels::accepted_transaction>())
,applied_transaction_channel(app().get_channel<channels::applied_transaction>())
,incoming_block_channel(app().get_channel<incoming::channels::block>())
,incoming_block_sync_method(app().get_method<incoming::methods::block_sync>())
,incoming_transaction_async_method(app().get_method<incoming::methods::transaction_async>())
{}
bfs::path blocks_dir;
bool readonly = false;
flat_map<uint32_t,block_id_type> loaded_checkpoints;
bool accept_transactions = false;
bool api_accept_transactions = true;
bool account_queries_enabled = false;
std::optional<controller::config> chain_config;
std::optional<controller> chain;
std::optional<genesis_state> genesis;
//txn_msg_rate_limits rate_limits;
std::optional<vm_type> wasm_runtime;
fc::microseconds abi_serializer_max_time_us;
std::optional<bfs::path> snapshot_path;
// retained references to channels for easy publication
channels::pre_accepted_block::channel_type& pre_accepted_block_channel;
channels::accepted_block_header::channel_type& accepted_block_header_channel;
channels::accepted_block::channel_type& accepted_block_channel;
channels::irreversible_block::channel_type& irreversible_block_channel;
channels::accepted_transaction::channel_type& accepted_transaction_channel;
channels::applied_transaction::channel_type& applied_transaction_channel;
incoming::channels::block::channel_type& incoming_block_channel;
// retained references to methods for easy calling
incoming::methods::block_sync::method_type& incoming_block_sync_method;
incoming::methods::transaction_async::method_type& incoming_transaction_async_method;
// method provider handles
methods::get_block_by_number::method_type::handle get_block_by_number_provider;
methods::get_block_by_id::method_type::handle get_block_by_id_provider;
methods::get_head_block_id::method_type::handle get_head_block_id_provider;
methods::get_last_irreversible_block_number::method_type::handle get_last_irreversible_block_number_provider;
// scoped connections for chain controller
std::optional<scoped_connection> pre_accepted_block_connection;
std::optional<scoped_connection> accepted_block_header_connection;
std::optional<scoped_connection> accepted_block_connection;
std::optional<scoped_connection> irreversible_block_connection;
std::optional<scoped_connection> accepted_transaction_connection;
std::optional<scoped_connection> applied_transaction_connection;
std::optional<scoped_connection> block_start_connection;
std::optional<chain_apis::account_query_db> _account_query_db;
const producer_plugin* producer_plug;
std::optional<chain_apis::trx_retry_db> _trx_retry_db;
chain_apis::trx_finality_status_processing_ptr _trx_finality_status_processing;
};
chain_plugin::chain_plugin()
:my(new chain_plugin_impl()) {
app().register_config_type<eosio::chain::db_read_mode>();
app().register_config_type<eosio::chain::validation_mode>();
app().register_config_type<chainbase::pinnable_mapped_file::map_mode>();
app().register_config_type<eosio::chain::wasm_interface::vm_type>();
}
chain_plugin::~chain_plugin(){}
void chain_plugin::set_program_options(options_description& cli, options_description& cfg)
{
// build wasm_runtime help text
std::string wasm_runtime_opt = "Override default WASM runtime (";
std::string wasm_runtime_desc;
std::string delim;
#ifdef EOSIO_EOS_VM_JIT_RUNTIME_ENABLED
wasm_runtime_opt += " \"eos-vm-jit\"";
wasm_runtime_desc += "\"eos-vm-jit\" : A WebAssembly runtime that compiles WebAssembly code to native x86 code prior to execution.\n";
delim = ", ";
#endif
#ifdef EOSIO_EOS_VM_RUNTIME_ENABLED
wasm_runtime_opt += delim + "\"eos-vm\"";
wasm_runtime_desc += "\"eos-vm\" : A WebAssembly interpreter.\n";
delim = ", ";
#endif
#ifdef EOSIO_EOS_VM_OC_DEVELOPER
wasm_runtime_opt += delim + "\"eos-vm-oc\"";
wasm_runtime_desc += "\"eos-vm-oc\" : Unsupported. Instead, use one of the other runtimes along with the option enable-eos-vm-oc.\n";
#endif
wasm_runtime_opt += ")\n" + wasm_runtime_desc;
std::string default_wasm_runtime_str= eosio::chain::wasm_interface::vm_type_string(eosio::chain::config::default_wasm_runtime);
cfg.add_options()
("blocks-dir", bpo::value<bfs::path>()->default_value("blocks"),
"the location of the blocks directory (absolute path or relative to application data dir)")
("protocol-features-dir", bpo::value<bfs::path>()->default_value("protocol_features"),
"the location of the protocol_features directory (absolute path or relative to application config dir)")
("checkpoint", bpo::value<vector<string>>()->composing(), "Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints.")
("wasm-runtime", bpo::value<eosio::chain::wasm_interface::vm_type>()->value_name("runtime")->notifier([](const auto& vm){
#ifndef EOSIO_EOS_VM_OC_DEVELOPER
//throwing an exception here (like EOS_ASSERT) is just gobbled up with a "Failed to initialize" error :(
if(vm == wasm_interface::vm_type::eos_vm_oc) {
elog("EOS VM OC is a tier-up compiler and works in conjunction with the configured base WASM runtime. Enable EOS VM OC via 'eos-vm-oc-enable' option");
EOS_ASSERT(false, plugin_exception, "");
}
#endif
})->default_value(eosio::chain::config::default_wasm_runtime, default_wasm_runtime_str), wasm_runtime_opt.c_str()
)
("profile-account", boost::program_options::value<vector<string>>()->composing(),
"The name of an account whose code will be profiled")
("abi-serializer-max-time-ms", bpo::value<uint32_t>()->default_value(config::default_abi_serializer_max_time_us / 1000),
"Override default maximum ABI serialization time allowed in ms")
("chain-state-db-size-mb", bpo::value<uint64_t>()->default_value(config::default_state_size / (1024 * 1024)), "Maximum size (in MiB) of the chain state database")
("chain-state-db-guard-size-mb", bpo::value<uint64_t>()->default_value(config::default_state_guard_size / (1024 * 1024)), "Safely shut down node when free space remaining in the chain state database drops below this size (in MiB).")
("signature-cpu-billable-pct", bpo::value<uint32_t>()->default_value(config::default_sig_cpu_bill_pct / config::percent_1),
"Percentage of actual signature recovery cpu to bill. Whole number percentages, e.g. 50 for 50%")
("chain-threads", bpo::value<uint16_t>()->default_value(config::default_controller_thread_pool_size),
"Number of worker threads in controller thread pool")
("contracts-console", bpo::bool_switch()->default_value(false),
"print contract's output to console")
("deep-mind", bpo::bool_switch()->default_value(false),
"print deeper information about chain operations")
("actor-whitelist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Account added to actor whitelist (may specify multiple times)")
("actor-blacklist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Account added to actor blacklist (may specify multiple times)")
("contract-whitelist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Contract account added to contract whitelist (may specify multiple times)")
("contract-blacklist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Contract account added to contract blacklist (may specify multiple times)")
("action-blacklist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Action (in the form code::action) added to action blacklist (may specify multiple times)")
("key-blacklist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Public key added to blacklist of keys that should not be included in authorities (may specify multiple times)")
("sender-bypass-whiteblacklist", boost::program_options::value<vector<string>>()->composing()->multitoken(),
"Deferred transactions sent by accounts in this list do not have any of the subjective whitelist/blacklist checks applied to them (may specify multiple times)")
("read-mode", boost::program_options::value<eosio::chain::db_read_mode>()->default_value(eosio::chain::db_read_mode::SPECULATIVE),
"Database read mode (\"speculative\", \"head\", \"read-only\", \"irreversible\").\n"
"In \"speculative\" mode: database contains state changes by transactions in the blockchain up to the head block as well as some transactions not yet included in the blockchain.\n"
"In \"head\" mode: database contains state changes by only transactions in the blockchain up to the head block; transactions received by the node are relayed if valid.\n"
"In \"read-only\" mode: (DEPRECATED: see p2p-accept-transactions & api-accept-transactions) database contains state changes by only transactions in the blockchain up to the head block; transactions received via the P2P network are not relayed and transactions cannot be pushed via the chain API.\n"
"In \"irreversible\" mode: database contains state changes by only transactions in the blockchain up to the last irreversible block; transactions received via the P2P network are not relayed and transactions cannot be pushed via the chain API.\n"
)
( "api-accept-transactions", bpo::value<bool>()->default_value(true), "Allow API transactions to be evaluated and relayed if valid.")
("validation-mode", boost::program_options::value<eosio::chain::validation_mode>()->default_value(eosio::chain::validation_mode::FULL),
"Chain validation mode (\"full\" or \"light\").\n"
"In \"full\" mode all incoming blocks will be fully validated.\n"
"In \"light\" mode all incoming blocks headers will be fully validated; transactions in those validated blocks will be trusted \n")
("disable-ram-billing-notify-checks", bpo::bool_switch()->default_value(false),
"Disable the check which subjectively fails a transaction if a contract bills more RAM to another account within the context of a notification handler (i.e. when the receiver is not the code of the action).")
#ifdef EOSIO_DEVELOPER
("disable-all-subjective-mitigations", bpo::bool_switch()->default_value(false),
"Disable all subjective mitigations checks in the entire codebase.")
#endif
("maximum-variable-signature-length", bpo::value<uint32_t>()->default_value(16384u),
"Subjectively limit the maximum length of variable components in a variable legnth signature to this size in bytes")
("trusted-producer", bpo::value<vector<string>>()->composing(), "Indicate a producer whose blocks headers signed by it will be fully validated, but transactions in those validated blocks will be trusted.")
("database-map-mode", bpo::value<chainbase::pinnable_mapped_file::map_mode>()->default_value(chainbase::pinnable_mapped_file::map_mode::mapped),
"Database map mode (\"mapped\", \"heap\", or \"locked\").\n"
"In \"mapped\" mode database is memory mapped as a file.\n"
#ifndef _WIN32
"In \"heap\" mode database is preloaded in to swappable memory and will use huge pages if available.\n"
"In \"locked\" mode database is preloaded, locked in to memory, and will use huge pages if available.\n"
#endif
)
#ifdef EOSIO_EOS_VM_OC_RUNTIME_ENABLED
("eos-vm-oc-cache-size-mb", bpo::value<uint64_t>()->default_value(eosvmoc::config().cache_size / (1024u*1024u)), "Maximum size (in MiB) of the EOS VM OC code cache")
("eos-vm-oc-compile-threads", bpo::value<uint64_t>()->default_value(1u)->notifier([](const auto t) {
if(t == 0) {
elog("eos-vm-oc-compile-threads must be set to a non-zero value");
EOS_ASSERT(false, plugin_exception, "");
}
}), "Number of threads to use for EOS VM OC tier-up")
("eos-vm-oc-enable", bpo::bool_switch(), "Enable EOS VM OC tier-up runtime")
#endif
("enable-account-queries", bpo::value<bool>()->default_value(false), "enable queries to find accounts by various metadata.")
("max-nonprivileged-inline-action-size", bpo::value<uint32_t>()->default_value(config::default_max_nonprivileged_inline_action_size), "maximum allowed size (in bytes) of an inline action for a nonprivileged account")
("transaction-retry-max-storage-size-gb", bpo::value<uint64_t>(),
"Maximum size (in GiB) allowed to be allocated for the Transaction Retry feature. Setting above 0 enables this feature.")
("transaction-retry-interval-sec", bpo::value<uint32_t>()->default_value(20),
"How often, in seconds, to resend an incoming transaction to network if not seen in a block.")
("transaction-retry-max-expiration-sec", bpo::value<uint32_t>()->default_value(120),
"Maximum allowed transaction expiration for retry transactions, will retry transactions up to this value.")
("transaction-finality-status-max-storage-size-gb", bpo::value<uint64_t>(),
"Maximum size (in GiB) allowed to be allocated for the Transaction Finality Status feature. Setting above 0 enables this feature.")
("transaction-finality-status-success-duration-sec", bpo::value<uint64_t>()->default_value(config::default_max_transaction_finality_status_success_duration_sec),
"Duration (in seconds) a successful transaction's Finality Status will remain available from being first identified.")
("transaction-finality-status-failure-duration-sec", bpo::value<uint64_t>()->default_value(config::default_max_transaction_finality_status_failure_duration_sec),
"Duration (in seconds) a failed transaction's Finality Status will remain available from being first identified.")
("integrity-hash-on-start", bpo::bool_switch(), "Log the state integrity hash on startup")
("integrity-hash-on-stop", bpo::bool_switch(), "Log the state integrity hash on shutdown");
cfg.add_options()("block-log-retain-blocks", bpo::value<uint32_t>(), "If set to greater than 0, periodically prune the block log to store only configured number of most recent blocks.\n"
"If set to 0, no blocks are be written to the block log; block log file is removed after startup.");
// TODO: rate limiting
/*("per-authorized-account-transaction-msg-rate-limit-time-frame-sec", bpo::value<uint32_t>()->default_value(default_per_auth_account_time_frame_seconds),
"The time frame, in seconds, that the per-authorized-account-transaction-msg-rate-limit is imposed over.")
("per-authorized-account-transaction-msg-rate-limit", bpo::value<uint32_t>()->default_value(default_per_auth_account),
"Limits the maximum rate of transaction messages that an account is allowed each per-authorized-account-transaction-msg-rate-limit-time-frame-sec.")
("per-code-account-transaction-msg-rate-limit-time-frame-sec", bpo::value<uint32_t>()->default_value(default_per_code_account_time_frame_seconds),
"The time frame, in seconds, that the per-code-account-transaction-msg-rate-limit is imposed over.")
("per-code-account-transaction-msg-rate-limit", bpo::value<uint32_t>()->default_value(default_per_code_account),
"Limits the maximum rate of transaction messages that an account's code is allowed each per-code-account-transaction-msg-rate-limit-time-frame-sec.")*/
cli.add_options()
("genesis-json", bpo::value<bfs::path>(), "File to read Genesis State from")
("genesis-timestamp", bpo::value<string>(), "override the initial timestamp in the Genesis State file")
("print-genesis-json", bpo::bool_switch()->default_value(false),
"extract genesis_state from blocks.log as JSON, print to console, and exit")
("extract-genesis-json", bpo::value<bfs::path>(),
"extract genesis_state from blocks.log as JSON, write into specified file, and exit")
("print-build-info", bpo::bool_switch()->default_value(false),
"print build environment information to console as JSON and exit")
("extract-build-info", bpo::value<bfs::path>(),
"extract build environment information as JSON, write into specified file, and exit")
("force-all-checks", bpo::bool_switch()->default_value(false),
"do not skip any validation checks while replaying blocks (useful for replaying blocks from untrusted source)")
("disable-replay-opts", bpo::bool_switch()->default_value(false),
"disable optimizations that specifically target replay")
("replay-blockchain", bpo::bool_switch()->default_value(false),
"clear chain state database and replay all blocks")
("hard-replay-blockchain", bpo::bool_switch()->default_value(false),
"clear chain state database, recover as many blocks as possible from the block log, and then replay those blocks")
("delete-all-blocks", bpo::bool_switch()->default_value(false),
"clear chain state database and block log")
("truncate-at-block", bpo::value<uint32_t>()->default_value(0),
"stop hard replay / block log recovery at this block number (if set to non-zero number)")
("terminate-at-block", bpo::value<uint32_t>()->default_value(0),
"terminate after reaching this block number (if set to a non-zero number)")
("snapshot", bpo::value<bfs::path>(), "File to read Snapshot State from")
;
}
#define LOAD_VALUE_SET(options, op_name, container) \
if( options.count(op_name) ) { \
const std::vector<std::string>& ops = options[op_name].as<std::vector<std::string>>(); \
for( const auto& v : ops ) { \
container.emplace( eosio::chain::name( v ) ); \
} \
}
fc::time_point calculate_genesis_timestamp( string tstr ) {
fc::time_point genesis_timestamp;
if( strcasecmp (tstr.c_str(), "now") == 0 ) {
genesis_timestamp = fc::time_point::now();
} else {
genesis_timestamp = time_point::from_iso_string( tstr );
}
auto epoch_us = genesis_timestamp.time_since_epoch().count();
auto diff_us = epoch_us % config::block_interval_us;
if (diff_us > 0) {
auto delay_us = (config::block_interval_us - diff_us);
genesis_timestamp += fc::microseconds(delay_us);
dlog("pausing ${us} microseconds to the next interval",("us",delay_us));
}
ilog( "Adjusting genesis timestamp to ${timestamp}", ("timestamp", genesis_timestamp) );
return genesis_timestamp;
}
void clear_directory_contents( const fc::path& p ) {
using boost::filesystem::directory_iterator;
if( !fc::is_directory( p ) )
return;
for( directory_iterator enditr, itr{p}; itr != enditr; ++itr ) {
fc::remove_all( itr->path() );
}
}
void clear_chainbase_files( const fc::path& p ) {
if( !fc::is_directory( p ) )
return;
fc::remove( p / "shared_memory.bin" );
fc::remove( p / "shared_memory.meta" );
}
std::optional<builtin_protocol_feature> read_builtin_protocol_feature( const fc::path& p ) {
try {
return fc::json::from_file<builtin_protocol_feature>( p );
} catch( const fc::exception& e ) {
wlog( "problem encountered while reading '${path}':\n${details}",
("path", p.generic_string())("details",e.to_detail_string()) );
} catch( ... ) {
dlog( "unknown problem encountered while reading '${path}'",
("path", p.generic_string()) );
}
return {};
}
protocol_feature_set initialize_protocol_features( const fc::path& p, bool populate_missing_builtins = true ) {
using boost::filesystem::directory_iterator;
protocol_feature_set pfs;
bool directory_exists = true;
if( fc::exists( p ) ) {
EOS_ASSERT( fc::is_directory( p ), plugin_exception,
"Path to protocol-features is not a directory: ${path}",
("path", p.generic_string())
);
} else {
if( populate_missing_builtins )
bfs::create_directories( p );
else
directory_exists = false;
}
auto log_recognized_protocol_feature = []( const builtin_protocol_feature& f, const digest_type& feature_digest ) {
if( f.subjective_restrictions.enabled ) {
if( f.subjective_restrictions.preactivation_required ) {
if( f.subjective_restrictions.earliest_allowed_activation_time == time_point{} ) {
ilog( "Support for builtin protocol feature '${codename}' (with digest of '${digest}') is enabled with preactivation required",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
);
} else {
ilog( "Support for builtin protocol feature '${codename}' (with digest of '${digest}') is enabled with preactivation required and with an earliest allowed activation time of ${earliest_time}",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
("earliest_time", f.subjective_restrictions.earliest_allowed_activation_time)
);
}
} else {
if( f.subjective_restrictions.earliest_allowed_activation_time == time_point{} ) {
ilog( "Support for builtin protocol feature '${codename}' (with digest of '${digest}') is enabled without activation restrictions",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
);
} else {
ilog( "Support for builtin protocol feature '${codename}' (with digest of '${digest}') is enabled without preactivation required but with an earliest allowed activation time of ${earliest_time}",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
("earliest_time", f.subjective_restrictions.earliest_allowed_activation_time)
);
}
}
} else {
ilog( "Recognized builtin protocol feature '${codename}' (with digest of '${digest}') but support for it is not enabled",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
);
}
};
map<builtin_protocol_feature_t, fc::path> found_builtin_protocol_features;
map<digest_type, std::pair<builtin_protocol_feature, bool> > builtin_protocol_features_to_add;
// The bool in the pair is set to true if the builtin protocol feature has already been visited to add
map< builtin_protocol_feature_t, std::optional<digest_type> > visited_builtins;
// Read all builtin protocol features
if( directory_exists ) {
for( directory_iterator enditr, itr{p}; itr != enditr; ++itr ) {
auto file_path = itr->path();
if( !fc::is_regular_file( file_path ) || file_path.extension().generic_string().compare( ".json" ) != 0 )
continue;
auto f = read_builtin_protocol_feature( file_path );
if( !f ) continue;
auto res = found_builtin_protocol_features.emplace( f->get_codename(), file_path );
EOS_ASSERT( res.second, plugin_exception,
"Builtin protocol feature '${codename}' was already included from a previous_file",
("codename", builtin_protocol_feature_codename(f->get_codename()))
("current_file", file_path.generic_string())
("previous_file", res.first->second.generic_string())
);
const auto feature_digest = f->digest();
builtin_protocol_features_to_add.emplace( std::piecewise_construct,
std::forward_as_tuple( feature_digest ),
std::forward_as_tuple( *f, false ) );
}
}
// Add builtin protocol features to the protocol feature manager in the right order (to satisfy dependencies)
using itr_type = map<digest_type, std::pair<builtin_protocol_feature, bool>>::iterator;
std::function<void(const itr_type&)> add_protocol_feature =
[&pfs, &builtin_protocol_features_to_add, &visited_builtins, &log_recognized_protocol_feature, &add_protocol_feature]( const itr_type& itr ) -> void {
if( itr->second.second ) {
return;
} else {
itr->second.second = true;
visited_builtins.emplace( itr->second.first.get_codename(), itr->first );
}
for( const auto& d : itr->second.first.dependencies ) {
auto itr2 = builtin_protocol_features_to_add.find( d );
if( itr2 != builtin_protocol_features_to_add.end() ) {
add_protocol_feature( itr2 );
}
}
pfs.add_feature( itr->second.first );
log_recognized_protocol_feature( itr->second.first, itr->first );
};
for( auto itr = builtin_protocol_features_to_add.begin(); itr != builtin_protocol_features_to_add.end(); ++itr ) {
add_protocol_feature( itr );
}
auto output_protocol_feature = [&p]( const builtin_protocol_feature& f, const digest_type& feature_digest ) {
static constexpr int max_tries = 10;
string filename( "BUILTIN-" );
filename += builtin_protocol_feature_codename( f.get_codename() );
filename += ".json";
auto file_path = p / filename;
EOS_ASSERT( !fc::exists( file_path ), plugin_exception,
"Could not save builtin protocol feature with codename '${codename}' because a file at the following path already exists: ${path}",
("codename", builtin_protocol_feature_codename( f.get_codename() ))
("path", file_path.generic_string())
);
if( fc::json::save_to_file( f, file_path ) ) {
ilog( "Saved default specification for builtin protocol feature '${codename}' (with digest of '${digest}') to: ${path}",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
("path", file_path.generic_string())
);
} else {
elog( "Error occurred while writing default specification for builtin protocol feature '${codename}' (with digest of '${digest}') to: ${path}",
("codename", builtin_protocol_feature_codename(f.get_codename()))
("digest", feature_digest)
("path", file_path.generic_string())
);
}
};
std::function<digest_type(builtin_protocol_feature_t)> add_missing_builtins =
[&pfs, &visited_builtins, &output_protocol_feature, &log_recognized_protocol_feature, &add_missing_builtins, populate_missing_builtins]
( builtin_protocol_feature_t codename ) -> digest_type {
auto res = visited_builtins.emplace( codename, std::optional<digest_type>() );
if( !res.second ) {
EOS_ASSERT( res.first->second, protocol_feature_exception,
"invariant failure: cycle found in builtin protocol feature dependencies"
);
return *res.first->second;
}
auto f = protocol_feature_set::make_default_builtin_protocol_feature( codename,
[&add_missing_builtins]( builtin_protocol_feature_t d ) {
return add_missing_builtins( d );
} );
if( !populate_missing_builtins )
f.subjective_restrictions.enabled = false;
const auto& pf = pfs.add_feature( f );
res.first->second = pf.feature_digest;
log_recognized_protocol_feature( f, pf.feature_digest );
if( populate_missing_builtins )
output_protocol_feature( f, pf.feature_digest );
return pf.feature_digest;
};
for( const auto& p : builtin_protocol_feature_codenames ) {
auto itr = found_builtin_protocol_features.find( p.first );
if( itr != found_builtin_protocol_features.end() ) continue;
add_missing_builtins( p.first );
}
return pfs;
}
namespace {
// This can be removed when versions of eosio that support reversible chainbase state file no longer supported.
void upgrade_from_reversible_to_fork_db(chain_plugin_impl* my) {
namespace bfs = boost::filesystem;
bfs::path old_fork_db = my->chain_config->state_dir / config::forkdb_filename;
bfs::path new_fork_db = my->blocks_dir / config::reversible_blocks_dir_name / config::forkdb_filename;
if( bfs::exists( old_fork_db ) && bfs::is_regular_file( old_fork_db ) ) {
bool copy_file = false;
if( bfs::exists( new_fork_db ) && bfs::is_regular_file( new_fork_db ) ) {
if( bfs::last_write_time( old_fork_db ) > bfs::last_write_time( new_fork_db ) ) {
copy_file = true;
}
} else {
copy_file = true;
bfs::create_directories( my->blocks_dir / config::reversible_blocks_dir_name );
}
if( copy_file ) {
fc::rename( old_fork_db, new_fork_db );
} else {
fc::remove( old_fork_db );
}
}
}
}
void
chain_plugin::do_hard_replay(const variables_map& options) {
ilog( "Hard replay requested: deleting state database" );
clear_directory_contents( my->chain_config->state_dir );
auto backup_dir = block_log::repair_log( my->blocks_dir, options.at( "truncate-at-block" ).as<uint32_t>(), config::reversible_blocks_dir_name);
}
void chain_plugin::plugin_initialize(const variables_map& options) {
ilog("initializing chain plugin");
try {
try {
genesis_state gs; // Check if EOSIO_ROOT_KEY is bad
} catch ( const std::exception& ) {
elog( "EOSIO_ROOT_KEY ('${root_key}') is invalid. Recompile with a valid public key.",
("root_key", genesis_state::eosio_root_key));
throw;
}
my->chain_config = controller::config();
if( options.at( "print-build-info" ).as<bool>() || options.count( "extract-build-info") ) {
if( options.at( "print-build-info" ).as<bool>() ) {
ilog( "Build environment JSON:\n${e}", ("e", json::to_pretty_string( chainbase::environment() )) );
}
if( options.count( "extract-build-info") ) {
auto p = options.at( "extract-build-info" ).as<bfs::path>();
if( p.is_relative()) {
p = bfs::current_path() / p;
}
EOS_ASSERT( fc::json::save_to_file( chainbase::environment(), p, true ), misc_exception,
"Error occurred while writing build info JSON to '${path}'",
("path", p.generic_string())
);
ilog( "Saved build info JSON to '${path}'", ("path", p.generic_string()) );
}
EOS_THROW( node_management_success, "reported build environment information" );
}
LOAD_VALUE_SET( options, "sender-bypass-whiteblacklist", my->chain_config->sender_bypass_whiteblacklist );
LOAD_VALUE_SET( options, "actor-whitelist", my->chain_config->actor_whitelist );
LOAD_VALUE_SET( options, "actor-blacklist", my->chain_config->actor_blacklist );
LOAD_VALUE_SET( options, "contract-whitelist", my->chain_config->contract_whitelist );
LOAD_VALUE_SET( options, "contract-blacklist", my->chain_config->contract_blacklist );
LOAD_VALUE_SET( options, "trusted-producer", my->chain_config->trusted_producers );
if( options.count( "action-blacklist" )) {
const std::vector<std::string>& acts = options["action-blacklist"].as<std::vector<std::string>>();
auto& list = my->chain_config->action_blacklist;
for( const auto& a : acts ) {
auto pos = a.find( "::" );
EOS_ASSERT( pos != std::string::npos, plugin_config_exception, "Invalid entry in action-blacklist: '${a}'", ("a", a));
account_name code( a.substr( 0, pos ));
action_name act( a.substr( pos + 2 ));
list.emplace( code, act );
}
}
if( options.count( "key-blacklist" )) {
const std::vector<std::string>& keys = options["key-blacklist"].as<std::vector<std::string>>();
auto& list = my->chain_config->key_blacklist;
for( const auto& key_str : keys ) {
list.emplace( key_str );
}
}
if( options.count( "blocks-dir" )) {
auto bld = options.at( "blocks-dir" ).as<bfs::path>();
if( bld.is_relative())
my->blocks_dir = app().data_dir() / bld;
else
my->blocks_dir = bld;
}
protocol_feature_set pfs;
{
fc::path protocol_features_dir;
auto pfd = options.at( "protocol-features-dir" ).as<bfs::path>();
if( pfd.is_relative())
protocol_features_dir = app().config_dir() / pfd;
else
protocol_features_dir = pfd;
pfs = initialize_protocol_features( protocol_features_dir );
}
if( options.count("checkpoint") ) {
auto cps = options.at("checkpoint").as<vector<string>>();
my->loaded_checkpoints.reserve(cps.size());
for( const auto& cp : cps ) {
auto item = fc::json::from_string(cp).as<std::pair<uint32_t,block_id_type>>();
auto itr = my->loaded_checkpoints.find(item.first);
if( itr != my->loaded_checkpoints.end() ) {
EOS_ASSERT( itr->second == item.second,
plugin_config_exception,
"redefining existing checkpoint at block number ${num}: original: ${orig} new: ${new}",
("num", item.first)("orig", itr->second)("new", item.second)
);
} else {
my->loaded_checkpoints[item.first] = item.second;
}
}
}
if( options.count( "wasm-runtime" ))
my->wasm_runtime = options.at( "wasm-runtime" ).as<vm_type>();
LOAD_VALUE_SET( options, "profile-account", my->chain_config->profile_accounts );
my->abi_serializer_max_time_us = fc::microseconds(options.at("abi-serializer-max-time-ms").as<uint32_t>() * 1000);
my->chain_config->blocks_dir = my->blocks_dir;
my->chain_config->state_dir = app().data_dir() / config::default_state_dir_name;
my->chain_config->read_only = my->readonly;
if (auto resmon_plugin = app().find_plugin<resource_monitor_plugin>()) {
resmon_plugin->monitor_directory(my->chain_config->blocks_dir);
resmon_plugin->monitor_directory(my->chain_config->state_dir);
}
if( options.count( "chain-state-db-size-mb" ))
my->chain_config->state_size = options.at( "chain-state-db-size-mb" ).as<uint64_t>() * 1024 * 1024;
if( options.count( "chain-state-db-guard-size-mb" ))
my->chain_config->state_guard_size = options.at( "chain-state-db-guard-size-mb" ).as<uint64_t>() * 1024 * 1024;
if( options.count( "max-nonprivileged-inline-action-size" ))
my->chain_config->max_nonprivileged_inline_action_size = options.at( "max-nonprivileged-inline-action-size" ).as<uint32_t>();
if( options.count( "transaction-finality-status-max-storage-size-gb" )) {
const uint64_t max_storage_size = options.at( "transaction-finality-status-max-storage-size-gb" ).as<uint64_t>() * 1024 * 1024 * 1024;
if (max_storage_size > 0) {
const fc::microseconds success_duration = fc::seconds(options.at( "transaction-finality-status-success-duration-sec" ).as<uint64_t>());
const fc::microseconds failure_duration = fc::seconds(options.at( "transaction-finality-status-failure-duration-sec" ).as<uint64_t>());
my->_trx_finality_status_processing.reset(
new chain_apis::trx_finality_status_processing(max_storage_size, success_duration, failure_duration));
}
}
if( options.count( "chain-threads" )) {
my->chain_config->thread_pool_size = options.at( "chain-threads" ).as<uint16_t>();
EOS_ASSERT( my->chain_config->thread_pool_size > 0, plugin_config_exception,
"chain-threads ${num} must be greater than 0", ("num", my->chain_config->thread_pool_size) );
}
my->chain_config->sig_cpu_bill_pct = options.at("signature-cpu-billable-pct").as<uint32_t>();
EOS_ASSERT( my->chain_config->sig_cpu_bill_pct >= 0 && my->chain_config->sig_cpu_bill_pct <= 100, plugin_config_exception,
"signature-cpu-billable-pct must be 0 - 100, ${pct}", ("pct", my->chain_config->sig_cpu_bill_pct) );
my->chain_config->sig_cpu_bill_pct *= config::percent_1;
if( my->wasm_runtime )
my->chain_config->wasm_runtime = *my->wasm_runtime;
my->chain_config->force_all_checks = options.at( "force-all-checks" ).as<bool>();
my->chain_config->disable_replay_opts = options.at( "disable-replay-opts" ).as<bool>();
my->chain_config->contracts_console = options.at( "contracts-console" ).as<bool>();
my->chain_config->allow_ram_billing_in_notify = options.at( "disable-ram-billing-notify-checks" ).as<bool>();
#ifdef EOSIO_DEVELOPER
my->chain_config->disable_all_subjective_mitigations = options.at( "disable-all-subjective-mitigations" ).as<bool>();
#endif
my->chain_config->maximum_variable_signature_length = options.at( "maximum-variable-signature-length" ).as<uint32_t>();
if( options.count( "terminate-at-block" ))
my->chain_config->terminate_at_block = options.at( "terminate-at-block" ).as<uint32_t>();
if( options.count( "extract-genesis-json" ) || options.at( "print-genesis-json" ).as<bool>()) {
std::optional<genesis_state> gs;
if( fc::exists( my->blocks_dir / "blocks.log" )) {
gs = block_log::extract_genesis_state( my->blocks_dir );
EOS_ASSERT( gs,
plugin_config_exception,
"Block log at '${path}' does not contain a genesis state, it only has the chain-id.",
("path", (my->blocks_dir / "blocks.log").generic_string())
);
} else {
wlog( "No blocks.log found at '${p}'. Using default genesis state.",
("p", (my->blocks_dir / "blocks.log").generic_string()));
gs.emplace();
}
if( options.at( "print-genesis-json" ).as<bool>()) {
ilog( "Genesis JSON:\n${genesis}", ("genesis", json::to_pretty_string( *gs )));
}
if( options.count( "extract-genesis-json" )) {
auto p = options.at( "extract-genesis-json" ).as<bfs::path>();
if( p.is_relative()) {
p = bfs::current_path() / p;
}
EOS_ASSERT( fc::json::save_to_file( *gs, p, true ),
misc_exception,
"Error occurred while writing genesis JSON to '${path}'",
("path", p.generic_string())
);
ilog( "Saved genesis JSON to '${path}'", ("path", p.generic_string()) );
}
EOS_THROW( extract_genesis_state_exception, "extracted genesis state from blocks.log" );
}
// move fork_db to new location
upgrade_from_reversible_to_fork_db( my.get() );
if(options.count( "block-log-retain-blocks" )) {
my->chain_config->prune_config.emplace();
my->chain_config->prune_config->prune_blocks = options.at( "block-log-retain-blocks" ).as<uint32_t>();
if ( my->chain_config->prune_config->prune_blocks == 0 ) {
// clear out empty blocks.log. otherwise block_log::extract_genesis_state
// will return version 0 which asserts.
if( fc::exists( my->blocks_dir / "blocks.log" ) && fc::file_size( my->blocks_dir / "blocks.log" ) == 0 ) {
fc::remove( my->blocks_dir / "blocks.log" );
fc::remove( my->blocks_dir / "blocks.index" );
}
} else {
EOS_ASSERT(cfile::supports_hole_punching(), plugin_config_exception, "block-log-retain-blocks cannot be greater than 0 because the file system does not support hole punching");
}
}
if( options.at( "delete-all-blocks" ).as<bool>()) {
ilog( "Deleting state database and blocks" );
if( options.at( "truncate-at-block" ).as<uint32_t>() > 0 )
wlog( "The --truncate-at-block option does not make sense when deleting all blocks." );
clear_directory_contents( my->chain_config->state_dir );
clear_directory_contents( my->blocks_dir );
} else if( options.at( "hard-replay-blockchain" ).as<bool>()) {
do_hard_replay(options);
} else if( options.at( "replay-blockchain" ).as<bool>()) {
ilog( "Replay requested: deleting state database" );
if( options.at( "truncate-at-block" ).as<uint32_t>() > 0 )
wlog( "The --truncate-at-block option does not work for a regular replay of the blockchain." );
clear_chainbase_files( my->chain_config->state_dir );
} else if( options.at( "truncate-at-block" ).as<uint32_t>() > 0 ) {
wlog( "The --truncate-at-block option can only be used with --hard-replay-blockchain." );
}
std::optional<chain_id_type> chain_id;
if (options.count( "snapshot" )) {
my->snapshot_path = options.at( "snapshot" ).as<bfs::path>();
EOS_ASSERT( fc::exists(*my->snapshot_path), plugin_config_exception,
"Cannot load snapshot, ${name} does not exist", ("name", my->snapshot_path->generic_string()) );
// recover genesis information from the snapshot
// used for validation code below
auto infile = std::ifstream(my->snapshot_path->generic_string(), (std::ios::in | std::ios::binary));
istream_snapshot_reader reader(infile);
reader.validate();
chain_id = controller::extract_chain_id(reader);
infile.close();
EOS_ASSERT( options.count( "genesis-timestamp" ) == 0,
plugin_config_exception,
"--snapshot is incompatible with --genesis-timestamp as the snapshot contains genesis information");
EOS_ASSERT( options.count( "genesis-json" ) == 0,
plugin_config_exception,
"--snapshot is incompatible with --genesis-json as the snapshot contains genesis information");
auto shared_mem_path = my->chain_config->state_dir / "shared_memory.bin";
EOS_ASSERT( !fc::is_regular_file(shared_mem_path),
plugin_config_exception,
"Snapshot can only be used to initialize an empty database." );
if( fc::is_regular_file( my->blocks_dir / "blocks.log" )) {
auto block_log_genesis = block_log::extract_genesis_state(my->blocks_dir);
if( block_log_genesis ) {
const auto& block_log_chain_id = block_log_genesis->compute_chain_id();
EOS_ASSERT( *chain_id == block_log_chain_id,
plugin_config_exception,
"snapshot chain ID (${snapshot_chain_id}) does not match the chain ID from the genesis state in the block log (${block_log_chain_id})",
("snapshot_chain_id", *chain_id)
("block_log_chain_id", block_log_chain_id)
);
} else {
const auto& block_log_chain_id = block_log::extract_chain_id(my->blocks_dir);
EOS_ASSERT( *chain_id == block_log_chain_id,
plugin_config_exception,
"snapshot chain ID (${snapshot_chain_id}) does not match the chain ID (${block_log_chain_id}) in the block log",
("snapshot_chain_id", *chain_id)
("block_log_chain_id", block_log_chain_id)
);
}
}
} else {
chain_id = controller::extract_chain_id_from_db( my->chain_config->state_dir );
std::optional<genesis_state> block_log_genesis;
std::optional<chain_id_type> block_log_chain_id;
if( fc::is_regular_file( my->blocks_dir / "blocks.log" ) ) {
block_log_genesis = block_log::extract_genesis_state( my->blocks_dir );
if( block_log_genesis ) {
block_log_chain_id = block_log_genesis->compute_chain_id();
} else {
block_log_chain_id = block_log::extract_chain_id( my->blocks_dir );
}
if( chain_id ) {
EOS_ASSERT( *block_log_chain_id == *chain_id, block_log_exception,
"Chain ID in blocks.log (${block_log_chain_id}) does not match the existing "
" chain ID in state (${state_chain_id}).",
("block_log_chain_id", *block_log_chain_id)
("state_chain_id", *chain_id)
);
} else if( block_log_genesis ) {
ilog( "Starting fresh blockchain state using genesis state extracted from blocks.log." );
my->genesis = block_log_genesis;
// Delay setting chain_id until later so that the code handling genesis-json below can know
// that chain_id still only represents a chain ID extracted from the state (assuming it exists).
}
}
if( options.count( "genesis-json" ) ) {
bfs::path genesis_file = options.at( "genesis-json" ).as<bfs::path>();
if( genesis_file.is_relative()) {
genesis_file = bfs::current_path() / genesis_file;
}
EOS_ASSERT( fc::is_regular_file( genesis_file ),
plugin_config_exception,
"Specified genesis file '${genesis}' does not exist.",
("genesis", genesis_file.generic_string()));
genesis_state provided_genesis = fc::json::from_file( genesis_file ).as<genesis_state>();
if( options.count( "genesis-timestamp" ) ) {
provided_genesis.initial_timestamp = calculate_genesis_timestamp( options.at( "genesis-timestamp" ).as<string>() );
ilog( "Using genesis state provided in '${genesis}' but with adjusted genesis timestamp",
("genesis", genesis_file.generic_string()) );
} else {
ilog( "Using genesis state provided in '${genesis}'", ("genesis", genesis_file.generic_string()));
}
if( block_log_genesis ) {
EOS_ASSERT( *block_log_genesis == provided_genesis, plugin_config_exception,