/
database.cpp
5478 lines (4688 loc) · 205 KB
/
database.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 <steem/protocol/steem_operations.hpp>
#include <steem/chain/block_summary_object.hpp>
#include <steem/chain/compound.hpp>
#include <steem/chain/custom_operation_interpreter.hpp>
#include <steem/chain/database.hpp>
#include <steem/chain/database_exceptions.hpp>
#include <steem/chain/db_with.hpp>
#include <steem/chain/evaluator_registry.hpp>
#include <steem/chain/global_property_object.hpp>
#include <steem/chain/history_object.hpp>
#include <steem/chain/index.hpp>
#include <steem/chain/pending_required_action_object.hpp>
#include <steem/chain/pending_optional_action_object.hpp>
#include <steem/chain/smt_objects.hpp>
#include <steem/chain/steem_evaluator.hpp>
#include <steem/chain/steem_objects.hpp>
#include <steem/chain/transaction_object.hpp>
#include <steem/chain/shared_db_merkle.hpp>
#include <steem/chain/witness_schedule.hpp>
#include <steem/chain/util/asset.hpp>
#include <steem/chain/util/reward.hpp>
#include <steem/chain/util/uint256.hpp>
#include <steem/chain/util/reward.hpp>
#include <steem/chain/util/manabar.hpp>
#include <steem/chain/util/rd_setup.hpp>
#include <fc/smart_ref_impl.hpp>
#include <fc/uint128.hpp>
#include <fc/container/deque.hpp>
#include <fc/io/fstream.hpp>
#include <boost/scope_exit.hpp>
#include <cstdint>
#include <deque>
#include <fstream>
#include <functional>
namespace steem { namespace chain {
struct object_schema_repr
{
std::pair< uint16_t, uint16_t > space_type;
std::string type;
};
struct operation_schema_repr
{
std::string id;
std::string type;
};
struct db_schema
{
std::map< std::string, std::string > types;
std::vector< object_schema_repr > object_types;
std::string operation_type;
std::vector< operation_schema_repr > custom_operation_types;
};
} }
FC_REFLECT( steem::chain::object_schema_repr, (space_type)(type) )
FC_REFLECT( steem::chain::operation_schema_repr, (id)(type) )
FC_REFLECT( steem::chain::db_schema, (types)(object_types)(operation_type)(custom_operation_types) )
namespace steem { namespace chain {
using boost::container::flat_set;
struct reward_fund_context
{
uint128_t recent_claims = 0;
asset reward_balance = asset( 0, STEEM_SYMBOL );
share_type steem_awarded = 0;
};
class database_impl
{
public:
database_impl( database& self );
database& _self;
evaluator_registry< operation > _evaluator_registry;
};
database_impl::database_impl( database& self )
: _self(self), _evaluator_registry(self) {}
database::database()
: _my( new database_impl(*this) ) {}
database::~database()
{
clear_pending();
}
void database::open( const open_args& args )
{
try
{
init_schema();
chainbase::database::open( args.shared_mem_dir, args.chainbase_flags, args.shared_file_size );
initialize_indexes();
initialize_evaluators();
if( !find< dynamic_global_property_object >() )
with_write_lock( [&]()
{
init_genesis( args.initial_supply );
});
_benchmark_dumper.set_enabled( args.benchmark_is_enabled );
_block_log.open( args.data_dir / "block_log" );
auto log_head = _block_log.head();
// Rewind all undo state. This should return us to the state at the last irreversible block.
with_write_lock( [&]()
{
undo_all();
FC_ASSERT( revision() == head_block_num(), "Chainbase revision does not match head block num",
("rev", revision())("head_block", head_block_num()) );
if (args.do_validate_invariants)
validate_invariants();
});
if( head_block_num() )
{
auto head_block = _block_log.read_block_by_num( head_block_num() );
// This assertion should be caught and a reindex should occur
FC_ASSERT( head_block.valid() && head_block->id() == head_block_id(), "Chain state does not match block log. Please reindex blockchain." );
_fork_db.start_block( *head_block );
}
with_read_lock( [&]()
{
init_hardforks(); // Writes to local state, but reads from db
});
if (args.benchmark.first)
{
args.benchmark.second(0, get_abstract_index_cntr());
auto last_block_num = _block_log.head()->block_num();
args.benchmark.second(last_block_num, get_abstract_index_cntr());
}
_shared_file_full_threshold = args.shared_file_full_threshold;
_shared_file_scale_rate = args.shared_file_scale_rate;
auto account = find< account_object, by_name >( "nijeah" );
if( account != nullptr && account->to_withdraw < 0 )
{
auto session = start_undo_session();
modify( *account, []( account_object& a )
{
a.to_withdraw = 0;
a.next_vesting_withdrawal = fc::time_point_sec::maximum();
});
session.squash();
}
}
FC_CAPTURE_LOG_AND_RETHROW( (args.data_dir)(args.shared_mem_dir)(args.shared_file_size) )
}
uint32_t database::reindex( const open_args& args )
{
reindex_notification note;
BOOST_SCOPE_EXIT(this_,¬e) {
STEEM_TRY_NOTIFY(this_->_post_reindex_signal, note);
} BOOST_SCOPE_EXIT_END
try
{
STEEM_TRY_NOTIFY(_pre_reindex_signal, note);
ilog( "Reindexing Blockchain" );
wipe( args.data_dir, args.shared_mem_dir, false );
open( args );
_fork_db.reset(); // override effect of _fork_db.start_block() call in open()
auto start = fc::time_point::now();
STEEM_ASSERT( _block_log.head(), block_log_exception, "No blocks in block log. Cannot reindex an empty chain." );
ilog( "Replaying blocks..." );
uint64_t skip_flags =
skip_witness_signature |
skip_transaction_signatures |
skip_transaction_dupe_check |
skip_tapos_check |
skip_merkle_check |
skip_witness_schedule_check |
skip_authority_check |
skip_validate | /// no need to validate operations
skip_validate_invariants |
skip_block_log;
with_write_lock( [&]()
{
_block_log.set_locking( false );
auto itr = _block_log.read_block( 0 );
auto last_block_num = _block_log.head()->block_num();
if( args.stop_replay_at > 0 && args.stop_replay_at < last_block_num )
last_block_num = args.stop_replay_at;
if( args.benchmark.first > 0 )
{
args.benchmark.second( 0, get_abstract_index_cntr() );
}
while( itr.first.block_num() != last_block_num )
{
auto cur_block_num = itr.first.block_num();
if( cur_block_num % 100000 == 0 )
std::cerr << " " << double( cur_block_num * 100 ) / last_block_num << "% " << cur_block_num << " of " << last_block_num <<
" (" << (get_free_memory() / (1024*1024)) << "M free)\n";
apply_block( itr.first, skip_flags );
if( (args.benchmark.first > 0) && (cur_block_num % args.benchmark.first == 0) )
args.benchmark.second( cur_block_num, get_abstract_index_cntr() );
itr = _block_log.read_block( itr.second );
}
apply_block( itr.first, skip_flags );
note.last_block_number = itr.first.block_num();
if( (args.benchmark.first > 0) && (note.last_block_number % args.benchmark.first == 0) )
args.benchmark.second( note.last_block_number, get_abstract_index_cntr() );
set_revision( head_block_num() );
_block_log.set_locking( true );
});
if( _block_log.head()->block_num() )
_fork_db.start_block( *_block_log.head() );
auto end = fc::time_point::now();
ilog( "Done reindexing, elapsed time: ${t} sec", ("t",double((end-start).count())/1000000.0 ) );
note.reindex_success = true;
return note.last_block_number;
}
FC_CAPTURE_AND_RETHROW( (args.data_dir)(args.shared_mem_dir) )
}
void database::wipe( const fc::path& data_dir, const fc::path& shared_mem_dir, bool include_blocks)
{
close();
chainbase::database::wipe( shared_mem_dir );
if( include_blocks )
{
fc::remove_all( data_dir / "block_log" );
fc::remove_all( data_dir / "block_log.index" );
}
}
void database::close(bool rewind)
{
try
{
// Since pop_block() will move tx's in the popped blocks into pending,
// we have to clear_pending() after we're done popping to get a clean
// DB state (issue #336).
clear_pending();
chainbase::database::flush();
chainbase::database::close();
_block_log.close();
_fork_db.reset();
}
FC_CAPTURE_AND_RETHROW()
}
bool database::is_known_block( const block_id_type& id )const
{ try {
return fetch_block_by_id( id ).valid();
} FC_CAPTURE_AND_RETHROW() }
/**
* Only return true *if* the transaction has not expired or been invalidated. If this
* method is called with a VERY old transaction we will return false, they should
* query things by blocks if they are that old.
*/
bool database::is_known_transaction( const transaction_id_type& id )const
{ try {
const auto& trx_idx = get_index<transaction_index>().indices().get<by_trx_id>();
return trx_idx.find( id ) != trx_idx.end();
} FC_CAPTURE_AND_RETHROW() }
block_id_type database::find_block_id_for_num( uint32_t block_num )const
{
try
{
if( block_num == 0 )
return block_id_type();
// Reversible blocks are *usually* in the TAPOS buffer. Since this
// is the fastest check, we do it first.
block_summary_id_type bsid = block_num & 0xFFFF;
const block_summary_object* bs = find< block_summary_object, by_id >( bsid );
if( bs != nullptr )
{
if( protocol::block_header::num_from_id(bs->block_id) == block_num )
return bs->block_id;
}
// Next we query the block log. Irreversible blocks are here.
auto b = _block_log.read_block_by_num( block_num );
if( b.valid() )
return b->id();
// Finally we query the fork DB.
shared_ptr< fork_item > fitem = _fork_db.fetch_block_on_main_branch_by_number( block_num );
if( fitem )
return fitem->id;
return block_id_type();
}
FC_CAPTURE_AND_RETHROW( (block_num) )
}
block_id_type database::get_block_id_for_num( uint32_t block_num )const
{
block_id_type bid = find_block_id_for_num( block_num );
FC_ASSERT( bid != block_id_type() );
return bid;
}
optional<signed_block> database::fetch_block_by_id( const block_id_type& id )const
{ try {
auto b = _fork_db.fetch_block( id );
if( !b )
{
auto tmp = _block_log.read_block_by_num( protocol::block_header::num_from_id( id ) );
if( tmp && tmp->id() == id )
return tmp;
tmp.reset();
return tmp;
}
return b->data;
} FC_CAPTURE_AND_RETHROW() }
optional<signed_block> database::fetch_block_by_number( uint32_t block_num )const
{ try {
optional< signed_block > b;
shared_ptr< fork_item > fitem = _fork_db.fetch_block_on_main_branch_by_number( block_num );
if( fitem )
b = fitem->data;
else
b = _block_log.read_block_by_num( block_num );
return b;
} FC_LOG_AND_RETHROW() }
const signed_transaction database::get_recent_transaction( const transaction_id_type& trx_id ) const
{ try {
auto& index = get_index<transaction_index>().indices().get<by_trx_id>();
auto itr = index.find(trx_id);
FC_ASSERT(itr != index.end());
signed_transaction trx;
fc::raw::unpack_from_buffer( itr->packed_trx, trx );
return trx;;
} FC_CAPTURE_AND_RETHROW() }
std::vector< block_id_type > database::get_block_ids_on_fork( block_id_type head_of_fork ) const
{ try {
pair<fork_database::branch_type, fork_database::branch_type> branches = _fork_db.fetch_branch_from(head_block_id(), head_of_fork);
if( !((branches.first.back()->previous_id() == branches.second.back()->previous_id())) )
{
edump( (head_of_fork)
(head_block_id())
(branches.first.size())
(branches.second.size()) );
assert(branches.first.back()->previous_id() == branches.second.back()->previous_id());
}
std::vector< block_id_type > result;
for( const item_ptr& fork_block : branches.second )
result.emplace_back(fork_block->id);
result.emplace_back(branches.first.back()->previous_id());
return result;
} FC_CAPTURE_AND_RETHROW() }
chain_id_type database::get_chain_id() const
{
return steem_chain_id;
}
void database::set_chain_id( const chain_id_type& chain_id )
{
steem_chain_id = chain_id;
idump( (steem_chain_id) );
}
void database::foreach_block(std::function<bool(const signed_block_header&, const signed_block&)> processor) const
{
if(!_block_log.head())
return;
auto itr = _block_log.read_block( 0 );
auto last_block_num = _block_log.head()->block_num();
signed_block_header previousBlockHeader = itr.first;
while( itr.first.block_num() != last_block_num )
{
const signed_block& b = itr.first;
if(processor(previousBlockHeader, b) == false)
return;
previousBlockHeader = b;
itr = _block_log.read_block( itr.second );
}
processor(previousBlockHeader, itr.first);
}
void database::foreach_tx(std::function<bool(const signed_block_header&, const signed_block&,
const signed_transaction&, uint32_t)> processor) const
{
foreach_block([&processor](const signed_block_header& prevBlockHeader, const signed_block& block) -> bool
{
uint32_t txInBlock = 0;
for( const auto& trx : block.transactions )
{
if(processor(prevBlockHeader, block, trx, txInBlock) == false)
return false;
++txInBlock;
}
return true;
}
);
}
void database::foreach_operation(std::function<bool(const signed_block_header&,const signed_block&,
const signed_transaction&, uint32_t, const operation&, uint16_t)> processor) const
{
foreach_tx([&processor](const signed_block_header& prevBlockHeader, const signed_block& block,
const signed_transaction& tx, uint32_t txInBlock) -> bool
{
uint16_t opInTx = 0;
for(const auto& op : tx.operations)
{
if(processor(prevBlockHeader, block, tx, txInBlock, op, opInTx) == false)
return false;
++opInTx;
}
return true;
}
);
}
const witness_object& database::get_witness( const account_name_type& name ) const
{ try {
return get< witness_object, by_name >( name );
} FC_CAPTURE_AND_RETHROW( (name) ) }
const witness_object* database::find_witness( const account_name_type& name ) const
{
return find< witness_object, by_name >( name );
}
const account_object& database::get_account( const account_name_type& name )const
{ try {
return get< account_object, by_name >( name );
} FC_CAPTURE_AND_RETHROW( (name) ) }
const account_object* database::find_account( const account_name_type& name )const
{
return find< account_object, by_name >( name );
}
const comment_object& database::get_comment( const account_name_type& author, const shared_string& permlink )const
{ try {
return get< comment_object, by_permlink >( boost::make_tuple( author, permlink ) );
} FC_CAPTURE_AND_RETHROW( (author)(permlink) ) }
const comment_object* database::find_comment( const account_name_type& author, const shared_string& permlink )const
{
return find< comment_object, by_permlink >( boost::make_tuple( author, permlink ) );
}
#ifndef ENABLE_STD_ALLOCATOR
const comment_object& database::get_comment( const account_name_type& author, const string& permlink )const
{ try {
return get< comment_object, by_permlink >( boost::make_tuple( author, permlink) );
} FC_CAPTURE_AND_RETHROW( (author)(permlink) ) }
const comment_object* database::find_comment( const account_name_type& author, const string& permlink )const
{
return find< comment_object, by_permlink >( boost::make_tuple( author, permlink ) );
}
#endif
const escrow_object& database::get_escrow( const account_name_type& name, uint32_t escrow_id )const
{ try {
return get< escrow_object, by_from_id >( boost::make_tuple( name, escrow_id ) );
} FC_CAPTURE_AND_RETHROW( (name)(escrow_id) ) }
const escrow_object* database::find_escrow( const account_name_type& name, uint32_t escrow_id )const
{
return find< escrow_object, by_from_id >( boost::make_tuple( name, escrow_id ) );
}
const limit_order_object& database::get_limit_order( const account_name_type& name, uint32_t orderid )const
{ try {
if( !has_hardfork( STEEM_HARDFORK_0_6__127 ) )
orderid = orderid & 0x0000FFFF;
return get< limit_order_object, by_account >( boost::make_tuple( name, orderid ) );
} FC_CAPTURE_AND_RETHROW( (name)(orderid) ) }
const limit_order_object* database::find_limit_order( const account_name_type& name, uint32_t orderid )const
{
if( !has_hardfork( STEEM_HARDFORK_0_6__127 ) )
orderid = orderid & 0x0000FFFF;
return find< limit_order_object, by_account >( boost::make_tuple( name, orderid ) );
}
const savings_withdraw_object& database::get_savings_withdraw( const account_name_type& owner, uint32_t request_id )const
{ try {
return get< savings_withdraw_object, by_from_rid >( boost::make_tuple( owner, request_id ) );
} FC_CAPTURE_AND_RETHROW( (owner)(request_id) ) }
const savings_withdraw_object* database::find_savings_withdraw( const account_name_type& owner, uint32_t request_id )const
{
return find< savings_withdraw_object, by_from_rid >( boost::make_tuple( owner, request_id ) );
}
const dynamic_global_property_object&database::get_dynamic_global_properties() const
{ try {
return get< dynamic_global_property_object >();
} FC_CAPTURE_AND_RETHROW() }
const node_property_object& database::get_node_properties() const
{
return _node_property_object;
}
const feed_history_object& database::get_feed_history()const
{ try {
return get< feed_history_object >();
} FC_CAPTURE_AND_RETHROW() }
const witness_schedule_object& database::get_witness_schedule_object()const
{ try {
return get< witness_schedule_object >();
} FC_CAPTURE_AND_RETHROW() }
const hardfork_property_object& database::get_hardfork_property_object()const
{ try {
return get< hardfork_property_object >();
} FC_CAPTURE_AND_RETHROW() }
const time_point_sec database::calculate_discussion_payout_time( const comment_object& comment )const
{
if( has_hardfork( STEEM_HARDFORK_0_17__769 ) || comment.parent_author == STEEM_ROOT_POST_PARENT )
return comment.cashout_time;
else
return get< comment_object >( comment.root_comment ).cashout_time;
}
const reward_fund_object& database::get_reward_fund( const comment_object& c ) const
{
return get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME );
}
asset database::get_effective_vesting_shares( const account_object& account, asset_symbol_type vested_symbol )const
{
if( vested_symbol == VESTS_SYMBOL )
return account.vesting_shares - account.delegated_vesting_shares + account.received_vesting_shares;
#ifdef STEEM_ENABLE_SMT
FC_ASSERT( vested_symbol.space() == asset_symbol_type::smt_nai_space );
FC_ASSERT( vested_symbol.is_vesting() );
#pragma message( "TODO: Update the code below when delegation is modified to support SMTs." )
const account_regular_balance_object* bo = find< account_regular_balance_object, by_owner_liquid_symbol >(
boost::make_tuple( account.name, vested_symbol.get_paired_symbol() ) );
if( bo == nullptr )
return asset( 0, vested_symbol );
return bo->vesting;
#else
FC_ASSERT( false, "Invalid symbol" );
#endif
}
uint32_t database::witness_participation_rate()const
{
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
return uint64_t(STEEM_100_PERCENT) * dpo.recent_slots_filled.popcount() / 128;
}
void database::add_checkpoints( const flat_map< uint32_t, block_id_type >& checkpts )
{
for( const auto& i : checkpts )
_checkpoints[i.first] = i.second;
}
bool database::before_last_checkpoint()const
{
return (_checkpoints.size() > 0) && (_checkpoints.rbegin()->first >= head_block_num());
}
/**
* Push block "may fail" in which case every partial change is unwound. After
* push block is successful the block is appended to the chain database on disk.
*
* @return true if we switched forks as a result of this push.
*/
bool database::push_block(const signed_block& new_block, uint32_t skip)
{
//fc::time_point begin_time = fc::time_point::now();
auto block_num = new_block.block_num();
if( _checkpoints.size() && _checkpoints.rbegin()->second != block_id_type() )
{
auto itr = _checkpoints.find( block_num );
if( itr != _checkpoints.end() )
FC_ASSERT( new_block.id() == itr->second, "Block did not match checkpoint", ("checkpoint",*itr)("block_id",new_block.id()) );
if( _checkpoints.rbegin()->first >= block_num )
skip = skip_witness_signature
| skip_transaction_signatures
| skip_transaction_dupe_check
/*| skip_fork_db Fork db cannot be skipped or else blocks will not be written out to block log */
| skip_block_size_check
| skip_tapos_check
| skip_authority_check
/* | skip_merkle_check While blockchain is being downloaded, txs need to be validated against block headers */
| skip_undo_history_check
| skip_witness_schedule_check
| skip_validate
| skip_validate_invariants
;
}
bool result;
detail::with_skip_flags( *this, skip, [&]()
{
detail::without_pending_transactions( *this, std::move(_pending_tx), [&]()
{
try
{
result = _push_block(new_block);
}
FC_CAPTURE_AND_RETHROW( (new_block) )
check_free_memory( false, new_block.block_num() );
});
});
//fc::time_point end_time = fc::time_point::now();
//fc::microseconds dt = end_time - begin_time;
//if( ( new_block.block_num() % 10000 ) == 0 )
// ilog( "push_block ${b} took ${t} microseconds", ("b", new_block.block_num())("t", dt.count()) );
return result;
}
void database::_maybe_warn_multiple_production( uint32_t height )const
{
auto blocks = _fork_db.fetch_block_by_number( height );
if( blocks.size() > 1 )
{
vector< std::pair< account_name_type, fc::time_point_sec > > witness_time_pairs;
for( const auto& b : blocks )
{
witness_time_pairs.push_back( std::make_pair( b->data.witness, b->data.timestamp ) );
}
ilog( "Encountered block num collision at block ${n} due to a fork, witnesses are: ${w}", ("n", height)("w", witness_time_pairs) );
}
return;
}
bool database::_push_block(const signed_block& new_block)
{ try {
#ifdef IS_TEST_NET
FC_ASSERT(new_block.block_num() < TESTNET_BLOCK_LIMIT, "Testnet block limit exceeded");
#endif /// IS_TEST_NET
uint32_t skip = get_node_properties().skip_flags;
//uint32_t skip_undo_db = skip & skip_undo_block;
if( !(skip&skip_fork_db) )
{
shared_ptr<fork_item> new_head = _fork_db.push_block(new_block);
_maybe_warn_multiple_production( new_head->num );
//If the head block from the longest chain does not build off of the current head, we need to switch forks.
if( new_head->data.previous != head_block_id() )
{
//If the newly pushed block is the same height as head, we get head back in new_head
//Only switch forks if new_head is actually higher than head
if( new_head->data.block_num() > head_block_num() )
{
wlog( "Switching to fork: ${id}", ("id",new_head->data.id()) );
auto branches = _fork_db.fetch_branch_from(new_head->data.id(), head_block_id());
// pop blocks until we hit the forked block
while( head_block_id() != branches.second.back()->data.previous )
pop_block();
// push all blocks on the new fork
for( auto ritr = branches.first.rbegin(); ritr != branches.first.rend(); ++ritr )
{
ilog( "pushing blocks from fork ${n} ${id}", ("n",(*ritr)->data.block_num())("id",(*ritr)->data.id()) );
optional<fc::exception> except;
try
{
_fork_db.set_head( *ritr );
auto session = start_undo_session();
apply_block( (*ritr)->data, skip );
session.push();
}
catch ( const fc::exception& e ) { except = e; }
if( except )
{
wlog( "exception thrown while switching forks ${e}", ("e",except->to_detail_string() ) );
// remove the rest of branches.first from the fork_db, those blocks are invalid
while( ritr != branches.first.rend() )
{
_fork_db.remove( (*ritr)->data.id() );
++ritr;
}
// pop all blocks from the bad fork
while( head_block_id() != branches.second.back()->data.previous )
pop_block();
// restore all blocks from the good fork
for( auto ritr = branches.second.rbegin(); ritr != branches.second.rend(); ++ritr )
{
_fork_db.set_head( *ritr );
auto session = start_undo_session();
apply_block( (*ritr)->data, skip );
session.push();
}
throw *except;
}
}
return true;
}
else
return false;
}
}
try
{
auto session = start_undo_session();
apply_block(new_block, skip);
session.push();
}
catch( const fc::exception& e )
{
elog("Failed to push new block:\n${e}", ("e", e.to_detail_string()));
_fork_db.remove(new_block.id());
throw;
}
return false;
} FC_CAPTURE_AND_RETHROW() }
/**
* Attempts to push the transaction into the pending queue
*
* When called to push a locally generated transaction, set the skip_block_size_check bit on the skip argument. This
* will allow the transaction to be pushed even if it causes the pending block size to exceed the maximum block size.
* Although the transaction will probably not propagate further now, as the peers are likely to have their pending
* queues full as well, it will be kept in the queue to be propagated later when a new block flushes out the pending
* queues.
*/
void database::push_transaction( const signed_transaction& trx, uint32_t skip )
{
try
{
try
{
FC_ASSERT( fc::raw::pack_size(trx) <= (get_dynamic_global_properties().maximum_block_size - 256) );
set_producing( true );
set_pending_tx( true );
detail::with_skip_flags( *this, skip,
[&]()
{
_push_transaction( trx );
});
set_producing( false );
set_pending_tx( false );
}
catch( ... )
{
set_producing( false );
set_pending_tx( false );
throw;
}
}
FC_CAPTURE_AND_RETHROW( (trx) )
}
void database::_push_transaction( const signed_transaction& trx )
{
// If this is the first transaction pushed after applying a block, start a new undo session.
// This allows us to quickly rewind to the clean state of the head block, in case a new block arrives.
if( !_pending_tx_session.valid() )
_pending_tx_session = start_undo_session();
// Create a temporary undo session as a child of _pending_tx_session.
// The temporary session will be discarded by the destructor if
// _apply_transaction fails. If we make it to merge(), we
// apply the changes.
auto temp_session = start_undo_session();
_apply_transaction( trx );
_pending_tx.push_back( trx );
notify_changed_objects();
// The transaction applied successfully. Merge its changes into the pending block session.
temp_session.squash();
}
signed_block database::generate_block(
fc::time_point_sec when,
const account_name_type& witness_owner,
const fc::ecc::private_key& block_signing_private_key,
uint32_t skip /* = 0 */
)
{
signed_block result;
detail::with_skip_flags( *this, skip, [&]()
{
try
{
result = _generate_block( when, witness_owner, block_signing_private_key );
}
FC_CAPTURE_AND_RETHROW( (witness_owner) )
});
return result;
}
signed_block database::_generate_block(
fc::time_point_sec when,
const account_name_type& witness_owner,
const fc::ecc::private_key& block_signing_private_key
)
{
uint32_t skip = get_node_properties().skip_flags;
uint32_t slot_num = get_slot_at_time( when );
FC_ASSERT( slot_num > 0 );
string scheduled_witness = get_scheduled_witness( slot_num );
FC_ASSERT( scheduled_witness == witness_owner );
const auto& witness_obj = get_witness( witness_owner );
if( !(skip & skip_witness_signature) )
FC_ASSERT( witness_obj.signing_key == block_signing_private_key.get_public_key() );
signed_block pending_block;
pending_block.previous = head_block_id();
pending_block.timestamp = when;
pending_block.witness = witness_owner;
if( has_hardfork( STEEM_HARDFORK_0_5__54 ) )
{
const auto& witness = get_witness( witness_owner );
if( witness.running_version != STEEM_BLOCKCHAIN_VERSION )
pending_block.extensions.insert( block_header_extensions( STEEM_BLOCKCHAIN_VERSION ) );
const auto& hfp = get_hardfork_property_object();
if( hfp.current_hardfork_version < STEEM_BLOCKCHAIN_VERSION // Binary is newer hardfork than has been applied
&& ( witness.hardfork_version_vote != _hardfork_versions[ hfp.last_hardfork + 1 ] || witness.hardfork_time_vote != _hardfork_times[ hfp.last_hardfork + 1 ] ) ) // Witness vote does not match binary configuration
{
// Make vote match binary configuration
pending_block.extensions.insert( block_header_extensions( hardfork_version_vote( _hardfork_versions[ hfp.last_hardfork + 1 ], _hardfork_times[ hfp.last_hardfork + 1 ] ) ) );
}
else if( hfp.current_hardfork_version == STEEM_BLOCKCHAIN_VERSION // Binary does not know of a new hardfork
&& witness.hardfork_version_vote > STEEM_BLOCKCHAIN_VERSION ) // Voting for hardfork in the future, that we do not know of...
{
// Make vote match binary configuration. This is vote to not apply the new hardfork.
pending_block.extensions.insert( block_header_extensions( hardfork_version_vote( _hardfork_versions[ hfp.last_hardfork ], _hardfork_times[ hfp.last_hardfork ] ) ) );
}
}
// The 4 is for the max size of the transaction vector length
size_t total_block_size = fc::raw::pack_size( pending_block ) + 4;
auto maximum_block_size = get_dynamic_global_properties().maximum_block_size; //STEEM_MAX_BLOCK_SIZE;
//
// The following code throws away existing pending_tx_session and
// rebuilds it by re-applying pending transactions.
//
// This rebuild is necessary because pending transactions' validity
// and semantics may have changed since they were received, because
// time-based semantics are evaluated based on the current block
// time. These changes can only be reflected in the database when
// the value of the "when" variable is known, which means we need to
// re-apply pending transactions in this method.
//
_pending_tx_session.reset();
_pending_tx_session = start_undo_session();
FC_TODO( "Safe to remove after HF20 occurs because no more pre HF20 blocks will be generated" );
if( has_hardfork( STEEM_HARDFORK_0_20 ) )
{
/// modify current witness so transaction evaluators can know who included the transaction
modify( get_dynamic_global_properties(), [&]( dynamic_global_property_object& dgp )
{
dgp.current_witness = scheduled_witness;
});
}
uint64_t postponed_tx_count = 0;
// pop pending state (reset to head block state)
for( const signed_transaction& tx : _pending_tx )
{
// Only include transactions that have not expired yet for currently generating block,
// this should clear problem transactions and allow block production to continue
if( tx.expiration < when )
continue;
uint64_t new_total_size = total_block_size + fc::raw::pack_size( tx );
// postpone transaction if it would make block too big
if( new_total_size >= maximum_block_size )
{
postponed_tx_count++;
continue;
}
try
{
auto temp_session = start_undo_session();
_apply_transaction( tx );
temp_session.squash();
total_block_size += fc::raw::pack_size( tx );
pending_block.transactions.push_back( tx );
}
catch ( const fc::exception& e )
{
// Do nothing, transaction will not be re-applied
//wlog( "Transaction was not processed while generating block due to ${e}", ("e", e) );
//wlog( "The transaction was ${t}", ("t", tx) );
}
}
if( postponed_tx_count > 0 )
{
wlog( "Postponed ${n} transactions due to block size limit", ("n", postponed_tx_count) );
}
_pending_tx_session.reset();
// We have temporarily broken the invariant that
// _pending_tx_session is the result of applying _pending_tx, as
// _pending_tx now consists of the set of postponed transactions.
// However, the push_block() call below will re-create the
// _pending_tx_session.
pending_block.transaction_merkle_root = pending_block.calculate_merkle_root();
if( !(skip & skip_witness_signature) )
pending_block.sign( block_signing_private_key, has_hardfork( STEEM_HARDFORK_0_20__1944 ) ? fc::ecc::bip_0062 : fc::ecc::fc_canonical );
// TODO: Move this to _push_block() so session is restored.
if( !(skip & skip_block_size_check) )
{
FC_ASSERT( fc::raw::pack_size(pending_block) <= STEEM_MAX_BLOCK_SIZE );
}
push_block( pending_block, skip );
return pending_block;
}
/**
* Removes the most recent block from the database and