-
Notifications
You must be signed in to change notification settings - Fork 63
/
blockchain_storage.cpp
3089 lines (2804 loc) · 123 KB
/
blockchain_storage.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
// Copyright (c) 2012-2013 The Cryptonote developers
// Copyright (c) 2012-2013 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <algorithm>
#include <cstdio>
#include <algorithm>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "include_base_utils.h"
#include "common/db_backend_lmdb.h"
#include "currency_basic_impl.h"
#include "blockchain_storage.h"
#include "currency_format_utils.h"
#include "currency_boost_serialization.h"
#include "blockchain_storage_boost_serialization.h"
#include "currency_config.h"
#include "miner.h"
#include "misc_language.h"
#include "profile_tools.h"
#include "file_io_utils.h"
#include "common/boost_serialization_helper.h"
#include "common/command_line.h"
#include "warnings.h"
#include "crypto/hash.h"
#include "miner_common.h"
#include "version.h"
using namespace std;
using namespace epee;
using namespace currency;
#define BLOCKCHAIN_CONTAINER_SPENT_KEYS "spent_keys"
#define BLOCKCHAIN_CONTAINER_BLOCKS "blocks"
#define BLOCKCHAIN_CONTAINER_OUTPUTS "outputs"
#define BLOCKCHAIN_CONTAINER_MULTISIG_OUTS "multisig_outs"
#define BLOCKCHAIN_CONTAINER_INVALID_BLOCKS "invalid_blocks"
#define BLOCKCHAIN_CONTAINER_TRANSACTIONS "transactions"
#define BLOCKCHAIN_CONTAINER_SOLO_OPTIONS "solo"
#define BLOCKCHAIN_CONTAINER_ALIASES "aliases"
#define BLOCKCHAIN_CONTAINER_ADDR_TO_ALIAS "addr_to_alias"
#define BLOCKCHAIN_CONTAINER_SCRATCHPAD "scratchpad"
#define BLOCKCHAIN_CONTAINER_BLOCKS_INDEX "blocks_index"
#define BLOCKCHAIN_OPTIONS_ID_CURRENT_BLOCK_CUMUL_SZ_LIMIT 0
#define BLOCKCHAIN_OPTIONS_ID_CURRENT_PRUNED_RS_HEIGHT 1
#define BLOCKCHAIN_OPTIONS_ID_LAST_WORKED_VERSION 2
#define BLOCKCHAIN_OPTIONS_ID_STORAGE_MAJOR_COMPABILITY_VERSION 3 //mismatch here means full resync
#define BLOCKCHAIN_STORAGE_MAJOR_COMPABILITY_VERSION 1
DISABLE_VS_WARNINGS(4267)
namespace
{
const command_line::arg_descriptor<std::string> arg_macos_debuger_dummy_option = {"-NSDocumentRevisionsDebugMode", "XCode weird paramter", "", true};
}
//------------------------------------------------------------------
blockchain_storage::blockchain_storage(tx_memory_pool& tx_pool) :m_db(std::shared_ptr<tools::db::i_db_backend>(new tools::db::lmdb_db_backend), m_stub_lock),
m_db_blocks(m_db),
m_db_blocks_index(m_db),
m_db_transactions(m_db),
m_db_spent_keys(m_db),
m_db_outputs(m_db),
m_db_solo_options(m_db),
m_db_aliases(m_db),
m_db_addr_to_alias(m_db),
m_db_scratchpad_internal(m_db),
m_scratchpad_wr(m_db_scratchpad_internal),
m_db_current_block_cumul_sz_limit(BLOCKCHAIN_OPTIONS_ID_CURRENT_BLOCK_CUMUL_SZ_LIMIT, m_db_solo_options),
m_db_current_pruned_rs_height(BLOCKCHAIN_OPTIONS_ID_CURRENT_PRUNED_RS_HEIGHT, m_db_solo_options),
m_db_last_worked_version(BLOCKCHAIN_OPTIONS_ID_LAST_WORKED_VERSION, m_db_solo_options),
m_db_storage_major_compability_version(BLOCKCHAIN_OPTIONS_ID_STORAGE_MAJOR_COMPABILITY_VERSION, m_db_solo_options),
m_tx_pool(tx_pool),
m_is_in_checkpoint_zone(false),
m_donations_account(AUTO_VAL_INIT(m_donations_account)),
m_royalty_account(AUTO_VAL_INIT(m_royalty_account)),
m_locker_file(0),
m_exclusive_batch_active(false),
m_last_median_ts_checked_top_block_id(null_hash),
m_last_median_ts_checked(0)
{
bool r = get_donation_accounts(m_donations_account, m_royalty_account);
CHECK_AND_ASSERT_THROW_MES(r, "failed to load donation accounts");
}
//------------------------------------------------------------------
void blockchain_storage::init_options(boost::program_options::options_description& desc)
{
command_line::add_arg(desc, arg_macos_debuger_dummy_option);
//db::lmdb_adapter::init_options(desc);
}
//------------------------------------------------------
bool blockchain_storage::init(const boost::program_options::variables_map& vm, const std::string& config_folder)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
//bool res = m_lmdb_adapter->init(vm);
//CHECK_AND_ASSERT_MES(res, false, "Unable to init lmdb adapter");
m_config_folder = config_folder;
// remove old incompatible DB
const std::string old_db_folder_path = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FOLDERNAME_OLD;
if (boost::filesystem::exists(old_db_folder_path))
{
LOG_PRINT_YELLOW("Removing old DB in " << old_db_folder_path << "...", LOG_LEVEL_0);
boost::filesystem::remove_all(old_db_folder_path);
}
LOG_PRINT_L0("Loading blockchain...");
const std::string folder_name = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FOLDERNAME;
tools::create_directories_if_necessary(folder_name);
if (!check_instance(m_config_folder))
return false;
bool res = m_db.open(folder_name);
CHECK_AND_ASSERT_MES(res, false, "Failed to initialize database in folder: " << folder_name);
res = m_db_blocks.init(BLOCKCHAIN_CONTAINER_BLOCKS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_blocks_index.init(BLOCKCHAIN_CONTAINER_BLOCKS_INDEX);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_transactions.init(BLOCKCHAIN_CONTAINER_TRANSACTIONS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_spent_keys.init(BLOCKCHAIN_CONTAINER_SPENT_KEYS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_outputs.init(BLOCKCHAIN_CONTAINER_OUTPUTS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_solo_options.init(BLOCKCHAIN_CONTAINER_SOLO_OPTIONS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_aliases.init(BLOCKCHAIN_CONTAINER_ALIASES);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_addr_to_alias.init(BLOCKCHAIN_CONTAINER_ADDR_TO_ALIAS);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_db_scratchpad_internal.init(BLOCKCHAIN_CONTAINER_SCRATCHPAD);
CHECK_AND_ASSERT_MES(res, false, "Unable to init db container");
res = m_scratchpad_wr.init(config_folder);
CHECK_AND_ASSERT_MES(res, false, "Unable to init scratchpad wrapper");
bool need_reinit = false;
if (!m_db_blocks.size())
need_reinit = true;
else if (m_db_storage_major_compability_version != BLOCKCHAIN_STORAGE_MAJOR_COMPABILITY_VERSION)
need_reinit = true;
if (need_reinit)
{
clear();
block bl = boost::value_initialized<block>();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
generate_genesis_block(bl);
add_new_block(bl, bvc);
CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain");
LOG_PRINT_MAGENTA("Storage initialized with genesis", LOG_LEVEL_0);
}
initialize_db_solo_options_values();
//print information message
uint64_t timestamp_diff = time(nullptr) - m_db_blocks.back()->bl.timestamp;
if (!m_db_blocks.back()->bl.timestamp)
timestamp_diff = time(nullptr) - 1341378000;
LOG_PRINT_GREEN("Blockchain initialized. last block: " << m_db_blocks.size() - 1
<< ", " << misc_utils::get_time_interval_string(timestamp_diff) << " time ago", LOG_LEVEL_0);
return true;
}
//------------------------------------------------------
bool blockchain_storage::deinit()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_scratchpad_wr.deinit();
m_db.close();
tools::unlock_and_close_file(m_locker_file);
return true;
}
//------------------------------------------------------
bool blockchain_storage::start_batch_exclusive_operation()
{
CRITICAL_REGION_BEGIN(m_exclusive_batch_lock);
m_exclusive_batch_active = true;
CRITICAL_REGION_END();
CRITICAL_SECTION_LOCK(m_blockchain_lock);
//m_db.begin_batch_exclusive_operation();
LOG_PRINT_MAGENTA("[START_BATCH_EXCLUSIVE_OPERATION]", LOG_LEVEL_0);
return true;
}
//------------------------------------------------------
bool blockchain_storage::finish_batch_exclusive_operation(bool success)
{
//m_db.finish_batch_exclusive_operation(success);
CRITICAL_SECTION_UNLOCK(m_blockchain_lock);
CRITICAL_REGION_BEGIN(m_exclusive_batch_lock);
m_exclusive_batch_active = false;
CRITICAL_REGION_END();
LOG_PRINT_MAGENTA("[FINISH_BATCH_EXCLUSIVE_OPERATION]", LOG_LEVEL_0);
return true;
}
//------------------------------------------------------
bool blockchain_storage::set_checkpoints(checkpoints&& chk_pts)
{
m_checkpoints = chk_pts;
try
{
m_db.begin_transaction();
prune_ring_signatures_if_need();
m_db.commit_transaction();
if (!m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height()))
{
m_is_in_checkpoint_zone = false;
}
else
{
m_is_in_checkpoint_zone = true;
}
return true;
}
catch (const std::exception& ex)
{
m_db.abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK: " << ex.what());
return false;
}
catch (...)
{
m_db.abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK.");
return false;
}
}
//------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (start_offset >= m_db_blocks.size())
return false;
for (size_t i = start_offset; i < start_offset + count && i < m_db_blocks.size(); i++)
blocks.push_back(m_db_blocks[i]->bl);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks, std::list<transaction>& txs)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (start_offset >= m_db_blocks.size())
return false;
for (size_t i = start_offset; i < start_offset + count && i < m_db_blocks.size(); i++)
{
blocks.push_back(m_db_blocks[i]->bl);
std::list<crypto::hash> missed_ids;
get_transactions(m_db_blocks[i]->bl.tx_hashes, txs, missed_ids);
CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "have missed transactions in own block in main blockchain");
}
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_alternative_blocks(std::list<block>& blocks)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(const auto& alt_bl, m_alternative_chains)
{
blocks.push_back(alt_bl.second.bl);
}
return true;
}
//------------------------------------------------------
size_t blockchain_storage::get_alternative_blocks_count()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_alternative_chains.size();
}
//------------------------------------------------------
crypto::hash blockchain_storage::get_block_id_by_height(uint64_t height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (height >= m_db_blocks.size())
return null_hash;
return get_block_hash(m_db_blocks[height]->bl);
}
//------------------------------------------------------
bool blockchain_storage::get_block_by_hash(const crypto::hash &h, block &blk) {
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// try to find block in main chain
auto it = m_db_blocks_index.find(h);
if (m_db_blocks_index.end() != it)
{
blk = m_db_blocks[*it]->bl;
return true;
}
// try to find block in alternative chain
blocks_ext_by_hash::const_iterator it_alt = m_alternative_chains.find(h);
if (m_alternative_chains.end() != it_alt)
{
blk = it_alt->second.bl;
return true;
}
return false;
}
//------------------------------------------------------
bool blockchain_storage::get_block_by_height(uint64_t h, block &blk)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (h >= m_db_blocks.size())
return false;
blk = m_db_blocks[h]->bl;
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_block_swap_transactions(uint64_t height, const crypto::secret_key& sk, std::string& block_id, std::string& prev_block_id, uint64_t& timestamp, std::list<swap_transaction_info>& swap_txs_list)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// try to find block in main chain
if (height >= m_db_blocks.size())
{
return false;
}
auto b_ptr = m_db_blocks[height];
block_id = string_tools::pod_to_hex(get_block_hash(b_ptr->bl));
prev_block_id = string_tools::pod_to_hex(b_ptr->bl.prev_id);
timestamp = b_ptr->bl.timestamp;
for (auto& tx_id : b_ptr->bl.tx_hashes)
{
swap_transaction_info si = AUTO_VAL_INIT(si);
auto tx_ptr = get_tx(tx_id);
CHECK_AND_ASSERT_MES(tx_ptr.get(), false, "Failed to get tx with id " << tx_id << " from block " << block_id);
if (!get_swap_info_from_tx(*tx_ptr, sk, si))
continue;
swap_txs_list.push_back(si);
}
return true;
}
//------------------------------------------------------
bool blockchain_storage::have_tx(const crypto::hash &id)
{
PROFILE_FUNC("blockchain_storage::have_tx");
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db_transactions.find(id) != m_db_transactions.end();
}
//------------------------------------------------------
bool blockchain_storage::have_tx_keyimges_as_spent(const transaction &tx)
{
BOOST_FOREACH(const txin_v& in, tx.vin)
{
CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true);
if (have_tx_keyimg_as_spent(in_to_key.k_image))
return true;
}
return false;
}
//------------------------------------------------------
bool blockchain_storage::have_tx_keyimg_as_spent(const crypto::key_image &key_im)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db_spent_keys.find(key_im) != m_db_spent_keys.end();
}
//------------------------------------------------------
std::shared_ptr<transaction> blockchain_storage::get_tx(const crypto::hash &id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_db_transactions.find(id);
if (it == m_db_transactions.end())
return std::shared_ptr<transaction>(nullptr);
return std::make_shared<transaction>(it->tx);
}
//------------------------------------------------------
uint64_t blockchain_storage::get_current_blockchain_height()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db_blocks.size();
}
//------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
crypto::hash id = null_hash;
if (m_db_blocks.size())
{
get_block_hash(m_db_blocks.back()->bl, id);
}
return id;
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id(uint64_t& height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
height = get_current_blockchain_height() - 1;
return get_top_block_id();
}
//------------------------------------------------------
bool blockchain_storage::get_top_block(block& b)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(m_db_blocks.size(), false, "Wrong blockchain state, m_blocks.size()=0!");
auto val_ptr = m_db_blocks.back();
CHECK_AND_ASSERT_MES(val_ptr.get(), false, "m_blocks.back() returned null");
b = val_ptr->bl;
return true;
}
//------------------------------------------------------
wide_difficulty_type blockchain_storage::get_difficulty_for_next_block()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
size_t offset = m_db_blocks.size() - std::min<uint64_t>(m_db_blocks.size(), static_cast<uint64_t>(DIFFICULTY_BLOCKS_COUNT));
if (!offset)
++offset;//skip genesis block
for (; offset < m_db_blocks.size(); offset++)
{
timestamps.push_back(m_db_blocks[offset]->bl.timestamp);
commulative_difficulties.push_back(m_db_blocks[offset]->cumulative_difficulty);
}
return next_difficulty(timestamps, commulative_difficulties);
}
//------------------------------------------------------
bool blockchain_storage::add_new_block(const block& bl_, block_verification_context& bvc)
{
PROFILE_FUNC("blockchain_storage::add_new_block");
try
{
block bl = bl_;
crypto::hash id = get_block_hash(bl);
CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process
CRITICAL_REGION_LOCAL1(m_blockchain_lock);
PROF_L2_START(time_have_block_check);
if (have_block(id))
{
LOG_PRINT_L3("block with id = " << id << " already exists");
bvc.m_already_exists = true;
return false;
}
PROF_L2_FINISH(time_have_block_check);
//check that block refers to chain tail
PROF_L2_START(time_handle_alt);
if (!(bl.prev_id == get_top_block_id()))
{
//chain switching or wrong block
bvc.m_added_to_main_chain = false;
m_db.begin_transaction();
bool r = handle_alternative_block(bl, id, bvc);
m_db.commit_transaction();
return r;
//never relay alternative blocks
}
PROF_L2_FINISH(time_handle_alt);
PROF_L2_START(time_handle_main);
PROF_L2_START(time_handle_main_1);
m_db.begin_transaction();
PROF_L2_FINISH(time_handle_main_1);
PROF_L2_START(time_handle_main_2);
bool res = handle_block_to_main_chain(bl, id, bvc);
PROF_L2_FINISH(time_handle_main_2);
PROF_L2_START(time_handle_main_3);
m_db.commit_transaction();
PROF_L2_FINISH(time_handle_main_3);
PROF_L2_FINISH(time_handle_main);
#if PROFILING_LEVEL >= 2
LOG_PRINT_L2("bcs::add_new_block timings (ms) have block: " << print_mcsec_as_ms(time_have_block_check) << ", handle alt: " << print_mcsec_as_ms(time_handle_alt) <<
", handle main: " << print_mcsec_as_ms(time_handle_main) << "(" << print_mcsec_as_ms(time_handle_main_1) << "+" << print_mcsec_as_ms(time_handle_main_2) << "+" << print_mcsec_as_ms(time_handle_main_3) << ")");
#endif
return res;
}
catch (const std::exception& ex)
{
bvc.m_verifivation_failed = true;
bvc.m_added_to_main_chain = false;
m_db.abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK: " << ex.what());
return false;
}
catch (...)
{
bvc.m_verifivation_failed = true;
bvc.m_added_to_main_chain = false;
m_db.abort_transaction();
LOG_ERROR("UNKNOWN EXCEPTION WHILE ADDINIG NEW BLOCK.");
return false;
}
}
//------------------------------------------------------
bool blockchain_storage::reset_and_set_genesis_block(const block& b)
{
clear();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
add_new_block(b, bvc);
if (!bvc.m_added_to_main_chain || bvc.m_verifivation_failed)
{
LOG_ERROR("Blockchain reset failed.")
return false;
}
LOG_PRINT_GREEN("Blockchain reset. Genesis block: " << get_block_hash(b) << ", " << misc_utils::get_time_interval_string(time(nullptr) - b.timestamp) << " ago", LOG_LEVEL_0);
return true;
}
//------------------------------------------------------
bool blockchain_storage::create_block_template(block& b, const account_public_address& miner_address, wide_difficulty_type& diffic, uint64_t& height, const blobdata& ex_nonce, bool vote_for_donation, const alias_info& ai)
{
size_t median_size;
uint64_t already_generated_coins;
uint64_t already_donated_coins;
uint64_t donation_amount_for_this_block = 0;
CRITICAL_REGION_BEGIN(m_blockchain_lock);
b.major_version = CURRENT_BLOCK_MAJOR_VERSION;
b.minor_version = CURRENT_BLOCK_MINOR_VERSION;
b.prev_id = get_top_block_id();
b.timestamp = time(NULL);
b.flags = 0;
if (!vote_for_donation)
b.flags = BLOCK_FLAGS_SUPPRESS_DONATION;
height = m_db_blocks.size();
diffic = get_difficulty_for_next_block();
if (!(height%CURRENCY_DONATIONS_INTERVAL))
get_required_donations_value_for_next_block(donation_amount_for_this_block);
CHECK_AND_ASSERT_MES(diffic, false, "difficulty owverhead.");
median_size = m_db_current_block_cumul_sz_limit / 2;
already_generated_coins = m_db_blocks.back()->already_generated_coins;
already_donated_coins = m_db_blocks.back()->already_donated_coins;
CRITICAL_REGION_END();
size_t txs_size;
uint64_t fee;
if (!m_tx_pool.fill_block_template(b, median_size, already_generated_coins, already_donated_coins, txs_size, fee)) {
return false;
}
/*
two-phase miner transaction generation: we don't know exact block size until we prepare block, but we don't know reward until we know
block size, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block size
*/
//make blocks coin-base tx looks close to real coinbase tx to get truthful blob size
bool r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins,
txs_size,
fee,
miner_address,
m_donations_account.m_account_address,
m_royalty_account.m_account_address,
b.miner_tx, ex_nonce,
11, donation_amount_for_this_block, ai);
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance");
#ifdef _DEBUG
std::list<size_t> try_val;
try_val.push_back(get_object_blobsize(b.miner_tx));
#endif
size_t cumulative_size = txs_size + get_object_blobsize(b.miner_tx);
for (size_t try_count = 0; try_count != 10; ++try_count) {
r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins,
cumulative_size,
fee,
miner_address,
m_donations_account.m_account_address,
m_royalty_account.m_account_address,
b.miner_tx, ex_nonce,
11,
donation_amount_for_this_block, ai);
#ifdef _DEBUG
try_val.push_back(get_object_blobsize(b.miner_tx));
#endif
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, second chance");
size_t coinbase_blob_size = get_object_blobsize(b.miner_tx);
if (coinbase_blob_size > cumulative_size - txs_size) {
cumulative_size = txs_size + coinbase_blob_size;
continue;
}
if (coinbase_blob_size < cumulative_size - txs_size) {
size_t delta = cumulative_size - txs_size - coinbase_blob_size;
b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0);
//here could be 1 byte difference, because of extra field counter is varint, and it can become from 1-byte len to 2-bytes len.
if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) {
CHECK_AND_ASSERT_MES(cumulative_size + 1 == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " + 1 is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx));
b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1);
if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) {
//fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_size
LOG_PRINT_RED("Miner tx creation have no luck with delta_extra size = " << delta << " and " << delta - 1, LOG_LEVEL_2);
cumulative_size += delta - 1;
continue;
}
LOG_PRINT_GREEN("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count, LOG_LEVEL_1);
}
}
CHECK_AND_ASSERT_MES(cumulative_size == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx));
return true;
}
LOG_ERROR("Failed to create_block_template with " << 10 << " tries");
return false;
}
//------------------------------------------------------
bool blockchain_storage::have_block(const crypto::hash& id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (m_db_blocks_index.find(id))
return true;
if (m_alternative_chains.count(id))
return true;
/*if(m_orphaned_blocks.get<by_id>().count(id))
return true;*/
/*if(m_orphaned_by_tx.count(id))
return true;*/
if (m_invalid_blocks.count(id))
return true;
return false;
}
//------------------------------------------------------
size_t blockchain_storage::get_total_transactions()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db_transactions.size();
}
//------------------------------------------------------
bool blockchain_storage::get_outs(uint64_t amount, std::list<crypto::public_key>& pkeys)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t sz = m_db_outputs.get_item_size(amount);
if (!sz)
return true;
for (uint64_t i = 0; i != sz; i++)
{
auto out_entry_ptr = m_db_outputs.get_subitem(amount, i);
auto tx_ptr = m_db_transactions.find(out_entry_ptr->first);
CHECK_AND_ASSERT_MES(tx_ptr, false, "transactions outs global index consistency broken: wrong tx id in index");
CHECK_AND_ASSERT_MES(tx_ptr->tx.vout.size() > out_entry_ptr->second, false, "transactions outs global index consistency broken: index in tx_outx more then size");
CHECK_AND_ASSERT_MES(tx_ptr->tx.vout[out_entry_ptr->second].target.type() == typeid(txout_to_key), false, "transactions outs global index consistency broken: index in tx_outx more then size");
pkeys.push_back(boost::get<txout_to_key>(tx_ptr->tx.vout[out_entry_ptr->second].target).key);
}
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_short_chain_history(std::list<crypto::hash>& ids)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t i = 0;
size_t current_multiplier = 1;
size_t sz = m_db_blocks.size();
if (!sz)
return true;
size_t current_back_offset = 1;
bool genesis_included = false;
while (current_back_offset < sz)
{
ids.push_back(get_block_hash(m_db_blocks[sz - current_back_offset]->bl));
if (sz - current_back_offset == 0)
genesis_included = true;
if (i < 10)
{
++current_back_offset;
}
else
{
current_back_offset += current_multiplier *= 2;
}
++i;
}
if (!genesis_included)
ids.push_back(get_block_hash(m_db_blocks[0]->bl));
return true;
}
//------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::list<std::pair<block, std::list<transaction> > >& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
PROF_L2_START(find_blockchain_supplement_time);
if (!find_blockchain_supplement(qblock_ids, start_height))
return false;
PROF_L2_FINISH(find_blockchain_supplement_time);
PROF_L2_START(get_transactions_time);
total_height = get_current_blockchain_height();
size_t count = 0;
size_t txs_count = 0;
for (size_t i = start_height; i != m_db_blocks.size() && count < max_count; i++, count++)
{
blocks.resize(blocks.size() + 1);
blocks.back().first = m_db_blocks[i]->bl;
std::list<crypto::hash> mis;
get_transactions(m_db_blocks[i]->bl.tx_hashes, blocks.back().second, mis);
CHECK_AND_ASSERT_MES(!mis.size(), false, "internal error, transaction from block not found");
txs_count += blocks.back().second.size();
}
PROF_L2_FINISH(get_transactions_time);
PROF_L2_LOG_PRINT("find_blockchain_supplement(5): " << blocks.size() << " blocks, " << txs_count << " txs, timings: " << print_mcsec_as_ms(find_blockchain_supplement_time) << " / " << print_mcsec_as_ms(get_transactions_time), LOG_LEVEL_1);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (!qblock_ids.size() /*|| !req.m_total_height*/)
{
LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << /*", m_height=" << req.m_total_height <<*/ ", dropping connection");
return false;
}
//check genesis match
if (qblock_ids.back() != get_block_hash(m_db_blocks[0]->bl))
{
LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block missmatch: " << ENDL << "id: "
<< qblock_ids.back() << ", " << ENDL << "expected: " << get_block_hash(m_db_blocks[0]->bl)
<< "," << ENDL << " dropping connection");
return false;
}
/* Figure out what blocks we should request to get state_normal */
size_t i = 0;
auto bl_it = qblock_ids.begin();
auto block_index_ptr = m_db_blocks_index.find(*bl_it);
for (; bl_it != qblock_ids.end(); bl_it++, i++)
{
block_index_ptr = m_db_blocks_index.find(*bl_it);
if (block_index_ptr)
break;
}
if (bl_it == qblock_ids.end())
{
LOG_ERROR("Internal error handling connection, can't find split point");
return false;
}
if (!block_index_ptr)
{
//this should NEVER happen, but, dose of paranoia in such cases is not too bad
LOG_ERROR("Internal error handling connection, can't find split point");
return false;
}
//we start to put block ids INCLUDING last known id, just to make other side be sure
starter_offset = *block_index_ptr;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (!find_blockchain_supplement(qblock_ids, resp.start_height))
return false;
resp.total_height = get_current_blockchain_height();
size_t count = 0;
for (size_t i = resp.start_height; i != m_db_blocks.size() && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++)
resp.m_block_ids.push_back(get_block_hash(m_db_blocks[i]->bl));
return true;
}
//------------------------------------------------------
bool blockchain_storage::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
rsp.current_blockchain_height = get_current_blockchain_height();
std::list<block> blocks;
get_blocks(arg.blocks, blocks, rsp.missed_ids);
BOOST_FOREACH(const auto& bl, blocks)
{
std::list<crypto::hash> missed_tx_id;
std::list<transaction> txs;
get_transactions(bl.tx_hashes, txs, rsp.missed_ids);
CHECK_AND_ASSERT_MES(!missed_tx_id.size(), false, "Internal error: have missed missed_tx_id.size()=" << missed_tx_id.size()
<< ENDL << "for block id = " << get_block_hash(bl));
rsp.blocks.push_back(block_complete_entry());
block_complete_entry& e = rsp.blocks.back();
//pack block
e.block = t_serializable_object_to_blob(bl);
//pack transactions
BOOST_FOREACH(transaction& tx, txs)
e.txs.push_back(t_serializable_object_to_blob(tx));
}
//get another transactions, if need
std::list<transaction> txs;
get_transactions(arg.txs, txs, rsp.missed_ids);
//pack aside transactions
BOOST_FOREACH(const auto& tx, txs)
rsp.txs.push_back(t_serializable_object_to_blob(tx));
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(uint64_t amount, req.amounts)
{
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs = *res.outs.insert(res.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount());
result_outs.amount = amount;
uint64_t outs_container_size = m_db_outputs.get_item_size(amount);
if (!outs_container_size)
{
LOG_ERROR("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: not outs for amount " << amount << ", wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist");
continue;//actually this is strange situation, wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist
}
//it is not good idea to use top fresh outs, because it increases possibility of transaction canceling on split
//lets find upper bound of not fresh outs
size_t up_index_limit = find_end_of_allowed_index(amount);
CHECK_AND_ASSERT_MES(up_index_limit <= outs_container_size, false, "internal error: find_end_of_allowed_index returned wrong index=" << up_index_limit << ", with amount_outs.size = " << outs_container_size);
if (up_index_limit >= req.outs_count)
{
std::set<size_t> used;
size_t try_count = 0;
for (uint64_t j = 0; j != req.outs_count && try_count < up_index_limit;)
{
size_t i = crypto::rand<size_t>() % up_index_limit;
if (used.count(i))
continue;
bool added = add_out_to_get_random_outs(result_outs, amount, i, req.outs_count, req.use_forced_mix_outs);
used.insert(i);
if (added)
++j;
++try_count;
}
if (result_outs.outs.size() < req.outs_count)
{
LOG_PRINT_RED_L0("Not enough inputs for amount " << amount << ", needed " << req.outs_count << ", added " << result_outs.outs.size() << " good outs from " << up_index_limit << " unlocked of " << outs_container_size << " total");
}
}
else
{
size_t added = 0;
for (size_t i = 0; i != up_index_limit; i++)
added += add_out_to_get_random_outs(result_outs, amount, i, req.outs_count, req.use_forced_mix_outs) ? 1 : 0;
LOG_PRINT_RED_L0("Not enough inputs for amount " << amount << ", needed " << req.outs_count << ", added " << added << " good outs from " << up_index_limit << " unlocked of " << outs_container_size << " total - respond with all good outs");
}
}
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_backward_blocks_sizes(size_t from_height, std::vector<size_t>& sz, size_t count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(from_height < m_db_blocks.size(), false, "Internal error: get_backward_blocks_sizes called with from_height=" << from_height << ", blockchain height = " << m_db_blocks.size());
size_t start_offset = (from_height + 1) - std::min((from_height + 1), count);
for (size_t i = start_offset; i != from_height + 1; i++)
sz.push_back(m_db_blocks[i]->block_cumulative_size);
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto tx_ptr = m_db_transactions.find(tx_id);
if (!tx_ptr)
{
LOG_PRINT_RED_L0("warning: get_tx_outputs_gindexs failed to find transaction with id = " << tx_id);
return false;
}
CHECK_AND_ASSERT_MES(tx_ptr->m_global_output_indexes.size(), false, "internal error: global indexes for transaction " << tx_id << " is empty");
indexs = tx_ptr->m_global_output_indexes;
return true;
}
//------------------------------------------------------
bool blockchain_storage::get_alias_info(const std::string& alias, alias_info_base& info)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto al_ptr = m_db_aliases.find(alias);
if (al_ptr)
{
if (al_ptr->size())
{
info = al_ptr->back();
return true;
}
}
return false;
}
//------------------------------------------------------
std::string blockchain_storage::get_alias_by_address(const account_public_address& addr)
{
auto alias_ptr = m_db_addr_to_alias.find(addr);
if (alias_ptr && alias_ptr->size())
{
return *(alias_ptr->begin());
}
return "";
}
//------------------------------------------------------
bool blockchain_storage::get_all_aliases(std::list<alias_info>& aliases)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_db_aliases.enumerate_items([&](uint64_t i, const std::string& alias, const std::list<alias_info_base>& elias_entries)
{
if (elias_entries.size())
{
aliases.push_back(alias_info());
aliases.back().m_alias = alias;
static_cast<alias_info_base&>(aliases.back()) = elias_entries.back();
}
return true;
});
return true;
}
//------------------------------------------------------
uint64_t blockchain_storage::get_aliases_count()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db_aliases.size();
}
//------------------------------------------------------
uint64_t blockchain_storage::get_scratchpad_size()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_scratchpad_wr.get_scratchpad().size() * 32;
}
//------------------------------------------------------
bool blockchain_storage::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, uint64_t* pmax_related_block_height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
struct outputs_visitor
{
std::vector<crypto::public_key>& m_results_collector;
blockchain_storage& m_bch;
outputs_visitor(std::vector<crypto::public_key>& results_collector, blockchain_storage& bch) :m_results_collector(results_collector), m_bch(bch)
{}
bool handle_output(const transaction& tx, const tx_out& out)
{
//check tx unlock time
if (!m_bch.is_tx_spendtime_unlocked(tx.unlock_time))
{
LOG_PRINT_L0("One of outputs for one of inputs have wrong tx.unlock_time = " << tx.unlock_time);
return false;
}
if (out.target.type() != typeid(txout_to_key))
{
LOG_PRINT_L0("Output have wrong type id, which=" << out.target.which());
return false;
}
m_results_collector.push_back(boost::get<txout_to_key>(out.target).key);
return true;
}
};
//check ring signature
std::vector<crypto::public_key> output_keys;
outputs_visitor vi(output_keys, *this);
if (!scan_outputkeys_for_indexes(txin, vi, pmax_related_block_height))
{
LOG_PRINT_L0("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size());
return false;
}
if (txin.key_offsets.size() != output_keys.size())
{
LOG_PRINT_L0("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size());
return false;
}
if (m_is_in_checkpoint_zone)
return true;
bool r = crypto::validate_key_image(txin.k_image);
CHECK_AND_ASSERT_MES(r, false, "key image for tx" << tx_prefix_hash << " is invalid: " << txin.k_image);
CHECK_AND_ASSERT_MES(sig.size() == output_keys.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << output_keys.size());
return crypto::check_ring_signature(tx_prefix_hash, txin.k_image, output_keys, sig.data());
}
//------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, const crypto::hash& tx_prefix_hash, uint64_t* pmax_used_block_height)
{