/
controller.cpp
2361 lines (1938 loc) · 96.4 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/block_summary_object.hpp>
#include <eosio/chain/eosio_contract.hpp>
#include <eosio/chain/global_property_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/reversible_block_object.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 <chainbase/chainbase.hpp>
#include <fc/io/json.hpp>
#include <fc/scoped_exit.hpp>
#include <fc/variant_object.hpp>
namespace eosio { namespace chain {
using resource_limits::resource_limits_manager;
using controller_index_set = index_set<
account_index,
account_sequence_index,
global_property_multi_index,
global_property2_multi_index,
dynamic_global_property_multi_index,
block_summary_multi_index,
transaction_multi_index,
generated_transaction_multi_index,
table_id_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 = 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 = move(*mv._session);
mv._session.reset();
} else {
_session.reset();
}
return *this;
};
private:
optional<database::session> _session;
};
struct pending_state {
pending_state( maybe_session&& s )
:_db_session( move(s) ){}
maybe_session _db_session;
block_state_ptr _pending_block_state;
vector<action_receipt> _actions;
controller::block_status _block_status = controller::block_status::incomplete;
optional<block_id_type> _producer_block_id;
std::function<signature_type(digest_type)> _signer;
void push() {
_db_session.push();
}
};
struct controller_impl {
controller& self;
chainbase::database db;
chainbase::database reversible_blocks; ///< a special database to persist blocks that have successfully been applied but are still reversible
block_log blog;
optional<pending_state> pending;
block_state_ptr head;
fork_database fork_db;
wasm_interface wasmif;
resource_limits_manager resource_limits;
authorization_manager authorization;
controller::config conf;
chain_id_type chain_id;
bool replaying= false;
optional<fc::time_point> replay_head_time;
db_read_mode read_mode = db_read_mode::SPECULATIVE;
bool in_trx_requiring_checks = false; ///< if true, checks that are normally skipped on replay (e.g. auth checks) cannot be skipped
optional<fc::microseconds> subjective_cpu_leeway;
bool trusted_producer_light_validation = false;
uint32_t snapshot_head_block = 0;
boost::asio::thread_pool thread_pool;
typedef pair<scope_name,action_name> handler_key;
map< account_name, map<handler_key, apply_handler> > apply_handlers;
/**
* Transactions that were undone by pop_block or abort_block, transactions
* are removed from this list if they are re-applied in other blocks. Producers
* can query this list when scheduling new transactions into blocks.
*/
unapplied_transactions_type unapplied_transactions;
void pop_block() {
auto prev = fork_db.get_block( head->header.previous );
EOS_ASSERT( prev, block_validate_exception, "attempt to pop beyond last irreversible block" );
if( const auto* b = reversible_blocks.find<reversible_block_object,by_num>(head->block_num) )
{
reversible_blocks.remove( *b );
}
if ( read_mode == db_read_mode::SPECULATIVE ) {
EOS_ASSERT( head->block, block_validate_exception, "attempting to pop a block that was sparsely loaded from a snapshot");
for( const auto& t : head->trxs )
unapplied_transactions[t->signed_id] = t;
}
head = prev;
db.undo();
}
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 )
:self(s),
db( cfg.state_dir,
cfg.read_only ? database::read_only : database::read_write,
cfg.state_size ),
reversible_blocks( cfg.blocks_dir/config::reversible_blocks_dir_name,
cfg.read_only ? database::read_only : database::read_write,
cfg.reversible_cache_size ),
blog( cfg.blocks_dir ),
fork_db( cfg.state_dir ),
wasmif( cfg.wasm_runtime ),
resource_limits( db ),
authorization( s, db ),
conf( cfg ),
chain_id( cfg.genesis.compute_chain_id() ),
read_mode( cfg.read_mode ),
thread_pool( cfg.thread_pool_size )
{
#define SET_APP_HANDLER( receiver, contract, action) \
set_apply_handler( #receiver, #contract, #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 );
fork_db.irreversible.connect( [&]( auto b ) {
on_irreversible(b);
});
}
/**
* 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 (boost::interprocess::bad_alloc& e) {
wlog( "bad alloc" );
throw e;
} catch ( controller_emit_signal_exception& e ) {
wlog( "${details}", ("details", e.to_detail_string()) );
throw e;
} catch ( fc::exception& e ) {
wlog( "${details}", ("details", e.to_detail_string()) );
} catch ( ... ) {
wlog( "signal handler threw exception" );
}
}
void on_irreversible( const block_state_ptr& s ) {
if( !blog.head() )
blog.read_head();
const auto& log_head = blog.head();
bool append_to_blog = false;
if (!log_head) {
if (s->block) {
EOS_ASSERT(s->block_num == blog.first_block_num(), block_log_exception, "block log has no blocks and is appending the wrong first block. Expected ${expected}, but received: ${actual}",
("expected", blog.first_block_num())("actual", s->block_num));
append_to_blog = true;
} else {
EOS_ASSERT(s->block_num == blog.first_block_num() - 1, block_log_exception, "block log has no blocks and is not properly set up to start after the snapshot");
}
} else {
auto lh_block_num = log_head->block_num();
if (s->block_num > lh_block_num) {
EOS_ASSERT(s->block_num - 1 == lh_block_num, unlinkable_block_exception, "unlinkable block", ("s->block_num", s->block_num)("lh_block_num", lh_block_num));
EOS_ASSERT(s->block->previous == log_head->id(), unlinkable_block_exception, "irreversible doesn't link to block log head");
append_to_blog = true;
}
}
db.commit( s->block_num );
if( append_to_blog ) {
blog.append(s->block);
}
const auto& ubi = reversible_blocks.get_index<reversible_block_index,by_num>();
auto objitr = ubi.begin();
while( objitr != ubi.end() && objitr->blocknum <= s->block_num ) {
reversible_blocks.remove( *objitr );
objitr = ubi.begin();
}
// the "head" block when a snapshot is loaded is virtual and has no block data, all of its effects
// should already have been loaded from the snapshot so, it cannot be applied
if (s->block) {
if (read_mode == db_read_mode::IRREVERSIBLE) {
// when applying a snapshot, head may not be present
// when not applying a snapshot, make sure this is the next block
if (!head || s->block_num == head->block_num + 1) {
apply_block(s->block, controller::block_status::complete);
head = s;
} else {
// otherwise, assert the one odd case where initializing a chain
// from genesis creates and applies the first block automatically.
// when syncing from another chain, this is pushed in again
EOS_ASSERT(!head || head->block_num == 1, block_validate_exception, "Attempting to re-apply an irreversible block that was not the implied genesis block");
}
fork_db.mark_in_current_chain(head, true);
fork_db.set_validity(head, true);
}
emit(self.irreversible_block, s);
}
}
void replay(std::function<bool()> shutdown) {
auto blog_head = blog.read_head();
auto blog_head_time = blog_head->timestamp.to_time_point();
replaying = true;
replay_head_time = blog_head_time;
auto start_block_num = head->block_num + 1;
ilog( "existing block log, attempting to replay from ${s} to ${n} blocks",
("s", start_block_num)("n", blog_head->block_num()) );
auto start = fc::time_point::now();
while( auto next = blog.read_block_by_num( head->block_num + 1 ) ) {
replay_push_block( next, controller::block_status::irreversible );
if( next->block_num() % 100 == 0 ) {
std::cerr << std::setw(10) << next->block_num() << " of " << blog_head->block_num() <<"\r";
if( shutdown() ) break;
}
}
std::cerr<< "\n";
ilog( "${n} blocks replayed", ("n", head->block_num - start_block_num) );
// 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);
int rev = 0;
while( auto obj = reversible_blocks.find<reversible_block_object,by_num>(head->block_num+1) ) {
++rev;
replay_push_block( obj->get_block(), controller::block_status::validated );
}
ilog( "${n} reversible blocks replayed", ("n",rev) );
auto end = fc::time_point::now();
ilog( "replayed ${n} blocks in ${duration} seconds, ${mspb} ms/block",
("n", head->block_num - start_block_num)("duration", (end-start).count()/1000000)
("mspb", ((end-start).count()/1000.0)/(head->block_num-start_block_num)) );
replaying = false;
replay_head_time.reset();
}
void init(std::function<bool()> shutdown, const snapshot_reader_ptr& snapshot) {
bool report_integrity_hash = !!snapshot;
if (snapshot) {
EOS_ASSERT( !head, fork_database_exception, "" );
snapshot->validate();
read_from_snapshot( snapshot );
auto end = blog.read_head();
if( !end ) {
blog.reset( conf.genesis, signed_block_ptr(), head->block_num + 1 );
} else if( end->block_num() > head->block_num ) {
replay( shutdown );
} else {
EOS_ASSERT( end->block_num() == head->block_num, fork_database_exception,
"Block log is provided with snapshot but does not contain the head block from the snapshot" );
}
} else {
if( !head ) {
initialize_fork_db(); // set head to genesis state
}
auto end = blog.read_head();
if( !end ) {
blog.reset( conf.genesis, head->block );
} else if( end->block_num() > head->block_num ) {
replay( shutdown );
report_integrity_hash = true;
}
}
if( shutdown() ) return;
const auto& ubi = reversible_blocks.get_index<reversible_block_index,by_num>();
auto objitr = ubi.rbegin();
if( objitr != ubi.rend() ) {
EOS_ASSERT( objitr->blocknum == head->block_num, fork_database_exception,
"reversible block database is inconsistent with fork database, replay blockchain",
("head",head->block_num)("unconfimed", objitr->blocknum) );
} else {
auto end = blog.read_head();
EOS_ASSERT( !end || end->block_num() == head->block_num, fork_database_exception,
"fork database exists but reversible block database does not, replay blockchain",
("blog_head",end->block_num())("head",head->block_num) );
}
EOS_ASSERT( db.revision() >= head->block_num, fork_database_exception, "fork database is inconsistent with shared memory",
("db",db.revision())("head",head->block_num) );
if( db.revision() > head->block_num ) {
wlog( "warning: 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();
}
if( report_integrity_hash ) {
const auto hash = calculate_integrity_hash();
ilog( "database initialized with hash: ${hash}", ("hash", hash) );
}
//*bos begin*
sync_name_list(list_type::actor_blacklist_type,true);
sync_name_list(list_type::contract_blacklist_type,true);
sync_name_list(list_type::resource_greylist_type,true);
//*bos end*
}
~controller_impl() {
pending.reset();
db.flush();
reversible_blocks.flush();
}
void add_indices() {
reversible_blocks.add_index<reversible_block_index>();
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.with_write_lock([&] {
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 ) const {
snapshot->write_section<chain_snapshot_header>([this]( auto §ion ){
section.add_row(chain_snapshot_header(), db);
});
snapshot->write_section<genesis_state>([this]( auto §ion ){
section.add_row(conf.genesis, db);
});
snapshot->write_section<block_state>([this]( auto §ion ){
section.template add_row<block_header_state>(*fork_db.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;
}
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);
}
void read_from_snapshot( const snapshot_reader_ptr& snapshot ) {
snapshot->read_section<chain_snapshot_header>([this]( auto §ion ){
chain_snapshot_header header;
section.read_row(header, db);
header.validate();
});
snapshot->read_section<block_state>([this]( auto §ion ){
block_header_state head_header_state;
section.read_row(head_header_state, db);
auto head_state = std::make_shared<block_state>(head_header_state);
fork_db.set(head_state);
fork_db.set_validity(head_state, true);
fork_db.mark_in_current_chain(head_state, true);
head = head_state;
snapshot_head_block = head->block_num;
});
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;
}
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);
});
}
});
});
read_contract_tables_from_snapshot(snapshot);
authorization.read_from_snapshot(snapshot);
resource_limits.read_from_snapshot(snapshot);
db.set_revision( head->block_num );
}
sha256 calculate_integrity_hash() const {
sha256::encoder enc;
auto hash_writer = std::make_shared<integrity_hash_snapshot_writer>(enc);
add_to_snapshot(hash_writer);
hash_writer->finalize();
return enc.result();
}
/**
* Sets fork database head to the genesis state.
*/
void initialize_fork_db() {
wlog( " Initializing new blockchain with genesis state " );
producer_schedule_type initial_schedule{ 0, {{config::system_account_name, conf.genesis.initial_key}} };
block_header_state genheader;
genheader.active_schedule = initial_schedule;
genheader.pending_schedule = initial_schedule;
genheader.pending_schedule_hash = fc::sha256::hash(initial_schedule);
genheader.header.timestamp = conf.genesis.initial_timestamp;
genheader.header.action_mroot = conf.genesis.compute_chain_id();
genheader.id = genheader.header.id();
genheader.block_num = genheader.header.block_num();
head = std::make_shared<block_state>( genheader );
head->block = std::make_shared<signed_block>(genheader.header);
fork_db.set( head );
db.set_revision( head->block_num );
initialize_database();
}
void create_native_account( account_name name, const authority& owner, const authority& active, bool is_privileged = false ) {
db.create<account_object>([&](auto& a) {
a.name = name;
a.creation_date = conf.genesis.initial_timestamp;
a.privileged = is_privileged;
if( name == config::system_account_name ) {
a.set_abi(eosio_contract_abi(abi_def()));
}
});
db.create<account_sequence_object>([&](auto & a) {
a.name = name;
});
const auto& owner_permission = authorization.create_permission(name, config::owner_name, 0,
owner, conf.genesis.initial_timestamp );
const auto& active_permission = authorization.create_permission(name, config::active_name, owner_permission.id,
active, conf.genesis.initial_timestamp );
resource_limits.initialize_account(name);
int64_t ram_delta = config::overhead_per_account_ram_bytes;
ram_delta += 2*config::billable_size_v<permission_object>;
ram_delta += owner_permission.auth.get_billable_size();
ram_delta += active_permission.auth.get_billable_size();
resource_limits.add_pending_ram_usage(name, ram_delta);
resource_limits.verify_account_ram_usage(name);
}
void initialize_database() {
// Initialize block summary index
for (int i = 0; i < 0x10000; i++)
db.create<block_summary_object>([&](block_summary_object&) {});
const auto& tapos_block_summary = db.get<block_summary_object>(1);
db.modify( tapos_block_summary, [&]( auto& bs ) {
bs.block_id = head->id;
});
conf.genesis.initial_configuration.validate();
db.create<global_property_object>([&](auto& gpo ){
gpo.configuration = conf.genesis.initial_configuration;
});
db.create<dynamic_global_property_object>([](auto&){});
// *bos begin*
//guaranteed minimum resources which is abbreviated gmr
db.create<global_property2_object>([&](auto &gpo) {
gpo.gmr.cpu_us = config::default_gmr_cpu_limit;
gpo.gmr.net_byte = config::default_gmr_net_limit;
gpo.gmr.ram_byte = config::default_gmr_ram_limit;
});
// *bos end*
authorization.initialize_database();
resource_limits.initialize_database();
authority system_auth(conf.genesis.initial_key);
create_native_account( config::system_account_name, system_auth, system_auth, true );
auto empty_authority = authority(1, {}, {});
auto active_producers_authority = authority(1, {}, {});
active_producers_authority.accounts.push_back({{config::system_account_name, config::active_name}, 1});
create_native_account( config::null_account_name, empty_authority, empty_authority );
create_native_account( config::producers_account_name, empty_authority, active_producers_authority );
const auto& active_permission = authorization.get_permission({config::producers_account_name, config::active_name});
const auto& majority_permission = authorization.create_permission( config::producers_account_name,
config::majority_producers_permission_name,
active_permission.id,
active_producers_authority,
conf.genesis.initial_timestamp );
const auto& minority_permission = authorization.create_permission( config::producers_account_name,
config::minority_producers_permission_name,
majority_permission.id,
active_producers_authority,
conf.genesis.initial_timestamp );
}
// "bos begin"
void set_name_list(list_type list, list_action_type action, std::vector<account_name> name_list)
{
int64_t lst = static_cast<int64_t>(list);
EOS_ASSERT(list >= list_type::actor_blacklist_type && list < list_type::list_type_count, transaction_exception, "unknown list type : ${l}, action: ${n}", ("l", static_cast<int64_t>(list))("n", static_cast<int64_t>(action)));
vector<flat_set<account_name> *> lists = {&conf.actor_blacklist, &conf.contract_blacklist, &conf.resource_greylist};
EOS_ASSERT(lists.size() == static_cast<int64_t>(list_type::list_type_count) - 1, transaction_exception, " list size wrong : ${l}, action: ${n}", ("l", static_cast<int64_t>(list))("n", static_cast<int64_t>(action)));
flat_set<account_name> &lo = *lists[lst - 1];
if (action == list_action_type::insert_type)
{
lo.insert(name_list.begin(), name_list.end());
}
else if (action == list_action_type::remove_type)
{
flat_set<account_name> name_set(name_list.begin(), name_list.end());
flat_set<account_name> results;
results.reserve(lo.size());
set_difference(lo.begin(), lo.end(),
name_set.begin(), name_set.end(),
std::inserter(results,results.begin()));
lo = results;
}
sync_name_list(list);
}
void sync_list_and_db(list_type list, global_property2_object &gprops2,bool isMerge=false)
{
int64_t lst = static_cast<int64_t>(list);
EOS_ASSERT( list >= list_type::actor_blacklist_type && list < list_type::list_type_count, transaction_exception, "unknown list type : ${l}, ismerge: ${n}", ("l", static_cast<int64_t>(list))("n", isMerge));
vector<shared_vector<account_name> *> lists = {&gprops2.cfg.actor_blacklist, &gprops2.cfg.contract_blacklist, &gprops2.cfg.resource_greylist};
vector<flat_set<account_name> *> conflists = {&conf.actor_blacklist, &conf.contract_blacklist, &conf.resource_greylist};
EOS_ASSERT(lists.size() == static_cast<int64_t>(list_type::list_type_count) - 1, transaction_exception, " list size wrong : ${l}, ismerge: ${n}", ("l", static_cast<int64_t>(list))("n", isMerge));
shared_vector<account_name> &lo = *lists[lst - 1];
flat_set<account_name> &clo = *conflists[lst - 1];
if (isMerge)
{
//initialize, merge elements and deduplication between list and db.result save to list
for (auto &a : lo)
{
clo.insert(a);
}
}
//clear list from db and save merge result to db object
lo.clear();
for (auto &a : clo)
{
lo.push_back(a);
}
}
void sync_name_list(list_type list,bool isMerge=false)
{
try
{
const auto &gpo2 = db.get<global_property2_object>();
db.modify(gpo2, [&](auto &gprops2) {
sync_list_and_db(list, gprops2, isMerge);
});
}
catch (...)
{
wlog("plugin initialize sync list ignore before initialize database");
}
}
// "bos end"
/**
* @post regardless of the success of commit block there is no active pending block
*/
void commit_block( bool add_to_fork_db ) {
auto reset_pending_on_exit = fc::make_scoped_exit([this]{
pending.reset();
});
try {
if (add_to_fork_db) {
pending->_pending_block_state->validated = true;
auto new_bsp = fork_db.add(pending->_pending_block_state, true);
emit(self.accepted_block_header, pending->_pending_block_state);
head = fork_db.head();
EOS_ASSERT(new_bsp == head, fork_database_exception, "committed block did not become the new head in fork database");
}
if( !replaying ) {
reversible_blocks.create<reversible_block_object>( [&]( auto& ubo ) {
ubo.blocknum = pending->_pending_block_state->block_num;
ubo.set_block( pending->_pending_block_state->block );
});
}
emit( self.accepted_block, pending->_pending_block_state );
} catch (...) {
// dont bother resetting pending, instead abort the block
reset_pending_on_exit.cancel();
abort_block();
throw;
}
// push the state for pending.
pending->push();
}
// The returned scoped_exit should not exceed the lifetime of the pending which existed when make_block_restore_point was called.
fc::scoped_exit<std::function<void()>> make_block_restore_point() {
auto orig_block_transactions_size = pending->_pending_block_state->block->transactions.size();
auto orig_state_transactions_size = pending->_pending_block_state->trxs.size();
auto orig_state_actions_size = pending->_actions.size();
std::function<void()> callback = [this,
orig_block_transactions_size,
orig_state_transactions_size,
orig_state_actions_size]()
{
pending->_pending_block_state->block->transactions.resize(orig_block_transactions_size);
pending->_pending_block_state->trxs.resize(orig_state_transactions_size);
pending->_actions.resize(orig_state_actions_size);
};
return fc::make_scoped_exit( std::move(callback) );
}
transaction_trace_ptr apply_onerror( const generated_transaction& gtrx,
fc::time_point deadline,
fc::time_point start,
uint32_t& cpu_time_to_bill_us, // only set on failure
uint32_t billed_cpu_time_us,
bool explicit_billed_cpu_time = false,
bool enforce_whiteblacklist = true
)
{
signed_transaction etrx;
// Deliver onerror action containing the failed deferred transaction directly back to the sender.
etrx.actions.emplace_back( vector<permission_level>{{gtrx.sender, config::active_name}},
onerror( gtrx.sender_id, gtrx.packed_trx.data(), gtrx.packed_trx.size() ) );
etrx.expiration = self.pending_block_time() + fc::microseconds(999'999); // Round up to avoid appearing expired
etrx.set_reference_block( self.head_block_id() );
transaction_context trx_context( self, etrx, etrx.id(), start );
trx_context.deadline = deadline;
trx_context.explicit_billed_cpu_time = explicit_billed_cpu_time;
trx_context.billed_cpu_time_us = billed_cpu_time_us;
trx_context.enforce_whiteblacklist = enforce_whiteblacklist;
transaction_trace_ptr trace = trx_context.trace;
try {
trx_context.init_for_implicit_trx();
trx_context.published = gtrx.published;
trx_context.trace->action_traces.emplace_back();
trx_context.dispatch_action( trx_context.trace->action_traces.back(), etrx.actions.back(), gtrx.sender );
trx_context.finalize(); // Automatically rounds up network and CPU usage in trace and bills payers if successful
auto restore = make_block_restore_point();
trace->receipt = push_receipt( gtrx.trx_id, transaction_receipt::soft_fail,
trx_context.billed_cpu_time_us, trace->net_usage );
fc::move_append( pending->_actions, move(trx_context.executed) );
trx_context.squash();
restore.cancel();
return trace;
} catch( const fc::exception& e ) {
cpu_time_to_bill_us = trx_context.update_billed_cpu_time( fc::time_point::now() );
trace->except = e;
trace->except_ptr = std::current_exception();
}
return trace;
}
void remove_scheduled_transaction( const generated_transaction_object& gto ) {
resource_limits.add_pending_ram_usage(
gto.payer,
-(config::billable_size_v<generated_transaction_object> + gto.packed_trx.size())
);
// No need to verify_account_ram_usage since we are only reducing memory
db.remove( gto );
}
bool failure_is_subjective( const fc::exception& e ) const {
auto code = e.code();
return (code == subjective_block_production_exception::code_value)
|| (code == block_net_usage_exceeded::code_value)
|| (code == greylist_net_usage_exceeded::code_value)
|| (code == block_cpu_usage_exceeded::code_value)
|| (code == greylist_cpu_usage_exceeded::code_value)
|| (code == deadline_exception::code_value)
|| (code == leeway_deadline_exception::code_value)
|| (code == actor_whitelist_exception::code_value)
|| (code == actor_blacklist_exception::code_value)
|| (code == contract_whitelist_exception::code_value)
|| (code == contract_blacklist_exception::code_value)
|| (code == action_blacklist_exception::code_value)
|| (code == key_blacklist_exception::code_value);
}
bool scheduled_failure_is_subjective( const fc::exception& e ) const {
auto code = e.code();
return (code == tx_cpu_usage_exceeded::code_value)
|| failure_is_subjective(e);
}
transaction_trace_ptr push_scheduled_transaction( const transaction_id_type& trxid, fc::time_point deadline, uint32_t billed_cpu_time_us, bool explicit_billed_cpu_time = false ) {
const auto& idx = db.get_index<generated_transaction_multi_index,by_trx_id>();
auto itr = idx.find( trxid );
EOS_ASSERT( itr != idx.end(), unknown_transaction_exception, "unknown transaction" );
return push_scheduled_transaction( *itr, deadline, billed_cpu_time_us, explicit_billed_cpu_time );
}
transaction_trace_ptr push_scheduled_transaction( const generated_transaction_object& gto, fc::time_point deadline, uint32_t billed_cpu_time_us, bool explicit_billed_cpu_time = false )
{ try {
maybe_session undo_session;
if ( !self.skip_db_sessions() )
undo_session = maybe_session(db);
auto gtrx = generated_transaction(gto);
// remove the generated transaction object after making a copy
// this will ensure that anything which affects the GTO multi-index-container will not invalidate
// data we need to successfully retire this transaction.
//
// IF the transaction FAILs in a subjective way, `undo_session` should expire without being squashed
// resulting in the GTO being restored and available for a future block to retire.
remove_scheduled_transaction(gto);
fc::datastream<const char*> ds( gtrx.packed_trx.data(), gtrx.packed_trx.size() );
EOS_ASSERT( gtrx.delay_until <= self.pending_block_time(), transaction_exception, "this transaction isn't ready",
("gtrx.delay_until",gtrx.delay_until)("pbt",self.pending_block_time()) );
signed_transaction dtrx;
fc::raw::unpack(ds,static_cast<transaction&>(dtrx) );
transaction_metadata_ptr trx = std::make_shared<transaction_metadata>( dtrx );
trx->accepted = true;
trx->scheduled = true;
transaction_trace_ptr trace;
if( gtrx.expiration < self.pending_block_time() ) {
trace = std::make_shared<transaction_trace>();
trace->id = gtrx.trx_id;
trace->block_num = self.pending_block_state()->block_num;
trace->block_time = self.pending_block_time();
trace->producer_block_id = self.pending_producer_block_id();
trace->scheduled = true;
trace->receipt = push_receipt( gtrx.trx_id, transaction_receipt::expired, billed_cpu_time_us, 0 ); // expire the transaction
emit( self.accepted_transaction, trx );
emit( self.applied_transaction, trace );
undo_session.squash();
return trace;
}
auto reset_in_trx_requiring_checks = fc::make_scoped_exit([old_value=in_trx_requiring_checks,this](){
in_trx_requiring_checks = old_value;
});
in_trx_requiring_checks = true;
uint32_t cpu_time_to_bill_us = billed_cpu_time_us;
transaction_context trx_context( self, dtrx, gtrx.trx_id );
trx_context.leeway = fc::microseconds(0); // avoid stealing cpu resource
trx_context.deadline = deadline;
trx_context.explicit_billed_cpu_time = explicit_billed_cpu_time;
trx_context.billed_cpu_time_us = billed_cpu_time_us;
trx_context.enforce_whiteblacklist = gtrx.sender.empty() ? true : !sender_avoids_whitelist_blacklist_enforcement( gtrx.sender );
trace = trx_context.trace;
try {
trx_context.init_for_deferred_trx( gtrx.published );
if( trx_context.enforce_whiteblacklist && pending->_block_status == controller::block_status::incomplete ) {
check_actor_list( trx_context.bill_to_accounts ); // Assumes bill_to_accounts is the set of actors authorizing the transaction
}
trx_context.exec();
trx_context.finalize(); // Automatically rounds up network and CPU usage in trace and bills payers if successful
auto restore = make_block_restore_point();
trace->receipt = push_receipt( gtrx.trx_id,
transaction_receipt::executed,
trx_context.billed_cpu_time_us,
trace->net_usage );
fc::move_append( pending->_actions, move(trx_context.executed) );
emit( self.accepted_transaction, trx );
emit( self.applied_transaction, trace );
trx_context.squash();
undo_session.squash();
restore.cancel();
return trace;
} catch( const fc::exception& e ) {
cpu_time_to_bill_us = trx_context.update_billed_cpu_time( fc::time_point::now() );
trace->except = e;
trace->except_ptr = std::current_exception();
trace->elapsed = fc::time_point::now() - trx_context.start;
}
trx_context.undo();