This repository has been archived by the owner on Feb 21, 2019. It is now read-only.
/
chain_database.cpp
2035 lines (1742 loc) · 81.1 KB
/
chain_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
//#define DEFAULT_LOGGER "blockchain"
#include <bts/blockchain/exceptions.hpp>
#include <bts/blockchain/chain_database.hpp>
#include <bts/blockchain/config.hpp>
#include <bts/blockchain/genesis_config.hpp>
#include <bts/blockchain/time.hpp>
#include <bts/blockchain/operation_factory.hpp>
#include <bts/blockchain/fire_operation.hpp>
#include <bts/blockchain/genesis_json.hpp>
#include <bts/blockchain/transaction_evaluation_state.hpp>
#include <bts/db/level_map.hpp>
#include <bts/db/level_pod_map.hpp>
#include <fc/io/json.hpp>
#include <fc/io/raw_variant.hpp>
#include <fc/io/fstream.hpp>
#include <fc/log/logger.hpp>
#include <algorithm>
#include <fstream>
#include <iostream>
using namespace bts::blockchain;
struct vote_del
{
vote_del( int64_t v = 0, account_id_type del = 0 )
:votes(v),delegate_id(del){}
int64_t votes;
account_id_type delegate_id;
friend bool operator == ( const vote_del& a, const vote_del& b )
{
return a.votes == b.votes && a.delegate_id == b.delegate_id;
}
friend bool operator < ( const vote_del& a, const vote_del& b )
{
if( a.votes > b.votes ) return true;
if( a.votes < b.votes ) return false;
return a.delegate_id < b.delegate_id; /* Lowest id wins in ties */
}
};
FC_REFLECT( vote_del, (votes)(delegate_id) )
struct fee_index
{
fee_index( share_type fees = 0, transaction_id_type trx = transaction_id_type() )
:_fees(fees),_trx(trx){}
share_type _fees;
transaction_id_type _trx;
friend bool operator == ( const fee_index& a, const fee_index& b )
{
return a._fees == b._fees && a._trx == b._trx;
}
friend bool operator < ( const fee_index& a, const fee_index& b )
{
if( a._fees == b._fees ) return a._trx < b._trx; /* Lowest id wins in ties */
return a._fees > b._fees; /* Reverse so that highest fee is placed first in sorted maps */
}
};
FC_REFLECT( fee_index, (_fees)(_trx) )
FC_REFLECT_TYPENAME( std::vector<bts::blockchain::block_id_type> )
namespace bts { namespace blockchain {
// register exceptions here so it doesn't get optimized out by the linker
FC_REGISTER_EXCEPTIONS( (blockchain_exception)
(invalid_pts_address)
(addition_overflow)
(addition_underthrow)
(asset_type_mismatch)
(unsupported_chain_operation) )
namespace detail
{
class chain_database_impl
{
public:
chain_database_impl():self(nullptr){}
void initialize_genesis(fc::optional<fc::path> genesis_file);
block_fork_data store_and_index( const block_id_type& id, const full_block& blk );
void clear_pending( const full_block& blk );
void switch_to_fork( const block_id_type& block_id );
void extend_chain( const full_block& blk );
vector<block_id_type> get_fork_history( const block_id_type& id );
void pop_block();
void mark_invalid( const block_id_type& id );
void mark_included( const block_id_type& id, bool state );
void verify_header( const full_block& );
void apply_transactions( uint32_t block_num,
const std::vector<signed_transaction>&,
const pending_chain_state_ptr& );
void pay_delegate( fc::time_point_sec time_slot, share_type amount,
const pending_chain_state_ptr& );
void save_undo_state( const block_id_type& id,
const pending_chain_state_ptr& );
void update_head_block( const full_block& blk );
std::vector<block_id_type> fetch_blocks_at_number( uint32_t block_num );
void recursive_mark_as_linked( const std::unordered_set<block_id_type>& ids );
void recursive_mark_as_invalid( const std::unordered_set<block_id_type>& ids );
void update_random_seed( secret_hash_type new_secret,
const pending_chain_state_ptr& pending_state );
void update_active_delegate_list(const full_block& block_data,
const pending_chain_state_ptr& pending_state );
void update_delegate_production_info( const full_block& block_data,
const pending_chain_state_ptr& pending_state );
/**
* Used to track the cumulative effect of all pending transactions that are known,
* new incomming transactions are evaluated relative to this state.
*
* After a new block is pushed this state is recalculated based upon what ever
* pending transactions remain.
*/
pending_chain_state_ptr _pending_trx_state;
chain_database* self;
unordered_set<chain_observer*> _observers;
digest_type _chain_id;
bts::db::level_map<slate_id_type, delegate_slate > _slate_db;
bts::db::level_map<uint32_t, std::vector<block_id_type> > _fork_number_db;
bts::db::level_map<block_id_type,block_fork_data> _fork_db;
bts::db::level_map<uint32_t, fc::variant > _property_db;
bts::db::level_map<proposal_id_type, proposal_record > _proposal_db;
bts::db::level_map<proposal_vote_id_type, proposal_vote > _proposal_vote_db;
/** the data required to 'undo' the changes a block made to the database */
bts::db::level_map<block_id_type,pending_chain_state> _undo_state_db;
// blocks in the current 'official' chain.
bts::db::level_map<uint32_t,block_id_type> _block_num_to_id_db;
// all blocks from any fork..
//bts::db::level_map<block_id_type,full_block> _block_id_to_block_db;
bts::db::level_map<block_id_type,block_record> _block_id_to_block_record_db;
bts::db::level_map<block_id_type,full_block> _block_id_to_block_data_db;
bts::db::level_map<transaction_id_type,transaction_record> _id_to_transaction_record_db;
// used to revert block state in the event of a fork
// bts::db::level_map<uint32_t,undo_data> _block_num_to_undo_data_db;
signed_block_header _head_block_header;
block_id_type _head_block_id;
bts::db::level_map< transaction_id_type, signed_transaction> _pending_transaction_db;
std::map< fee_index, transaction_evaluation_state_ptr > _pending_fee_index;
bts::db::level_map< asset_id_type, asset_record > _asset_db;
bts::db::level_map< balance_id_type, balance_record > _balance_db;
bts::db::level_map< account_id_type, account_record > _account_db;
bts::db::level_map< address, account_id_type > _address_to_account_db;
bts::db::level_map< string, account_id_type > _account_index_db;
bts::db::level_map< string, asset_id_type > _symbol_index_db;
bts::db::level_pod_map< vote_del, int > _delegate_vote_index_db;
/* Negative block number means block was missed */
bts::db::level_map< std::pair< account_id_type, uint32_t >, delegate_block_stats >
_delegate_block_stats_db;
bts::db::level_map< market_index_key, order_record > _ask_db;
bts::db::level_map< market_index_key, order_record > _bid_db;
bts::db::level_map< market_index_key, order_record > _short_db;
bts::db::level_map< market_index_key, collateral_record > _collateral_db;
/** used to prevent duplicate processing */
// bts::db::level_pod_map< transaction_id_type, transaction_location > _processed_transaction_id_db;
void open_database( const fc::path& data_dir );
};
void chain_database_impl::open_database( const fc::path& data_dir )
{ try {
_property_db.open( data_dir / "property_db" );
auto database_version = _property_db.fetch_optional( chain_property_enum::database_version );
if( !database_version || database_version->as_int64() < BTS_BLOCKCHAIN_DATABASE_VERSION )
{
wlog( "old database version, upgrade and re-sync" );
_property_db.close();
fc::remove_all( data_dir );
fc::create_directories( data_dir );
_property_db.open( data_dir / "property_db" );
self->set_property( chain_property_enum::database_version, BTS_BLOCKCHAIN_DATABASE_VERSION );
}
else if( database_version && !database_version->is_null() && database_version->as_int64() > BTS_BLOCKCHAIN_DATABASE_VERSION )
{
FC_CAPTURE_AND_THROW( new_database_version, (database_version)(BTS_BLOCKCHAIN_DATABASE_VERSION) );
}
_fork_number_db.open( data_dir / "fork_number_db" );
_fork_db.open( data_dir / "fork_db" );
_slate_db.open( data_dir / "slate_db" );
_proposal_db.open( data_dir / "proposal_db" );
_proposal_vote_db.open( data_dir / "proposal_vote_db" );
_undo_state_db.open( data_dir / "undo_state_db" );
_block_num_to_id_db.open( data_dir / "block_num_to_id_db" );
_block_id_to_block_record_db.open( data_dir / "block_id_to_block_record_db" );
_block_id_to_block_data_db.open( data_dir / "block_id_to_block_data_db" );
_id_to_transaction_record_db.open( data_dir / "id_to_transaction_record_db" );
_pending_transaction_db.open( data_dir / "pending_transaction_db" );
_asset_db.open( data_dir / "asset_db" );
_balance_db.open( data_dir / "balance_db" );
_account_db.open( data_dir / "account_db" );
_address_to_account_db.open( data_dir / "address_to_account_db" );
_account_index_db.open( data_dir / "account_index_db" );
_symbol_index_db.open( data_dir / "symbol_index_db" );
_delegate_vote_index_db.open( data_dir / "delegate_vote_index_db" );
_delegate_block_stats_db.open( data_dir / "delegate_block_stats_db" );
_ask_db.open( data_dir / "ask_db" );
_bid_db.open( data_dir / "bid_db" );
_short_db.open( data_dir / "short_db" );
_collateral_db.open( data_dir / "collateral_db" );
_pending_trx_state = std::make_shared<pending_chain_state>( self->shared_from_this() );
} FC_CAPTURE_AND_RETHROW( (data_dir) ) }
std::vector<block_id_type> chain_database_impl::fetch_blocks_at_number( uint32_t block_num )
{
std::vector<block_id_type> current_blocks;
auto itr = _fork_number_db.find( block_num );
if( itr.valid() ) return itr.value();
return current_blocks;
}
void chain_database_impl::clear_pending( const full_block& blk )
{ //try {
std::unordered_set<transaction_id_type> confirmed_trx_ids;
for( auto trx : blk.user_transactions )
{
auto id = trx.id();
confirmed_trx_ids.insert( id );
_pending_transaction_db.remove( id );
}
_pending_fee_index.clear();
vector<transaction_id_type> trx_to_discard;
_pending_trx_state = std::make_shared<pending_chain_state>( self->shared_from_this() );
auto itr = _pending_transaction_db.begin();
while( itr.valid() )
{
auto trx = itr.value();
auto trx_id = trx.id();
try {
auto eval_state = self->evaluate_transaction( trx );
share_type fees = eval_state->get_fees();
_pending_fee_index[ fee_index( fees, trx_id ) ] = eval_state;
_pending_transaction_db.store( trx_id, trx );
}
catch ( const fc::exception& )
{
trx_to_discard.push_back(trx_id);
wlog( "discarding invalid transaction: ${id} => ${trx}",
("id",trx_id)("trx",trx) );
}
++itr;
}
for( auto item : trx_to_discard )
_pending_transaction_db.remove( item );
}// FC_CAPTURE_AND_RETHROW( blk ) }
void chain_database_impl::recursive_mark_as_linked( const std::unordered_set<block_id_type>& ids )
{
std::unordered_set<block_id_type> next_ids = ids;
while( next_ids.size() )
{
std::unordered_set<block_id_type> pending;
for( auto item : next_ids )
{
block_fork_data record = _fork_db.fetch( item );
record.is_linked = true;
pending.insert( record.next_blocks.begin(), record.next_blocks.end() );
//ilog( "store: ${id} => ${data}", ("id",item)("data",record) );
_fork_db.store( item, record );
}
next_ids = pending;
}
}
void chain_database_impl::recursive_mark_as_invalid( const std::unordered_set<block_id_type>& ids )
{
std::unordered_set<block_id_type> next_ids = ids;
while( next_ids.size() )
{
std::unordered_set<block_id_type> pending;
for( auto item : next_ids )
{
block_fork_data record = _fork_db.fetch( item );
record.is_valid = false;
pending.insert( record.next_blocks.begin(), record.next_blocks.end() );
//ilog( "store: ${id} => ${data}", ("id",item)("data",record) );
_fork_db.store( item, record );
}
next_ids = pending;
}
}
/**
* Place the block in the block tree, the block tree contains all blocks
* and tracks whether they are valid, linked, and current.
*
* There are several options for this block:
*
* 1) It extends an existing block
* - a valid chain
* - an invalid chain
* - an unlinked chain
* 2) It is free floating and doesn't link to anything we have
* - create two entries into the database
* - one for this block
* - placeholder for previous
* - mark both as unlinked
* 3) It it provides the missing link between a the genesis block and existing chain
* - all next blocks need to be updated to change state to 'linked'
*/
block_fork_data chain_database_impl::store_and_index( const block_id_type& block_id,
const full_block& block_data )
{ try {
//ilog( "block_number: ${n} id: ${id} prev: ${prev}",
// ("n",block_data.block_num)("id",block_id)("prev",block_data.previous) );
// first of all store this block at the given block number
_block_id_to_block_data_db.store( block_id, block_data );
_block_id_to_block_record_db.store( block_id, block_record( block_data,
block_data.block_size(),
self->get_current_random_seed()) );
// update the parallel block list
vector<block_id_type> parallel_blocks = fetch_blocks_at_number( block_data.block_num );
if (std::find( parallel_blocks.begin(), parallel_blocks.end(), block_id ) == parallel_blocks.end())
{
// don't add the block to the list if it's already there.
// TODO: do we need to execute any of the rest of this function (or, for that matter, its caller) if the block is already there
parallel_blocks.push_back( block_id );
_fork_number_db.store( block_data.block_num, parallel_blocks );
}
// now find how it links in.
block_fork_data prev_fork_data;
auto prev_itr = _fork_db.find( block_data.previous );
if( prev_itr.valid() ) // we already know about its previous
{
ilog( " we already know about its previous: ${p}", ("p",block_data.previous) );
prev_fork_data = prev_itr.value();
prev_fork_data.next_blocks.insert(block_id);
//ilog( " ${id} = ${record}", ("id",prev_itr.key())("record",prev_fork_data) );
_fork_db.store( prev_itr.key(), prev_fork_data );
}
else
{
elog( " we don't know about its previous: ${p}", ("p",block_data.previous) );
// create it... we do not know about the previous block so
// we must create it and assume it is not linked...
prev_fork_data.next_blocks.insert(block_id);
prev_fork_data.is_linked = block_data.previous == block_id_type(); //false;
//ilog( " ${id} = ${record}", ("id",block_data.previous)("record",prev_fork_data) );
_fork_db.store( block_data.previous, prev_fork_data );
}
block_fork_data current_fork;
auto cur_itr = _fork_db.find( block_id );
current_fork.is_known = true;
if( cur_itr.valid() )
{
current_fork = cur_itr.value();
ilog( " current_fork: ${fork}", ("fork",current_fork) );
ilog( " prev_fork: ${prev_fork}", ("prev_fork",prev_fork_data) );
if( !current_fork.is_linked && prev_fork_data.is_linked )
{
// we found the missing link
current_fork.is_linked = true;
recursive_mark_as_linked( current_fork.next_blocks );
}
}
else
{
current_fork.is_linked = prev_fork_data.is_linked;
//ilog( " current_fork: ${id} = ${fork}", ("id",block_id)("fork",current_fork) );
}
_fork_db.store( block_id, current_fork );
return current_fork;
} FC_CAPTURE_AND_RETHROW( (block_id) ) }
void chain_database_impl::mark_invalid( const block_id_type& block_id )
{
// fetch the fork data for block_id, mark it as invalid and
// then mark every item after it as invalid as well.
auto fork_data = _fork_db.fetch( block_id );
fork_data.is_valid = false;
_fork_db.store( block_id, fork_data );
recursive_mark_as_invalid( fork_data.next_blocks );
}
void chain_database_impl::mark_included( const block_id_type& block_id, bool included )
{ try {
//ilog( "included: ${block_id} = ${state}", ("block_id",block_id)("state",included) );
auto fork_data = _fork_db.fetch( block_id );
// if( fork_data.is_included != included )
{
fork_data.is_included = included;
if( included )
{
fork_data.is_valid = true;
}
//ilog( "store: ${id} => ${data}", ("id",block_id)("data",fork_data) );
_fork_db.store( block_id, fork_data );
}
// fetch the fork data for block_id, mark it as included and
} FC_RETHROW_EXCEPTIONS( warn, "", ("block_id",block_id)("included",included) ) }
void chain_database_impl::switch_to_fork( const block_id_type& block_id )
{ try {
ilog( "switch from fork ${id} to ${to_id}", ("id",_head_block_id)("to_id",block_id) );
vector<block_id_type> history = get_fork_history( block_id );
FC_ASSERT( history.size() > 0 );
while( history.back() != _head_block_id )
{
ilog( " pop ${id}", ("id",_head_block_id) );
pop_block();
}
for( int32_t i = history.size()-2; i >= 0 ; --i )
{
ilog( " extend ${i}", ("i",history[i]) );
extend_chain( self->get_block( history[i] ) );
}
} FC_CAPTURE_AND_RETHROW( (block_id) ) }
void chain_database_impl::apply_transactions( uint32_t block_num,
const std::vector<signed_transaction>& user_transactions,
const pending_chain_state_ptr& pending_state )
{
ilog( "apply transactions from block: ${block_num} ${trxs}", ("block_num",block_num)("trxs",user_transactions) );
uint32_t trx_num = 0;
try {
// apply changes from each transaction
for( auto trx : user_transactions )
{
ilog( "applying ${trx}", ("trx",trx) );
transaction_evaluation_state_ptr trx_eval_state =
std::make_shared<transaction_evaluation_state>(pending_state,_chain_id);
trx_eval_state->evaluate( trx );
//ilog( "evaluation: ${e}", ("e",*trx_eval_state) );
// TODO: capture the evaluation state with a callback for wallets...
// summary.transaction_states.emplace_back( std::move(trx_eval_state) );
transaction_location trx_loc( block_num, trx_num );
//ilog( "store trx location: ${loc}", ("loc",trx_loc) );
pending_state->store_transaction( trx.id(), transaction_record( trx_loc, *trx_eval_state) );
++trx_num;
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("trx_num",trx_num) ) }
void chain_database_impl::pay_delegate( fc::time_point_sec time_slot,
share_type amount,
const pending_chain_state_ptr& pending_state )
{ try {
auto delegate_record = pending_state->get_account_record( self->get_signing_delegate_id( time_slot ) );
FC_ASSERT( delegate_record.valid() );
FC_ASSERT( delegate_record->is_delegate() );
auto pay_rate = delegate_record->delegate_info->delegate_production_fee;
FC_ASSERT( pay_rate <= 100 );
auto pay = (amount*pay_rate)/100;
delegate_record->delegate_info->pay_balance += pay;
delegate_record->delegate_info->votes_for += pay;
pending_state->store_account_record( *delegate_record );
auto base_asset_record = pending_state->get_asset_record( asset_id_type(0) );
FC_ASSERT( base_asset_record.valid() );
base_asset_record->current_share_supply += pay;
pending_state->store_asset_record( *base_asset_record );
} FC_RETHROW_EXCEPTIONS( warn, "", ("time_slot",time_slot)("amount",amount) ) }
void chain_database_impl::save_undo_state( const block_id_type& block_id,
const pending_chain_state_ptr& pending_state )
{ try {
pending_chain_state_ptr undo_state = std::make_shared<pending_chain_state>(nullptr);
pending_state->get_undo_state( undo_state );
_undo_state_db.store( block_id, *undo_state );
} FC_RETHROW_EXCEPTIONS( warn, "", ("block_id",block_id) ) }
void chain_database_impl::verify_header( const full_block& block_data )
{ try {
// validate preliminaries:
if( block_data.block_num != _head_block_header.block_num + 1 )
FC_CAPTURE_AND_THROW( block_numbers_not_sequential, (block_data)(_head_block_header) );
if( block_data.previous != _head_block_id )
FC_CAPTURE_AND_THROW( invalid_previous_block_id, (block_data)(_head_block_id) );
if( block_data.timestamp.sec_since_epoch() % BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC != 0 )
FC_CAPTURE_AND_THROW( invalid_block_time );
if( block_data.timestamp <= _head_block_header.timestamp )
FC_CAPTURE_AND_THROW( time_in_past, (block_data.timestamp)(_head_block_header.timestamp) );
fc::time_point_sec now = bts::blockchain::now();
auto delta_seconds = (block_data.timestamp - now).to_seconds();
if( block_data.timestamp > (now + BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC*2) )
FC_CAPTURE_AND_THROW( time_in_future, (block_data.timestamp)(now)(delta_seconds) );
size_t block_size = block_data.block_size();
auto expected_next_fee = block_data.next_fee( self->get_fee_rate(), block_size );
if( block_data.fee_rate != expected_next_fee )
FC_CAPTURE_AND_THROW( invalid_fee_rate, (block_data.fee_rate)(expected_next_fee) );
digest_block digest_data(block_data);
if( NOT digest_data.validate_digest() )
FC_CAPTURE_AND_THROW( invalid_block_digest );
FC_ASSERT( digest_data.validate_unique() );
// signing delegate id:
auto expected_delegate_id = self->get_signing_delegate_id( block_data.timestamp );
if( NOT block_data.validate_signee( self->get_signing_delegate_key(block_data.timestamp) ) )
FC_CAPTURE_AND_THROW( invalid_delegate_signee, (expected_delegate_id) );
} FC_CAPTURE_AND_RETHROW( (block_data) ) }
void chain_database_impl::update_head_block( const full_block& block_data )
{
_head_block_header = block_data;
_head_block_id = block_data.id();
_block_id_to_block_record_db.store( block_data.id(), block_record( block_data,
block_data.block_size(),
self->get_current_random_seed()) );
}
/**
* A block should be produced every BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC. If we do not have
* a block for any multiple of this interval between block_data and the current head block then
* we need to lookup the delegates that should have produced a block at that interval and then
* increment their missed block count.
*
* Then we need to increment the produced_block count for the delegate that produced block_data.
*
* Note that the header of block_data has already been verified by the caller and that updates
* are applied to pending_state.
*/
void chain_database_impl::update_delegate_production_info( const full_block& produced_block,
const pending_chain_state_ptr& pending_state )
{
auto now = bts::blockchain::now();
/* Validate secret */
{
auto delegate_id = self->get_signing_delegate_id( produced_block.timestamp );
auto delegate_rec = pending_state->get_account_record( delegate_id );
if( delegate_rec->delegate_info->blocks_produced > 0 )
{
auto hash_of_previous_secret = fc::ripemd160::hash(produced_block.previous_secret);
FC_ASSERT( hash_of_previous_secret == delegate_rec->delegate_info->next_secret_hash,
"",
("previous_secret",produced_block.previous_secret)
("hash_of_previous_secret",hash_of_previous_secret)
("delegate",*delegate_rec) );
}
delegate_rec->delegate_info->next_secret_hash = produced_block.next_secret_hash;
delegate_rec->delegate_info->last_block_num_produced = produced_block.block_num;
pending_state->store_account_record( *delegate_rec );
}
auto current_block_num = _head_block_header.block_num;
auto current_block_timestamp = _head_block_header.timestamp;
/* Handle genesis block timestamp */
if( _head_block_header.block_num == 0 )
{
current_block_timestamp = produced_block.timestamp;
current_block_timestamp -= BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC;
}
int64_t required_confirmations = pending_state->get_property( confirmation_requirement ).as_int64();
do
{
++current_block_num;
current_block_timestamp += BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC;
auto delegate_id = self->get_signing_delegate_id( current_block_timestamp );
auto delegate_rec = pending_state->get_account_record( delegate_id );
/* For storing in _delegate_block_stats_db */
delegate_block_stats block_stats;
if( current_block_timestamp != produced_block.timestamp )
{
delegate_rec->delegate_info->blocks_missed += 1;
required_confirmations += 2;
block_stats.missed = true;
}
else
{
delegate_rec->delegate_info->blocks_produced += 1;
block_stats.missed = false;
/* TODO: Use actual block received time rather than time this function was called */
int64_t latency = (now - produced_block.timestamp).to_seconds();
if( latency < BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC )
block_stats.latency = (uint32_t)latency;
}
// TODO: all updates should be to pending_state and not the database directly...
// This can result in inconsistencies when dealing with forks.
_delegate_block_stats_db.store( std::make_pair( delegate_id, current_block_num ), block_stats );
pending_state->store_account_record( *delegate_rec );
}
while( current_block_timestamp < produced_block.timestamp );
required_confirmations -= 1;
if( required_confirmations < 1 )
required_confirmations = 1;
if( required_confirmations > BTS_BLOCKCHAIN_NUM_DELEGATES*3 )
required_confirmations = 3*BTS_BLOCKCHAIN_NUM_DELEGATES;
pending_state->set_property( confirmation_requirement, required_confirmations );
}
void chain_database_impl::update_random_seed( secret_hash_type new_secret,
const pending_chain_state_ptr& pending_state )
{
auto current_seed = pending_state->get_current_random_seed();
fc::sha512::encoder enc;
fc::raw::pack( enc, new_secret );
fc::raw::pack( enc, current_seed );
pending_state->set_property( last_random_seed_id,
fc::variant(fc::ripemd160::hash( enc.result() )) );
}
void chain_database_impl::update_active_delegate_list( const full_block& block_data,
const pending_chain_state_ptr& pending_state )
{
if( block_data.block_num % BTS_BLOCKCHAIN_NUM_DELEGATES == 0 )
{
// perform a random shuffle of the sorted delegate list.
auto active_del = self->next_round_active_delegates();
auto rand_seed = fc::sha256::hash(self->get_current_random_seed());
size_t num_del = active_del.size();
for( uint32_t i = 0; i < num_del; ++i )
{
for( uint32_t x = 0; x < 4 && i < num_del; ++x, ++i )
std::swap( active_del[i], active_del[rand_seed._hash[x]%num_del] );
rand_seed = fc::sha256::hash(rand_seed);
}
pending_state->set_property( chain_property_enum::active_delegate_list_id, fc::variant(active_del) );
}
}
/**
* Performs all of the block validation steps and throws if error.
*/
void chain_database_impl::extend_chain( const full_block& block_data )
{ try {
auto block_id = block_data.id();
block_summary summary;
try {
verify_header( block_data );
summary.block_data = block_data;
/* Create a pending state to track changes that would apply as we evaluate the block */
pending_chain_state_ptr pending_state = std::make_shared<pending_chain_state>(self->shared_from_this());
summary.applied_changes = pending_state;
/** Increment the blocks produced or missed for all delegates. This must be done
* before applying transactions because it depends upon the current order.
**/
update_delegate_production_info( block_data, pending_state );
// apply any deterministic operations such as market operations before we preterb indexes
//apply_deterministic_updates(pending_state);
//ilog( "block data: ${block_data}", ("block_data",block_data) );
ilog( "apply transactions " );
apply_transactions( block_data.block_num, block_data.user_transactions, pending_state );
ilog( "pay delegate" );
pay_delegate( block_data.timestamp, block_data.delegate_pay_rate, pending_state );
update_active_delegate_list(block_data, pending_state);
update_random_seed( block_data.previous_secret, pending_state );
save_undo_state( block_id, pending_state );
// TODO: verify that apply changes can be called any number of
// times without changing the database other than the first
// attempt.
// ilog( "apply changes\n${s}", ("s",fc::json::to_pretty_string( *pending_state) ) );
ilog( "apply changes" );
pending_state->apply_changes();
mark_included( block_id, true );
update_head_block( block_data );
clear_pending( block_data );
_block_num_to_id_db.store( block_data.block_num, block_id );
// self->sanity_check();
}
catch ( const fc::exception& e )
{
wlog( "error applying block: ${e}", ("e",e.to_detail_string() ));
mark_invalid( block_id );
throw;
}
// just in case something changes while calling observer
auto tmp = _observers;
for( auto o : tmp )
{
try {
o->block_applied( summary );
} catch ( const fc::exception& e )
{
wlog( "${e}", ("e",e.to_detail_string() ) );
}
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("block",block_data) ) }
/**
* Traverse the previous links of all blocks in fork until we find one that is_included
*
* The last item in the result will be the only block id that is already included in
* the blockchain.
*/
std::vector<block_id_type> chain_database_impl::get_fork_history( const block_id_type& id )
{ try {
ilog( "" );
std::vector<block_id_type> history;
history.push_back( id );
block_id_type next_id = id;
while( true )
{
auto header = self->get_block_header( next_id );
//ilog( "header: ${h}", ("h",header) );
history.push_back( header.previous );
if( header.previous == block_id_type() )
{
ilog( "return: ${h}", ("h",history) );
return history;
}
auto prev_fork_data = _fork_db.fetch( header.previous );
/// this shouldn't happen if the database invariants are properly maintained
FC_ASSERT( prev_fork_data.is_linked, "we hit a dead end, this fork isn't really linked!" );
if( prev_fork_data.is_included )
{
ilog( "return: ${h}", ("h",history) );
return history;
}
next_id = header.previous;
}
ilog( "${h}", ("h",history) );
return history;
} FC_RETHROW_EXCEPTIONS( warn, "", ("block_id",id) ) }
void chain_database_impl::pop_block()
{ try {
FC_ASSERT( _head_block_header.block_num > 0 );
// update the is_included flag on the fork data
mark_included( _head_block_id, false );
// update the block_num_to_block_id index
_block_num_to_id_db.remove( _head_block_header.block_num );
auto previous_block_id = _head_block_header.previous;
bts::blockchain::pending_chain_state_ptr undo_state = std::make_shared<bts::blockchain::pending_chain_state>(_undo_state_db.fetch( _head_block_id ));
undo_state->set_prev_state( self->shared_from_this() );
undo_state->apply_changes();
_head_block_id = previous_block_id;
_head_block_header = self->get_block_header( _head_block_id );
auto tmp = _observers;
for( auto o : tmp ) o->state_changed( undo_state );
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
} // namespace detail
chain_database::chain_database()
:my( new detail::chain_database_impl() )
{
my->self = this;
}
chain_database::~chain_database()
{
try {
close();
}
catch ( const fc::exception& e )
{
wlog( "unexpected exception closing database\n ${e}", ("e",e.to_detail_string() ) );
}
catch ( ... )
{
wlog( "unexpected exception closing database\n" );
}
}
std::vector<account_id_type> chain_database::next_round_active_delegates()const
{
return get_delegates_by_vote( 0, BTS_BLOCKCHAIN_NUM_DELEGATES );
}
vector<account_id_type> chain_database::current_round_active_delegates()const
{
return get_property( chain_property_enum::active_delegate_list_id ).as<vector<account_id_type>>();
}
/**
* @return the top BTS_BLOCKCHAIN_NUM_DELEGATES by vote
*/
std::vector<account_id_type> chain_database::get_delegates_by_vote(uint32_t first, uint32_t count )const
{ try {
auto del_vote_itr = my->_delegate_vote_index_db.begin();
std::vector<account_id_type> sorted_delegates;
uint32_t pos = 0;
while( sorted_delegates.size() < count && del_vote_itr.valid() )
{
if( pos >= first )
sorted_delegates.push_back( del_vote_itr.key().delegate_id );
++pos;
++del_vote_itr;
}
return sorted_delegates;
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
/**
* @return the top BTS_BLOCKCHAIN_NUM_DELEGATES by vote
*/
std::vector<account_record> chain_database::get_delegate_records_by_vote(uint32_t first, uint32_t count )const
{ try {
auto del_vote_itr = my->_delegate_vote_index_db.begin();
std::vector<account_record> sorted_delegates;
uint32_t pos = 0;
while( sorted_delegates.size() < count && del_vote_itr.valid() )
{
if( pos >= first )
sorted_delegates.push_back( *get_account_record(del_vote_itr.value()) );
++pos;
++del_vote_itr;
}
return sorted_delegates;
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
void chain_database::open( const fc::path& data_dir, fc::optional<fc::path> genesis_file )
{ try {
wlog( "....." );
bool is_new_data_dir = !fc::exists( data_dir );
try
{
fc::create_directories( data_dir );
my->open_database( data_dir );
// TODO: check to see if we crashed during the last write
// if so, then apply the last undo operation stored.
uint32_t last_block_num = -1;
block_id_type last_block_id;
my->_block_num_to_id_db.last( last_block_num, last_block_id );
if( last_block_num != uint32_t(-1) )
{
my->_head_block_header = get_block_digest( last_block_id );
my->_head_block_id = last_block_id;
}
if( last_block_num == uint32_t(-1) )
{
close();
fc::remove_all( data_dir );
fc::create_directories( data_dir );
my->open_database( data_dir );
my->initialize_genesis(genesis_file);
}
my->_chain_id = get_property( bts::blockchain::chain_id ).as<digest_type>();
// process the pending transactions to cache by fees
auto pending_itr = my->_pending_transaction_db.begin();
wlog( "loading pending trx..." );
while( pending_itr.valid() )
{
try {
auto trx = pending_itr.value();
wlog( " laoding pending transaction ${trx}", ("trx",trx) );
auto trx_id = trx.id();
auto eval_state = evaluate_transaction( trx );
share_type fees = eval_state->get_fees();
my->_pending_fee_index[ fee_index( fees, trx_id ) ] = eval_state;
my->_pending_transaction_db.store( trx_id, trx );
}
catch ( const fc::exception& e )
{
wlog( "error processing pending transaction: ${e}", ("e",e.to_detail_string() ) );
}
++pending_itr;
}
}
catch( ... )
{
elog( "error opening database" );
close();
if( is_new_data_dir ) fc::remove_all( data_dir );
throw;
}
} FC_RETHROW_EXCEPTIONS( warn, "", ("data_dir",data_dir) ) }
void chain_database::close()
{ try {
my->_fork_number_db.close();
my->_fork_db.close();
my->_slate_db.close();
my->_property_db.close();
my->_proposal_db.close();
my->_proposal_vote_db.close();
my->_undo_state_db.close();
my->_block_num_to_id_db.close();
my->_block_id_to_block_record_db.close();
my->_block_id_to_block_data_db.close();
my->_id_to_transaction_record_db.close();
my->_pending_transaction_db.close();
my->_asset_db.close();
my->_balance_db.close();
my->_account_db.close();
my->_address_to_account_db.close();
my->_account_index_db.close();
my->_symbol_index_db.close();
my->_delegate_vote_index_db.close();
my->_delegate_block_stats_db.close();
my->_ask_db.close();
my->_bid_db.close();
my->_short_db.close();
my->_collateral_db.close();
// my->_processed_transaction_id_db.close();
} FC_RETHROW_EXCEPTIONS( warn, "" ) }
account_id_type chain_database::get_signing_delegate_id( const fc::time_point_sec& block_timestamp,
const std::vector<account_id_type>& sorted_delegates )const
{ try {
uint64_t interval_number = block_timestamp.sec_since_epoch() / BTS_BLOCKCHAIN_BLOCK_INTERVAL_SEC;
uint32_t delegate_pos = (uint32_t)(interval_number % BTS_BLOCKCHAIN_NUM_DELEGATES);
FC_ASSERT( delegate_pos < sorted_delegates.size() );
return sorted_delegates[delegate_pos];
} FC_RETHROW_EXCEPTIONS( warn, "", ("block_timestamp",block_timestamp) ) }
public_key_type chain_database::get_signing_delegate_key( const fc::time_point_sec& block_timestamp,
const std::vector<account_id_type>& sorted_delegates )const
{ try {
auto delegate_record = get_account_record( get_signing_delegate_id( block_timestamp, sorted_delegates ) );
FC_ASSERT( delegate_record.valid() );
return delegate_record->active_key();