-
Notifications
You must be signed in to change notification settings - Fork 790
/
database.cpp
4407 lines (3757 loc) · 161 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 <steemit/protocol/steem_operations.hpp>
#include <steemit/chain/block_summary_object.hpp>
#include <steemit/chain/compound.hpp>
#include <steemit/chain/custom_operation_interpreter.hpp>
#include <steemit/chain/database.hpp>
#include <steemit/chain/database_exceptions.hpp>
#include <steemit/chain/db_with.hpp>
#include <steemit/chain/evaluator_registry.hpp>
#include <steemit/chain/global_property_object.hpp>
#include <steemit/chain/history_object.hpp>
#include <steemit/chain/steem_evaluator.hpp>
#include <steemit/chain/steem_objects.hpp>
#include <steemit/chain/transaction_object.hpp>
#include <steemit/chain/shared_db_merkle.hpp>
#include <steemit/chain/operation_notification.hpp>
#include <fc/smart_ref_impl.hpp>
#include <fc/uint128.hpp>
#include <fc/container/deque.hpp>
#include <fc/io/fstream.hpp>
#include <cstdint>
#include <deque>
#include <fstream>
#include <functional>
#define VIRTUAL_SCHEDULE_LAP_LENGTH ( fc::uint128(uint64_t(-1)) )
#define VIRTUAL_SCHEDULE_LAP_LENGTH2 ( fc::uint128::max_value() )
namespace steemit { namespace chain {
//namespace db2 = graphene::db2;
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( steemit::chain::object_schema_repr, (space_type)(type) )
FC_REFLECT( steemit::chain::operation_schema_repr, (id)(type) )
FC_REFLECT( steemit::chain::db_schema, (types)(object_types)(operation_type)(custom_operation_types) )
namespace steemit { namespace chain {
using boost::container::flat_set;
inline u256 to256( const fc::uint128& t ) {
u256 v(t.hi);
v <<= 64;
v += t.lo;
return v;
}
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 fc::path& data_dir, uint64_t initial_supply, uint64_t shared_file_size )
{
try
{
init_schema();
chainbase::database::open( data_dir, chainbase::database::read_write, shared_file_size );
with_write_lock( [&]()
{
initialize_indexes();
initialize_evaluators();
_block_log.open( data_dir / "block_log" );
if( !find< dynamic_global_property_object >() )
init_genesis( initial_supply );
init_hardforks();
// block_log.head must be in block stats
// If it is not, print warning and exit
auto log_head = _block_log.head();
if( log_head && head_block_num() )
FC_ASSERT( get< block_stats_object >( log_head->block_num() - 1 ).block_id == log_head->id(),
"Head block of log file is not included in current chain state. log_head: ${log_head}", ("log_head", log_head) );
// Rewind all undo state. This should return us to the state at the last irreversible block.
undo_all();
});
if( head_block_num() )
_fork_db.start_block( *fetch_block_by_number( head_block_num() ) );
}
FC_CAPTURE_LOG_AND_RETHROW( (data_dir) )
}
void database::reindex( fc::path data_dir, uint64_t shared_file_size )
{
try
{
ilog( "Reindexing Blockchain" );
wipe( data_dir, false );
open( data_dir, 0, shared_file_size );
_fork_db.reset(); // override effect of _fork_db.start_block() call in open()
auto start = fc::time_point::now();
STEEMIT_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;
with_write_lock( [&]()
{
auto itr = _block_log.read_block( 0 );
auto last_block_num = _block_log.head()->block_num();
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 << " \n";
apply_block( itr.first, skip_flags );
itr = _block_log.read_block( itr.second );
}
apply_block( itr.first, skip_flags );
set_revision( head_block_num() );
});
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 ) );
}
FC_CAPTURE_AND_RETHROW( (data_dir) )
}
void database::wipe(const fc::path& data_dir, bool include_blocks)
{
close();
chainbase::database::wipe( data_dir );
if( include_blocks )
fc::remove_all( data_dir / "block_log" );
}
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
{
return _fork_db.is_known_block(id) || find< block_stats_object, by_block_id >( id );
}
/**
* 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
{
const auto& trx_idx = get_index<transaction_index>().indices().get<by_trx_id>();
return trx_idx.find( id ) != trx_idx.end();
}
block_id_type database::get_block_id_for_num( uint32_t block_num )const
{
return get< block_stats_object >( block_num - 1 ).block_id;
}
optional<signed_block> database::fetch_block_by_id( const block_id_type& id )const
{
auto b = _fork_db.fetch_block( id );
if( !b )
{
auto tmp = fetch_block_by_number( protocol::block_header::num_from_id( id ) );
if( tmp && tmp->id() == id )
return tmp;
tmp.reset();
return tmp;
}
return b->data;
}
optional<signed_block> database::fetch_block_by_number( uint32_t block_num )const
{
optional< signed_block > b;
const auto* stats = find< block_stats_object >( block_num - 1 );
if( !stats )
return b;
signed_block block;
fc::raw::unpack( stats->packed_block, block );
b = block;
return b;
}
const signed_transaction database::get_recent_transaction( const transaction_id_type& trx_id ) const
{
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( itr->packed_trx, trx );
return trx;;
}
std::vector< block_id_type > database::get_block_ids_on_fork( block_id_type head_of_fork ) const
{
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;
}
chain_id_type database::get_chain_id() const
{
return STEEMIT_CHAIN_ID;
}
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 ) );
}
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 ) );
}
const category_object& database::get_category( const shared_string& name )const
{ try {
return get< category_object, by_name >( name );
} FC_CAPTURE_AND_RETHROW( (name) ) }
const category_object* database::find_category( const shared_string& name )const
{
return find< category_object, by_name >( name );
}
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( STEEMIT_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( STEEMIT_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( comment.parent_author == STEEMIT_ROOT_POST_PARENT )
return comment.cashout_time;
else
return get< comment_object >( comment.root_comment ).cashout_time;
}
void database::pay_fee( const account_object& account, asset fee )
{
FC_ASSERT( fee.amount >= 0 ); /// NOTE if this fails then validate() on some operation is probably wrong
if( fee.amount == 0 )
return;
FC_ASSERT( account.balance >= fee );
adjust_balance( account, -fee );
adjust_supply( -fee );
}
void database::update_account_bandwidth( const account_object& a, uint32_t trx_size )
{
const auto& props = get_dynamic_global_properties();
if( props.total_vesting_shares.amount > 0 )
{
modify( a, [&]( account_object& acnt )
{
acnt.lifetime_bandwidth += trx_size * STEEMIT_BANDWIDTH_PRECISION;
auto now = head_block_time();
auto delta_time = (now - a.last_bandwidth_update).to_seconds();
uint64_t N = trx_size * STEEMIT_BANDWIDTH_PRECISION;
if( delta_time >= STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS )
acnt.average_bandwidth = N;
else
{
auto old_weight = acnt.average_bandwidth * (STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS - delta_time);
auto new_weight = delta_time * N;
acnt.average_bandwidth = (old_weight + new_weight) / (STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS);
}
if( props.total_vesting_shares.amount > 0 )
{
FC_ASSERT( a.vesting_shares.amount > 0, "only accounts with a positive vesting balance may transact" );
fc::uint128 account_vshares(a.vesting_shares.amount.value);
fc::uint128 total_vshares( props.total_vesting_shares.amount.value );
fc::uint128 account_average_bandwidth( acnt.average_bandwidth );
fc::uint128 max_virtual_bandwidth( props.max_virtual_bandwidth );
// account_vshares / total_vshares > account_average_bandwidth / max_virtual_bandwidth
FC_ASSERT( (account_vshares * max_virtual_bandwidth) > (account_average_bandwidth * total_vshares),
"account exceeded maximum allowed bandwidth per vesting share account_vshares: ${account_vshares} account_average_bandwidth: ${account_average_bandwidth} max_virtual_bandwidth: ${max_virtual_bandwidth} total_vesting_shares: ${total_vesting_shares}",
("account_vshares",account_vshares)
("account_average_bandwidth",account_average_bandwidth)
("max_virtual_bandwidth",max_virtual_bandwidth)
("total_vesting_shares",total_vshares) );
}
acnt.last_bandwidth_update = now;
} );
}
}
void database::update_account_market_bandwidth( const account_object& a, uint32_t trx_size )
{
const auto& props = get_dynamic_global_properties();
if( props.total_vesting_shares.amount > 0 )
{
modify( a, [&]( account_object& acnt )
{
auto now = head_block_time();
auto delta_time = (now - a.last_market_bandwidth_update).to_seconds();
uint64_t N = trx_size * STEEMIT_BANDWIDTH_PRECISION;
if( delta_time >= STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS )
acnt.average_market_bandwidth = N;
else
{
auto old_weight = acnt.average_market_bandwidth * (STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS - delta_time);
auto new_weight = delta_time * N;
acnt.average_market_bandwidth = (old_weight + new_weight) / (STEEMIT_BANDWIDTH_AVERAGE_WINDOW_SECONDS);
}
if( props.total_vesting_shares.amount > 0 )
{
FC_ASSERT( a.vesting_shares.amount > 0, "only accounts with a positive vesting balance may transact" );
fc::uint128 account_vshares(a.vesting_shares.amount.value);
fc::uint128 total_vshares( props.total_vesting_shares.amount.value );
fc::uint128 account_average_bandwidth( acnt.average_market_bandwidth );
fc::uint128 max_virtual_bandwidth( props.max_virtual_bandwidth / 10 ); /// only 10% of bandwidth can be market
// account_vshares / total_vshares > account_average_bandwidth / max_virtual_bandwidth
FC_ASSERT( (account_vshares * max_virtual_bandwidth) > (account_average_bandwidth * total_vshares),
"account exceeded maximum allowed bandwidth per vesting share account_vshares: ${account_vshares} account_average_bandwidth: ${account_average_bandwidth} max_virtual_bandwidth: ${max_virtual_bandwidth} total_vesting_shares: ${total_vesting_shares}",
("account_vshares",account_vshares)
("account_average_bandwidth",account_average_bandwidth)
("max_virtual_bandwidth",max_virtual_bandwidth)
("total_vshares",total_vshares) );
}
acnt.last_market_bandwidth_update = now;
} );
}
}
uint32_t database::witness_participation_rate()const
{
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
return uint64_t(STEEMIT_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)
{
bool result;
detail::with_skip_flags( *this, skip, [&]()
{
detail::without_pending_transactions( *this, std::move(_pending_tx),
[&]()
{
try
{
with_write_lock( [&]()
{
result = _push_block(new_block);
});
}
FC_CAPTURE_AND_RETHROW( (new_block) )
});
});
return result;
}
bool database::_push_block(const signed_block& new_block)
{
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);
//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
{
auto session = start_undo_session( true );
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;
}
_fork_db.set_head( branches.second.front() );
// 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 )
{
auto session = start_undo_session( true );
apply_block( (*ritr)->data, skip );
session.push();
}
throw *except;
}
}
return true;
}
else
return false;
}
}
try
{
auto session = start_undo_session( true );
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;
}
/**
* 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 );
detail::with_skip_flags( *this, skip,
[&]()
{
with_write_lock( [&]()
{
_push_transaction( trx );
});
});
set_producing( false );
}
catch( ... )
{
set_producing( 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( true );
// 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( true );
_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();
// notify anyone listening to pending transactions
notify_on_pending_transaction( trx );
}
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() );
static const size_t max_block_header_size = fc::raw::pack_size( signed_block_header() ) + 4;
auto maximum_block_size = get_dynamic_global_properties().maximum_block_size; //STEEMIT_MAX_BLOCK_SIZE;
size_t total_block_size = max_block_header_size;
signed_block pending_block;
with_write_lock( [&]()
{
//
// 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( true );
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( true );
_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.previous = head_block_id();
pending_block.timestamp = when;
pending_block.transaction_merkle_root = pending_block.calculate_merkle_root();
pending_block.witness = witness_owner;
if( has_hardfork( STEEMIT_HARDFORK_0_5__54 ) )
{
const auto& witness = get_witness( witness_owner );
if( witness.running_version != STEEMIT_BLOCKCHAIN_VERSION )
pending_block.extensions.insert( block_header_extensions( STEEMIT_BLOCKCHAIN_VERSION ) );
const auto& hfp = get_hardfork_property_object();
if( hfp.current_hardfork_version < STEEMIT_BLOCKCHAIN_HARDFORK_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 == STEEMIT_BLOCKCHAIN_HARDFORK_VERSION // Binary does not know of a new hardfork
&& witness.hardfork_version_vote > STEEMIT_BLOCKCHAIN_HARDFORK_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 ] ) ) );
}
}
if( !(skip & skip_witness_signature) )
pending_block.sign( block_signing_private_key );
// TODO: Move this to _push_block() so session is restored.
if( !(skip & skip_block_size_check) )
{
FC_ASSERT( fc::raw::pack_size(pending_block) <= STEEMIT_MAX_BLOCK_SIZE );
}
push_block( pending_block, skip );
return pending_block;
}
/**
* Removes the most recent block from the database and
* undoes any changes it made.
*/
void database::pop_block()
{
try
{
_pending_tx_session.reset();
auto head_id = head_block_id();
/// save the head block so we can recover its transactions
optional<signed_block> head_block = fetch_block_by_id( head_id );
STEEMIT_ASSERT( head_block.valid(), pop_empty_chain, "there are no blocks to pop" );
_fork_db.pop_block();
undo();
_popped_tx.insert( _popped_tx.begin(), head_block->transactions.begin(), head_block->transactions.end() );
}
FC_CAPTURE_AND_RETHROW()
}
void database::clear_pending()
{
try
{
assert( (_pending_tx.size() == 0) || _pending_tx_session.valid() );
_pending_tx.clear();
_pending_tx_session.reset();
}
FC_CAPTURE_AND_RETHROW()
}
void database::notify_pre_apply_operation( operation_notification& note )
{
note.trx_id = _current_trx_id;
note.block = _current_block_num;
note.trx_in_block = _current_trx_in_block;
note.op_in_trx = _current_op_in_trx;
STEEMIT_TRY_NOTIFY( pre_apply_operation, note )
}
void database::notify_post_apply_operation( const operation_notification& note )
{
STEEMIT_TRY_NOTIFY( post_apply_operation, note )
}
inline const void database::push_virtual_operation( const operation& op, bool force )
{
if( !force )
{
#if defined( IS_LOW_MEM ) && ! defined( IS_TEST_NET )
return;
#endif
}
FC_ASSERT( is_virtual_operation( op ) );
operation_notification note(op);
notify_pre_apply_operation( note );
notify_post_apply_operation( note );
}
void database::notify_applied_block( const signed_block& block )
{
STEEMIT_TRY_NOTIFY( applied_block, block )
}
void database::notify_on_pending_transaction( const signed_transaction& tx )
{
STEEMIT_TRY_NOTIFY( on_pending_transaction, tx )
}
void database::notify_on_applied_transaction( const signed_transaction& tx )
{
STEEMIT_TRY_NOTIFY( on_applied_transaction, tx )
}
account_name_type database::get_scheduled_witness( uint32_t slot_num )const
{
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
const witness_schedule_object& wso = get_witness_schedule_object();
uint64_t current_aslot = dpo.current_aslot + slot_num;
return wso.current_shuffled_witnesses[ current_aslot % wso.num_scheduled_witnesses ];
}
fc::time_point_sec database::get_slot_time(uint32_t slot_num)const
{
if( slot_num == 0 )
return fc::time_point_sec();
auto interval = STEEMIT_BLOCK_INTERVAL;
const dynamic_global_property_object& dpo = get_dynamic_global_properties();
if( head_block_num() == 0 )
{
// n.b. first block is at genesis_time plus one block interval
fc::time_point_sec genesis_time = dpo.time;
return genesis_time + slot_num * interval;
}
int64_t head_block_abs_slot = head_block_time().sec_since_epoch() / interval;
fc::time_point_sec head_slot_time( head_block_abs_slot * interval );
// "slot 0" is head_slot_time
// "slot 1" is head_slot_time,
// plus maint interval if head block is a maint block
// plus block interval if head block is not a maint block
return head_slot_time + (slot_num * interval);
}
uint32_t database::get_slot_at_time(fc::time_point_sec when)const
{
fc::time_point_sec first_slot_time = get_slot_time( 1 );
if( when < first_slot_time )
return 0;
return (when - first_slot_time).to_seconds() / STEEMIT_BLOCK_INTERVAL + 1;
}
/**
* Converts STEEM into sbd and adds it to to_account while reducing the STEEM supply
* by STEEM and increasing the sbd supply by the specified amount.
*/
std::pair< asset, asset > database::create_sbd( const account_object& to_account, asset steem )
{
std::pair< asset, asset > assets( asset( 0, SBD_SYMBOL ), asset( 0, STEEM_SYMBOL ) );
try
{
if( steem.amount == 0 )
return assets;
const auto& median_price = get_feed_history().current_median_history;
const auto& gpo = get_dynamic_global_properties();
if( !median_price.is_null() )
{
auto to_sbd = ( gpo.sbd_print_rate * steem.amount ) / STEEMIT_100_PERCENT;
auto to_steem = steem.amount - to_sbd;
auto sbd = asset( to_sbd, STEEM_SYMBOL ) * median_price;
adjust_balance( to_account, sbd );
adjust_balance( to_account, asset( to_steem, STEEM_SYMBOL ) );
adjust_supply( asset( -to_sbd, STEEM_SYMBOL ) );
adjust_supply( sbd );
assets.first = sbd;
assets.second = to_steem;
}
else