-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
blockchain.cpp
2137 lines (1933 loc) · 80.9 KB
/
blockchain.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) 2014, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#include <algorithm>
#include <cstdio>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "include_base_utils.h"
#include "cryptonote_basic_impl.h"
#include "blockchain.h"
#include "cryptonote_format_utils.h"
#include "cryptonote_boost_serialization.h"
#include "cryptonote_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 "warnings.h"
#include "crypto/hash.h"
//#include "serialization/json_archive.h"
/* TODO:
* Clean up code:
* Possibly change how outputs are referred to/indexed in blockchain and wallets
*
*/
using namespace cryptonote;
DISABLE_VS_WARNINGS(4267)
//------------------------------------------------------------------
// TODO: initialize m_db with a concrete implementation of BlockchainDB
Blockchain::Blockchain(tx_memory_pool& tx_pool):m_db(), m_tx_pool(tx_pool), m_current_block_cumul_sz_limit(0), m_is_in_checkpoint_zone(false), m_is_blockchain_storing(false)
{
if (m_db == NULL)
{
throw new DB_ERROR("database pointer null in blockchain init");
}
}
//------------------------------------------------------------------
//TODO: is this still needed? I don't think so - tewinget
template<class archive_t>
void Blockchain::serialize(archive_t & ar, const unsigned int version)
{
if(version < 11)
return;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
ar & m_blocks;
ar & m_blocks_index;
ar & m_transactions;
ar & m_spent_keys;
ar & m_alternative_chains;
ar & m_outputs;
ar & m_invalid_blocks;
ar & m_current_block_cumul_sz_limit;
/*serialization bug workaround*/
if(version > 11)
{
uint64_t total_check_count = m_db->height() + m_blocks_index.size() + m_transactions.size() + m_spent_keys.size() + m_alternative_chains.size() + m_outputs.size() + m_invalid_blocks.size() + m_current_block_cumul_sz_limit;
if(archive_t::is_saving::value)
{
ar & total_check_count;
}else
{
uint64_t total_check_count_loaded = 0;
ar & total_check_count_loaded;
if(total_check_count != total_check_count_loaded)
{
LOG_ERROR("Blockchain storage data corruption detected. total_count loaded from file = " << total_check_count_loaded << ", expected = " << total_check_count);
LOG_PRINT_L0("Blockchain storage:" << std::endl <<
"m_blocks: " << m_db->height() << std::endl <<
"m_blocks_index: " << m_blocks_index.size() << std::endl <<
"m_transactions: " << m_transactions.size() << std::endl <<
"m_spent_keys: " << m_spent_keys.size() << std::endl <<
"m_alternative_chains: " << m_alternative_chains.size() << std::endl <<
"m_outputs: " << m_outputs.size() << std::endl <<
"m_invalid_blocks: " << m_invalid_blocks.size() << std::endl <<
"m_current_block_cumul_sz_limit: " << m_current_block_cumul_sz_limit);
throw std::runtime_error("Blockchain data corruption");
}
}
}
LOG_PRINT_L2("Blockchain storage:" << std::endl <<
"m_blocks: " << m_db->height() << std::endl <<
"m_blocks_index: " << m_blocks_index.size() << std::endl <<
"m_transactions: " << m_transactions.size() << std::endl <<
"m_spent_keys: " << m_spent_keys.size() << std::endl <<
"m_alternative_chains: " << m_alternative_chains.size() << std::endl <<
"m_outputs: " << m_outputs.size() << std::endl <<
"m_invalid_blocks: " << m_invalid_blocks.size() << std::endl <<
"m_current_block_cumul_sz_limit: " << m_current_block_cumul_sz_limit);
}
//------------------------------------------------------------------
bool Blockchain::have_tx(const crypto::hash &id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db->tx_exists(id);
}
//------------------------------------------------------------------
bool Blockchain::have_tx_keyimg_as_spent(const crypto::key_image &key_im)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db->has_key_image(key_im);
}
//------------------------------------------------------------------
// This function makes sure that each "input" in an input (mixins) exists
// and collects the public key for each from the transaction it was included in
// via the visitor passed to it.
template<class visitor_t>
bool Blockchain::scan_outputkeys_for_indexes(const txin_to_key& tx_in_to_key, visitor_t& vis, uint64_t* pmax_related_block_height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// verify that the input has key offsets (that it exists properly, really)
if(!tx_in_to_key.key_offsets.size())
return false;
// cryptonote_format_utils uses relative offsets for indexing to the global
// outputs list. that is to say that absolute offset #2 is absolute offset
// #1 plus relative offset #2.
// TODO: Investigate if this is necessary / why this is done.
std::vector<uint64_t> absolute_offsets = relative_output_offsets_to_absolute(tx_in_to_key.key_offsets);
//std::vector<std::pair<crypto::hash, size_t> >& amount_outs_vec = it->second;
size_t count = 0;
for (const uint64_t& i : absolute_offsets)
{
try
{
// get tx hash and output index for output
auto output_index = m_db->get_output_tx_and_index(tx_in_to_key.amount, i);
// get tx that output is from
auto tx = m_db->get_tx(output_index.first);
// make sure output index is within range for the given transaction
if (output_index.second >= tx.vout.size())
{
LOG_PRINT_L0("Output does not exist. tx = " << output_index.first << ", index = " << output_index.second);
return false;
}
// call to the passed boost visitor to grab the public key for the output
if(!vis.handle_output(tx, tx.vout[output_index.second]))
{
LOG_PRINT_L0("Failed to handle_output for output no = " << count << ", with absolute offset " << i);
return false;
}
// if on last output and pmax_related_block_height not null pointer
if(++count == absolute_offsets.size() && pmax_related_block_height)
{
// set *pmax_related_block_height to tx block height for this output
auto h = m_db->get_tx_block_height(output_index.first);
if(*pmax_related_block_height < h)
{
*pmax_related_block_height = h;
}
}
}
catch (const OUTPUT_DNE& e)
{
LOG_PRINT_L0("Output does not exist: " << e.what());
return false;
}
catch (const TX_DNE& e)
{
LOG_PRINT_L0("Transaction does not exist: " << e.what());
return false;
}
}
return true;
}
//------------------------------------------------------------------
uint64_t Blockchain::get_current_blockchain_height()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db->height();
}
//------------------------------------------------------------------
//FIXME: possibly move this into the constructor, to avoid accidentally
// dereferencing a null BlockchainDB pointer
bool Blockchain::init(const std::string& config_folder)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_config_folder = config_folder;
LOG_PRINT_L0("Loading blockchain...");
//FIXME: update filename for BlockchainDB
const std::string filename = m_config_folder + "/" CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
try
{
m_db->open(filename);
}
catch (const DB_OPEN_FAILURE& e)
{
LOG_PRINT_L0("No blockchain file found, attempting to create one.");
try
{
m_db->create(filename);
}
catch (const DB_CREATE_FAILURE& db_create_error)
{
LOG_PRINT_L0("Unable to create BlockchainDB! This is not good...");
//TODO: make sure whatever calls this handles the return value properly
return false;
}
}
// if the blockchain is new, add the genesis block
// this feels kinda kludgy to do it this way, but can be looked at later.
if(!m_db->height())
{
LOG_PRINT_L0("Blockchain not loaded, generating genesis block.");
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");
}
// check how far behind we are
uint64_t top_block_timestamp = m_db->get_top_block_timestamp();
uint64_t timestamp_diff = time(NULL) - top_block_timestamp;
// genesis block has no timestamp, could probably change it to have timestamp of 1341378000...
if(!top_block_timestamp)
timestamp_diff = time(NULL) - 1341378000;
LOG_PRINT_GREEN("Blockchain initialized. last block: " << m_db->height() - 1 << ", " << epee::misc_utils::get_time_interval_string(timestamp_diff) << " time ago, current difficulty: " << get_difficulty_for_next_block(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
bool Blockchain::store_blockchain()
{
// TODO: make sure if this throws that it is not simply ignored higher
// up the call stack
try
{
m_db->sync();
}
catch (const std::exception& e)
{
LOG_PRINT_L0(std::string("Error syncing blockchain db: ") + e.what() + "-- shutting down now to prevent issues!");
throw;
}
catch (...)
{
LOG_PRINT_L0("There was an issue storing the blockchain, shutting down now to prevent issues!");
throw;
}
LOG_PRINT_L0("Blockchain stored OK.");
return true;
}
//------------------------------------------------------------------
bool Blockchain::deinit()
{
// as this should be called if handling a SIGSEGV, need to check
// if m_db is a NULL pointer (and thus may have caused the illegal
// memory operation), otherwise we may cause a loop.
if (m_db == NULL)
{
throw new DB_ERROR("The db pointer is null in Blockchain, the blockchain may be corrupt!");
}
try
{
m_db->close();
}
catch (const std::exception& e)
{
LOG_PRINT_L0(std::string("Error closing blockchain db: ") + e.what());
}
catch (...)
{
LOG_PRINT_L0("There was an issue closing/storing the blockchain, shutting down now to prevent issues!");
}
return true;
}
//------------------------------------------------------------------
// This function tells BlockchainDB to remove the top block from the
// blockchain and then returns all transactions (except the miner tx, of course)
// from it to the tx_pool
block Blockchain::pop_block_from_blockchain()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
block popped_block;
std::vector<transaction> popped_txs;
try
{
m_db->pop_block(popped_block, popped_txs);
}
// anything that could cause this to throw is likely catastrophic,
// so we re-throw
catch (const std::exception& e)
{
LOG_ERROR("Error popping block from blockchain: " << e.what());
throw;
}
catch (...)
{
LOG_ERROR("Error popping block from blockchain, throwing!");
throw;
}
// return transactions from popped block to the tx_pool
for (transaction& tx : popped_txs)
{
if (!is_coinbase(tx))
{
cryptonote::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
bool r = m_tx_pool.add_tx(tx, tvc, true);
if (!r)
{
LOG_ERROR("Error returning transaction to tx_pool");
}
}
}
return popped_block;
}
//------------------------------------------------------------------
bool Blockchain::reset_and_set_genesis_block(const block& b)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_transactions.clear();
m_spent_keys.clear();
m_blocks.clear();
m_blocks_index.clear();
m_alternative_chains.clear();
m_outputs.clear();
m_db->reset();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
add_new_block(b, bvc);
return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed;
}
//------------------------------------------------------------------
//TODO: move to BlockchainDB subclass
bool Blockchain::purge_transaction_keyimages_from_blockchain(const transaction& tx, bool strict_check)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
struct purge_transaction_visitor: public boost::static_visitor<bool>
{
key_images_container& m_spent_keys;
bool m_strict_check;
purge_transaction_visitor(key_images_container& spent_keys, bool strict_check):m_spent_keys(spent_keys), m_strict_check(strict_check){}
bool operator()(const txin_to_key& inp) const
{
//const crypto::key_image& ki = inp.k_image;
auto r = m_spent_keys.find(inp.k_image);
if(r != m_spent_keys.end())
{
m_spent_keys.erase(r);
}else
{
CHECK_AND_ASSERT_MES(!m_strict_check, false, "purge_block_data_from_blockchain: key image in transaction not found");
}
return true;
}
bool operator()(const txin_gen& inp) const
{
return true;
}
bool operator()(const txin_to_script& tx) const
{
return false;
}
bool operator()(const txin_to_scripthash& tx) const
{
return false;
}
};
BOOST_FOREACH(const txin_v& in, tx.vin)
{
bool r = boost::apply_visitor(purge_transaction_visitor(m_spent_keys, strict_check), in);
CHECK_AND_ASSERT_MES(!strict_check || r, false, "failed to process purge_transaction_visitor");
}
return true;
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_tail_id(uint64_t& height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
height = m_db->height();
return get_tail_id();
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_tail_id()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_db->top_block_hash();
}
//------------------------------------------------------------------
/*TODO: this function was...poorly written. As such, I'm not entirely
* certain on what it was supposed to be doing. Need to look into this,
* but it doesn't seem terribly important just yet.
*
* puts into list <ids> a list of hashes representing certain blocks
* from the blockchain in reverse chronological order
*
* the blocks chosen, at the time of this writing, are:
* the most recent 11
* powers of 2 less recent from there, so 13, 17, 25, etc...
*
*/
bool Blockchain::get_short_chain_history(std::list<crypto::hash>& ids)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t i = 0;
uint64_t current_multiplier = 1;
uint64_t sz = m_db->height();
if(!sz)
return true;
uint64_t current_back_offset = 0;
while(current_back_offset < sz)
{
ids.push_back(m_db->get_block_hash_from_height(sz-current_back_offset));
if(i < 10)
{
++current_back_offset;
}
else
{
current_multiplier *= 2;
current_back_offset += current_multiplier;
}
++i;
}
return true;
}
//------------------------------------------------------------------
crypto::hash Blockchain::get_block_id_by_height(uint64_t height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
try
{
return m_db->get_block_hash_from_height(height);
}
catch (const BLOCK_DNE& e)
{
}
catch (const std::exception& e)
{
LOG_PRINT_L0(std::string("Something went wrong fetching block hash by height: ") + e.what());
throw;
}
catch (...)
{
LOG_PRINT_L0(std::string("Something went wrong fetching block hash by height"));
throw;
}
return null_hash;
}
//------------------------------------------------------------------
bool Blockchain::get_block_by_hash(const crypto::hash &h, block &blk)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// try to find block in main chain
try
{
blk = m_db->get_block(h);
return true;
}
// try to find block in alternative chain
catch (const BLOCK_DNE& e)
{
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;
}
}
catch (const std::exception& e)
{
LOG_PRINT_L0(std::string("Something went wrong fetching block by hash: ") + e.what());
throw;
}
catch (...)
{
LOG_PRINT_L0(std::string("Something went wrong fetching block hash by hash"));
throw;
}
return false;
}
//------------------------------------------------------------------
void Blockchain::get_all_known_block_ids(std::list<crypto::hash> &main, std::list<crypto::hash> &alt, std::list<crypto::hash> &invalid)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
main = m_db->get_hashes_range(0, m_db->height());
BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_alternative_chains)
alt.push_back(v.first);
BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_invalid_blocks)
invalid.push_back(v.first);
}
//------------------------------------------------------------------
// This function aggregates the cumulative difficulties and timestamps of the
// last DIFFICULTY_BLOCKS_COUNT blocks and passes them to next_difficulty,
// returning the result of that call. Ignores the genesis block, and can use
// less blocks than desired if there aren't enough.
difficulty_type Blockchain::get_difficulty_for_next_block()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
std::vector<uint64_t> timestamps;
std::vector<difficulty_type> cumulative_difficulties;
auto h = m_db->height();
size_t offset = h - std::min(h, static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
// because BlockchainDB::height() returns the index of the top block, the
// first index we need to get needs to be one
// higher than height() - DIFFICULTY_BLOCKS_COUNT. This also conveniently
// makes sure we don't use the genesis block.
++offset;
for(; offset <= h; offset++)
{
timestamps.push_back(m_db->get_block_timestamp(offset));
cumulative_difficulties.push_back(m_db->get_block_cumulative_difficulty(offset));
}
return next_difficulty(timestamps, cumulative_difficulties);
}
//------------------------------------------------------------------
// This function removes blocks from the blockchain until it gets to the
// position where the blockchain switch started and then re-adds the blocks
// that had been removed.
bool Blockchain::rollback_blockchain_switching(std::list<block>& original_chain)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// remove blocks from blockchain until we get back to where we were.
// Conveniently, that's until our top block's hash == the parent block of
// the first block we need to add back.
while (m_db->top_block_hash() != original_chain.front().prev_id)
{
pop_block_from_blockchain();
}
//return back original chain
for (auto& bl : original_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_block_to_main_chain(bl, bvc);
CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC!!! failed to add (again) block while chain switching during the rollback!");
}
return true;
}
//------------------------------------------------------------------
// This function attempts to switch to an alternate chain, returning
// boolean based on success therein.
bool Blockchain::switch_to_alternative_blockchain(std::list<blocks_ext_by_hash::iterator>& alt_chain, bool discard_disconnected_chain)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// if empty alt chain passed (not sure how that could happen), return false
CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed");
// verify that main chain has front of alt chain's parent block
if (!m_db->block_exists(alt_chain.front()->second.bl.prev_id))
{
LOG_ERROR("Attempting to move to an alternate chain, but it doesn't appear to connect to the main chain!");
return false;
}
// pop blocks from the blockchain until the top block is the parent
// of the front block of the alt chain.
std::list<block> disconnected_chain;
while (m_db->top_block_hash() != alt_chain.front()->second.bl.prev_id)
{
block b = pop_block_from_blockchain();
disconnected_chain.push_front(b);
}
auto split_height = m_db->height();
//connecting new alternative chain
for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++)
{
auto ch_ent = *alt_ch_iter;
block_verification_context bvc = boost::value_initialized<block_verification_context>();
// add block to main chain
bool r = handle_block_to_main_chain(ch_ent->second.bl, bvc);
// if adding block to main chain failed, rollback to previous state and
// return false
if(!r || !bvc.m_added_to_main_chain)
{
LOG_PRINT_L0("Failed to switch to alternative blockchain");
rollback_blockchain_switching(disconnected_chain);
// FIXME: Why do we keep invalid blocks around? Possibly in case we hear
// about them again so we can immediately dismiss them, but needs some
// looking into.
add_block_as_invalid(ch_ent->second, get_block_hash(ch_ent->second.bl));
LOG_PRINT_L0("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl));
m_alternative_chains.erase(ch_ent);
for(auto alt_ch_to_orph_iter = ++alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); alt_ch_to_orph_iter++)
{
add_block_as_invalid((*alt_ch_iter)->second, (*alt_ch_iter)->first);
m_alternative_chains.erase(*alt_ch_to_orph_iter);
}
return false;
}
}
// if we're to keep the disconnected blocks, add them as alternates
if(!discard_disconnected_chain)
{
//pushing old chain as alternative chain
for (auto& old_ch_ent : disconnected_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc);
if(!r)
{
LOG_ERROR("Failed to push ex-main chain blocks to alternative chain ");
// previously this would fail the blockchain switching, but I don't
// think this is bad enough to warrant that.
}
}
}
//removing alt_chain entries from alternative chain
BOOST_FOREACH(auto ch_ent, alt_chain)
{
m_alternative_chains.erase(ch_ent);
}
LOG_PRINT_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_db->height(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
// This function calculates the difficulty target for the block being added to
// an alternate chain.
difficulty_type Blockchain::get_next_difficulty_for_alternative_chain(const std::list<blocks_ext_by_hash::iterator>& alt_chain, block_extended_info& bei)
{
std::vector<uint64_t> timestamps;
std::vector<difficulty_type> cumulative_difficulties;
// if the alt chain isn't long enough to calculate the difficulty target
// based on its blocks alone, need to get more blocks from the main chain
if(alt_chain.size()< DIFFICULTY_BLOCKS_COUNT)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// Figure out start and stop offsets for main chain blocks
size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front()->second.height : bei.height;
size_t main_chain_count = DIFFICULTY_BLOCKS_COUNT - std::min(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT), alt_chain.size());
main_chain_count = std::min(main_chain_count, main_chain_stop_offset);
size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count;
if(!main_chain_start_offset)
++main_chain_start_offset; //skip genesis block
// get difficulties and timestamps from relevant main chain blocks
for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset)
{
timestamps.push_back(m_db->get_block_timestamp(main_chain_start_offset));
cumulative_difficulties.push_back(m_db->get_block_cumulative_difficulty(main_chain_start_offset));
}
// make sure we haven't accidentally grabbed too many blocks...maybe don't need this check?
CHECK_AND_ASSERT_MES((alt_chain.size() + timestamps.size()) <= DIFFICULTY_BLOCKS_COUNT, false,
"Internal error, alt_chain.size()[" << alt_chain.size()
<< "] + vtimestampsec.size()[" << timestamps.size()
<< "] NOT <= DIFFICULTY_WINDOW[]" << DIFFICULTY_BLOCKS_COUNT
);
for (auto it : alt_chain)
{
timestamps.push_back(it->second.bl.timestamp);
cumulative_difficulties.push_back(it->second.cumulative_difficulty);
}
}
// if the alt chain is long enough for the difficulty calc, grab difficulties
// and timestamps from it alone
else
{
timestamps.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
cumulative_difficulties.resize(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
size_t count = 0;
size_t max_i = timestamps.size()-1;
// get difficulties and timestamps from most recent blocks in alt chain
BOOST_REVERSE_FOREACH(auto it, alt_chain)
{
timestamps[max_i - count] = it->second.bl.timestamp;
cumulative_difficulties[max_i - count] = it->second.cumulative_difficulty;
count++;
if(count >= DIFFICULTY_BLOCKS_COUNT)
break;
}
}
// calculate the difficulty target for the block and return it
return next_difficulty(timestamps, cumulative_difficulties);
}
//------------------------------------------------------------------
// This function does a sanity check on basic things that all miner
// transactions have in common, such as:
// one input, of type txin_gen, with height set to the block's height
// correct miner tx unlock time
// a non-overflowing tx amount (dubious necessity on this check)
bool Blockchain::prevalidate_miner_transaction(const block& b, uint64_t height)
{
CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs");
CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type");
if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height)
{
LOG_PRINT_RED_L0("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height);
return false;
}
CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW,
false,
"coinbase transaction transaction have wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CRYPTONOTE_MINED_MONEY_UNLOCK_WINDOW);
//check outs overflow
//NOTE: not entirely sure this is necessary, given that this function is
// designed simply to make sure the total amount for a transaction
// does not overflow a uint64_t, and this transaction *is* a uint64_t...
if(!check_outs_overflow(b.miner_tx))
{
LOG_PRINT_RED_L0("miner transaction have money overflow in block " << get_block_hash(b));
return false;
}
return true;
}
//------------------------------------------------------------------
// This function validates the miner transaction reward
bool Blockchain::validate_miner_transaction(const block& b, size_t cumulative_block_size, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins)
{
//validate reward
uint64_t money_in_use = 0;
BOOST_FOREACH(auto& o, b.miner_tx.vout)
money_in_use += o.amount;
std::vector<size_t> last_blocks_sizes;
get_last_n_blocks_sizes(last_blocks_sizes, CRYPTONOTE_REWARD_BLOCKS_WINDOW);
if (!get_block_reward(epee::misc_utils::median(last_blocks_sizes), cumulative_block_size, already_generated_coins, base_reward)) {
LOG_PRINT_L0("block size " << cumulative_block_size << " is bigger than allowed for this blockchain");
return false;
}
if(base_reward + fee < money_in_use)
{
LOG_ERROR("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")");
return false;
}
if(base_reward + fee != money_in_use)
{
LOG_ERROR("coinbase transaction doesn't use full amount of block reward: spent: "
<< print_money(money_in_use) << ", block reward " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")");
return false;
}
return true;
}
//------------------------------------------------------------------
// get the block sizes of the last <count> blocks, starting at <from_height>
// and return by reference <sz>.
void Blockchain::get_last_n_blocks_sizes(std::vector<size_t>& sz, size_t count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto h = m_db->height();
// this function is meaningless for an empty blockchain...granted it should never be empty
if(h == 0)
return;
// add size of last <count> blocks to vector <sz> (or less, if blockchain size < count)
size_t start_offset = (h+1) - std::min((h+1), count);
for(size_t i = start_offset; i <= h; i++)
{
sz.push_back(m_db->get_block_size(i));
}
}
//------------------------------------------------------------------
uint64_t Blockchain::get_current_cumulative_blocksize_limit()
{
return m_current_block_cumul_sz_limit;
}
//------------------------------------------------------------------
//TODO: This function only needed minor modification to work with BlockchainDB,
// and *works*. As such, to reduce the number of things that might break
// in moving to BlockchainDB, this function will remain otherwise
// unchanged for the time being.
//
// This function makes a new block for a miner to mine the hash for
//
// FIXME: this codebase references #if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
// in a lot of places. That flag is not referenced in any of the code
// nor any of the makefiles, howeve. Need to look into whether or not it's
// necessary at all.
bool Blockchain::create_block_template(block& b, const account_public_address& miner_address, difficulty_type& diffic, uint64_t& height, const blobdata& ex_nonce)
{
size_t median_size;
uint64_t already_generated_coins;
CRITICAL_REGION_BEGIN(m_blockchain_lock);
b.major_version = CURRENT_BLOCK_MAJOR_VERSION;
b.minor_version = CURRENT_BLOCK_MINOR_VERSION;
b.prev_id = get_tail_id();
b.timestamp = time(NULL);
auto old_height = m_db->height();
height = old_height + 1;
diffic = get_difficulty_for_next_block();
CHECK_AND_ASSERT_MES(diffic, false, "difficulty owverhead.");
median_size = m_current_block_cumul_sz_limit / 2;
already_generated_coins = m_db->get_block_already_generated_coins(old_height);
CRITICAL_REGION_END();
size_t txs_size;
uint64_t fee;
if (!m_tx_pool.fill_block_template(b, median_size, already_generated_coins, txs_size, fee)) {
return false;
}
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
size_t real_txs_size = 0;
uint64_t real_fee = 0;
CRITICAL_REGION_BEGIN(m_tx_pool.m_transactions_lock);
BOOST_FOREACH(crypto::hash &cur_hash, b.tx_hashes) {
auto cur_res = m_tx_pool.m_transactions.find(cur_hash);
if (cur_res == m_tx_pool.m_transactions.end()) {
LOG_ERROR("Creating block template: error: transaction not found");
continue;
}
tx_memory_pool::tx_details &cur_tx = cur_res->second;
real_txs_size += cur_tx.blob_size;
real_fee += cur_tx.fee;
if (cur_tx.blob_size != get_object_blobsize(cur_tx.tx)) {
LOG_ERROR("Creating block template: error: invalid transaction size");
}
uint64_t inputs_amount;
if (!get_inputs_money_amount(cur_tx.tx, inputs_amount)) {
LOG_ERROR("Creating block template: error: cannot get inputs amount");
} else if (cur_tx.fee != inputs_amount - get_outs_money_amount(cur_tx.tx)) {
LOG_ERROR("Creating block template: error: invalid fee");
}
}
if (txs_size != real_txs_size) {
LOG_ERROR("Creating block template: error: wrongly calculated transaction size");
}
if (fee != real_fee) {
LOG_ERROR("Creating block template: error: wrongly calculated fee");
}
CRITICAL_REGION_END();
LOG_PRINT_L1("Creating block template: height " << height <<
", median size " << median_size <<
", already generated coins " << already_generated_coins <<
", transaction size " << txs_size <<
", fee " << fee);
#endif
/*
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, txs_size, fee, miner_address, b.miner_tx, ex_nonce, 11);
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance");
size_t cumulative_size = txs_size + get_object_blobsize(b.miner_tx);
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: miner tx size " << get_object_blobsize(b.miner_tx) <<
", cumulative size " << cumulative_size);
#endif
for (size_t try_count = 0; try_count != 10; ++try_count) {
r = construct_miner_tx(height, median_size, already_generated_coins, cumulative_size, fee, miner_address, b.miner_tx, ex_nonce, 11);
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;
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size <<
", cumulative size " << cumulative_size << " is greater then before");
#endif
continue;
}
if (coinbase_blob_size < cumulative_size - txs_size) {
size_t delta = cumulative_size - txs_size - coinbase_blob_size;
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size <<
", cumulative size " << txs_size + coinbase_blob_size <<
" is less then before, adding " << delta << " zero bytes");
#endif
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));
#if defined(DEBUG_CREATE_BLOCK_TEMPLATE)
LOG_PRINT_L1("Creating block template: miner tx size " << coinbase_blob_size <<
", cumulative size " << cumulative_size << " is now good");
#endif
return true;
}
LOG_ERROR("Failed to create_block_template with " << 10 << " tries");
return false;
}
//------------------------------------------------------------------
// for an alternate chain, get the timestamps from the main chain to complete
// the needed number of timestamps for the BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW.
bool Blockchain::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps)
{
if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
return true;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size();
CHECK_AND_ASSERT_MES(start_top_height <= m_db->height(), false, "internal error: passed start_height > " << " m_db->height() -- " << start_top_height << " > " << m_db->height());
size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements : 0;
while (start_top_height != stop_offset);
{
timestamps.push_back(m_db->get_block_timestamp(start_top_height));
--start_top_height;
}
return true;
}
//------------------------------------------------------------------
// If a block is to be added and its parent block is not the current
// main chain top block, then we need to see if we know about its parent block.
// If its parent block is part of a known forked chain, then we need to see
// if that chain is long enough to become the main chain and re-org accordingly
// if so. If not, we need to hang on to the block in case it becomes part of
// a long forked chain eventually.
bool Blockchain::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t block_height = get_block_height(b);
if(0 == block_height)
{