-
Notifications
You must be signed in to change notification settings - Fork 71
/
controller.cpp
3853 lines (3203 loc) · 167 KB
/
controller.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/controller.hpp>
#include <eosio/chain/transaction_context.hpp>
#include <eosio/chain/block_log.hpp>
#include <eosio/chain/fork_database.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/account_object.hpp>
#include <eosio/chain/code_object.hpp>
#include <eosio/chain/block_summary_object.hpp>
#include <eosio/chain/eosio_contract.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <eosio/chain/protocol_state_object.hpp>
#include <eosio/chain/contract_table_objects.hpp>
#include <eosio/chain/generated_transaction_object.hpp>
#include <eosio/chain/transaction_object.hpp>
#include <eosio/chain/genesis_intrinsics.hpp>
#include <eosio/chain/whitelisted_intrinsics.hpp>
#include <eosio/chain/database_header_object.hpp>
#include <eosio/chain/protocol_feature_manager.hpp>
#include <eosio/chain/authorization_manager.hpp>
#include <eosio/chain/resource_limits.hpp>
#include <eosio/chain/chain_snapshot.hpp>
#include <eosio/chain/thread_utils.hpp>
#include <eosio/chain/platform_timer.hpp>
#include <eosio/chain/deep_mind.hpp>
#include <chainbase/chainbase.hpp>
#include <eosio/vm/allocator.hpp>
#include <fc/io/json.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/scoped_exit.hpp>
#include <fc/variant_object.hpp>
#include <new>
#include <shared_mutex>
namespace eosio { namespace chain {
using resource_limits::resource_limits_manager;
using controller_index_set = index_set<
account_index,
account_metadata_index,
account_ram_correction_index,
global_property_multi_index,
protocol_state_multi_index,
dynamic_global_property_multi_index,
block_summary_multi_index,
transaction_multi_index,
generated_transaction_multi_index,
table_id_multi_index,
code_index,
database_header_multi_index
>;
using contract_database_index_set = index_set<
key_value_index,
index64_index,
index128_index,
index256_index,
index_double_index,
index_long_double_index
>;
class maybe_session {
public:
maybe_session() = default;
maybe_session( maybe_session&& other)
:_session(move(other._session))
{
}
explicit maybe_session(database& db) {
_session.emplace(db.start_undo_session(true));
}
maybe_session(const maybe_session&) = delete;
void squash() {
if (_session)
_session->squash();
}
void undo() {
if (_session)
_session->undo();
}
void push() {
if (_session)
_session->push();
}
maybe_session& operator = ( maybe_session&& mv ) {
if (mv._session) {
_session.emplace(move(*mv._session));
mv._session.reset();
} else {
_session.reset();
}
return *this;
};
private:
std::optional<database::session> _session;
};
struct building_block {
building_block( const block_header_state& prev,
block_timestamp_type when,
uint16_t num_prev_blocks_to_confirm,
const vector<digest_type>& new_protocol_feature_activations )
:_pending_block_header_state( prev.next( when, num_prev_blocks_to_confirm ) )
,_new_protocol_feature_activations( new_protocol_feature_activations )
,_trx_mroot_or_receipt_digests( digests_t{} )
{}
pending_block_header_state _pending_block_header_state;
std::optional<producer_authority_schedule> _new_pending_producer_schedule;
vector<digest_type> _new_protocol_feature_activations;
size_t _num_new_protocol_features_that_have_activated = 0;
deque<transaction_metadata_ptr> _pending_trx_metas;
deque<transaction_receipt> _pending_trx_receipts; // boost deque in 1.71 with 1024 elements performs better
std::variant<checksum256_type, digests_t> _trx_mroot_or_receipt_digests;
digests_t _action_receipt_digests;
};
struct assembled_block {
block_id_type _id;
pending_block_header_state _pending_block_header_state;
deque<transaction_metadata_ptr> _trx_metas;
signed_block_ptr _unsigned_block;
// if the _unsigned_block pre-dates block-signing authorities this may be present.
std::optional<producer_authority_schedule> _new_producer_authority_cache;
};
struct completed_block {
block_state_ptr _block_state;
};
using block_stage_type = std::variant<building_block, assembled_block, completed_block>;
struct pending_state {
pending_state( maybe_session&& s, const block_header_state& prev,
block_timestamp_type when,
uint16_t num_prev_blocks_to_confirm,
const vector<digest_type>& new_protocol_feature_activations )
:_db_session( move(s) )
,_block_stage( building_block( prev, when, num_prev_blocks_to_confirm, new_protocol_feature_activations ) )
{}
maybe_session _db_session;
block_stage_type _block_stage;
controller::block_status _block_status = controller::block_status::ephemeral;
std::optional<block_id_type> _producer_block_id;
controller::block_report _block_report{};
/** @pre _block_stage cannot hold completed_block alternative */
const pending_block_header_state& get_pending_block_header_state()const {
if( std::holds_alternative<building_block>(_block_stage) )
return std::get<building_block>(_block_stage)._pending_block_header_state;
return std::get<assembled_block>(_block_stage)._pending_block_header_state;
}
deque<transaction_metadata_ptr> extract_trx_metas() {
if( std::holds_alternative<building_block>(_block_stage) )
return std::move( std::get<building_block>(_block_stage)._pending_trx_metas );
if( std::holds_alternative<assembled_block>(_block_stage) )
return std::move( std::get<assembled_block>(_block_stage)._trx_metas );
return std::get<completed_block>(_block_stage)._block_state->extract_trxs_metas();
}
bool is_protocol_feature_activated( const digest_type& feature_digest )const {
if( std::holds_alternative<building_block>(_block_stage) ) {
auto& bb = std::get<building_block>(_block_stage);
const auto& activated_features = bb._pending_block_header_state.prev_activated_protocol_features->protocol_features;
if( activated_features.find( feature_digest ) != activated_features.end() ) return true;
if( bb._num_new_protocol_features_that_have_activated == 0 ) return false;
auto end = bb._new_protocol_feature_activations.begin() + bb._num_new_protocol_features_that_have_activated;
return (std::find( bb._new_protocol_feature_activations.begin(), end, feature_digest ) != end);
}
if( std::holds_alternative<assembled_block>(_block_stage) ) {
// Calling is_protocol_feature_activated during the assembled_block stage is not efficient.
// We should avoid doing it.
// In fact for now it isn't even implemented.
EOS_THROW( misc_exception,
"checking if protocol feature is activated in the assembled_block stage is not yet supported" );
// TODO: implement this
}
const auto& activated_features = std::get<completed_block>(_block_stage)._block_state->activated_protocol_features->protocol_features;
return (activated_features.find( feature_digest ) != activated_features.end());
}
void push() {
_db_session.push();
}
};
struct controller_impl {
enum class app_window_type {
write, // Only main thread is running; read-only threads are not running.
// All read-write and read-only tasks are sequentially executed.
read // Main thread and read-only threads are running read-ony tasks in parallel.
// Read-write tasks are not being executed.
};
// LLVM sets the new handler, we need to reset this to throw a bad_alloc exception so we can possibly exit cleanly
// and not just abort.
struct reset_new_handler {
reset_new_handler() { std::set_new_handler([](){ throw std::bad_alloc(); }); }
};
reset_new_handler rnh; // placed here to allow for this to be set before constructing the other fields
controller& self;
std::function<void()> shutdown;
chainbase::database db;
block_log blog;
std::optional<pending_state> pending;
block_state_ptr head;
fork_database fork_db;
resource_limits_manager resource_limits;
authorization_manager authorization;
protocol_feature_manager protocol_features;
controller::config conf;
const chain_id_type chain_id; // read by thread_pool threads, value will not be changed
bool replaying = false;
db_read_mode read_mode = db_read_mode::HEAD;
bool in_trx_requiring_checks = false; ///< if true, checks that are normally skipped on replay (e.g. auth checks) cannot be skipped
std::optional<fc::microseconds> subjective_cpu_leeway;
bool trusted_producer_light_validation = false;
uint32_t snapshot_head_block = 0;
struct chain; // chain is a namespace so use an embedded type for the named_thread_pool tag
named_thread_pool<chain> thread_pool;
deep_mind_handler* deep_mind_logger = nullptr;
bool okay_to_print_integrity_hash_on_stop = false;
std::thread::id main_thread_id;
thread_local static platform_timer timer; // a copy for main thread and each read-only thread
#if defined(EOSIO_EOS_VM_RUNTIME_ENABLED) || defined(EOSIO_EOS_VM_JIT_RUNTIME_ENABLED)
thread_local static vm::wasm_allocator wasm_alloc; // a copy for main thread and each read-only thread
#endif
wasm_interface wasmif; // used by main thread and all threads for EOSVMOC
std::mutex threaded_wasmifs_mtx;
std::unordered_map<std::thread::id, std::unique_ptr<wasm_interface>> threaded_wasmifs; // one for each read-only thread, used by eos-vm and eos-vm-jit
app_window_type app_window = app_window_type::write;
typedef pair<scope_name,action_name> handler_key;
map< account_name, map<handler_key, apply_handler> > apply_handlers;
unordered_map< builtin_protocol_feature_t, std::function<void(controller_impl&)>, enum_hash<builtin_protocol_feature_t> > protocol_feature_activation_handlers;
void pop_block() {
auto prev = fork_db.get_block( head->header.previous );
if( !prev ) {
EOS_ASSERT( fork_db.root()->id == head->header.previous, block_validate_exception, "attempt to pop beyond last irreversible block" );
prev = fork_db.root();
}
if ( read_mode == db_read_mode::HEAD ) {
EOS_ASSERT( head->block, block_validate_exception, "attempting to pop a block that was sparsely loaded from a snapshot");
}
head = prev;
db.undo();
protocol_features.popped_blocks_to( prev->block_num );
}
template<builtin_protocol_feature_t F>
void on_activation();
template<builtin_protocol_feature_t F>
inline void set_activation_handler() {
auto res = protocol_feature_activation_handlers.emplace( F, &controller_impl::on_activation<F> );
EOS_ASSERT( res.second, misc_exception, "attempting to set activation handler twice" );
}
inline void trigger_activation_handler( builtin_protocol_feature_t f ) {
auto itr = protocol_feature_activation_handlers.find( f );
if( itr == protocol_feature_activation_handlers.end() ) return;
(itr->second)( *this );
}
void set_apply_handler( account_name receiver, account_name contract, action_name action, apply_handler v ) {
apply_handlers[receiver][make_pair(contract,action)] = v;
}
controller_impl( const controller::config& cfg, controller& s, protocol_feature_set&& pfs, const chain_id_type& chain_id )
:rnh(),
self(s),
db( cfg.state_dir,
cfg.read_only ? database::read_only : database::read_write,
cfg.state_size, false, cfg.db_map_mode ),
blog( cfg.blocks_dir, cfg.blog ),
fork_db( cfg.blocks_dir / config::reversible_blocks_dir_name ),
resource_limits( db, [&s](bool is_trx_transient) { return s.get_deep_mind_logger(is_trx_transient); }),
authorization( s, db ),
protocol_features( std::move(pfs), [&s](bool is_trx_transient) { return s.get_deep_mind_logger(is_trx_transient); } ),
conf( cfg ),
chain_id( chain_id ),
read_mode( cfg.read_mode ),
thread_pool(),
main_thread_id( std::this_thread::get_id() ),
wasmif( conf.wasm_runtime, conf.eosvmoc_tierup, db, conf.state_dir, conf.eosvmoc_config, !conf.profile_accounts.empty() )
{
fork_db.open( [this]( block_timestamp_type timestamp,
const flat_set<digest_type>& cur_features,
const vector<digest_type>& new_features )
{ check_protocol_features( timestamp, cur_features, new_features ); }
);
thread_pool.start( cfg.thread_pool_size, [this]( const fc::exception& e ) {
elog( "Exception in chain thread pool, exiting: ${e}", ("e", e.to_detail_string()) );
if( shutdown ) shutdown();
} );
set_activation_handler<builtin_protocol_feature_t::preactivate_feature>();
set_activation_handler<builtin_protocol_feature_t::replace_deferred>();
set_activation_handler<builtin_protocol_feature_t::get_sender>();
set_activation_handler<builtin_protocol_feature_t::webauthn_key>();
set_activation_handler<builtin_protocol_feature_t::wtmsig_block_signatures>();
set_activation_handler<builtin_protocol_feature_t::action_return_value>();
set_activation_handler<builtin_protocol_feature_t::configurable_wasm_limits>();
set_activation_handler<builtin_protocol_feature_t::blockchain_parameters>();
set_activation_handler<builtin_protocol_feature_t::get_code_hash>();
set_activation_handler<builtin_protocol_feature_t::get_block_num>();
set_activation_handler<builtin_protocol_feature_t::crypto_primitives>();
self.irreversible_block.connect([this](const block_state_ptr& bsp) {
// producer_plugin has already asserted irreversible_block signal is
// called in write window
wasmif.current_lib(bsp->block_num);
for (auto& w: threaded_wasmifs) {
w.second->current_lib(bsp->block_num);
}
});
#define SET_APP_HANDLER( receiver, contract, action) \
set_apply_handler( account_name(#receiver), account_name(#contract), action_name(#action), \
&BOOST_PP_CAT(apply_, BOOST_PP_CAT(contract, BOOST_PP_CAT(_,action) ) ) )
SET_APP_HANDLER( eosio, eosio, newaccount );
SET_APP_HANDLER( eosio, eosio, setcode );
SET_APP_HANDLER( eosio, eosio, setabi );
SET_APP_HANDLER( eosio, eosio, updateauth );
SET_APP_HANDLER( eosio, eosio, deleteauth );
SET_APP_HANDLER( eosio, eosio, linkauth );
SET_APP_HANDLER( eosio, eosio, unlinkauth );
/*
SET_APP_HANDLER( eosio, eosio, postrecovery );
SET_APP_HANDLER( eosio, eosio, passrecovery );
SET_APP_HANDLER( eosio, eosio, vetorecovery );
*/
SET_APP_HANDLER( eosio, eosio, canceldelay );
}
/**
* Plugins / observers listening to signals emited (such as accepted_transaction) might trigger
* errors and throw exceptions. Unless those exceptions are caught it could impact consensus and/or
* cause a node to fork.
*
* If it is ever desirable to let a signal handler bubble an exception out of this method
* a full audit of its uses needs to be undertaken.
*
*/
template<typename Signal, typename Arg>
void emit( const Signal& s, Arg&& a ) {
try {
s( std::forward<Arg>( a ));
} catch (std::bad_alloc& e) {
wlog( "std::bad_alloc: ${w}", ("w", e.what()) );
throw e;
} catch (boost::interprocess::bad_alloc& e) {
wlog( "boost::interprocess::bad alloc: ${w}", ("w", e.what()) );
throw e;
} catch ( controller_emit_signal_exception& e ) {
wlog( "controller_emit_signal_exception: ${details}", ("details", e.to_detail_string()) );
throw e;
} catch ( fc::exception& e ) {
wlog( "fc::exception: ${details}", ("details", e.to_detail_string()) );
} catch ( std::exception& e ) {
wlog( "std::exception: ${details}", ("details", e.what()) );
} catch ( ... ) {
wlog( "signal handler threw exception" );
}
}
void dmlog_applied_transaction(const transaction_trace_ptr& t) {
// dmlog_applied_transaction is called by push_scheduled_transaction
// where transient transactions are not possible, and by push_transaction
// only when the transaction is not transient
if (auto dm_logger = get_deep_mind_logger(false)) {
dm_logger->on_applied_transaction(self.head_block_num() + 1, t);
}
}
void log_irreversible() {
EOS_ASSERT( fork_db.root(), fork_database_exception, "fork database not properly initialized" );
const block_id_type log_head_id = blog.head_id();
const bool valid_log_head = !log_head_id.empty();
const auto lib_num = valid_log_head ? block_header::num_from_id(log_head_id) : (blog.first_block_num() - 1);
auto root_id = fork_db.root()->id;
if( valid_log_head ) {
EOS_ASSERT( root_id == log_head_id, fork_database_exception, "fork database root does not match block log head" );
} else {
EOS_ASSERT( fork_db.root()->block_num == lib_num, fork_database_exception,
"empty block log expects the first appended block to build off a block that is not the fork database root. root block number: ${block_num}, lib: ${lib_num}", ("block_num", fork_db.root()->block_num) ("lib_num", lib_num) );
}
const auto fork_head = fork_db_head();
if( fork_head->dpos_irreversible_blocknum <= lib_num )
return;
auto branch = fork_db.fetch_branch( fork_head->id, fork_head->dpos_irreversible_blocknum );
try {
std::vector<std::future<std::vector<char>>> v;
v.reserve( branch.size() );
for( auto bitr = branch.rbegin(); bitr != branch.rend(); ++bitr ) {
v.emplace_back( post_async_task( thread_pool.get_executor(), [b=(*bitr)->block]() { return fc::raw::pack(*b); } ) );
}
auto it = v.begin();
for( auto bitr = branch.rbegin(); bitr != branch.rend(); ++bitr ) {
if( read_mode == db_read_mode::IRREVERSIBLE ) {
controller::block_report br;
apply_block( br, *bitr, controller::block_status::complete, trx_meta_cache_lookup{} );
head = (*bitr);
fork_db.mark_valid( head );
}
emit( self.irreversible_block, *bitr );
// blog.append could fail due to failures like running out of space.
// Do it before commit so that in case it throws, DB can be rolled back.
blog.append( (*bitr)->block, (*bitr)->id, it->get() );
++it;
db.commit( (*bitr)->block_num );
root_id = (*bitr)->id;
}
} catch( std::exception& ) {
if( root_id != fork_db.root()->id ) {
fork_db.advance_root( root_id );
}
throw;
}
//db.commit( fork_head->dpos_irreversible_blocknum ); // redundant
if( root_id != fork_db.root()->id ) {
branch.emplace_back(fork_db.root());
fork_db.advance_root( root_id );
}
// delete branch in thread pool
boost::asio::post( thread_pool.get_executor(), [branch{std::move(branch)}]() {} );
}
/**
* Sets fork database head to the genesis state.
*/
void initialize_blockchain_state(const genesis_state& genesis) {
wlog( "Initializing new blockchain with genesis state" );
producer_authority_schedule initial_schedule = { 0, { producer_authority{config::system_account_name, block_signing_authority_v0{ 1, {{genesis.initial_key, 1}} } } } };
legacy::producer_schedule_type initial_legacy_schedule{ 0, {{config::system_account_name, genesis.initial_key}} };
block_header_state genheader;
genheader.active_schedule = initial_schedule;
genheader.pending_schedule.schedule = initial_schedule;
// NOTE: if wtmsig block signatures are enabled at genesis time this should be the hash of a producer authority schedule
genheader.pending_schedule.schedule_hash = fc::sha256::hash(initial_legacy_schedule);
genheader.header.timestamp = genesis.initial_timestamp;
genheader.header.action_mroot = genesis.compute_chain_id();
genheader.id = genheader.header.calculate_id();
genheader.block_num = genheader.header.block_num();
head = std::make_shared<block_state>();
static_cast<block_header_state&>(*head) = genheader;
head->activated_protocol_features = std::make_shared<protocol_feature_activation_set>();
head->block = std::make_shared<signed_block>(genheader.header);
db.set_revision( head->block_num );
initialize_database(genesis);
}
void replay(std::function<bool()> check_shutdown) {
auto blog_head = blog.head();
if( !fork_db.root() ) {
fork_db.reset( *head );
if (!blog_head)
return;
}
replaying = true;
auto start_block_num = head->block_num + 1;
auto start = fc::time_point::now();
std::exception_ptr except_ptr;
if( blog_head && start_block_num <= blog_head->block_num() ) {
ilog( "existing block log, attempting to replay from ${s} to ${n} blocks",
("s", start_block_num)("n", blog_head->block_num()) );
try {
while( auto next = blog.read_block_by_num( head->block_num + 1 ) ) {
replay_push_block( next, controller::block_status::irreversible );
if( check_shutdown() ) break;
if( next->block_num() % 500 == 0 ) {
ilog( "${n} of ${head}", ("n", next->block_num())("head", blog_head->block_num()) );
}
}
} catch( const database_guard_exception& e ) {
except_ptr = std::current_exception();
}
ilog( "${n} irreversible blocks replayed", ("n", 1 + head->block_num - start_block_num) );
auto pending_head = fork_db.pending_head();
if( pending_head ) {
ilog( "fork database head ${h}, root ${r}", ("h", pending_head->block_num)( "r", fork_db.root()->block_num ) );
if( pending_head->block_num < head->block_num || head->block_num < fork_db.root()->block_num ) {
ilog( "resetting fork database with new last irreversible block as the new root: ${id}", ("id", head->id) );
fork_db.reset( *head );
} else if( head->block_num != fork_db.root()->block_num ) {
auto new_root = fork_db.search_on_branch( pending_head->id, head->block_num );
EOS_ASSERT( new_root, fork_database_exception,
"unexpected error: could not find new LIB in fork database" );
ilog( "advancing fork database root to new last irreversible block within existing fork database: ${id}",
("id", new_root->id) );
fork_db.mark_valid( new_root );
fork_db.advance_root( new_root->id );
}
}
// if the irreverible log is played without undo sessions enabled, we need to sync the
// revision ordinal to the appropriate expected value here.
if( self.skip_db_sessions( controller::block_status::irreversible ) )
db.set_revision( head->block_num );
} else {
ilog( "no irreversible blocks need to be replayed" );
}
if( !except_ptr && !check_shutdown() && fork_db.head() ) {
auto head_block_num = head->block_num;
auto branch = fork_db.fetch_branch( fork_db.head()->id );
int rev = 0;
for( auto i = branch.rbegin(); i != branch.rend(); ++i ) {
if( check_shutdown() ) break;
if( (*i)->block_num <= head_block_num ) continue;
++rev;
replay_push_block( (*i)->block, controller::block_status::validated );
}
ilog( "${n} reversible blocks replayed", ("n",rev) );
}
if( !fork_db.head() ) {
fork_db.reset( *head );
}
auto end = fc::time_point::now();
ilog( "replayed ${n} blocks in ${duration} seconds, ${mspb} ms/block",
("n", head->block_num + 1 - start_block_num)("duration", (end-start).count()/1000000)
("mspb", ((end-start).count()/1000.0)/(head->block_num-start_block_num)) );
replaying = false;
if( except_ptr ) {
std::rethrow_exception( except_ptr );
}
}
void startup(std::function<void()> shutdown, std::function<bool()> check_shutdown, const snapshot_reader_ptr& snapshot) {
EOS_ASSERT( snapshot, snapshot_exception, "No snapshot reader provided" );
this->shutdown = shutdown;
ilog( "Starting initialization from snapshot, this may take a significant amount of time" );
try {
snapshot->validate();
if( auto blog_head = blog.head() ) {
read_from_snapshot( snapshot, blog.first_block_num(), blog_head->block_num() );
} else {
read_from_snapshot( snapshot, 0, std::numeric_limits<uint32_t>::max() );
const uint32_t lib_num = head->block_num;
EOS_ASSERT( lib_num > 0, snapshot_exception,
"Snapshot indicates controller head at block number 0, but that is not allowed. "
"Snapshot is invalid." );
blog.reset( chain_id, lib_num + 1 );
}
init(check_shutdown);
ilog( "Finished initialization from snapshot" );
} catch (boost::interprocess::bad_alloc& e) {
elog( "Failed initialization from snapshot - db storage not configured to have enough storage for the provided snapshot, please increase and retry snapshot" );
shutdown();
}
}
void startup(std::function<void()> shutdown, std::function<bool()> check_shutdown, const genesis_state& genesis) {
EOS_ASSERT( db.revision() < 1, database_exception, "This version of controller::startup only works with a fresh state database." );
const auto& genesis_chain_id = genesis.compute_chain_id();
EOS_ASSERT( genesis_chain_id == chain_id, chain_id_type_exception,
"genesis state provided to startup corresponds to a chain ID (${genesis_chain_id}) that does not match the chain ID that controller was constructed with (${controller_chain_id})",
("genesis_chain_id", genesis_chain_id)("controller_chain_id", chain_id)
);
this->shutdown = shutdown;
if( fork_db.head() ) {
if( read_mode == db_read_mode::IRREVERSIBLE && fork_db.head()->id != fork_db.root()->id ) {
fork_db.rollback_head_to_root();
}
wlog( "No existing chain state. Initializing fresh blockchain state." );
} else {
wlog( "No existing chain state or fork database. Initializing fresh blockchain state and resetting fork database.");
}
initialize_blockchain_state(genesis); // sets head to genesis state
if( !fork_db.head() ) {
fork_db.reset( *head );
}
if( blog.head() ) {
EOS_ASSERT( blog.first_block_num() == 1, block_log_exception,
"block log does not start with genesis block"
);
} else {
blog.reset( genesis, head->block );
}
init(check_shutdown);
}
void startup(std::function<void()> shutdown, std::function<bool()> check_shutdown) {
EOS_ASSERT( db.revision() >= 1, database_exception, "This version of controller::startup does not work with a fresh state database." );
EOS_ASSERT( fork_db.head(), fork_database_exception, "No existing fork database despite existing chain state. Replay required." );
this->shutdown = shutdown;
uint32_t lib_num = fork_db.root()->block_num;
auto first_block_num = blog.first_block_num();
if( auto blog_head = blog.head() ) {
EOS_ASSERT( first_block_num <= lib_num && lib_num <= blog_head->block_num(),
block_log_exception,
"block log (ranging from ${block_log_first_num} to ${block_log_last_num}) does not contain the last irreversible block (${fork_db_lib})",
("block_log_first_num", first_block_num)
("block_log_last_num", blog_head->block_num())
("fork_db_lib", lib_num)
);
lib_num = blog_head->block_num();
} else {
if( first_block_num != (lib_num + 1) ) {
blog.reset( chain_id, lib_num + 1 );
}
}
if( read_mode == db_read_mode::IRREVERSIBLE && fork_db.head()->id != fork_db.root()->id ) {
fork_db.rollback_head_to_root();
}
head = fork_db.head();
init(check_shutdown);
}
static auto validate_db_version( const chainbase::database& db ) {
// check database version
const auto& header_idx = db.get_index<database_header_multi_index>().indices().get<by_id>();
EOS_ASSERT(header_idx.begin() != header_idx.end(), bad_database_version_exception,
"state database version pre-dates versioning, please restore from a compatible snapshot or replay!");
auto header_itr = header_idx.begin();
header_itr->validate();
return header_itr;
}
void init(std::function<bool()> check_shutdown) {
auto header_itr = validate_db_version( db );
{
const auto& state_chain_id = db.get<global_property_object>().chain_id;
EOS_ASSERT( state_chain_id == chain_id, chain_id_type_exception,
"chain ID in state (${state_chain_id}) does not match the chain ID that controller was constructed with (${controller_chain_id})",
("state_chain_id", state_chain_id)("controller_chain_id", chain_id)
);
}
// upgrade to the latest compatible version
if (header_itr->version != database_header_object::current_version) {
db.modify(*header_itr, [](auto& header) {
header.version = database_header_object::current_version;
});
}
// At this point head != nullptr
EOS_ASSERT( db.revision() >= head->block_num, fork_database_exception,
"fork database head (${head}) is inconsistent with state (${db})",
("db",db.revision())("head",head->block_num) );
if( db.revision() > head->block_num ) {
wlog( "database revision (${db}) is greater than head block number (${head}), "
"attempting to undo pending changes",
("db",db.revision())("head",head->block_num) );
}
while( db.revision() > head->block_num ) {
db.undo();
}
protocol_features.init( db );
// At startup, no transaction specific logging is possible
if (auto dm_logger = get_deep_mind_logger(false)) {
dm_logger->on_startup(db, head->block_num);
}
if( conf.integrity_hash_on_start )
ilog( "chain database started with hash: ${hash}", ("hash", calculate_integrity_hash()) );
okay_to_print_integrity_hash_on_stop = true;
replay( check_shutdown ); // replay any irreversible and reversible blocks ahead of current head
if( check_shutdown() ) return;
// At this point head != nullptr && fork_db.head() != nullptr && fork_db.root() != nullptr.
// Furthermore, fork_db.root()->block_num <= lib_num.
// Also, even though blog.head() may still be nullptr, blog.first_block_num() is guaranteed to be lib_num + 1.
if( read_mode != db_read_mode::IRREVERSIBLE
&& fork_db.pending_head()->id != fork_db.head()->id
&& fork_db.head()->id == fork_db.root()->id
) {
wlog( "read_mode has changed from irreversible: applying best branch from fork database" );
for( auto pending_head = fork_db.pending_head();
pending_head->id != fork_db.head()->id;
pending_head = fork_db.pending_head()
) {
wlog( "applying branch from fork database ending with block: ${id}", ("id", pending_head->id) );
controller::block_report br;
maybe_switch_forks( br, pending_head, controller::block_status::complete, forked_branch_callback{}, trx_meta_cache_lookup{} );
}
}
}
~controller_impl() {
thread_pool.stop();
pending.reset();
//only log this not just if configured to, but also if initialization made it to the point we'd log the startup too
if(okay_to_print_integrity_hash_on_stop && conf.integrity_hash_on_stop)
ilog( "chain database stopped with hash: ${hash}", ("hash", calculate_integrity_hash()) );
}
void add_indices() {
controller_index_set::add_indices(db);
contract_database_index_set::add_indices(db);
authorization.add_indices();
resource_limits.add_indices();
}
void clear_all_undo() {
// Rewind the database to the last irreversible block
db.undo_all();
/*
FC_ASSERT(db.revision() == self.head_block_num(),
"Chainbase revision does not match head block num",
("rev", db.revision())("head_block", self.head_block_num()));
*/
}
void add_contract_tables_to_snapshot( const snapshot_writer_ptr& snapshot ) const {
snapshot->write_section("contract_tables", [this]( auto& section ) {
index_utils<table_id_multi_index>::walk(db, [this, §ion]( const table_id_object& table_row ){
// add a row for the table
section.add_row(table_row, db);
// followed by a size row and then N data rows for each type of table
contract_database_index_set::walk_indices([this, §ion, &table_row]( auto utils ) {
using utils_t = decltype(utils);
using value_t = typename decltype(utils)::index_t::value_type;
using by_table_id = object_to_table_id_tag_t<value_t>;
auto tid_key = boost::make_tuple(table_row.id);
auto next_tid_key = boost::make_tuple(table_id_object::id_type(table_row.id._id + 1));
unsigned_int size = utils_t::template size_range<by_table_id>(db, tid_key, next_tid_key);
section.add_row(size, db);
utils_t::template walk_range<by_table_id>(db, tid_key, next_tid_key, [this, §ion]( const auto &row ) {
section.add_row(row, db);
});
});
});
});
}
void read_contract_tables_from_snapshot( const snapshot_reader_ptr& snapshot ) {
snapshot->read_section("contract_tables", [this]( auto& section ) {
bool more = !section.empty();
while (more) {
// read the row for the table
table_id_object::id_type t_id;
index_utils<table_id_multi_index>::create(db, [this, §ion, &t_id](auto& row) {
section.read_row(row, db);
t_id = row.id;
});
// read the size and data rows for each type of table
contract_database_index_set::walk_indices([this, §ion, &t_id, &more](auto utils) {
using utils_t = decltype(utils);
unsigned_int size;
more = section.read_row(size, db);
for (size_t idx = 0; idx < size.value; idx++) {
utils_t::create(db, [this, §ion, &more, &t_id](auto& row) {
row.t_id = t_id;
more = section.read_row(row, db);
});
}
});
}
});
}
void add_to_snapshot( const snapshot_writer_ptr& snapshot ) {
// clear in case the previous call to clear did not finish in time of deadline
clear_expired_input_transactions( fc::time_point::maximum() );
snapshot->write_section<chain_snapshot_header>([this]( auto §ion ){
section.add_row(chain_snapshot_header(), db);
});
snapshot->write_section<block_state>([this]( auto §ion ){
section.template add_row<block_header_state>(*head, db);
});
controller_index_set::walk_indices([this, &snapshot]( auto utils ){
using value_t = typename decltype(utils)::index_t::value_type;
// skip the table_id_object as its inlined with contract tables section
if (std::is_same<value_t, table_id_object>::value) {
return;
}
// skip the database_header as it is only relevant to in-memory database
if (std::is_same<value_t, database_header_object>::value) {
return;
}
snapshot->write_section<value_t>([this]( auto& section ){
decltype(utils)::walk(db, [this, §ion]( const auto &row ) {
section.add_row(row, db);
});
});
});
add_contract_tables_to_snapshot(snapshot);
authorization.add_to_snapshot(snapshot);
resource_limits.add_to_snapshot(snapshot);
}
static std::optional<genesis_state> extract_legacy_genesis_state( snapshot_reader& snapshot, uint32_t version ) {
std::optional<genesis_state> genesis;
using v2 = legacy::snapshot_global_property_object_v2;
if (std::clamp(version, v2::minimum_version, v2::maximum_version) == version ) {
genesis.emplace();
snapshot.read_section<genesis_state>([&genesis=*genesis]( auto §ion ){
section.read_row(genesis);
});
}
return genesis;
}
void read_from_snapshot( const snapshot_reader_ptr& snapshot, uint32_t blog_start, uint32_t blog_end ) {
chain_snapshot_header header;
snapshot->read_section<chain_snapshot_header>([this, &header]( auto §ion ){
section.read_row(header, db);
header.validate();
});
{ /// load and upgrade the block header state
block_header_state head_header_state;
using v2 = legacy::snapshot_block_header_state_v2;
if (std::clamp(header.version, v2::minimum_version, v2::maximum_version) == header.version ) {
snapshot->read_section<block_state>([this, &head_header_state]( auto §ion ) {
legacy::snapshot_block_header_state_v2 legacy_header_state;
section.read_row(legacy_header_state, db);
head_header_state = block_header_state(std::move(legacy_header_state));
});
} else {
snapshot->read_section<block_state>([this,&head_header_state]( auto §ion ){
section.read_row(head_header_state, db);
});
}
snapshot_head_block = head_header_state.block_num;
EOS_ASSERT( blog_start <= (snapshot_head_block + 1) && snapshot_head_block <= blog_end,
block_log_exception,
"Block log is provided with snapshot but does not contain the head block from the snapshot nor a block right after it",
("snapshot_head_block", snapshot_head_block)
("block_log_first_num", blog_start)
("block_log_last_num", blog_end)
);
head = std::make_shared<block_state>();
static_cast<block_header_state&>(*head) = head_header_state;
}
controller_index_set::walk_indices([this, &snapshot, &header]( auto utils ){
using value_t = typename decltype(utils)::index_t::value_type;
// skip the table_id_object as its inlined with contract tables section
if (std::is_same<value_t, table_id_object>::value) {
return;
}
// skip the database_header as it is only relevant to in-memory database
if (std::is_same<value_t, database_header_object>::value) {
return;
}
// special case for in-place upgrade of global_property_object
if (std::is_same<value_t, global_property_object>::value) {
using v2 = legacy::snapshot_global_property_object_v2;
using v3 = legacy::snapshot_global_property_object_v3;
using v4 = legacy::snapshot_global_property_object_v4;
if (std::clamp(header.version, v2::minimum_version, v2::maximum_version) == header.version ) {
std::optional<genesis_state> genesis = extract_legacy_genesis_state(*snapshot, header.version);
EOS_ASSERT( genesis, snapshot_exception,
"Snapshot indicates chain_snapshot_header version 2, but does not contain a genesis_state. "
"It must be corrupted.");
snapshot->read_section<global_property_object>([&db=this->db,gs_chain_id=genesis->compute_chain_id()]( auto §ion ) {
v2 legacy_global_properties;
section.read_row(legacy_global_properties, db);
db.create<global_property_object>([&legacy_global_properties,&gs_chain_id](auto& gpo ){
gpo.initalize_from(legacy_global_properties, gs_chain_id, kv_database_config{},
genesis_state::default_initial_wasm_configuration);
});
});
return; // early out to avoid default processing
}
if (std::clamp(header.version, v3::minimum_version, v3::maximum_version) == header.version ) {
snapshot->read_section<global_property_object>([&db=this->db]( auto §ion ) {
v3 legacy_global_properties;
section.read_row(legacy_global_properties, db);
db.create<global_property_object>([&legacy_global_properties](auto& gpo ){
gpo.initalize_from(legacy_global_properties, kv_database_config{},
genesis_state::default_initial_wasm_configuration);
});
});
return; // early out to avoid default processing
}
if (std::clamp(header.version, v4::minimum_version, v4::maximum_version) == header.version) {
snapshot->read_section<global_property_object>([&db = this->db](auto& section) {
v4 legacy_global_properties;
section.read_row(legacy_global_properties, db);
db.create<global_property_object>([&legacy_global_properties](auto& gpo) {
gpo.initalize_from(legacy_global_properties);
});
});
return; // early out to avoid default processing
}
}
snapshot->read_section<value_t>([this]( auto& section ) {
bool more = !section.empty();
while(more) {
decltype(utils)::create(db, [this, §ion, &more]( auto &row ) {
more = section.read_row(row, db);
});
}
});
});